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 gdb::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
);
1268 int putpkt (const char *buf
);
1269 int putpkt_binary (const char *buf
, int cnt
);
1271 int putpkt (const gdb::char_vector
&buf
)
1273 return putpkt (buf
.data ());
1277 long read_frame (gdb::char_vector
*buf_p
);
1278 int getpkt (gdb::char_vector
*buf
, bool forever
= false,
1279 bool *is_notif
= nullptr);
1280 int remote_vkill (int pid
);
1281 void remote_kill_k ();
1283 void extended_remote_disable_randomization (int val
);
1284 int extended_remote_run (const std::string
&args
);
1286 void send_environment_packet (const char *action
,
1290 void extended_remote_environment_support ();
1291 void extended_remote_set_inferior_cwd ();
1293 target_xfer_status
remote_write_qxfer (const char *object_name
,
1295 const gdb_byte
*writebuf
,
1296 ULONGEST offset
, LONGEST len
,
1297 ULONGEST
*xfered_len
,
1298 const unsigned int which_packet
);
1300 target_xfer_status
remote_read_qxfer (const char *object_name
,
1302 gdb_byte
*readbuf
, ULONGEST offset
,
1304 ULONGEST
*xfered_len
,
1305 const unsigned int which_packet
);
1307 void push_stop_reply (struct stop_reply
*new_event
);
1309 bool vcont_r_supported ();
1311 remote_features m_features
;
1315 bool start_remote_1 (int from_tty
, int extended_p
);
1317 /* The remote state. Don't reference this directly. Use the
1318 get_remote_state method instead. */
1319 remote_state m_remote_state
;
1322 static const target_info extended_remote_target_info
= {
1324 N_("Extended remote target using gdb-specific protocol"),
1328 /* Set up the extended remote target by extending the standard remote
1329 target and adding to it. */
1331 class extended_remote_target final
: public remote_target
1334 const target_info
&info () const override
1335 { return extended_remote_target_info
; }
1337 /* Open an extended-remote connection. */
1338 static void open (const char *, int);
1340 bool can_create_inferior () override
{ return true; }
1341 void create_inferior (const char *, const std::string
&,
1342 char **, int) override
;
1344 void detach (inferior
*, int) override
;
1346 bool can_attach () override
{ return true; }
1347 void attach (const char *, int) override
;
1349 void post_attach (int) override
;
1350 bool supports_disable_randomization () override
;
1353 struct stop_reply
: public notif_event
1357 /* The identifier of the thread about this event */
1360 /* The remote state this event is associated with. When the remote
1361 connection, represented by a remote_state object, is closed,
1362 all the associated stop_reply events should be released. */
1363 struct remote_state
*rs
;
1365 struct target_waitstatus ws
;
1367 /* The architecture associated with the expedited registers. */
1370 /* Expedited registers. This makes remote debugging a bit more
1371 efficient for those targets that provide critical registers as
1372 part of their normal status mechanism (as another roundtrip to
1373 fetch them is avoided). */
1374 std::vector
<cached_reg_t
> regcache
;
1376 enum target_stop_reason stop_reason
;
1378 CORE_ADDR watch_data_address
;
1383 /* Return TARGET as a remote_target if it is one, else nullptr. */
1385 static remote_target
*
1386 as_remote_target (process_stratum_target
*target
)
1388 return dynamic_cast<remote_target
*> (target
);
1394 is_remote_target (process_stratum_target
*target
)
1396 return as_remote_target (target
) != nullptr;
1399 /* Per-program-space data key. */
1400 static const registry
<program_space
>::key
<char, gdb::xfree_deleter
<char>>
1403 /* The variable registered as the control variable used by the
1404 remote exec-file commands. While the remote exec-file setting is
1405 per-program-space, the set/show machinery uses this as the
1406 location of the remote exec-file value. */
1407 static std::string remote_exec_file_var
;
1409 /* The size to align memory write packets, when practical. The protocol
1410 does not guarantee any alignment, and gdb will generate short
1411 writes and unaligned writes, but even as a best-effort attempt this
1412 can improve bulk transfers. For instance, if a write is misaligned
1413 relative to the target's data bus, the stub may need to make an extra
1414 round trip fetching data from the target. This doesn't make a
1415 huge difference, but it's easy to do, so we try to be helpful.
1417 The alignment chosen is arbitrary; usually data bus width is
1418 important here, not the possibly larger cache line size. */
1419 enum { REMOTE_ALIGN_WRITES
= 16 };
1421 /* Prototypes for local functions. */
1423 static int hexnumlen (ULONGEST num
);
1425 static int stubhex (int ch
);
1427 static int hexnumstr (char *, ULONGEST
);
1429 static int hexnumnstr (char *, ULONGEST
, int);
1431 static CORE_ADDR
remote_address_masked (CORE_ADDR
);
1433 static int stub_unpack_int (const char *buff
, int fieldlength
);
1435 static void set_remote_protocol_packet_cmd (const char *args
, int from_tty
,
1436 cmd_list_element
*c
);
1438 static void show_packet_config_cmd (ui_file
*file
,
1439 const unsigned int which_packet
,
1440 remote_target
*remote
);
1442 static void show_remote_protocol_packet_cmd (struct ui_file
*file
,
1444 struct cmd_list_element
*c
,
1447 static ptid_t
read_ptid (const char *buf
, const char **obuf
);
1449 static bool remote_read_description_p (struct target_ops
*target
);
1451 static void remote_console_output (const char *msg
);
1453 static void remote_btrace_reset (remote_state
*rs
);
1455 static void remote_unpush_and_throw (remote_target
*target
);
1459 static struct cmd_list_element
*remote_cmdlist
;
1461 /* For "set remote" and "show remote". */
1463 static struct cmd_list_element
*remote_set_cmdlist
;
1464 static struct cmd_list_element
*remote_show_cmdlist
;
1466 /* Controls whether GDB is willing to use range stepping. */
1468 static bool use_range_stepping
= true;
1470 /* From the remote target's point of view, each thread is in one of these three
1472 enum class resume_state
1474 /* Not resumed - we haven't been asked to resume this thread. */
1477 /* We have been asked to resume this thread, but haven't sent a vCont action
1478 for it yet. We'll need to consider it next time commit_resume is
1480 RESUMED_PENDING_VCONT
,
1482 /* We have been asked to resume this thread, and we have sent a vCont action
1487 /* Information about a thread's pending vCont-resume. Used when a thread is in
1488 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1489 stores this information which is then picked up by
1490 remote_target::commit_resume to know which is the proper action for this
1491 thread to include in the vCont packet. */
1492 struct resumed_pending_vcont_info
1494 /* True if the last resume call for this thread was a step request, false
1495 if a continue request. */
1498 /* The signal specified in the last resume call for this thread. */
1502 /* Private data that we'll store in (struct thread_info)->priv. */
1503 struct remote_thread_info
: public private_thread_info
1509 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1510 sequence of bytes. */
1511 gdb::byte_vector thread_handle
;
1513 /* Whether the target stopped for a breakpoint/watchpoint. */
1514 enum target_stop_reason stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
1516 /* This is set to the data address of the access causing the target
1517 to stop for a watchpoint. */
1518 CORE_ADDR watch_data_address
= 0;
1520 /* Get the thread's resume state. */
1521 enum resume_state
get_resume_state () const
1523 return m_resume_state
;
1526 /* Put the thread in the NOT_RESUMED state. */
1527 void set_not_resumed ()
1529 m_resume_state
= resume_state::NOT_RESUMED
;
1532 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1533 void set_resumed_pending_vcont (bool step
, gdb_signal sig
)
1535 m_resume_state
= resume_state::RESUMED_PENDING_VCONT
;
1536 m_resumed_pending_vcont_info
.step
= step
;
1537 m_resumed_pending_vcont_info
.sig
= sig
;
1540 /* Get the information this thread's pending vCont-resumption.
1542 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1544 const struct resumed_pending_vcont_info
&resumed_pending_vcont_info () const
1546 gdb_assert (m_resume_state
== resume_state::RESUMED_PENDING_VCONT
);
1548 return m_resumed_pending_vcont_info
;
1551 /* Put the thread in the VCONT_RESUMED state. */
1554 m_resume_state
= resume_state::RESUMED
;
1558 /* Resume state for this thread. This is used to implement vCont action
1559 coalescing (only when the target operates in non-stop mode).
1561 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1562 which notes that this thread must be considered in the next commit_resume
1565 remote_target::commit_resume sends a vCont packet with actions for the
1566 threads in the RESUMED_PENDING_VCONT state and moves them to the
1567 VCONT_RESUMED state.
1569 When reporting a stop to the core for a thread, that thread is moved back
1570 to the NOT_RESUMED state. */
1571 enum resume_state m_resume_state
= resume_state::NOT_RESUMED
;
1573 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1574 struct resumed_pending_vcont_info m_resumed_pending_vcont_info
;
1577 remote_state::remote_state ()
1582 remote_state::~remote_state ()
1584 xfree (this->last_pass_packet
);
1585 xfree (this->last_program_signals_packet
);
1586 xfree (this->finished_object
);
1587 xfree (this->finished_annex
);
1590 /* Utility: generate error from an incoming stub packet. */
1592 trace_error (char *buf
)
1595 return; /* not an error msg */
1598 case '1': /* malformed packet error */
1599 if (*++buf
== '0') /* general case: */
1600 error (_("remote.c: error in outgoing packet."));
1602 error (_("remote.c: error in outgoing packet at field #%ld."),
1603 strtol (buf
, NULL
, 16));
1605 error (_("Target returns error code '%s'."), buf
);
1609 /* Utility: wait for reply from stub, while accepting "O" packets. */
1612 remote_target::remote_get_noisy_reply ()
1614 struct remote_state
*rs
= get_remote_state ();
1616 do /* Loop on reply from remote stub. */
1620 QUIT
; /* Allow user to bail out with ^C. */
1622 buf
= rs
->buf
.data ();
1625 else if (startswith (buf
, "qRelocInsn:"))
1628 CORE_ADDR from
, to
, org_to
;
1630 int adjusted_size
= 0;
1633 p
= buf
+ strlen ("qRelocInsn:");
1634 pp
= unpack_varlen_hex (p
, &ul
);
1636 error (_("invalid qRelocInsn packet: %s"), buf
);
1640 unpack_varlen_hex (p
, &ul
);
1647 gdbarch_relocate_instruction (current_inferior ()->arch (),
1651 catch (const gdb_exception
&ex
)
1653 if (ex
.error
== MEMORY_ERROR
)
1655 /* Propagate memory errors silently back to the
1656 target. The stub may have limited the range of
1657 addresses we can write to, for example. */
1661 /* Something unexpectedly bad happened. Be verbose
1662 so we can tell what, and propagate the error back
1663 to the stub, so it doesn't get stuck waiting for
1665 exception_fprintf (gdb_stderr
, ex
,
1666 _("warning: relocating instruction: "));
1673 adjusted_size
= to
- org_to
;
1675 xsnprintf (buf
, rs
->buf
.size (), "qRelocInsn:%x", adjusted_size
);
1679 else if (buf
[0] == 'O' && buf
[1] != 'K')
1680 remote_console_output (buf
+ 1); /* 'O' message from stub */
1682 return buf
; /* Here's the actual reply. */
1687 struct remote_arch_state
*
1688 remote_state::get_remote_arch_state (struct gdbarch
*gdbarch
)
1690 remote_arch_state
*rsa
;
1692 auto it
= this->m_arch_states
.find (gdbarch
);
1693 if (it
== this->m_arch_states
.end ())
1695 auto p
= this->m_arch_states
.emplace (std::piecewise_construct
,
1696 std::forward_as_tuple (gdbarch
),
1697 std::forward_as_tuple (gdbarch
));
1698 rsa
= &p
.first
->second
;
1700 /* Make sure that the packet buffer is plenty big enough for
1701 this architecture. */
1702 if (this->buf
.size () < rsa
->remote_packet_size
)
1703 this->buf
.resize (2 * rsa
->remote_packet_size
);
1711 /* Fetch the global remote target state. */
1714 remote_target::get_remote_state ()
1716 /* Make sure that the remote architecture state has been
1717 initialized, because doing so might reallocate rs->buf. Any
1718 function which calls getpkt also needs to be mindful of changes
1719 to rs->buf, but this call limits the number of places which run
1721 m_remote_state
.get_remote_arch_state (current_inferior ()->arch ());
1723 return &m_remote_state
;
1726 /* Fetch the remote exec-file from the current program space. */
1729 get_remote_exec_file (void)
1731 char *remote_exec_file
;
1733 remote_exec_file
= remote_pspace_data
.get (current_program_space
);
1734 if (remote_exec_file
== NULL
)
1737 return remote_exec_file
;
1740 /* Set the remote exec file for PSPACE. */
1743 set_pspace_remote_exec_file (struct program_space
*pspace
,
1744 const char *remote_exec_file
)
1746 char *old_file
= remote_pspace_data
.get (pspace
);
1749 remote_pspace_data
.set (pspace
, xstrdup (remote_exec_file
));
1752 /* The "set/show remote exec-file" set command hook. */
1755 set_remote_exec_file (const char *ignored
, int from_tty
,
1756 struct cmd_list_element
*c
)
1758 set_pspace_remote_exec_file (current_program_space
,
1759 remote_exec_file_var
.c_str ());
1762 /* The "set/show remote exec-file" show command hook. */
1765 show_remote_exec_file (struct ui_file
*file
, int from_tty
,
1766 struct cmd_list_element
*cmd
, const char *value
)
1768 gdb_printf (file
, "%s\n", get_remote_exec_file ());
1772 map_regcache_remote_table (struct gdbarch
*gdbarch
, struct packet_reg
*regs
)
1774 int regnum
, num_remote_regs
, offset
;
1775 struct packet_reg
**remote_regs
;
1777 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
1779 struct packet_reg
*r
= ®s
[regnum
];
1781 if (register_size (gdbarch
, regnum
) == 0)
1782 /* Do not try to fetch zero-sized (placeholder) registers. */
1785 r
->pnum
= gdbarch_remote_register_number (gdbarch
, regnum
);
1790 /* Define the g/G packet format as the contents of each register
1791 with a remote protocol number, in order of ascending protocol
1794 remote_regs
= XALLOCAVEC (struct packet_reg
*, gdbarch_num_regs (gdbarch
));
1795 for (num_remote_regs
= 0, regnum
= 0;
1796 regnum
< gdbarch_num_regs (gdbarch
);
1798 if (regs
[regnum
].pnum
!= -1)
1799 remote_regs
[num_remote_regs
++] = ®s
[regnum
];
1801 std::sort (remote_regs
, remote_regs
+ num_remote_regs
,
1802 [] (const packet_reg
*a
, const packet_reg
*b
)
1803 { return a
->pnum
< b
->pnum
; });
1805 for (regnum
= 0, offset
= 0; regnum
< num_remote_regs
; regnum
++)
1807 remote_regs
[regnum
]->in_g_packet
= 1;
1808 remote_regs
[regnum
]->offset
= offset
;
1809 offset
+= register_size (gdbarch
, remote_regs
[regnum
]->regnum
);
1815 /* Given the architecture described by GDBARCH, return the remote
1816 protocol register's number and the register's offset in the g/G
1817 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1818 If the target does not have a mapping for REGNUM, return false,
1819 otherwise, return true. */
1822 remote_register_number_and_offset (struct gdbarch
*gdbarch
, int regnum
,
1823 int *pnum
, int *poffset
)
1825 gdb_assert (regnum
< gdbarch_num_regs (gdbarch
));
1827 std::vector
<packet_reg
> regs (gdbarch_num_regs (gdbarch
));
1829 map_regcache_remote_table (gdbarch
, regs
.data ());
1831 *pnum
= regs
[regnum
].pnum
;
1832 *poffset
= regs
[regnum
].offset
;
1837 remote_arch_state::remote_arch_state (struct gdbarch
*gdbarch
)
1839 /* Use the architecture to build a regnum<->pnum table, which will be
1840 1:1 unless a feature set specifies otherwise. */
1841 this->regs
.reset (new packet_reg
[gdbarch_num_regs (gdbarch
)] ());
1843 /* Record the maximum possible size of the g packet - it may turn out
1845 this->sizeof_g_packet
1846 = map_regcache_remote_table (gdbarch
, this->regs
.get ());
1848 /* Default maximum number of characters in a packet body. Many
1849 remote stubs have a hardwired buffer size of 400 bytes
1850 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1851 as the maximum packet-size to ensure that the packet and an extra
1852 NUL character can always fit in the buffer. This stops GDB
1853 trashing stubs that try to squeeze an extra NUL into what is
1854 already a full buffer (As of 1999-12-04 that was most stubs). */
1855 this->remote_packet_size
= 400 - 1;
1857 /* This one is filled in when a ``g'' packet is received. */
1858 this->actual_register_packet_size
= 0;
1860 /* Should rsa->sizeof_g_packet needs more space than the
1861 default, adjust the size accordingly. Remember that each byte is
1862 encoded as two characters. 32 is the overhead for the packet
1863 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1864 (``$NN:G...#NN'') is a better guess, the below has been padded a
1866 if (this->sizeof_g_packet
> ((this->remote_packet_size
- 32) / 2))
1867 this->remote_packet_size
= (this->sizeof_g_packet
* 2 + 32);
1870 /* Get a pointer to the current remote target. If not connected to a
1871 remote target, return NULL. */
1873 static remote_target
*
1874 get_current_remote_target ()
1876 target_ops
*proc_target
= current_inferior ()->process_target ();
1877 return dynamic_cast<remote_target
*> (proc_target
);
1880 /* Return the current allowed size of a remote packet. This is
1881 inferred from the current architecture, and should be used to
1882 limit the length of outgoing packets. */
1884 remote_target::get_remote_packet_size ()
1886 struct remote_state
*rs
= get_remote_state ();
1887 remote_arch_state
*rsa
1888 = rs
->get_remote_arch_state (current_inferior ()->arch ());
1890 if (rs
->explicit_packet_size
)
1891 return rs
->explicit_packet_size
;
1893 return rsa
->remote_packet_size
;
1896 static struct packet_reg
*
1897 packet_reg_from_regnum (struct gdbarch
*gdbarch
, struct remote_arch_state
*rsa
,
1900 if (regnum
< 0 && regnum
>= gdbarch_num_regs (gdbarch
))
1904 struct packet_reg
*r
= &rsa
->regs
[regnum
];
1906 gdb_assert (r
->regnum
== regnum
);
1911 static struct packet_reg
*
1912 packet_reg_from_pnum (struct gdbarch
*gdbarch
, struct remote_arch_state
*rsa
,
1917 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
1919 struct packet_reg
*r
= &rsa
->regs
[i
];
1921 if (r
->pnum
== pnum
)
1927 /* Allow the user to specify what sequence to send to the remote
1928 when he requests a program interruption: Although ^C is usually
1929 what remote systems expect (this is the default, here), it is
1930 sometimes preferable to send a break. On other systems such
1931 as the Linux kernel, a break followed by g, which is Magic SysRq g
1932 is required in order to interrupt the execution. */
1933 const char interrupt_sequence_control_c
[] = "Ctrl-C";
1934 const char interrupt_sequence_break
[] = "BREAK";
1935 const char interrupt_sequence_break_g
[] = "BREAK-g";
1936 static const char *const interrupt_sequence_modes
[] =
1938 interrupt_sequence_control_c
,
1939 interrupt_sequence_break
,
1940 interrupt_sequence_break_g
,
1943 static const char *interrupt_sequence_mode
= interrupt_sequence_control_c
;
1946 show_interrupt_sequence (struct ui_file
*file
, int from_tty
,
1947 struct cmd_list_element
*c
,
1950 if (interrupt_sequence_mode
== interrupt_sequence_control_c
)
1952 _("Send the ASCII ETX character (Ctrl-c) "
1953 "to the remote target to interrupt the "
1954 "execution of the program.\n"));
1955 else if (interrupt_sequence_mode
== interrupt_sequence_break
)
1957 _("send a break signal to the remote target "
1958 "to interrupt the execution of the program.\n"));
1959 else if (interrupt_sequence_mode
== interrupt_sequence_break_g
)
1961 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1962 "the remote target to interrupt the execution "
1963 "of Linux kernel.\n"));
1965 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1966 interrupt_sequence_mode
);
1969 /* This boolean variable specifies whether interrupt_sequence is sent
1970 to the remote target when gdb connects to it.
1971 This is mostly needed when you debug the Linux kernel: The Linux kernel
1972 expects BREAK g which is Magic SysRq g for connecting gdb. */
1973 static bool interrupt_on_connect
= false;
1975 /* This variable is used to implement the "set/show remotebreak" commands.
1976 Since these commands are now deprecated in favor of "set/show remote
1977 interrupt-sequence", it no longer has any effect on the code. */
1978 static bool remote_break
;
1981 set_remotebreak (const char *args
, int from_tty
, struct cmd_list_element
*c
)
1984 interrupt_sequence_mode
= interrupt_sequence_break
;
1986 interrupt_sequence_mode
= interrupt_sequence_control_c
;
1990 show_remotebreak (struct ui_file
*file
, int from_tty
,
1991 struct cmd_list_element
*c
,
1996 /* This variable sets the number of bits in an address that are to be
1997 sent in a memory ("M" or "m") packet. Normally, after stripping
1998 leading zeros, the entire address would be sent. This variable
1999 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2000 initial implementation of remote.c restricted the address sent in
2001 memory packets to ``host::sizeof long'' bytes - (typically 32
2002 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2003 address was never sent. Since fixing this bug may cause a break in
2004 some remote targets this variable is principally provided to
2005 facilitate backward compatibility. */
2007 static unsigned int remote_address_size
;
2010 /* The default max memory-write-packet-size, when the setting is
2011 "fixed". The 16k is historical. (It came from older GDB's using
2012 alloca for buffers and the knowledge (folklore?) that some hosts
2013 don't cope very well with large alloca calls.) */
2014 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2016 /* The minimum remote packet size for memory transfers. Ensures we
2017 can write at least one byte. */
2018 #define MIN_MEMORY_PACKET_SIZE 20
2020 /* Get the memory packet size, assuming it is fixed. */
2023 get_fixed_memory_packet_size (struct memory_packet_config
*config
)
2025 gdb_assert (config
->fixed_p
);
2027 if (config
->size
<= 0)
2028 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
;
2030 return config
->size
;
2033 /* Compute the current size of a read/write packet. Since this makes
2034 use of ``actual_register_packet_size'' the computation is dynamic. */
2037 remote_target::get_memory_packet_size (struct memory_packet_config
*config
)
2039 struct remote_state
*rs
= get_remote_state ();
2040 remote_arch_state
*rsa
2041 = rs
->get_remote_arch_state (current_inferior ()->arch ());
2044 if (config
->fixed_p
)
2045 what_they_get
= get_fixed_memory_packet_size (config
);
2048 what_they_get
= get_remote_packet_size ();
2049 /* Limit the packet to the size specified by the user. */
2050 if (config
->size
> 0
2051 && what_they_get
> config
->size
)
2052 what_they_get
= config
->size
;
2054 /* Limit it to the size of the targets ``g'' response unless we have
2055 permission from the stub to use a larger packet size. */
2056 if (rs
->explicit_packet_size
== 0
2057 && rsa
->actual_register_packet_size
> 0
2058 && what_they_get
> rsa
->actual_register_packet_size
)
2059 what_they_get
= rsa
->actual_register_packet_size
;
2061 if (what_they_get
< MIN_MEMORY_PACKET_SIZE
)
2062 what_they_get
= MIN_MEMORY_PACKET_SIZE
;
2064 /* Make sure there is room in the global buffer for this packet
2065 (including its trailing NUL byte). */
2066 if (rs
->buf
.size () < what_they_get
+ 1)
2067 rs
->buf
.resize (2 * what_they_get
);
2069 return what_they_get
;
2072 /* Update the size of a read/write packet. If they user wants
2073 something really big then do a sanity check. */
2076 set_memory_packet_size (const char *args
, struct memory_packet_config
*config
,
2077 bool target_connected
)
2079 int fixed_p
= config
->fixed_p
;
2080 long size
= config
->size
;
2083 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2084 else if (strcmp (args
, "hard") == 0
2085 || strcmp (args
, "fixed") == 0)
2087 else if (strcmp (args
, "soft") == 0
2088 || strcmp (args
, "limit") == 0)
2094 size
= strtoul (args
, &end
, 0);
2096 error (_("Invalid %s (bad syntax)."), config
->name
);
2098 /* Instead of explicitly capping the size of a packet to or
2099 disallowing it, the user is allowed to set the size to
2100 something arbitrarily large. */
2104 if (fixed_p
&& !config
->fixed_p
)
2106 /* So that the query shows the correct value. */
2107 long query_size
= (size
<= 0
2108 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2111 if (target_connected
2112 && !query (_("The target may not be able to correctly handle a %s\n"
2113 "of %ld bytes. Change the packet size? "),
2114 config
->name
, query_size
))
2115 error (_("Packet size not changed."));
2116 else if (!target_connected
2117 && !query (_("Future remote targets may not be able to "
2118 "correctly handle a %s\nof %ld bytes. Change the "
2119 "packet size for future remote targets? "),
2120 config
->name
, query_size
))
2121 error (_("Packet size not changed."));
2123 /* Update the config. */
2124 config
->fixed_p
= fixed_p
;
2125 config
->size
= size
;
2127 const char *target_type
= get_target_type_name (target_connected
);
2128 gdb_printf (_("The %s %s is set to \"%s\".\n"), config
->name
, target_type
,
2133 /* Show the memory-read or write-packet size configuration CONFIG of the
2134 target REMOTE. If REMOTE is nullptr, the default configuration for future
2135 remote targets should be passed in CONFIG. */
2138 show_memory_packet_size (memory_packet_config
*config
, remote_target
*remote
)
2140 const char *target_type
= get_target_type_name (remote
!= nullptr);
2142 if (config
->size
== 0)
2143 gdb_printf (_("The %s %s is 0 (default). "), config
->name
, target_type
);
2145 gdb_printf (_("The %s %s is %ld. "), config
->name
, target_type
,
2148 if (config
->fixed_p
)
2149 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2150 get_fixed_memory_packet_size (config
));
2153 if (remote
!= nullptr)
2154 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2155 remote
->get_memory_packet_size (config
));
2157 gdb_puts ("The actual limit will be further reduced "
2158 "dependent on the target.\n");
2162 /* Configure the memory-write-packet size of the currently selected target. If
2163 no target is available, the default configuration for future remote targets
2167 set_memory_write_packet_size (const char *args
, int from_tty
)
2169 remote_target
*remote
= get_current_remote_target ();
2170 if (remote
!= nullptr)
2172 set_memory_packet_size
2173 (args
, &remote
->m_features
.m_memory_write_packet_config
, true);
2177 memory_packet_config
* config
= &memory_write_packet_config
;
2178 set_memory_packet_size (args
, config
, false);
2182 /* Display the memory-write-packet size of the currently selected target. If
2183 no target is available, the default configuration for future remote targets
2187 show_memory_write_packet_size (const char *args
, int from_tty
)
2189 remote_target
*remote
= get_current_remote_target ();
2190 if (remote
!= nullptr)
2191 show_memory_packet_size (&remote
->m_features
.m_memory_write_packet_config
,
2194 show_memory_packet_size (&memory_write_packet_config
, nullptr);
2197 /* Show the number of hardware watchpoints that can be used. */
2200 show_hardware_watchpoint_limit (struct ui_file
*file
, int from_tty
,
2201 struct cmd_list_element
*c
,
2204 gdb_printf (file
, _("The maximum number of target hardware "
2205 "watchpoints is %s.\n"), value
);
2208 /* Show the length limit (in bytes) for hardware watchpoints. */
2211 show_hardware_watchpoint_length_limit (struct ui_file
*file
, int from_tty
,
2212 struct cmd_list_element
*c
,
2215 gdb_printf (file
, _("The maximum length (in bytes) of a target "
2216 "hardware watchpoint is %s.\n"), value
);
2219 /* Show the number of hardware breakpoints that can be used. */
2222 show_hardware_breakpoint_limit (struct ui_file
*file
, int from_tty
,
2223 struct cmd_list_element
*c
,
2226 gdb_printf (file
, _("The maximum number of target hardware "
2227 "breakpoints is %s.\n"), value
);
2230 /* Controls the maximum number of characters to display in the debug output
2231 for each remote packet. The remaining characters are omitted. */
2233 static int remote_packet_max_chars
= 512;
2235 /* Show the maximum number of characters to display for each remote packet
2236 when remote debugging is enabled. */
2239 show_remote_packet_max_chars (struct ui_file
*file
, int from_tty
,
2240 struct cmd_list_element
*c
,
2243 gdb_printf (file
, _("Number of remote packet characters to "
2244 "display is %s.\n"), value
);
2248 remote_target::get_memory_write_packet_size ()
2250 return get_memory_packet_size (&m_features
.m_memory_write_packet_config
);
2253 /* Configure the memory-read-packet size of the currently selected target. If
2254 no target is available, the default configuration for future remote targets
2258 set_memory_read_packet_size (const char *args
, int from_tty
)
2260 remote_target
*remote
= get_current_remote_target ();
2261 if (remote
!= nullptr)
2262 set_memory_packet_size
2263 (args
, &remote
->m_features
.m_memory_read_packet_config
, true);
2266 memory_packet_config
* config
= &memory_read_packet_config
;
2267 set_memory_packet_size (args
, config
, false);
2272 /* Display the memory-read-packet size of the currently selected target. If
2273 no target is available, the default configuration for future remote targets
2277 show_memory_read_packet_size (const char *args
, int from_tty
)
2279 remote_target
*remote
= get_current_remote_target ();
2280 if (remote
!= nullptr)
2281 show_memory_packet_size (&remote
->m_features
.m_memory_read_packet_config
,
2284 show_memory_packet_size (&memory_read_packet_config
, nullptr);
2288 remote_target::get_memory_read_packet_size ()
2290 long size
= get_memory_packet_size (&m_features
.m_memory_read_packet_config
);
2292 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2293 extra buffer size argument before the memory read size can be
2294 increased beyond this. */
2295 if (size
> get_remote_packet_size ())
2296 size
= get_remote_packet_size ();
2300 static enum packet_support
packet_config_support (const packet_config
*config
);
2304 set_remote_protocol_packet_cmd (const char *args
, int from_tty
,
2305 cmd_list_element
*c
)
2307 remote_target
*remote
= get_current_remote_target ();
2308 gdb_assert (c
->var
.has_value ());
2310 auto *default_config
= static_cast<packet_config
*> (c
->context ());
2311 const int packet_idx
= std::distance (remote_protocol_packets
,
2314 if (packet_idx
>= 0 && packet_idx
< PACKET_MAX
)
2316 const char *name
= packets_descriptions
[packet_idx
].name
;
2317 const auto_boolean value
= c
->var
->get
<auto_boolean
> ();
2318 const char *support
= get_packet_support_name (value
);
2319 const char *target_type
= get_target_type_name (remote
!= nullptr);
2321 if (remote
!= nullptr)
2322 remote
->m_features
.m_protocol_packets
[packet_idx
].detect
= value
;
2324 remote_protocol_packets
[packet_idx
].detect
= value
;
2326 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name
,
2327 target_type
, support
);
2331 internal_error (_("Could not find config for %s"), c
->name
);
2335 show_packet_config_cmd (ui_file
*file
, const unsigned int which_packet
,
2336 remote_target
*remote
)
2338 const char *support
= "internal-error";
2339 const char *target_type
= get_target_type_name (remote
!= nullptr);
2341 packet_config
*config
;
2342 if (remote
!= nullptr)
2343 config
= &remote
->m_features
.m_protocol_packets
[which_packet
];
2345 config
= &remote_protocol_packets
[which_packet
];
2347 switch (packet_config_support (config
))
2350 support
= "enabled";
2352 case PACKET_DISABLE
:
2353 support
= "disabled";
2355 case PACKET_SUPPORT_UNKNOWN
:
2356 support
= "unknown";
2359 switch (config
->detect
)
2361 case AUTO_BOOLEAN_AUTO
:
2363 _("Support for the '%s' packet %s is \"auto\", "
2365 packets_descriptions
[which_packet
].name
, target_type
,
2368 case AUTO_BOOLEAN_TRUE
:
2369 case AUTO_BOOLEAN_FALSE
:
2371 _("Support for the '%s' packet %s is \"%s\".\n"),
2372 packets_descriptions
[which_packet
].name
, target_type
,
2373 get_packet_support_name (config
->detect
));
2379 add_packet_config_cmd (const unsigned int which_packet
, const char *name
,
2380 const char *title
, int legacy
)
2382 packets_descriptions
[which_packet
].name
= name
;
2383 packets_descriptions
[which_packet
].title
= title
;
2385 packet_config
*config
= &remote_protocol_packets
[which_packet
];
2387 gdb::unique_xmalloc_ptr
<char> set_doc
2388 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2390 gdb::unique_xmalloc_ptr
<char> show_doc
2391 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2393 /* set/show TITLE-packet {auto,on,off} */
2394 gdb::unique_xmalloc_ptr
<char> cmd_name
= xstrprintf ("%s-packet", title
);
2395 set_show_commands cmds
2396 = add_setshow_auto_boolean_cmd (cmd_name
.release (), class_obscure
,
2397 &config
->detect
, set_doc
.get (),
2398 show_doc
.get (), NULL
, /* help_doc */
2399 set_remote_protocol_packet_cmd
,
2400 show_remote_protocol_packet_cmd
,
2401 &remote_set_cmdlist
, &remote_show_cmdlist
);
2402 cmds
.show
->set_context (config
);
2403 cmds
.set
->set_context (config
);
2405 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2408 /* It's not clear who should take ownership of the LEGACY_NAME string
2409 created below, so, for now, place the string into a static vector
2410 which ensures the strings is released when GDB exits. */
2411 static std::vector
<gdb::unique_xmalloc_ptr
<char>> legacy_names
;
2412 gdb::unique_xmalloc_ptr
<char> legacy_name
2413 = xstrprintf ("%s-packet", name
);
2414 add_alias_cmd (legacy_name
.get (), cmds
.set
, class_obscure
, 0,
2415 &remote_set_cmdlist
);
2416 add_alias_cmd (legacy_name
.get (), cmds
.show
, class_obscure
, 0,
2417 &remote_show_cmdlist
);
2418 legacy_names
.emplace_back (std::move (legacy_name
));
2422 static enum packet_result
2423 packet_check_result (const char *buf
)
2427 /* The stub recognized the packet request. Check that the
2428 operation succeeded. */
2430 && isxdigit (buf
[1]) && isxdigit (buf
[2])
2432 /* "Enn" - definitely an error. */
2433 return PACKET_ERROR
;
2435 /* Always treat "E." as an error. This will be used for
2436 more verbose error messages, such as E.memtypes. */
2437 if (buf
[0] == 'E' && buf
[1] == '.')
2438 return PACKET_ERROR
;
2440 /* The packet may or may not be OK. Just assume it is. */
2444 /* The stub does not support the packet. */
2445 return PACKET_UNKNOWN
;
2448 static enum packet_result
2449 packet_check_result (const gdb::char_vector
&buf
)
2451 return packet_check_result (buf
.data ());
2455 remote_features::packet_ok (const char *buf
, const int which_packet
)
2457 packet_config
*config
= &m_protocol_packets
[which_packet
];
2458 packet_description
*descr
= &packets_descriptions
[which_packet
];
2460 enum packet_result result
;
2462 if (config
->detect
!= AUTO_BOOLEAN_TRUE
2463 && config
->support
== PACKET_DISABLE
)
2464 internal_error (_("packet_ok: attempt to use a disabled packet"));
2466 result
= packet_check_result (buf
);
2471 /* The stub recognized the packet request. */
2472 if (config
->support
== PACKET_SUPPORT_UNKNOWN
)
2474 remote_debug_printf ("Packet %s (%s) is supported",
2475 descr
->name
, descr
->title
);
2476 config
->support
= PACKET_ENABLE
;
2479 case PACKET_UNKNOWN
:
2480 /* The stub does not support the packet. */
2481 if (config
->detect
== AUTO_BOOLEAN_AUTO
2482 && config
->support
== PACKET_ENABLE
)
2484 /* If the stub previously indicated that the packet was
2485 supported then there is a protocol error. */
2486 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2487 descr
->name
, descr
->title
);
2489 else if (config
->detect
== AUTO_BOOLEAN_TRUE
)
2491 /* The user set it wrong. */
2492 error (_("Enabled packet %s (%s) not recognized by stub"),
2493 descr
->name
, descr
->title
);
2496 remote_debug_printf ("Packet %s (%s) is NOT supported", descr
->name
,
2498 config
->support
= PACKET_DISABLE
;
2506 remote_features::packet_ok (const gdb::char_vector
&buf
, const int which_packet
)
2508 return packet_ok (buf
.data (), which_packet
);
2511 /* Returns whether a given packet or feature is supported. This takes
2512 into account the state of the corresponding "set remote foo-packet"
2513 command, which may be used to bypass auto-detection. */
2515 static enum packet_support
2516 packet_config_support (const packet_config
*config
)
2518 switch (config
->detect
)
2520 case AUTO_BOOLEAN_TRUE
:
2521 return PACKET_ENABLE
;
2522 case AUTO_BOOLEAN_FALSE
:
2523 return PACKET_DISABLE
;
2524 case AUTO_BOOLEAN_AUTO
:
2525 return config
->support
;
2527 gdb_assert_not_reached ("bad switch");
2532 remote_features::packet_support (int packet
) const
2534 const packet_config
*config
= &m_protocol_packets
[packet
];
2535 return packet_config_support (config
);
2539 show_remote_protocol_packet_cmd (struct ui_file
*file
, int from_tty
,
2540 struct cmd_list_element
*c
,
2543 remote_target
*remote
= get_current_remote_target ();
2544 gdb_assert (c
->var
.has_value ());
2546 auto *default_config
= static_cast<packet_config
*> (c
->context ());
2547 const int packet_idx
= std::distance (remote_protocol_packets
,
2550 if (packet_idx
>= 0 && packet_idx
< PACKET_MAX
)
2552 show_packet_config_cmd (file
, packet_idx
, remote
);
2555 internal_error (_("Could not find config for %s"), c
->name
);
2558 /* Should we try one of the 'Z' requests? */
2562 Z_PACKET_SOFTWARE_BP
,
2563 Z_PACKET_HARDWARE_BP
,
2570 /* For compatibility with older distributions. Provide a ``set remote
2571 Z-packet ...'' command that updates all the Z packet types. */
2573 static enum auto_boolean remote_Z_packet_detect
;
2576 set_remote_protocol_Z_packet_cmd (const char *args
, int from_tty
,
2577 struct cmd_list_element
*c
)
2579 remote_target
*remote
= get_current_remote_target ();
2582 for (i
= 0; i
< NR_Z_PACKET_TYPES
; i
++)
2584 if (remote
!= nullptr)
2585 remote
->m_features
.m_protocol_packets
[PACKET_Z0
+ i
].detect
2586 = remote_Z_packet_detect
;
2588 remote_protocol_packets
[PACKET_Z0
+ i
].detect
= remote_Z_packet_detect
;
2591 const char *support
= get_packet_support_name (remote_Z_packet_detect
);
2592 const char *target_type
= get_target_type_name (remote
!= nullptr);
2593 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type
,
2599 show_remote_protocol_Z_packet_cmd (struct ui_file
*file
, int from_tty
,
2600 struct cmd_list_element
*c
,
2603 remote_target
*remote
= get_current_remote_target ();
2606 for (i
= 0; i
< NR_Z_PACKET_TYPES
; i
++)
2607 show_packet_config_cmd (file
, PACKET_Z0
+ i
, remote
);
2610 /* Insert fork catchpoint target routine. If fork events are enabled
2611 then return success, nothing more to do. */
2614 remote_target::insert_fork_catchpoint (int pid
)
2616 return !m_features
.remote_fork_event_p ();
2619 /* Remove fork catchpoint target routine. Nothing to do, just
2623 remote_target::remove_fork_catchpoint (int pid
)
2628 /* Insert vfork catchpoint target routine. If vfork events are enabled
2629 then return success, nothing more to do. */
2632 remote_target::insert_vfork_catchpoint (int pid
)
2634 return !m_features
.remote_vfork_event_p ();
2637 /* Remove vfork catchpoint target routine. Nothing to do, just
2641 remote_target::remove_vfork_catchpoint (int pid
)
2646 /* Insert exec catchpoint target routine. If exec events are
2647 enabled, just return success. */
2650 remote_target::insert_exec_catchpoint (int pid
)
2652 return !m_features
.remote_exec_event_p ();
2655 /* Remove exec catchpoint target routine. Nothing to do, just
2659 remote_target::remove_exec_catchpoint (int pid
)
2666 /* Take advantage of the fact that the TID field is not used, to tag
2667 special ptids with it set to != 0. */
2668 static const ptid_t
magic_null_ptid (42000, -1, 1);
2669 static const ptid_t
not_sent_ptid (42000, -2, 1);
2670 static const ptid_t
any_thread_ptid (42000, 0, 1);
2672 /* Find out if the stub attached to PID (and hence GDB should offer to
2673 detach instead of killing it when bailing out). */
2676 remote_target::remote_query_attached (int pid
)
2678 struct remote_state
*rs
= get_remote_state ();
2679 size_t size
= get_remote_packet_size ();
2681 if (m_features
.packet_support (PACKET_qAttached
) == PACKET_DISABLE
)
2684 if (m_features
.remote_multi_process_p ())
2685 xsnprintf (rs
->buf
.data (), size
, "qAttached:%x", pid
);
2687 xsnprintf (rs
->buf
.data (), size
, "qAttached");
2692 switch (m_features
.packet_ok (rs
->buf
, PACKET_qAttached
))
2695 if (strcmp (rs
->buf
.data (), "1") == 0)
2699 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
2701 case PACKET_UNKNOWN
:
2708 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2709 has been invented by GDB, instead of reported by the target. Since
2710 we can be connected to a remote system before before knowing about
2711 any inferior, mark the target with execution when we find the first
2712 inferior. If ATTACHED is 1, then we had just attached to this
2713 inferior. If it is 0, then we just created this inferior. If it
2714 is -1, then try querying the remote stub to find out if it had
2715 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2716 attempt to open this inferior's executable as the main executable
2717 if no main executable is open already. */
2720 remote_target::remote_add_inferior (bool fake_pid_p
, int pid
, int attached
,
2723 struct inferior
*inf
;
2725 /* Check whether this process we're learning about is to be
2726 considered attached, or if is to be considered to have been
2727 spawned by the stub. */
2729 attached
= remote_query_attached (pid
);
2731 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2733 /* If the target shares code across all inferiors, then every
2734 attach adds a new inferior. */
2735 inf
= add_inferior (pid
);
2737 /* ... and every inferior is bound to the same program space.
2738 However, each inferior may still have its own address
2740 inf
->aspace
= maybe_new_address_space ();
2741 inf
->pspace
= current_program_space
;
2745 /* In the traditional debugging scenario, there's a 1-1 match
2746 between program/address spaces. We simply bind the inferior
2747 to the program space's address space. */
2748 inf
= current_inferior ();
2750 /* However, if the current inferior is already bound to a
2751 process, find some other empty inferior. */
2755 for (inferior
*it
: all_inferiors ())
2764 /* Since all inferiors were already bound to a process, add
2766 inf
= add_inferior_with_spaces ();
2768 switch_to_inferior_no_thread (inf
);
2769 inf
->push_target (this);
2770 inferior_appeared (inf
, pid
);
2773 inf
->attach_flag
= attached
;
2774 inf
->fake_pid_p
= fake_pid_p
;
2776 /* If no main executable is currently open then attempt to
2777 open the file that was executed to create this inferior. */
2778 if (try_open_exec
&& get_exec_file (0) == NULL
)
2779 exec_file_locate_attach (pid
, 0, 1);
2781 /* Check for exec file mismatch, and let the user solve it. */
2782 validate_exec_file (1);
2787 static remote_thread_info
*get_remote_thread_info (thread_info
*thread
);
2788 static remote_thread_info
*get_remote_thread_info (remote_target
*target
,
2791 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2792 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2793 remote_state::starting_up flag) is true then the new thread is added
2794 silently, otherwise the new thread will be announced to the user. */
2797 remote_target::remote_add_thread (ptid_t ptid
, bool running
, bool executing
,
2800 struct remote_state
*rs
= get_remote_state ();
2801 struct thread_info
*thread
;
2803 /* GDB historically didn't pull threads in the initial connection
2804 setup. If the remote target doesn't even have a concept of
2805 threads (e.g., a bare-metal target), even if internally we
2806 consider that a single-threaded target, mentioning a new thread
2807 might be confusing to the user. Be silent then, preserving the
2808 age old behavior. */
2809 if (rs
->starting_up
|| silent_p
)
2810 thread
= add_thread_silent (this, ptid
);
2812 thread
= add_thread (this, ptid
);
2815 get_remote_thread_info (thread
)->set_resumed ();
2816 set_executing (this, ptid
, executing
);
2817 set_running (this, ptid
, running
);
2822 /* Come here when we learn about a thread id from the remote target.
2823 It may be the first time we hear about such thread, so take the
2824 opportunity to add it to GDB's thread list. In case this is the
2825 first time we're noticing its corresponding inferior, add it to
2826 GDB's inferior list as well. EXECUTING indicates whether the
2827 thread is (internally) executing or stopped. */
2830 remote_target::remote_notice_new_inferior (ptid_t currthread
, bool executing
)
2832 /* In non-stop mode, we assume new found threads are (externally)
2833 running until proven otherwise with a stop reply. In all-stop,
2834 we can only get here if all threads are stopped. */
2835 bool running
= target_is_non_stop_p ();
2837 /* If this is a new thread, add it to GDB's thread list.
2838 If we leave it up to WFI to do this, bad things will happen. */
2840 thread_info
*tp
= this->find_thread (currthread
);
2841 if (tp
!= NULL
&& tp
->state
== THREAD_EXITED
)
2843 /* We're seeing an event on a thread id we knew had exited.
2844 This has to be a new thread reusing the old id. Add it. */
2845 remote_add_thread (currthread
, running
, executing
, false);
2849 if (!in_thread_list (this, currthread
))
2851 struct inferior
*inf
= NULL
;
2852 int pid
= currthread
.pid ();
2854 if (inferior_ptid
.is_pid ()
2855 && pid
== inferior_ptid
.pid ())
2857 /* inferior_ptid has no thread member yet. This can happen
2858 with the vAttach -> remote_wait,"TAAthread:" path if the
2859 stub doesn't support qC. This is the first stop reported
2860 after an attach, so this is the main thread. Update the
2861 ptid in the thread list. */
2862 if (in_thread_list (this, ptid_t (pid
)))
2863 thread_change_ptid (this, inferior_ptid
, currthread
);
2867 = remote_add_thread (currthread
, running
, executing
, false);
2868 switch_to_thread (thr
);
2873 if (magic_null_ptid
== inferior_ptid
)
2875 /* inferior_ptid is not set yet. This can happen with the
2876 vRun -> remote_wait,"TAAthread:" path if the stub
2877 doesn't support qC. This is the first stop reported
2878 after an attach, so this is the main thread. Update the
2879 ptid in the thread list. */
2880 thread_change_ptid (this, inferior_ptid
, currthread
);
2884 /* When connecting to a target remote, or to a target
2885 extended-remote which already was debugging an inferior, we
2886 may not know about it yet. Add it before adding its child
2887 thread, so notifications are emitted in a sensible order. */
2888 if (find_inferior_pid (this, currthread
.pid ()) == NULL
)
2890 bool fake_pid_p
= !m_features
.remote_multi_process_p ();
2892 inf
= remote_add_inferior (fake_pid_p
,
2893 currthread
.pid (), -1, 1);
2896 /* This is really a new thread. Add it. */
2897 thread_info
*new_thr
2898 = remote_add_thread (currthread
, running
, executing
, false);
2900 /* If we found a new inferior, let the common code do whatever
2901 it needs to with it (e.g., read shared libraries, insert
2902 breakpoints), unless we're just setting up an all-stop
2906 struct remote_state
*rs
= get_remote_state ();
2908 if (!rs
->starting_up
)
2909 notice_new_inferior (new_thr
, executing
, 0);
2914 /* Return THREAD's private thread data, creating it if necessary. */
2916 static remote_thread_info
*
2917 get_remote_thread_info (thread_info
*thread
)
2919 gdb_assert (thread
!= NULL
);
2921 if (thread
->priv
== NULL
)
2922 thread
->priv
.reset (new remote_thread_info
);
2924 return gdb::checked_static_cast
<remote_thread_info
*> (thread
->priv
.get ());
2927 /* Return PTID's private thread data, creating it if necessary. */
2929 static remote_thread_info
*
2930 get_remote_thread_info (remote_target
*target
, ptid_t ptid
)
2932 thread_info
*thr
= target
->find_thread (ptid
);
2933 return get_remote_thread_info (thr
);
2936 /* Call this function as a result of
2937 1) A halt indication (T packet) containing a thread id
2938 2) A direct query of currthread
2939 3) Successful execution of set thread */
2942 record_currthread (struct remote_state
*rs
, ptid_t currthread
)
2944 rs
->general_thread
= currthread
;
2947 /* If 'QPassSignals' is supported, tell the remote stub what signals
2948 it can simply pass through to the inferior without reporting. */
2951 remote_target::pass_signals (gdb::array_view
<const unsigned char> pass_signals
)
2953 if (m_features
.packet_support (PACKET_QPassSignals
) != PACKET_DISABLE
)
2955 char *pass_packet
, *p
;
2957 struct remote_state
*rs
= get_remote_state ();
2959 gdb_assert (pass_signals
.size () < 256);
2960 for (size_t i
= 0; i
< pass_signals
.size (); i
++)
2962 if (pass_signals
[i
])
2965 pass_packet
= (char *) xmalloc (count
* 3 + strlen ("QPassSignals:") + 1);
2966 strcpy (pass_packet
, "QPassSignals:");
2967 p
= pass_packet
+ strlen (pass_packet
);
2968 for (size_t i
= 0; i
< pass_signals
.size (); i
++)
2970 if (pass_signals
[i
])
2973 *p
++ = tohex (i
>> 4);
2974 *p
++ = tohex (i
& 15);
2983 if (!rs
->last_pass_packet
|| strcmp (rs
->last_pass_packet
, pass_packet
))
2985 putpkt (pass_packet
);
2987 m_features
.packet_ok (rs
->buf
, PACKET_QPassSignals
);
2988 xfree (rs
->last_pass_packet
);
2989 rs
->last_pass_packet
= pass_packet
;
2992 xfree (pass_packet
);
2996 /* If 'QCatchSyscalls' is supported, tell the remote stub
2997 to report syscalls to GDB. */
3000 remote_target::set_syscall_catchpoint (int pid
, bool needed
, int any_count
,
3001 gdb::array_view
<const int> syscall_counts
)
3003 const char *catch_packet
;
3004 enum packet_result result
;
3007 if (m_features
.packet_support (PACKET_QCatchSyscalls
) == PACKET_DISABLE
)
3009 /* Not supported. */
3013 if (needed
&& any_count
== 0)
3015 /* Count how many syscalls are to be caught. */
3016 for (size_t i
= 0; i
< syscall_counts
.size (); i
++)
3018 if (syscall_counts
[i
] != 0)
3023 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3024 pid
, needed
, any_count
, n_sysno
);
3026 std::string built_packet
;
3029 /* Prepare a packet with the sysno list, assuming max 8+1
3030 characters for a sysno. If the resulting packet size is too
3031 big, fallback on the non-selective packet. */
3032 const int maxpktsz
= strlen ("QCatchSyscalls:1") + n_sysno
* 9 + 1;
3033 built_packet
.reserve (maxpktsz
);
3034 built_packet
= "QCatchSyscalls:1";
3037 /* Add in each syscall to be caught. */
3038 for (size_t i
= 0; i
< syscall_counts
.size (); i
++)
3040 if (syscall_counts
[i
] != 0)
3041 string_appendf (built_packet
, ";%zx", i
);
3044 if (built_packet
.size () > get_remote_packet_size ())
3046 /* catch_packet too big. Fallback to less efficient
3047 non selective mode, with GDB doing the filtering. */
3048 catch_packet
= "QCatchSyscalls:1";
3051 catch_packet
= built_packet
.c_str ();
3054 catch_packet
= "QCatchSyscalls:0";
3056 struct remote_state
*rs
= get_remote_state ();
3058 putpkt (catch_packet
);
3060 result
= m_features
.packet_ok (rs
->buf
, PACKET_QCatchSyscalls
);
3061 if (result
== PACKET_OK
)
3067 /* If 'QProgramSignals' is supported, tell the remote stub what
3068 signals it should pass through to the inferior when detaching. */
3071 remote_target::program_signals (gdb::array_view
<const unsigned char> signals
)
3073 if (m_features
.packet_support (PACKET_QProgramSignals
) != PACKET_DISABLE
)
3077 struct remote_state
*rs
= get_remote_state ();
3079 gdb_assert (signals
.size () < 256);
3080 for (size_t i
= 0; i
< signals
.size (); i
++)
3085 packet
= (char *) xmalloc (count
* 3 + strlen ("QProgramSignals:") + 1);
3086 strcpy (packet
, "QProgramSignals:");
3087 p
= packet
+ strlen (packet
);
3088 for (size_t i
= 0; i
< signals
.size (); i
++)
3090 if (signal_pass_state (i
))
3093 *p
++ = tohex (i
>> 4);
3094 *p
++ = tohex (i
& 15);
3103 if (!rs
->last_program_signals_packet
3104 || strcmp (rs
->last_program_signals_packet
, packet
) != 0)
3108 m_features
.packet_ok (rs
->buf
, PACKET_QProgramSignals
);
3109 xfree (rs
->last_program_signals_packet
);
3110 rs
->last_program_signals_packet
= packet
;
3117 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3118 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3119 thread. If GEN is set, set the general thread, if not, then set
3120 the step/continue thread. */
3122 remote_target::set_thread (ptid_t ptid
, int gen
)
3124 struct remote_state
*rs
= get_remote_state ();
3125 ptid_t state
= gen
? rs
->general_thread
: rs
->continue_thread
;
3126 char *buf
= rs
->buf
.data ();
3127 char *endbuf
= buf
+ get_remote_packet_size ();
3133 *buf
++ = gen
? 'g' : 'c';
3134 if (ptid
== magic_null_ptid
)
3135 xsnprintf (buf
, endbuf
- buf
, "0");
3136 else if (ptid
== any_thread_ptid
)
3137 xsnprintf (buf
, endbuf
- buf
, "0");
3138 else if (ptid
== minus_one_ptid
)
3139 xsnprintf (buf
, endbuf
- buf
, "-1");
3141 write_ptid (buf
, endbuf
, ptid
);
3145 rs
->general_thread
= ptid
;
3147 rs
->continue_thread
= ptid
;
3151 remote_target::set_general_thread (ptid_t ptid
)
3153 set_thread (ptid
, 1);
3157 remote_target::set_continue_thread (ptid_t ptid
)
3159 set_thread (ptid
, 0);
3162 /* Change the remote current process. Which thread within the process
3163 ends up selected isn't important, as long as it is the same process
3164 as what INFERIOR_PTID points to.
3166 This comes from that fact that there is no explicit notion of
3167 "selected process" in the protocol. The selected process for
3168 general operations is the process the selected general thread
3172 remote_target::set_general_process ()
3174 /* If the remote can't handle multiple processes, don't bother. */
3175 if (!m_features
.remote_multi_process_p ())
3178 remote_state
*rs
= get_remote_state ();
3180 /* We only need to change the remote current thread if it's pointing
3181 at some other process. */
3182 if (rs
->general_thread
.pid () != inferior_ptid
.pid ())
3183 set_general_thread (inferior_ptid
);
3187 /* Return nonzero if this is the main thread that we made up ourselves
3188 to model non-threaded targets as single-threaded. */
3191 remote_thread_always_alive (ptid_t ptid
)
3193 if (ptid
== magic_null_ptid
)
3194 /* The main thread is always alive. */
3197 if (ptid
.pid () != 0 && ptid
.lwp () == 0)
3198 /* The main thread is always alive. This can happen after a
3199 vAttach, if the remote side doesn't support
3206 /* Return nonzero if the thread PTID is still alive on the remote
3210 remote_target::thread_alive (ptid_t ptid
)
3212 struct remote_state
*rs
= get_remote_state ();
3215 /* Check if this is a thread that we made up ourselves to model
3216 non-threaded targets as single-threaded. */
3217 if (remote_thread_always_alive (ptid
))
3220 p
= rs
->buf
.data ();
3221 endp
= p
+ get_remote_packet_size ();
3224 write_ptid (p
, endp
, ptid
);
3228 return (rs
->buf
[0] == 'O' && rs
->buf
[1] == 'K');
3231 /* Return a pointer to a thread name if we know it and NULL otherwise.
3232 The thread_info object owns the memory for the name. */
3235 remote_target::thread_name (struct thread_info
*info
)
3237 if (info
->priv
!= NULL
)
3239 const std::string
&name
= get_remote_thread_info (info
)->name
;
3240 return !name
.empty () ? name
.c_str () : NULL
;
3246 /* About these extended threadlist and threadinfo packets. They are
3247 variable length packets but, the fields within them are often fixed
3248 length. They are redundant enough to send over UDP as is the
3249 remote protocol in general. There is a matching unit test module
3252 /* WARNING: This threadref data structure comes from the remote O.S.,
3253 libstub protocol encoding, and remote.c. It is not particularly
3256 /* Right now, the internal structure is int. We want it to be bigger.
3257 Plan to fix this. */
3259 typedef int gdb_threadref
; /* Internal GDB thread reference. */
3261 /* gdb_ext_thread_info is an internal GDB data structure which is
3262 equivalent to the reply of the remote threadinfo packet. */
3264 struct gdb_ext_thread_info
3266 threadref threadid
; /* External form of thread reference. */
3267 int active
; /* Has state interesting to GDB?
3269 char display
[256]; /* Brief state display, name,
3270 blocked/suspended. */
3271 char shortname
[32]; /* To be used to name threads. */
3272 char more_display
[256]; /* Long info, statistics, queue depth,
3276 /* The volume of remote transfers can be limited by submitting
3277 a mask containing bits specifying the desired information.
3278 Use a union of these values as the 'selection' parameter to
3279 get_thread_info. FIXME: Make these TAG names more thread specific. */
3281 #define TAG_THREADID 1
3282 #define TAG_EXISTS 2
3283 #define TAG_DISPLAY 4
3284 #define TAG_THREADNAME 8
3285 #define TAG_MOREDISPLAY 16
3287 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3289 static const char *unpack_nibble (const char *buf
, int *val
);
3291 static const char *unpack_byte (const char *buf
, int *value
);
3293 static char *pack_int (char *buf
, int value
);
3295 static const char *unpack_int (const char *buf
, int *value
);
3297 static const char *unpack_string (const char *src
, char *dest
, int length
);
3299 static char *pack_threadid (char *pkt
, threadref
*id
);
3301 static const char *unpack_threadid (const char *inbuf
, threadref
*id
);
3303 void int_to_threadref (threadref
*id
, int value
);
3305 static int threadref_to_int (threadref
*ref
);
3307 static void copy_threadref (threadref
*dest
, threadref
*src
);
3309 static int threadmatch (threadref
*dest
, threadref
*src
);
3311 static char *pack_threadinfo_request (char *pkt
, int mode
,
3314 static char *pack_threadlist_request (char *pkt
, int startflag
,
3316 threadref
*nextthread
);
3318 static int remote_newthread_step (threadref
*ref
, void *context
);
3321 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3322 buffer we're allowed to write to. Returns
3323 BUF+CHARACTERS_WRITTEN. */
3326 remote_target::write_ptid (char *buf
, const char *endbuf
, ptid_t ptid
)
3330 if (m_features
.remote_multi_process_p ())
3334 buf
+= xsnprintf (buf
, endbuf
- buf
, "p-%x.", -pid
);
3336 buf
+= xsnprintf (buf
, endbuf
- buf
, "p%x.", pid
);
3340 buf
+= xsnprintf (buf
, endbuf
- buf
, "-%x", -tid
);
3342 buf
+= xsnprintf (buf
, endbuf
- buf
, "%x", tid
);
3347 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3348 last parsed char. Returns null_ptid if no thread id is found, and
3349 throws an error if the thread id has an invalid format. */
3352 read_ptid (const char *buf
, const char **obuf
)
3354 const char *p
= buf
;
3356 ULONGEST pid
= 0, tid
= 0;
3360 /* Multi-process ptid. */
3361 pp
= unpack_varlen_hex (p
+ 1, &pid
);
3363 error (_("invalid remote ptid: %s"), p
);
3366 pp
= unpack_varlen_hex (p
+ 1, &tid
);
3369 return ptid_t (pid
, tid
);
3372 /* No multi-process. Just a tid. */
3373 pp
= unpack_varlen_hex (p
, &tid
);
3375 /* Return null_ptid when no thread id is found. */
3383 /* Since the stub is not sending a process id, default to what's
3384 current_inferior, unless it doesn't have a PID yet. If so,
3385 then since there's no way to know the pid of the reported
3386 threads, use the magic number. */
3387 inferior
*inf
= current_inferior ();
3389 pid
= magic_null_ptid
.pid ();
3395 return ptid_t (pid
, tid
);
3401 if (ch
>= 'a' && ch
<= 'f')
3402 return ch
- 'a' + 10;
3403 if (ch
>= '0' && ch
<= '9')
3405 if (ch
>= 'A' && ch
<= 'F')
3406 return ch
- 'A' + 10;
3411 stub_unpack_int (const char *buff
, int fieldlength
)
3418 nibble
= stubhex (*buff
++);
3422 retval
= retval
<< 4;
3428 unpack_nibble (const char *buf
, int *val
)
3430 *val
= fromhex (*buf
++);
3435 unpack_byte (const char *buf
, int *value
)
3437 *value
= stub_unpack_int (buf
, 2);
3442 pack_int (char *buf
, int value
)
3444 buf
= pack_hex_byte (buf
, (value
>> 24) & 0xff);
3445 buf
= pack_hex_byte (buf
, (value
>> 16) & 0xff);
3446 buf
= pack_hex_byte (buf
, (value
>> 8) & 0x0ff);
3447 buf
= pack_hex_byte (buf
, (value
& 0xff));
3452 unpack_int (const char *buf
, int *value
)
3454 *value
= stub_unpack_int (buf
, 8);
3458 #if 0 /* Currently unused, uncomment when needed. */
3459 static char *pack_string (char *pkt
, char *string
);
3462 pack_string (char *pkt
, char *string
)
3467 len
= strlen (string
);
3469 len
= 200; /* Bigger than most GDB packets, junk??? */
3470 pkt
= pack_hex_byte (pkt
, len
);
3474 if ((ch
== '\0') || (ch
== '#'))
3475 ch
= '*'; /* Protect encapsulation. */
3480 #endif /* 0 (unused) */
3483 unpack_string (const char *src
, char *dest
, int length
)
3492 pack_threadid (char *pkt
, threadref
*id
)
3495 unsigned char *altid
;
3497 altid
= (unsigned char *) id
;
3498 limit
= pkt
+ BUF_THREAD_ID_SIZE
;
3500 pkt
= pack_hex_byte (pkt
, *altid
++);
3506 unpack_threadid (const char *inbuf
, threadref
*id
)
3509 const char *limit
= inbuf
+ BUF_THREAD_ID_SIZE
;
3512 altref
= (char *) id
;
3514 while (inbuf
< limit
)
3516 x
= stubhex (*inbuf
++);
3517 y
= stubhex (*inbuf
++);
3518 *altref
++ = (x
<< 4) | y
;
3523 /* Externally, threadrefs are 64 bits but internally, they are still
3524 ints. This is due to a mismatch of specifications. We would like
3525 to use 64bit thread references internally. This is an adapter
3529 int_to_threadref (threadref
*id
, int value
)
3531 unsigned char *scan
;
3533 scan
= (unsigned char *) id
;
3539 *scan
++ = (value
>> 24) & 0xff;
3540 *scan
++ = (value
>> 16) & 0xff;
3541 *scan
++ = (value
>> 8) & 0xff;
3542 *scan
++ = (value
& 0xff);
3546 threadref_to_int (threadref
*ref
)
3549 unsigned char *scan
;
3555 value
= (value
<< 8) | ((*scan
++) & 0xff);
3560 copy_threadref (threadref
*dest
, threadref
*src
)
3563 unsigned char *csrc
, *cdest
;
3565 csrc
= (unsigned char *) src
;
3566 cdest
= (unsigned char *) dest
;
3573 threadmatch (threadref
*dest
, threadref
*src
)
3575 /* Things are broken right now, so just assume we got a match. */
3577 unsigned char *srcp
, *destp
;
3579 srcp
= (char *) src
;
3580 destp
= (char *) dest
;
3584 result
&= (*srcp
++ == *destp
++) ? 1 : 0;
3591 threadid:1, # always request threadid
3598 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3601 pack_threadinfo_request (char *pkt
, int mode
, threadref
*id
)
3603 *pkt
++ = 'q'; /* Info Query */
3604 *pkt
++ = 'P'; /* process or thread info */
3605 pkt
= pack_int (pkt
, mode
); /* mode */
3606 pkt
= pack_threadid (pkt
, id
); /* threadid */
3607 *pkt
= '\0'; /* terminate */
3611 /* These values tag the fields in a thread info response packet. */
3612 /* Tagging the fields allows us to request specific fields and to
3613 add more fields as time goes by. */
3615 #define TAG_THREADID 1 /* Echo the thread identifier. */
3616 #define TAG_EXISTS 2 /* Is this process defined enough to
3617 fetch registers and its stack? */
3618 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3619 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3620 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3624 remote_target::remote_unpack_thread_info_response (const char *pkt
,
3625 threadref
*expectedref
,
3626 gdb_ext_thread_info
*info
)
3628 struct remote_state
*rs
= get_remote_state ();
3632 const char *limit
= pkt
+ rs
->buf
.size (); /* Plausible parsing limit. */
3635 /* info->threadid = 0; FIXME: implement zero_threadref. */
3637 info
->display
[0] = '\0';
3638 info
->shortname
[0] = '\0';
3639 info
->more_display
[0] = '\0';
3641 /* Assume the characters indicating the packet type have been
3643 pkt
= unpack_int (pkt
, &mask
); /* arg mask */
3644 pkt
= unpack_threadid (pkt
, &ref
);
3647 warning (_("Incomplete response to threadinfo request."));
3648 if (!threadmatch (&ref
, expectedref
))
3649 { /* This is an answer to a different request. */
3650 warning (_("ERROR RMT Thread info mismatch."));
3653 copy_threadref (&info
->threadid
, &ref
);
3655 /* Loop on tagged fields , try to bail if something goes wrong. */
3657 /* Packets are terminated with nulls. */
3658 while ((pkt
< limit
) && mask
&& *pkt
)
3660 pkt
= unpack_int (pkt
, &tag
); /* tag */
3661 pkt
= unpack_byte (pkt
, &length
); /* length */
3662 if (!(tag
& mask
)) /* Tags out of synch with mask. */
3664 warning (_("ERROR RMT: threadinfo tag mismatch."));
3668 if (tag
== TAG_THREADID
)
3672 warning (_("ERROR RMT: length of threadid is not 16."));
3676 pkt
= unpack_threadid (pkt
, &ref
);
3677 mask
= mask
& ~TAG_THREADID
;
3680 if (tag
== TAG_EXISTS
)
3682 info
->active
= stub_unpack_int (pkt
, length
);
3684 mask
= mask
& ~(TAG_EXISTS
);
3687 warning (_("ERROR RMT: 'exists' length too long."));
3693 if (tag
== TAG_THREADNAME
)
3695 pkt
= unpack_string (pkt
, &info
->shortname
[0], length
);
3696 mask
= mask
& ~TAG_THREADNAME
;
3699 if (tag
== TAG_DISPLAY
)
3701 pkt
= unpack_string (pkt
, &info
->display
[0], length
);
3702 mask
= mask
& ~TAG_DISPLAY
;
3705 if (tag
== TAG_MOREDISPLAY
)
3707 pkt
= unpack_string (pkt
, &info
->more_display
[0], length
);
3708 mask
= mask
& ~TAG_MOREDISPLAY
;
3711 warning (_("ERROR RMT: unknown thread info tag."));
3712 break; /* Not a tag we know about. */
3718 remote_target::remote_get_threadinfo (threadref
*threadid
,
3720 gdb_ext_thread_info
*info
)
3722 struct remote_state
*rs
= get_remote_state ();
3725 pack_threadinfo_request (rs
->buf
.data (), fieldset
, threadid
);
3729 if (rs
->buf
[0] == '\0')
3732 result
= remote_unpack_thread_info_response (&rs
->buf
[2],
3737 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3740 pack_threadlist_request (char *pkt
, int startflag
, int threadcount
,
3741 threadref
*nextthread
)
3743 *pkt
++ = 'q'; /* info query packet */
3744 *pkt
++ = 'L'; /* Process LIST or threadLIST request */
3745 pkt
= pack_nibble (pkt
, startflag
); /* initflag 1 bytes */
3746 pkt
= pack_hex_byte (pkt
, threadcount
); /* threadcount 2 bytes */
3747 pkt
= pack_threadid (pkt
, nextthread
); /* 64 bit thread identifier */
3752 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3755 remote_target::parse_threadlist_response (const char *pkt
, int result_limit
,
3756 threadref
*original_echo
,
3757 threadref
*resultlist
,
3760 struct remote_state
*rs
= get_remote_state ();
3761 int count
, resultcount
, done
;
3764 /* Assume the 'q' and 'M chars have been stripped. */
3765 const char *limit
= pkt
+ (rs
->buf
.size () - BUF_THREAD_ID_SIZE
);
3766 /* done parse past here */
3767 pkt
= unpack_byte (pkt
, &count
); /* count field */
3768 pkt
= unpack_nibble (pkt
, &done
);
3769 /* The first threadid is the argument threadid. */
3770 pkt
= unpack_threadid (pkt
, original_echo
); /* should match query packet */
3771 while ((count
-- > 0) && (pkt
< limit
))
3773 pkt
= unpack_threadid (pkt
, resultlist
++);
3774 if (resultcount
++ >= result_limit
)
3782 /* Fetch the next batch of threads from the remote. Returns -1 if the
3783 qL packet is not supported, 0 on error and 1 on success. */
3786 remote_target::remote_get_threadlist (int startflag
, threadref
*nextthread
,
3787 int result_limit
, int *done
, int *result_count
,
3788 threadref
*threadlist
)
3790 struct remote_state
*rs
= get_remote_state ();
3793 /* Truncate result limit to be smaller than the packet size. */
3794 if ((((result_limit
+ 1) * BUF_THREAD_ID_SIZE
) + 10)
3795 >= get_remote_packet_size ())
3796 result_limit
= (get_remote_packet_size () / BUF_THREAD_ID_SIZE
) - 2;
3798 pack_threadlist_request (rs
->buf
.data (), startflag
, result_limit
,
3802 if (rs
->buf
[0] == '\0')
3804 /* Packet not supported. */
3809 parse_threadlist_response (&rs
->buf
[2], result_limit
,
3810 &rs
->echo_nextthread
, threadlist
, done
);
3812 if (!threadmatch (&rs
->echo_nextthread
, nextthread
))
3814 /* FIXME: This is a good reason to drop the packet. */
3815 /* Possibly, there is a duplicate response. */
3817 retransmit immediatly - race conditions
3818 retransmit after timeout - yes
3820 wait for packet, then exit
3822 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3823 return 0; /* I choose simply exiting. */
3825 if (*result_count
<= 0)
3829 warning (_("RMT ERROR : failed to get remote thread list."));
3832 return result
; /* break; */
3834 if (*result_count
> result_limit
)
3837 warning (_("RMT ERROR: threadlist response longer than requested."));
3843 /* Fetch the list of remote threads, with the qL packet, and call
3844 STEPFUNCTION for each thread found. Stops iterating and returns 1
3845 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3846 STEPFUNCTION returns false. If the packet is not supported,
3850 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction
,
3851 void *context
, int looplimit
)
3853 struct remote_state
*rs
= get_remote_state ();
3854 int done
, i
, result_count
;
3862 if (loopcount
++ > looplimit
)
3865 warning (_("Remote fetch threadlist -infinite loop-."));
3868 result
= remote_get_threadlist (startflag
, &rs
->nextthread
,
3869 MAXTHREADLISTRESULTS
,
3870 &done
, &result_count
,
3871 rs
->resultthreadlist
);
3874 /* Clear for later iterations. */
3876 /* Setup to resume next batch of thread references, set nextthread. */
3877 if (result_count
>= 1)
3878 copy_threadref (&rs
->nextthread
,
3879 &rs
->resultthreadlist
[result_count
- 1]);
3881 while (result_count
--)
3883 if (!(*stepfunction
) (&rs
->resultthreadlist
[i
++], context
))
3893 /* A thread found on the remote target. */
3897 explicit thread_item (ptid_t ptid_
)
3901 thread_item (thread_item
&&other
) = default;
3902 thread_item
&operator= (thread_item
&&other
) = default;
3904 DISABLE_COPY_AND_ASSIGN (thread_item
);
3906 /* The thread's PTID. */
3909 /* The thread's extra info. */
3912 /* The thread's name. */
3915 /* The core the thread was running on. -1 if not known. */
3918 /* The thread handle associated with the thread. */
3919 gdb::byte_vector thread_handle
;
3922 /* Context passed around to the various methods listing remote
3923 threads. As new threads are found, they're added to the ITEMS
3926 struct threads_listing_context
3928 /* Return true if this object contains an entry for a thread with ptid
3931 bool contains_thread (ptid_t ptid
) const
3933 auto match_ptid
= [&] (const thread_item
&item
)
3935 return item
.ptid
== ptid
;
3938 auto it
= std::find_if (this->items
.begin (),
3942 return it
!= this->items
.end ();
3945 /* Remove the thread with ptid PTID. */
3947 void remove_thread (ptid_t ptid
)
3949 auto match_ptid
= [&] (const thread_item
&item
)
3951 return item
.ptid
== ptid
;
3954 auto it
= std::remove_if (this->items
.begin (),
3958 if (it
!= this->items
.end ())
3959 this->items
.erase (it
);
3962 /* The threads found on the remote target. */
3963 std::vector
<thread_item
> items
;
3967 remote_newthread_step (threadref
*ref
, void *data
)
3969 struct threads_listing_context
*context
3970 = (struct threads_listing_context
*) data
;
3971 int pid
= inferior_ptid
.pid ();
3972 int lwp
= threadref_to_int (ref
);
3973 ptid_t
ptid (pid
, lwp
);
3975 context
->items
.emplace_back (ptid
);
3977 return 1; /* continue iterator */
3980 #define CRAZY_MAX_THREADS 1000
3983 remote_target::remote_current_thread (ptid_t oldpid
)
3985 struct remote_state
*rs
= get_remote_state ();
3989 if (rs
->buf
[0] == 'Q' && rs
->buf
[1] == 'C')
3994 result
= read_ptid (&rs
->buf
[2], &obuf
);
3996 remote_debug_printf ("warning: garbage in qC reply");
4004 /* List remote threads using the deprecated qL packet. */
4007 remote_target::remote_get_threads_with_ql (threads_listing_context
*context
)
4009 if (remote_threadlist_iterator (remote_newthread_step
, context
,
4010 CRAZY_MAX_THREADS
) >= 0)
4016 #if defined(HAVE_LIBEXPAT)
4019 start_thread (struct gdb_xml_parser
*parser
,
4020 const struct gdb_xml_element
*element
,
4022 std::vector
<gdb_xml_value
> &attributes
)
4024 struct threads_listing_context
*data
4025 = (struct threads_listing_context
*) user_data
;
4026 struct gdb_xml_value
*attr
;
4028 char *id
= (char *) xml_find_attribute (attributes
, "id")->value
.get ();
4029 ptid_t ptid
= read_ptid (id
, NULL
);
4031 data
->items
.emplace_back (ptid
);
4032 thread_item
&item
= data
->items
.back ();
4034 attr
= xml_find_attribute (attributes
, "core");
4036 item
.core
= *(ULONGEST
*) attr
->value
.get ();
4038 attr
= xml_find_attribute (attributes
, "name");
4040 item
.name
= (const char *) attr
->value
.get ();
4042 attr
= xml_find_attribute (attributes
, "handle");
4044 item
.thread_handle
= hex2bin ((const char *) attr
->value
.get ());
4048 end_thread (struct gdb_xml_parser
*parser
,
4049 const struct gdb_xml_element
*element
,
4050 void *user_data
, const char *body_text
)
4052 struct threads_listing_context
*data
4053 = (struct threads_listing_context
*) user_data
;
4055 if (body_text
!= NULL
&& *body_text
!= '\0')
4056 data
->items
.back ().extra
= body_text
;
4059 const struct gdb_xml_attribute thread_attributes
[] = {
4060 { "id", GDB_XML_AF_NONE
, NULL
, NULL
},
4061 { "core", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
4062 { "name", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4063 { "handle", GDB_XML_AF_OPTIONAL
, NULL
, NULL
},
4064 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
4067 const struct gdb_xml_element thread_children
[] = {
4068 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4071 const struct gdb_xml_element threads_children
[] = {
4072 { "thread", thread_attributes
, thread_children
,
4073 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
,
4074 start_thread
, end_thread
},
4075 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4078 const struct gdb_xml_element threads_elements
[] = {
4079 { "threads", NULL
, threads_children
,
4080 GDB_XML_EF_NONE
, NULL
, NULL
},
4081 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
4086 /* List remote threads using qXfer:threads:read. */
4089 remote_target::remote_get_threads_with_qxfer (threads_listing_context
*context
)
4091 #if defined(HAVE_LIBEXPAT)
4092 if (m_features
.packet_support (PACKET_qXfer_threads
) == PACKET_ENABLE
)
4094 gdb::optional
<gdb::char_vector
> xml
4095 = target_read_stralloc (this, TARGET_OBJECT_THREADS
, NULL
);
4097 if (xml
&& (*xml
)[0] != '\0')
4099 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4100 threads_elements
, xml
->data (), context
);
4110 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4113 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context
*context
)
4115 struct remote_state
*rs
= get_remote_state ();
4117 if (rs
->use_threadinfo_query
)
4121 putpkt ("qfThreadInfo");
4123 bufp
= rs
->buf
.data ();
4124 if (bufp
[0] != '\0') /* q packet recognized */
4126 while (*bufp
++ == 'm') /* reply contains one or more TID */
4130 ptid_t ptid
= read_ptid (bufp
, &bufp
);
4131 context
->items
.emplace_back (ptid
);
4133 while (*bufp
++ == ','); /* comma-separated list */
4134 putpkt ("qsThreadInfo");
4136 bufp
= rs
->buf
.data ();
4142 /* Packet not recognized. */
4143 rs
->use_threadinfo_query
= 0;
4150 /* Return true if INF only has one non-exited thread. */
4153 has_single_non_exited_thread (inferior
*inf
)
4156 for (thread_info
*tp ATTRIBUTE_UNUSED
: inf
->non_exited_threads ())
4162 /* Implement the to_update_thread_list function for the remote
4166 remote_target::update_thread_list ()
4168 struct threads_listing_context context
;
4171 /* We have a few different mechanisms to fetch the thread list. Try
4172 them all, starting with the most preferred one first, falling
4173 back to older methods. */
4174 if (remote_get_threads_with_qxfer (&context
)
4175 || remote_get_threads_with_qthreadinfo (&context
)
4176 || remote_get_threads_with_ql (&context
))
4180 if (context
.items
.empty ()
4181 && remote_thread_always_alive (inferior_ptid
))
4183 /* Some targets don't really support threads, but still
4184 reply an (empty) thread list in response to the thread
4185 listing packets, instead of replying "packet not
4186 supported". Exit early so we don't delete the main
4191 /* CONTEXT now holds the current thread list on the remote
4192 target end. Delete GDB-side threads no longer found on the
4194 for (thread_info
*tp
: all_threads_safe ())
4196 if (tp
->inf
->process_target () != this)
4199 if (!context
.contains_thread (tp
->ptid
))
4201 /* Do not remove the thread if it is the last thread in
4202 the inferior. This situation happens when we have a
4203 pending exit process status to process. Otherwise we
4204 may end up with a seemingly live inferior (i.e. pid
4205 != 0) that has no threads. */
4206 if (has_single_non_exited_thread (tp
->inf
))
4214 /* Remove any unreported fork/vfork/clone child threads from
4215 CONTEXT so that we don't interfere with follow
4216 fork/vfork/clone, which is where creation of such threads is
4218 remove_new_children (&context
);
4220 /* And now add threads we don't know about yet to our list. */
4221 for (thread_item
&item
: context
.items
)
4223 if (item
.ptid
!= null_ptid
)
4225 /* In non-stop mode, we assume new found threads are
4226 executing until proven otherwise with a stop reply.
4227 In all-stop, we can only get here if all threads are
4229 bool executing
= target_is_non_stop_p ();
4231 remote_notice_new_inferior (item
.ptid
, executing
);
4233 thread_info
*tp
= this->find_thread (item
.ptid
);
4234 remote_thread_info
*info
= get_remote_thread_info (tp
);
4235 info
->core
= item
.core
;
4236 info
->extra
= std::move (item
.extra
);
4237 info
->name
= std::move (item
.name
);
4238 info
->thread_handle
= std::move (item
.thread_handle
);
4245 /* If no thread listing method is supported, then query whether
4246 each known thread is alive, one by one, with the T packet.
4247 If the target doesn't support threads at all, then this is a
4248 no-op. See remote_thread_alive. */
4254 * Collect a descriptive string about the given thread.
4255 * The target may say anything it wants to about the thread
4256 * (typically info about its blocked / runnable state, name, etc.).
4257 * This string will appear in the info threads display.
4259 * Optional: targets are not required to implement this function.
4263 remote_target::extra_thread_info (thread_info
*tp
)
4265 struct remote_state
*rs
= get_remote_state ();
4268 struct gdb_ext_thread_info threadinfo
;
4270 if (rs
->remote_desc
== 0) /* paranoia */
4271 internal_error (_("remote_threads_extra_info"));
4273 if (tp
->ptid
== magic_null_ptid
4274 || (tp
->ptid
.pid () != 0 && tp
->ptid
.lwp () == 0))
4275 /* This is the main thread which was added by GDB. The remote
4276 server doesn't know about it. */
4279 std::string
&extra
= get_remote_thread_info (tp
)->extra
;
4281 /* If already have cached info, use it. */
4282 if (!extra
.empty ())
4283 return extra
.c_str ();
4285 if (m_features
.packet_support (PACKET_qXfer_threads
) == PACKET_ENABLE
)
4287 /* If we're using qXfer:threads:read, then the extra info is
4288 included in the XML. So if we didn't have anything cached,
4289 it's because there's really no extra info. */
4293 if (rs
->use_threadextra_query
)
4295 char *b
= rs
->buf
.data ();
4296 char *endb
= b
+ get_remote_packet_size ();
4298 xsnprintf (b
, endb
- b
, "qThreadExtraInfo,");
4300 write_ptid (b
, endb
, tp
->ptid
);
4304 if (rs
->buf
[0] != 0)
4306 extra
.resize (strlen (rs
->buf
.data ()) / 2);
4307 hex2bin (rs
->buf
.data (), (gdb_byte
*) &extra
[0], extra
.size ());
4308 return extra
.c_str ();
4312 /* If the above query fails, fall back to the old method. */
4313 rs
->use_threadextra_query
= 0;
4314 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
4315 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
4316 int_to_threadref (&id
, tp
->ptid
.lwp ());
4317 if (remote_get_threadinfo (&id
, set
, &threadinfo
))
4318 if (threadinfo
.active
)
4320 if (*threadinfo
.shortname
)
4321 string_appendf (extra
, " Name: %s", threadinfo
.shortname
);
4322 if (*threadinfo
.display
)
4324 if (!extra
.empty ())
4326 string_appendf (extra
, " State: %s", threadinfo
.display
);
4328 if (*threadinfo
.more_display
)
4330 if (!extra
.empty ())
4332 string_appendf (extra
, " Priority: %s", threadinfo
.more_display
);
4334 return extra
.c_str ();
4341 remote_target::static_tracepoint_marker_at (CORE_ADDR addr
,
4342 struct static_tracepoint_marker
*marker
)
4344 struct remote_state
*rs
= get_remote_state ();
4345 char *p
= rs
->buf
.data ();
4347 xsnprintf (p
, get_remote_packet_size (), "qTSTMat:");
4349 p
+= hexnumstr (p
, addr
);
4352 p
= rs
->buf
.data ();
4355 error (_("Remote failure reply: %s"), p
);
4359 parse_static_tracepoint_marker_definition (p
, NULL
, marker
);
4366 std::vector
<static_tracepoint_marker
>
4367 remote_target::static_tracepoint_markers_by_strid (const char *strid
)
4369 struct remote_state
*rs
= get_remote_state ();
4370 std::vector
<static_tracepoint_marker
> markers
;
4372 static_tracepoint_marker marker
;
4374 /* Ask for a first packet of static tracepoint marker
4378 p
= rs
->buf
.data ();
4380 error (_("Remote failure reply: %s"), p
);
4386 parse_static_tracepoint_marker_definition (p
, &p
, &marker
);
4388 if (strid
== NULL
|| marker
.str_id
== strid
)
4389 markers
.push_back (std::move (marker
));
4391 while (*p
++ == ','); /* comma-separated list */
4392 /* Ask for another packet of static tracepoint definition. */
4395 p
= rs
->buf
.data ();
4402 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4405 remote_target::get_ada_task_ptid (long lwp
, ULONGEST thread
)
4407 return ptid_t (inferior_ptid
.pid (), lwp
);
4411 /* Restart the remote side; this is an extended protocol operation. */
4414 remote_target::extended_remote_restart ()
4416 struct remote_state
*rs
= get_remote_state ();
4418 /* Send the restart command; for reasons I don't understand the
4419 remote side really expects a number after the "R". */
4420 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "R%x", 0);
4423 remote_fileio_reset ();
4426 /* Clean up connection to a remote debugger. */
4429 remote_target::close ()
4431 /* Make sure we leave stdin registered in the event loop. */
4434 trace_reset_local_state ();
4439 remote_target::~remote_target ()
4441 struct remote_state
*rs
= get_remote_state ();
4443 /* Check for NULL because we may get here with a partially
4444 constructed target/connection. */
4445 if (rs
->remote_desc
== nullptr)
4448 serial_close (rs
->remote_desc
);
4450 /* We are destroying the remote target, so we should discard
4451 everything of this target. */
4452 discard_pending_stop_replies_in_queue ();
4454 rs
->delete_async_event_handler ();
4456 delete rs
->notif_state
;
4459 /* Query the remote side for the text, data and bss offsets. */
4462 remote_target::get_offsets ()
4464 struct remote_state
*rs
= get_remote_state ();
4467 int lose
, num_segments
= 0, do_sections
, do_segments
;
4468 CORE_ADDR text_addr
, data_addr
, bss_addr
, segments
[2];
4470 if (current_program_space
->symfile_object_file
== NULL
)
4473 putpkt ("qOffsets");
4475 buf
= rs
->buf
.data ();
4477 if (buf
[0] == '\000')
4478 return; /* Return silently. Stub doesn't support
4482 warning (_("Remote failure reply: %s"), buf
);
4486 /* Pick up each field in turn. This used to be done with scanf, but
4487 scanf will make trouble if CORE_ADDR size doesn't match
4488 conversion directives correctly. The following code will work
4489 with any size of CORE_ADDR. */
4490 text_addr
= data_addr
= bss_addr
= 0;
4494 if (startswith (ptr
, "Text="))
4497 /* Don't use strtol, could lose on big values. */
4498 while (*ptr
&& *ptr
!= ';')
4499 text_addr
= (text_addr
<< 4) + fromhex (*ptr
++);
4501 if (startswith (ptr
, ";Data="))
4504 while (*ptr
&& *ptr
!= ';')
4505 data_addr
= (data_addr
<< 4) + fromhex (*ptr
++);
4510 if (!lose
&& startswith (ptr
, ";Bss="))
4513 while (*ptr
&& *ptr
!= ';')
4514 bss_addr
= (bss_addr
<< 4) + fromhex (*ptr
++);
4516 if (bss_addr
!= data_addr
)
4517 warning (_("Target reported unsupported offsets: %s"), buf
);
4522 else if (startswith (ptr
, "TextSeg="))
4525 /* Don't use strtol, could lose on big values. */
4526 while (*ptr
&& *ptr
!= ';')
4527 text_addr
= (text_addr
<< 4) + fromhex (*ptr
++);
4530 if (startswith (ptr
, ";DataSeg="))
4533 while (*ptr
&& *ptr
!= ';')
4534 data_addr
= (data_addr
<< 4) + fromhex (*ptr
++);
4542 error (_("Malformed response to offset query, %s"), buf
);
4543 else if (*ptr
!= '\0')
4544 warning (_("Target reported unsupported offsets: %s"), buf
);
4546 objfile
*objf
= current_program_space
->symfile_object_file
;
4547 section_offsets offs
= objf
->section_offsets
;
4549 symfile_segment_data_up data
= get_symfile_segment_data (objf
->obfd
.get ());
4550 do_segments
= (data
!= NULL
);
4551 do_sections
= num_segments
== 0;
4553 if (num_segments
> 0)
4555 segments
[0] = text_addr
;
4556 segments
[1] = data_addr
;
4558 /* If we have two segments, we can still try to relocate everything
4559 by assuming that the .text and .data offsets apply to the whole
4560 text and data segments. Convert the offsets given in the packet
4561 to base addresses for symfile_map_offsets_to_segments. */
4562 else if (data
!= nullptr && data
->segments
.size () == 2)
4564 segments
[0] = data
->segments
[0].base
+ text_addr
;
4565 segments
[1] = data
->segments
[1].base
+ data_addr
;
4568 /* If the object file has only one segment, assume that it is text
4569 rather than data; main programs with no writable data are rare,
4570 but programs with no code are useless. Of course the code might
4571 have ended up in the data segment... to detect that we would need
4572 the permissions here. */
4573 else if (data
&& data
->segments
.size () == 1)
4575 segments
[0] = data
->segments
[0].base
+ text_addr
;
4578 /* There's no way to relocate by segment. */
4584 int ret
= symfile_map_offsets_to_segments (objf
->obfd
.get (),
4586 num_segments
, segments
);
4588 if (ret
== 0 && !do_sections
)
4589 error (_("Can not handle qOffsets TextSeg "
4590 "response with this symbol file"));
4598 offs
[SECT_OFF_TEXT (objf
)] = text_addr
;
4600 /* This is a temporary kludge to force data and bss to use the
4601 same offsets because that's what nlmconv does now. The real
4602 solution requires changes to the stub and remote.c that I
4603 don't have time to do right now. */
4605 offs
[SECT_OFF_DATA (objf
)] = data_addr
;
4606 offs
[SECT_OFF_BSS (objf
)] = data_addr
;
4609 objfile_relocate (objf
, offs
);
4612 /* Send interrupt_sequence to remote target. */
4615 remote_target::send_interrupt_sequence ()
4617 struct remote_state
*rs
= get_remote_state ();
4619 if (interrupt_sequence_mode
== interrupt_sequence_control_c
)
4620 remote_serial_write ("\x03", 1);
4621 else if (interrupt_sequence_mode
== interrupt_sequence_break
)
4622 serial_send_break (rs
->remote_desc
);
4623 else if (interrupt_sequence_mode
== interrupt_sequence_break_g
)
4625 serial_send_break (rs
->remote_desc
);
4626 remote_serial_write ("g", 1);
4629 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4630 interrupt_sequence_mode
);
4634 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4635 and extract the PTID. Returns NULL_PTID if not found. */
4638 stop_reply_extract_thread (const char *stop_reply
)
4640 if (stop_reply
[0] == 'T' && strlen (stop_reply
) > 3)
4644 /* Txx r:val ; r:val (...) */
4647 /* Look for "register" named "thread". */
4652 p1
= strchr (p
, ':');
4656 if (strncmp (p
, "thread", p1
- p
) == 0)
4657 return read_ptid (++p1
, &p
);
4659 p1
= strchr (p
, ';');
4671 /* Determine the remote side's current thread. If we have a stop
4672 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4673 "thread" register we can extract the current thread from. If not,
4674 ask the remote which is the current thread with qC. The former
4675 method avoids a roundtrip. */
4678 remote_target::get_current_thread (const char *wait_status
)
4680 ptid_t ptid
= null_ptid
;
4682 /* Note we don't use remote_parse_stop_reply as that makes use of
4683 the target architecture, which we haven't yet fully determined at
4685 if (wait_status
!= NULL
)
4686 ptid
= stop_reply_extract_thread (wait_status
);
4687 if (ptid
== null_ptid
)
4688 ptid
= remote_current_thread (inferior_ptid
);
4693 /* Query the remote target for which is the current thread/process,
4694 add it to our tables, and update INFERIOR_PTID. The caller is
4695 responsible for setting the state such that the remote end is ready
4696 to return the current thread.
4698 This function is called after handling the '?' or 'vRun' packets,
4699 whose response is a stop reply from which we can also try
4700 extracting the thread. If the target doesn't support the explicit
4701 qC query, we infer the current thread from that stop reply, passed
4702 in in WAIT_STATUS, which may be NULL.
4704 The function returns pointer to the main thread of the inferior. */
4707 remote_target::add_current_inferior_and_thread (const char *wait_status
)
4709 bool fake_pid_p
= false;
4711 switch_to_no_thread ();
4713 /* Now, if we have thread information, update the current thread's
4715 ptid_t curr_ptid
= get_current_thread (wait_status
);
4717 if (curr_ptid
!= null_ptid
)
4719 if (!m_features
.remote_multi_process_p ())
4724 /* Without this, some commands which require an active target
4725 (such as kill) won't work. This variable serves (at least)
4726 double duty as both the pid of the target process (if it has
4727 such), and as a flag indicating that a target is active. */
4728 curr_ptid
= magic_null_ptid
;
4732 remote_add_inferior (fake_pid_p
, curr_ptid
.pid (), -1, 1);
4734 /* Add the main thread and switch to it. Don't try reading
4735 registers yet, since we haven't fetched the target description
4737 thread_info
*tp
= add_thread_silent (this, curr_ptid
);
4738 switch_to_thread_no_regs (tp
);
4743 /* Print info about a thread that was found already stopped on
4747 remote_target::print_one_stopped_thread (thread_info
*thread
)
4749 target_waitstatus ws
;
4751 /* If there is a pending waitstatus, use it. If there isn't it's because
4752 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4753 and process_initial_stop_replies decided it wasn't interesting to save
4754 and report to the core. */
4755 if (thread
->has_pending_waitstatus ())
4757 ws
= thread
->pending_waitstatus ();
4758 thread
->clear_pending_waitstatus ();
4762 ws
.set_stopped (GDB_SIGNAL_0
);
4765 switch_to_thread (thread
);
4766 thread
->set_stop_pc (get_frame_pc (get_current_frame ()));
4767 set_current_sal_from_frame (get_current_frame ());
4769 /* For "info program". */
4770 set_last_target_status (this, thread
->ptid
, ws
);
4772 if (ws
.kind () == TARGET_WAITKIND_STOPPED
)
4774 enum gdb_signal sig
= ws
.sig ();
4776 if (signal_print_state (sig
))
4777 notify_signal_received (sig
);
4780 notify_normal_stop (nullptr, 1);
4783 /* Process all initial stop replies the remote side sent in response
4784 to the ? packet. These indicate threads that were already stopped
4785 on initial connection. We mark these threads as stopped and print
4786 their current frame before giving the user the prompt. */
4789 remote_target::process_initial_stop_replies (int from_tty
)
4791 int pending_stop_replies
= stop_reply_queue_length ();
4792 struct thread_info
*selected
= NULL
;
4793 struct thread_info
*lowest_stopped
= NULL
;
4794 struct thread_info
*first
= NULL
;
4796 /* This is only used when the target is non-stop. */
4797 gdb_assert (target_is_non_stop_p ());
4799 /* Consume the initial pending events. */
4800 while (pending_stop_replies
-- > 0)
4802 ptid_t waiton_ptid
= minus_one_ptid
;
4804 struct target_waitstatus ws
;
4805 int ignore_event
= 0;
4807 event_ptid
= target_wait (waiton_ptid
, &ws
, TARGET_WNOHANG
);
4809 print_target_wait_results (waiton_ptid
, event_ptid
, ws
);
4813 case TARGET_WAITKIND_IGNORE
:
4814 case TARGET_WAITKIND_NO_RESUMED
:
4815 case TARGET_WAITKIND_SIGNALLED
:
4816 case TARGET_WAITKIND_EXITED
:
4817 /* We shouldn't see these, but if we do, just ignore. */
4818 remote_debug_printf ("event ignored");
4829 thread_info
*evthread
= this->find_thread (event_ptid
);
4831 if (ws
.kind () == TARGET_WAITKIND_STOPPED
)
4833 enum gdb_signal sig
= ws
.sig ();
4835 /* Stubs traditionally report SIGTRAP as initial signal,
4836 instead of signal 0. Suppress it. */
4837 if (sig
== GDB_SIGNAL_TRAP
)
4839 evthread
->set_stop_signal (sig
);
4840 ws
.set_stopped (sig
);
4843 if (ws
.kind () != TARGET_WAITKIND_STOPPED
4844 || ws
.sig () != GDB_SIGNAL_0
)
4845 evthread
->set_pending_waitstatus (ws
);
4847 set_executing (this, event_ptid
, false);
4848 set_running (this, event_ptid
, false);
4849 get_remote_thread_info (evthread
)->set_not_resumed ();
4852 /* "Notice" the new inferiors before anything related to
4853 registers/memory. */
4854 for (inferior
*inf
: all_non_exited_inferiors (this))
4856 inf
->needs_setup
= true;
4860 thread_info
*thread
= any_live_thread_of_inferior (inf
);
4861 notice_new_inferior (thread
, thread
->state
== THREAD_RUNNING
,
4866 /* If all-stop on top of non-stop, pause all threads. Note this
4867 records the threads' stop pc, so must be done after "noticing"
4872 /* At this point, the remote target is not async. It needs to be for
4873 the poll in stop_all_threads to consider events from it, so enable
4875 gdb_assert (!this->is_async_p ());
4876 SCOPE_EXIT
{ target_async (false); };
4877 target_async (true);
4878 stop_all_threads ("remote connect in all-stop");
4881 /* If all threads of an inferior were already stopped, we
4882 haven't setup the inferior yet. */
4883 for (inferior
*inf
: all_non_exited_inferiors (this))
4885 if (inf
->needs_setup
)
4887 thread_info
*thread
= any_live_thread_of_inferior (inf
);
4888 switch_to_thread_no_regs (thread
);
4894 /* Now go over all threads that are stopped, and print their current
4895 frame. If all-stop, then if there's a signalled thread, pick
4897 for (thread_info
*thread
: all_non_exited_threads (this))
4903 thread
->set_running (false);
4904 else if (thread
->state
!= THREAD_STOPPED
)
4907 if (selected
== nullptr && thread
->has_pending_waitstatus ())
4910 if (lowest_stopped
== NULL
4911 || thread
->inf
->num
< lowest_stopped
->inf
->num
4912 || thread
->per_inf_num
< lowest_stopped
->per_inf_num
)
4913 lowest_stopped
= thread
;
4916 print_one_stopped_thread (thread
);
4919 /* In all-stop, we only print the status of one thread, and leave
4920 others with their status pending. */
4923 thread_info
*thread
= selected
;
4925 thread
= lowest_stopped
;
4929 print_one_stopped_thread (thread
);
4933 /* Mark a remote_target as starting (by setting the starting_up flag within
4934 its remote_state) for the lifetime of this object. The reference count
4935 on the remote target is temporarily incremented, to prevent the target
4936 being deleted under our feet. */
4938 struct scoped_mark_target_starting
4940 /* Constructor, TARGET is the target to be marked as starting, its
4941 reference count will be incremented. */
4942 scoped_mark_target_starting (remote_target
*target
)
4943 : m_remote_target (remote_target_ref::new_reference (target
)),
4944 m_restore_starting_up (set_starting_up_flag (target
))
4949 /* Helper function, set the starting_up flag on TARGET and return an
4950 object which, when it goes out of scope, will restore the previous
4951 value of the starting_up flag. */
4952 static scoped_restore_tmpl
<bool>
4953 set_starting_up_flag (remote_target
*target
)
4955 remote_state
*rs
= target
->get_remote_state ();
4956 gdb_assert (!rs
->starting_up
);
4957 return make_scoped_restore (&rs
->starting_up
, true);
4960 /* A gdb::ref_ptr pointer to a remote_target. */
4961 using remote_target_ref
= gdb::ref_ptr
<remote_target
, target_ops_ref_policy
>;
4963 /* A reference to the target on which we are operating. */
4964 remote_target_ref m_remote_target
;
4966 /* An object which restores the previous value of the starting_up flag
4967 when it goes out of scope. */
4968 scoped_restore_tmpl
<bool> m_restore_starting_up
;
4971 /* Helper for remote_target::start_remote, start the remote connection and
4972 sync state. Return true if everything goes OK, otherwise, return false.
4973 This function exists so that the scoped_restore created within it will
4974 expire before we return to remote_target::start_remote. */
4977 remote_target::start_remote_1 (int from_tty
, int extended_p
)
4979 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
4981 struct remote_state
*rs
= get_remote_state ();
4983 /* Signal other parts that we're going through the initial setup,
4984 and so things may not be stable yet. E.g., we don't try to
4985 install tracepoints until we've relocated symbols. Also, a
4986 Ctrl-C before we're connected and synced up can't interrupt the
4987 target. Instead, it offers to drop the (potentially wedged)
4989 scoped_mark_target_starting
target_is_starting (this);
4993 if (interrupt_on_connect
)
4994 send_interrupt_sequence ();
4996 /* Ack any packet which the remote side has already sent. */
4997 remote_serial_write ("+", 1);
4999 /* The first packet we send to the target is the optional "supported
5000 packets" request. If the target can answer this, it will tell us
5001 which later probes to skip. */
5002 remote_query_supported ();
5004 /* Check vCont support and set the remote state's vCont_action_support
5006 remote_vcont_probe ();
5008 /* If the stub wants to get a QAllow, compose one and send it. */
5009 if (m_features
.packet_support (PACKET_QAllow
) != PACKET_DISABLE
)
5012 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5013 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5014 as a reply to known packet. For packet "vFile:setfs:" it is an
5015 invalid reply and GDB would return error in
5016 remote_hostio_set_filesystem, making remote files access impossible.
5017 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5018 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5020 const char v_mustreplyempty
[] = "vMustReplyEmpty";
5022 putpkt (v_mustreplyempty
);
5024 if (strcmp (rs
->buf
.data (), "OK") == 0)
5026 m_features
.m_protocol_packets
[PACKET_vFile_setfs
].support
5029 else if (strcmp (rs
->buf
.data (), "") != 0)
5030 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty
,
5034 /* Next, we possibly activate noack mode.
5036 If the QStartNoAckMode packet configuration is set to AUTO,
5037 enable noack mode if the stub reported a wish for it with
5040 If set to TRUE, then enable noack mode even if the stub didn't
5041 report it in qSupported. If the stub doesn't reply OK, the
5042 session ends with an error.
5044 If FALSE, then don't activate noack mode, regardless of what the
5045 stub claimed should be the default with qSupported. */
5047 if (m_features
.packet_support (PACKET_QStartNoAckMode
) != PACKET_DISABLE
)
5049 putpkt ("QStartNoAckMode");
5051 if (m_features
.packet_ok (rs
->buf
, PACKET_QStartNoAckMode
) == PACKET_OK
)
5057 /* Tell the remote that we are using the extended protocol. */
5062 /* Let the target know which signals it is allowed to pass down to
5064 update_signals_program_target ();
5066 /* Next, if the target can specify a description, read it. We do
5067 this before anything involving memory or registers. */
5068 target_find_description ();
5070 /* Next, now that we know something about the target, update the
5071 address spaces in the program spaces. */
5072 update_address_spaces ();
5074 /* On OSs where the list of libraries is global to all
5075 processes, we fetch them early. */
5076 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5077 solib_add (NULL
, from_tty
, auto_solib_add
);
5079 if (target_is_non_stop_p ())
5081 if (m_features
.packet_support (PACKET_QNonStop
) != PACKET_ENABLE
)
5082 error (_("Non-stop mode requested, but remote "
5083 "does not support non-stop"));
5085 putpkt ("QNonStop:1");
5088 if (strcmp (rs
->buf
.data (), "OK") != 0)
5089 error (_("Remote refused setting non-stop mode with: %s"),
5092 /* Find about threads and processes the stub is already
5093 controlling. We default to adding them in the running state.
5094 The '?' query below will then tell us about which threads are
5096 this->update_thread_list ();
5098 else if (m_features
.packet_support (PACKET_QNonStop
) == PACKET_ENABLE
)
5100 /* Don't assume that the stub can operate in all-stop mode.
5101 Request it explicitly. */
5102 putpkt ("QNonStop:0");
5105 if (strcmp (rs
->buf
.data (), "OK") != 0)
5106 error (_("Remote refused setting all-stop mode with: %s"),
5110 /* Upload TSVs regardless of whether the target is running or not. The
5111 remote stub, such as GDBserver, may have some predefined or builtin
5112 TSVs, even if the target is not running. */
5113 if (get_trace_status (current_trace_status ()) != -1)
5115 struct uploaded_tsv
*uploaded_tsvs
= NULL
;
5117 upload_trace_state_variables (&uploaded_tsvs
);
5118 merge_uploaded_trace_state_variables (&uploaded_tsvs
);
5121 /* Check whether the target is running now. */
5125 if (!target_is_non_stop_p ())
5127 char *wait_status
= NULL
;
5129 if (rs
->buf
[0] == 'W' || rs
->buf
[0] == 'X')
5132 error (_("The target is not running (try extended-remote?)"));
5137 /* Save the reply for later. */
5138 wait_status
= (char *) alloca (strlen (rs
->buf
.data ()) + 1);
5139 strcpy (wait_status
, rs
->buf
.data ());
5142 /* Fetch thread list. */
5143 target_update_thread_list ();
5145 /* Let the stub know that we want it to return the thread. */
5146 set_continue_thread (minus_one_ptid
);
5148 if (thread_count (this) == 0)
5150 /* Target has no concept of threads at all. GDB treats
5151 non-threaded target as single-threaded; add a main
5153 thread_info
*tp
= add_current_inferior_and_thread (wait_status
);
5154 get_remote_thread_info (tp
)->set_resumed ();
5158 /* We have thread information; select the thread the target
5159 says should be current. If we're reconnecting to a
5160 multi-threaded program, this will ideally be the thread
5161 that last reported an event before GDB disconnected. */
5162 ptid_t curr_thread
= get_current_thread (wait_status
);
5163 if (curr_thread
== null_ptid
)
5165 /* Odd... The target was able to list threads, but not
5166 tell us which thread was current (no "thread"
5167 register in T stop reply?). Just pick the first
5168 thread in the thread list then. */
5170 remote_debug_printf ("warning: couldn't determine remote "
5171 "current thread; picking first in list.");
5173 for (thread_info
*tp
: all_non_exited_threads (this,
5176 switch_to_thread (tp
);
5181 switch_to_thread (this->find_thread (curr_thread
));
5183 get_remote_thread_info (inferior_thread ())->set_resumed ();
5186 /* init_wait_for_inferior should be called before get_offsets in order
5187 to manage `inserted' flag in bp loc in a correct state.
5188 breakpoint_init_inferior, called from init_wait_for_inferior, set
5189 `inserted' flag to 0, while before breakpoint_re_set, called from
5190 start_remote, set `inserted' flag to 1. In the initialization of
5191 inferior, breakpoint_init_inferior should be called first, and then
5192 breakpoint_re_set can be called. If this order is broken, state of
5193 `inserted' flag is wrong, and cause some problems on breakpoint
5195 init_wait_for_inferior ();
5197 get_offsets (); /* Get text, data & bss offsets. */
5199 /* If we could not find a description using qXfer, and we know
5200 how to do it some other way, try again. This is not
5201 supported for non-stop; it could be, but it is tricky if
5202 there are no stopped threads when we connect. */
5203 if (remote_read_description_p (this)
5204 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL
)
5206 target_clear_description ();
5207 target_find_description ();
5210 /* Use the previously fetched status. */
5211 gdb_assert (wait_status
!= NULL
);
5212 struct notif_event
*reply
5213 = remote_notif_parse (this, ¬if_client_stop
, wait_status
);
5214 push_stop_reply ((struct stop_reply
*) reply
);
5216 ::start_remote (from_tty
); /* Initialize gdb process mechanisms. */
5220 /* Clear WFI global state. Do this before finding about new
5221 threads and inferiors, and setting the current inferior.
5222 Otherwise we would clear the proceed status of the current
5223 inferior when we want its stop_soon state to be preserved
5224 (see notice_new_inferior). */
5225 init_wait_for_inferior ();
5227 /* In non-stop, we will either get an "OK", meaning that there
5228 are no stopped threads at this time; or, a regular stop
5229 reply. In the latter case, there may be more than one thread
5230 stopped --- we pull them all out using the vStopped
5232 if (strcmp (rs
->buf
.data (), "OK") != 0)
5234 const notif_client
*notif
= ¬if_client_stop
;
5236 /* remote_notif_get_pending_replies acks this one, and gets
5238 rs
->notif_state
->pending_event
[notif_client_stop
.id
]
5239 = remote_notif_parse (this, notif
, rs
->buf
.data ());
5240 remote_notif_get_pending_events (notif
);
5243 if (thread_count (this) == 0)
5246 error (_("The target is not running (try extended-remote?)"));
5250 /* Report all signals during attach/startup. */
5253 /* If there are already stopped threads, mark them stopped and
5254 report their stops before giving the prompt to the user. */
5255 process_initial_stop_replies (from_tty
);
5257 if (target_can_async_p ())
5258 target_async (true);
5261 /* Give the target a chance to look up symbols. */
5262 for (inferior
*inf
: all_inferiors (this))
5264 /* The inferiors that exist at this point were created from what
5265 was found already running on the remote side, so we know they
5267 gdb_assert (this->has_execution (inf
));
5269 /* No use without a symbol-file. */
5270 if (inf
->pspace
->symfile_object_file
== nullptr)
5273 /* Need to switch to a specific thread, because remote_check_symbols
5274 uses INFERIOR_PTID to set the general thread. */
5275 scoped_restore_current_thread restore_thread
;
5276 thread_info
*thread
= any_thread_of_inferior (inf
);
5277 switch_to_thread (thread
);
5278 this->remote_check_symbols ();
5281 /* Possibly the target has been engaged in a trace run started
5282 previously; find out where things are at. */
5283 if (get_trace_status (current_trace_status ()) != -1)
5285 struct uploaded_tp
*uploaded_tps
= NULL
;
5287 if (current_trace_status ()->running
)
5288 gdb_printf (_("Trace is already running on the target.\n"));
5290 upload_tracepoints (&uploaded_tps
);
5292 merge_uploaded_tracepoints (&uploaded_tps
);
5295 /* Possibly the target has been engaged in a btrace record started
5296 previously; find out where things are at. */
5297 remote_btrace_maybe_reopen ();
5302 /* Start the remote connection and sync state. */
5305 remote_target::start_remote (int from_tty
, int extended_p
)
5307 if (start_remote_1 (from_tty
, extended_p
)
5308 && breakpoints_should_be_inserted_now ())
5309 insert_breakpoints ();
5313 remote_target::connection_string ()
5315 remote_state
*rs
= get_remote_state ();
5317 if (rs
->remote_desc
->name
!= NULL
)
5318 return rs
->remote_desc
->name
;
5323 /* Open a connection to a remote debugger.
5324 NAME is the filename used for communication. */
5327 remote_target::open (const char *name
, int from_tty
)
5329 open_1 (name
, from_tty
, 0);
5332 /* Open a connection to a remote debugger using the extended
5333 remote gdb protocol. NAME is the filename used for communication. */
5336 extended_remote_target::open (const char *name
, int from_tty
)
5338 open_1 (name
, from_tty
, 1 /*extended_p */);
5342 remote_features::reset_all_packet_configs_support ()
5346 for (i
= 0; i
< PACKET_MAX
; i
++)
5347 m_protocol_packets
[i
].support
= PACKET_SUPPORT_UNKNOWN
;
5350 /* Initialize all packet configs. */
5353 init_all_packet_configs (void)
5357 for (i
= 0; i
< PACKET_MAX
; i
++)
5359 remote_protocol_packets
[i
].detect
= AUTO_BOOLEAN_AUTO
;
5360 remote_protocol_packets
[i
].support
= PACKET_SUPPORT_UNKNOWN
;
5364 /* Symbol look-up. */
5367 remote_target::remote_check_symbols ()
5372 /* It doesn't make sense to send a qSymbol packet for an inferior that
5373 doesn't have execution, because the remote side doesn't know about
5374 inferiors without execution. */
5375 gdb_assert (target_has_execution ());
5377 if (m_features
.packet_support (PACKET_qSymbol
) == PACKET_DISABLE
)
5380 /* Make sure the remote is pointing at the right process. Note
5381 there's no way to select "no process". */
5382 set_general_process ();
5384 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5385 because we need both at the same time. */
5386 gdb::char_vector
msg (get_remote_packet_size ());
5387 gdb::char_vector
reply (get_remote_packet_size ());
5389 /* Invite target to request symbol lookups. */
5391 putpkt ("qSymbol::");
5393 m_features
.packet_ok (reply
, PACKET_qSymbol
);
5395 while (startswith (reply
.data (), "qSymbol:"))
5397 struct bound_minimal_symbol sym
;
5400 end
= hex2bin (tmp
, reinterpret_cast <gdb_byte
*> (msg
.data ()),
5403 sym
= lookup_minimal_symbol (msg
.data (), NULL
, NULL
);
5404 if (sym
.minsym
== NULL
)
5405 xsnprintf (msg
.data (), get_remote_packet_size (), "qSymbol::%s",
5409 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5410 CORE_ADDR sym_addr
= sym
.value_address ();
5412 /* If this is a function address, return the start of code
5413 instead of any data function descriptor. */
5414 sym_addr
= gdbarch_convert_from_func_ptr_addr
5415 (current_inferior ()->arch (), sym_addr
,
5416 current_inferior ()->top_target ());
5418 xsnprintf (msg
.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5419 phex_nz (sym_addr
, addr_size
), &reply
[8]);
5422 putpkt (msg
.data ());
5427 static struct serial
*
5428 remote_serial_open (const char *name
)
5430 static int udp_warning
= 0;
5432 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5433 of in ser-tcp.c, because it is the remote protocol assuming that the
5434 serial connection is reliable and not the serial connection promising
5436 if (!udp_warning
&& startswith (name
, "udp:"))
5438 warning (_("The remote protocol may be unreliable over UDP.\n"
5439 "Some events may be lost, rendering further debugging "
5444 return serial_open (name
);
5447 /* Inform the target of our permission settings. The permission flags
5448 work without this, but if the target knows the settings, it can do
5449 a couple things. First, it can add its own check, to catch cases
5450 that somehow manage to get by the permissions checks in target
5451 methods. Second, if the target is wired to disallow particular
5452 settings (for instance, a system in the field that is not set up to
5453 be able to stop at a breakpoint), it can object to any unavailable
5457 remote_target::set_permissions ()
5459 struct remote_state
*rs
= get_remote_state ();
5461 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAllow:"
5462 "WriteReg:%x;WriteMem:%x;"
5463 "InsertBreak:%x;InsertTrace:%x;"
5464 "InsertFastTrace:%x;Stop:%x",
5465 may_write_registers
, may_write_memory
,
5466 may_insert_breakpoints
, may_insert_tracepoints
,
5467 may_insert_fast_tracepoints
, may_stop
);
5471 /* If the target didn't like the packet, warn the user. Do not try
5472 to undo the user's settings, that would just be maddening. */
5473 if (strcmp (rs
->buf
.data (), "OK") != 0)
5474 warning (_("Remote refused setting permissions with: %s"),
5478 /* This type describes each known response to the qSupported
5480 struct protocol_feature
5482 /* The name of this protocol feature. */
5485 /* The default for this protocol feature. */
5486 enum packet_support default_support
;
5488 /* The function to call when this feature is reported, or after
5489 qSupported processing if the feature is not supported.
5490 The first argument points to this structure. The second
5491 argument indicates whether the packet requested support be
5492 enabled, disabled, or probed (or the default, if this function
5493 is being called at the end of processing and this feature was
5494 not reported). The third argument may be NULL; if not NULL, it
5495 is a NUL-terminated string taken from the packet following
5496 this feature's name and an equals sign. */
5497 void (*func
) (remote_target
*remote
, const struct protocol_feature
*,
5498 enum packet_support
, const char *);
5500 /* The corresponding packet for this feature. Only used if
5501 FUNC is remote_supported_packet. */
5506 remote_supported_packet (remote_target
*remote
,
5507 const struct protocol_feature
*feature
,
5508 enum packet_support support
,
5509 const char *argument
)
5513 warning (_("Remote qSupported response supplied an unexpected value for"
5514 " \"%s\"."), feature
->name
);
5518 remote
->m_features
.m_protocol_packets
[feature
->packet
].support
= support
;
5522 remote_target::remote_packet_size (const protocol_feature
*feature
,
5523 enum packet_support support
,
5526 struct remote_state
*rs
= get_remote_state ();
5531 if (support
!= PACKET_ENABLE
)
5534 if (value
== NULL
|| *value
== '\0')
5536 warning (_("Remote target reported \"%s\" without a size."),
5542 packet_size
= strtol (value
, &value_end
, 16);
5543 if (errno
!= 0 || *value_end
!= '\0' || packet_size
< 0)
5545 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5546 feature
->name
, value
);
5550 /* Record the new maximum packet size. */
5551 rs
->explicit_packet_size
= packet_size
;
5555 remote_packet_size (remote_target
*remote
, const protocol_feature
*feature
,
5556 enum packet_support support
, const char *value
)
5558 remote
->remote_packet_size (feature
, support
, value
);
5562 remote_target::remote_supported_thread_options (const protocol_feature
*feature
,
5563 enum packet_support support
,
5566 struct remote_state
*rs
= get_remote_state ();
5568 m_features
.m_protocol_packets
[feature
->packet
].support
= support
;
5570 if (support
!= PACKET_ENABLE
)
5573 if (value
== nullptr || *value
== '\0')
5575 warning (_("Remote target reported \"%s\" without supported options."),
5580 ULONGEST options
= 0;
5581 const char *p
= unpack_varlen_hex (value
, &options
);
5585 warning (_("Remote target reported \"%s\" with "
5586 "bad thread options: \"%s\"."),
5587 feature
->name
, value
);
5591 /* Record the set of supported options. */
5592 rs
->supported_thread_options
= (gdb_thread_option
) options
;
5596 remote_supported_thread_options (remote_target
*remote
,
5597 const protocol_feature
*feature
,
5598 enum packet_support support
,
5601 remote
->remote_supported_thread_options (feature
, support
, value
);
5604 static const struct protocol_feature remote_protocol_features
[] = {
5605 { "PacketSize", PACKET_DISABLE
, remote_packet_size
, -1 },
5606 { "qXfer:auxv:read", PACKET_DISABLE
, remote_supported_packet
,
5607 PACKET_qXfer_auxv
},
5608 { "qXfer:exec-file:read", PACKET_DISABLE
, remote_supported_packet
,
5609 PACKET_qXfer_exec_file
},
5610 { "qXfer:features:read", PACKET_DISABLE
, remote_supported_packet
,
5611 PACKET_qXfer_features
},
5612 { "qXfer:libraries:read", PACKET_DISABLE
, remote_supported_packet
,
5613 PACKET_qXfer_libraries
},
5614 { "qXfer:libraries-svr4:read", PACKET_DISABLE
, remote_supported_packet
,
5615 PACKET_qXfer_libraries_svr4
},
5616 { "augmented-libraries-svr4-read", PACKET_DISABLE
,
5617 remote_supported_packet
, PACKET_augmented_libraries_svr4_read_feature
},
5618 { "qXfer:memory-map:read", PACKET_DISABLE
, remote_supported_packet
,
5619 PACKET_qXfer_memory_map
},
5620 { "qXfer:osdata:read", PACKET_DISABLE
, remote_supported_packet
,
5621 PACKET_qXfer_osdata
},
5622 { "qXfer:threads:read", PACKET_DISABLE
, remote_supported_packet
,
5623 PACKET_qXfer_threads
},
5624 { "qXfer:traceframe-info:read", PACKET_DISABLE
, remote_supported_packet
,
5625 PACKET_qXfer_traceframe_info
},
5626 { "QPassSignals", PACKET_DISABLE
, remote_supported_packet
,
5627 PACKET_QPassSignals
},
5628 { "QCatchSyscalls", PACKET_DISABLE
, remote_supported_packet
,
5629 PACKET_QCatchSyscalls
},
5630 { "QProgramSignals", PACKET_DISABLE
, remote_supported_packet
,
5631 PACKET_QProgramSignals
},
5632 { "QSetWorkingDir", PACKET_DISABLE
, remote_supported_packet
,
5633 PACKET_QSetWorkingDir
},
5634 { "QStartupWithShell", PACKET_DISABLE
, remote_supported_packet
,
5635 PACKET_QStartupWithShell
},
5636 { "QEnvironmentHexEncoded", PACKET_DISABLE
, remote_supported_packet
,
5637 PACKET_QEnvironmentHexEncoded
},
5638 { "QEnvironmentReset", PACKET_DISABLE
, remote_supported_packet
,
5639 PACKET_QEnvironmentReset
},
5640 { "QEnvironmentUnset", PACKET_DISABLE
, remote_supported_packet
,
5641 PACKET_QEnvironmentUnset
},
5642 { "QStartNoAckMode", PACKET_DISABLE
, remote_supported_packet
,
5643 PACKET_QStartNoAckMode
},
5644 { "multiprocess", PACKET_DISABLE
, remote_supported_packet
,
5645 PACKET_multiprocess_feature
},
5646 { "QNonStop", PACKET_DISABLE
, remote_supported_packet
, PACKET_QNonStop
},
5647 { "qXfer:siginfo:read", PACKET_DISABLE
, remote_supported_packet
,
5648 PACKET_qXfer_siginfo_read
},
5649 { "qXfer:siginfo:write", PACKET_DISABLE
, remote_supported_packet
,
5650 PACKET_qXfer_siginfo_write
},
5651 { "ConditionalTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5652 PACKET_ConditionalTracepoints
},
5653 { "ConditionalBreakpoints", PACKET_DISABLE
, remote_supported_packet
,
5654 PACKET_ConditionalBreakpoints
},
5655 { "BreakpointCommands", PACKET_DISABLE
, remote_supported_packet
,
5656 PACKET_BreakpointCommands
},
5657 { "FastTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5658 PACKET_FastTracepoints
},
5659 { "StaticTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5660 PACKET_StaticTracepoints
},
5661 {"InstallInTrace", PACKET_DISABLE
, remote_supported_packet
,
5662 PACKET_InstallInTrace
},
5663 { "DisconnectedTracing", PACKET_DISABLE
, remote_supported_packet
,
5664 PACKET_DisconnectedTracing_feature
},
5665 { "ReverseContinue", PACKET_DISABLE
, remote_supported_packet
,
5667 { "ReverseStep", PACKET_DISABLE
, remote_supported_packet
,
5669 { "TracepointSource", PACKET_DISABLE
, remote_supported_packet
,
5670 PACKET_TracepointSource
},
5671 { "QAllow", PACKET_DISABLE
, remote_supported_packet
,
5673 { "EnableDisableTracepoints", PACKET_DISABLE
, remote_supported_packet
,
5674 PACKET_EnableDisableTracepoints_feature
},
5675 { "qXfer:fdpic:read", PACKET_DISABLE
, remote_supported_packet
,
5676 PACKET_qXfer_fdpic
},
5677 { "qXfer:uib:read", PACKET_DISABLE
, remote_supported_packet
,
5679 { "QDisableRandomization", PACKET_DISABLE
, remote_supported_packet
,
5680 PACKET_QDisableRandomization
},
5681 { "QAgent", PACKET_DISABLE
, remote_supported_packet
, PACKET_QAgent
},
5682 { "QTBuffer:size", PACKET_DISABLE
,
5683 remote_supported_packet
, PACKET_QTBuffer_size
},
5684 { "tracenz", PACKET_DISABLE
, remote_supported_packet
, PACKET_tracenz_feature
},
5685 { "Qbtrace:off", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_off
},
5686 { "Qbtrace:bts", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_bts
},
5687 { "Qbtrace:pt", PACKET_DISABLE
, remote_supported_packet
, PACKET_Qbtrace_pt
},
5688 { "qXfer:btrace:read", PACKET_DISABLE
, remote_supported_packet
,
5689 PACKET_qXfer_btrace
},
5690 { "qXfer:btrace-conf:read", PACKET_DISABLE
, remote_supported_packet
,
5691 PACKET_qXfer_btrace_conf
},
5692 { "Qbtrace-conf:bts:size", PACKET_DISABLE
, remote_supported_packet
,
5693 PACKET_Qbtrace_conf_bts_size
},
5694 { "swbreak", PACKET_DISABLE
, remote_supported_packet
, PACKET_swbreak_feature
},
5695 { "hwbreak", PACKET_DISABLE
, remote_supported_packet
, PACKET_hwbreak_feature
},
5696 { "fork-events", PACKET_DISABLE
, remote_supported_packet
,
5697 PACKET_fork_event_feature
},
5698 { "vfork-events", PACKET_DISABLE
, remote_supported_packet
,
5699 PACKET_vfork_event_feature
},
5700 { "exec-events", PACKET_DISABLE
, remote_supported_packet
,
5701 PACKET_exec_event_feature
},
5702 { "Qbtrace-conf:pt:size", PACKET_DISABLE
, remote_supported_packet
,
5703 PACKET_Qbtrace_conf_pt_size
},
5704 { "vContSupported", PACKET_DISABLE
, remote_supported_packet
, PACKET_vContSupported
},
5705 { "QThreadEvents", PACKET_DISABLE
, remote_supported_packet
, PACKET_QThreadEvents
},
5706 { "QThreadOptions", PACKET_DISABLE
, remote_supported_thread_options
,
5707 PACKET_QThreadOptions
},
5708 { "no-resumed", PACKET_DISABLE
, remote_supported_packet
, PACKET_no_resumed
},
5709 { "memory-tagging", PACKET_DISABLE
, remote_supported_packet
,
5710 PACKET_memory_tagging_feature
},
5713 static char *remote_support_xml
;
5715 /* Register string appended to "xmlRegisters=" in qSupported query. */
5718 register_remote_support_xml (const char *xml
)
5720 #if defined(HAVE_LIBEXPAT)
5721 if (remote_support_xml
== NULL
)
5722 remote_support_xml
= concat ("xmlRegisters=", xml
, (char *) NULL
);
5725 char *copy
= xstrdup (remote_support_xml
+ 13);
5727 char *p
= strtok_r (copy
, ",", &saveptr
);
5731 if (strcmp (p
, xml
) == 0)
5738 while ((p
= strtok_r (NULL
, ",", &saveptr
)) != NULL
);
5741 remote_support_xml
= reconcat (remote_support_xml
,
5742 remote_support_xml
, ",", xml
,
5749 remote_query_supported_append (std::string
*msg
, const char *append
)
5753 msg
->append (append
);
5757 remote_target::remote_query_supported ()
5759 struct remote_state
*rs
= get_remote_state ();
5762 unsigned char seen
[ARRAY_SIZE (remote_protocol_features
)];
5764 /* The packet support flags are handled differently for this packet
5765 than for most others. We treat an error, a disabled packet, and
5766 an empty response identically: any features which must be reported
5767 to be used will be automatically disabled. An empty buffer
5768 accomplishes this, since that is also the representation for a list
5769 containing no features. */
5772 if (m_features
.packet_support (PACKET_qSupported
) != PACKET_DISABLE
)
5776 if (m_features
.packet_set_cmd_state (PACKET_multiprocess_feature
)
5777 != AUTO_BOOLEAN_FALSE
)
5778 remote_query_supported_append (&q
, "multiprocess+");
5780 if (m_features
.packet_set_cmd_state (PACKET_swbreak_feature
)
5781 != AUTO_BOOLEAN_FALSE
)
5782 remote_query_supported_append (&q
, "swbreak+");
5784 if (m_features
.packet_set_cmd_state (PACKET_hwbreak_feature
)
5785 != AUTO_BOOLEAN_FALSE
)
5786 remote_query_supported_append (&q
, "hwbreak+");
5788 remote_query_supported_append (&q
, "qRelocInsn+");
5790 if (m_features
.packet_set_cmd_state (PACKET_fork_event_feature
)
5791 != AUTO_BOOLEAN_FALSE
)
5792 remote_query_supported_append (&q
, "fork-events+");
5794 if (m_features
.packet_set_cmd_state (PACKET_vfork_event_feature
)
5795 != AUTO_BOOLEAN_FALSE
)
5796 remote_query_supported_append (&q
, "vfork-events+");
5798 if (m_features
.packet_set_cmd_state (PACKET_exec_event_feature
)
5799 != AUTO_BOOLEAN_FALSE
)
5800 remote_query_supported_append (&q
, "exec-events+");
5802 if (m_features
.packet_set_cmd_state (PACKET_vContSupported
)
5803 != AUTO_BOOLEAN_FALSE
)
5804 remote_query_supported_append (&q
, "vContSupported+");
5806 if (m_features
.packet_set_cmd_state (PACKET_QThreadEvents
)
5807 != AUTO_BOOLEAN_FALSE
)
5808 remote_query_supported_append (&q
, "QThreadEvents+");
5810 if (m_features
.packet_set_cmd_state (PACKET_QThreadOptions
)
5811 != AUTO_BOOLEAN_FALSE
)
5812 remote_query_supported_append (&q
, "QThreadOptions+");
5814 if (m_features
.packet_set_cmd_state (PACKET_no_resumed
)
5815 != AUTO_BOOLEAN_FALSE
)
5816 remote_query_supported_append (&q
, "no-resumed+");
5818 if (m_features
.packet_set_cmd_state (PACKET_memory_tagging_feature
)
5819 != AUTO_BOOLEAN_FALSE
)
5820 remote_query_supported_append (&q
, "memory-tagging+");
5822 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5823 the qSupported:xmlRegisters=i386 handling. */
5824 if (remote_support_xml
!= NULL
5825 && (m_features
.packet_support (PACKET_qXfer_features
)
5827 remote_query_supported_append (&q
, remote_support_xml
);
5829 q
= "qSupported:" + q
;
5830 putpkt (q
.c_str ());
5834 /* If an error occurred, warn, but do not return - just reset the
5835 buffer to empty and go on to disable features. */
5836 if (m_features
.packet_ok (rs
->buf
, PACKET_qSupported
) == PACKET_ERROR
)
5838 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
5843 memset (seen
, 0, sizeof (seen
));
5845 next
= rs
->buf
.data ();
5848 enum packet_support is_supported
;
5849 char *p
, *end
, *name_end
, *value
;
5851 /* First separate out this item from the rest of the packet. If
5852 there's another item after this, we overwrite the separator
5853 (terminated strings are much easier to work with). */
5855 end
= strchr (p
, ';');
5858 end
= p
+ strlen (p
);
5868 warning (_("empty item in \"qSupported\" response"));
5873 name_end
= strchr (p
, '=');
5876 /* This is a name=value entry. */
5877 is_supported
= PACKET_ENABLE
;
5878 value
= name_end
+ 1;
5887 is_supported
= PACKET_ENABLE
;
5891 is_supported
= PACKET_DISABLE
;
5895 is_supported
= PACKET_SUPPORT_UNKNOWN
;
5899 warning (_("unrecognized item \"%s\" "
5900 "in \"qSupported\" response"), p
);
5906 for (i
= 0; i
< ARRAY_SIZE (remote_protocol_features
); i
++)
5907 if (strcmp (remote_protocol_features
[i
].name
, p
) == 0)
5909 const struct protocol_feature
*feature
;
5912 feature
= &remote_protocol_features
[i
];
5913 feature
->func (this, feature
, is_supported
, value
);
5918 /* If we increased the packet size, make sure to increase the global
5919 buffer size also. We delay this until after parsing the entire
5920 qSupported packet, because this is the same buffer we were
5922 if (rs
->buf
.size () < rs
->explicit_packet_size
)
5923 rs
->buf
.resize (rs
->explicit_packet_size
);
5925 /* Handle the defaults for unmentioned features. */
5926 for (i
= 0; i
< ARRAY_SIZE (remote_protocol_features
); i
++)
5929 const struct protocol_feature
*feature
;
5931 feature
= &remote_protocol_features
[i
];
5932 feature
->func (this, feature
, feature
->default_support
, NULL
);
5936 /* Serial QUIT handler for the remote serial descriptor.
5938 Defers handling a Ctrl-C until we're done with the current
5939 command/response packet sequence, unless:
5941 - We're setting up the connection. Don't send a remote interrupt
5942 request, as we're not fully synced yet. Quit immediately
5945 - The target has been resumed in the foreground
5946 (target_terminal::is_ours is false) with a synchronous resume
5947 packet, and we're blocked waiting for the stop reply, thus a
5948 Ctrl-C should be immediately sent to the target.
5950 - We get a second Ctrl-C while still within the same serial read or
5951 write. In that case the serial is seemingly wedged --- offer to
5954 - We see a second Ctrl-C without target response, after having
5955 previously interrupted the target. In that case the target/stub
5956 is probably wedged --- offer to quit/disconnect.
5960 remote_target::remote_serial_quit_handler ()
5962 struct remote_state
*rs
= get_remote_state ();
5964 if (check_quit_flag ())
5966 /* If we're starting up, we're not fully synced yet. Quit
5968 if (rs
->starting_up
)
5970 else if (rs
->got_ctrlc_during_io
)
5972 if (query (_("The target is not responding to GDB commands.\n"
5973 "Stop debugging it? ")))
5974 remote_unpush_and_throw (this);
5976 /* If ^C has already been sent once, offer to disconnect. */
5977 else if (!target_terminal::is_ours () && rs
->ctrlc_pending_p
)
5979 /* All-stop protocol, and blocked waiting for stop reply. Send
5980 an interrupt request. */
5981 else if (!target_terminal::is_ours () && rs
->waiting_for_stop_reply
)
5982 target_interrupt ();
5984 rs
->got_ctrlc_during_io
= 1;
5988 /* The remote_target that is current while the quit handler is
5989 overridden with remote_serial_quit_handler. */
5990 static remote_target
*curr_quit_handler_target
;
5993 remote_serial_quit_handler ()
5995 curr_quit_handler_target
->remote_serial_quit_handler ();
5998 /* Remove the remote target from the target stack of each inferior
5999 that is using it. Upper targets depend on it so remove them
6003 remote_unpush_target (remote_target
*target
)
6005 /* We have to unpush the target from all inferiors, even those that
6007 scoped_restore_current_inferior restore_current_inferior
;
6009 for (inferior
*inf
: all_inferiors (target
))
6011 switch_to_inferior_no_thread (inf
);
6012 inf
->pop_all_targets_at_and_above (process_stratum
);
6013 generic_mourn_inferior ();
6016 /* Don't rely on target_close doing this when the target is popped
6017 from the last remote inferior above, because something may be
6018 holding a reference to the target higher up on the stack, meaning
6019 target_close won't be called yet. We lost the connection to the
6020 target, so clear these now, otherwise we may later throw
6021 TARGET_CLOSE_ERROR while trying to tell the remote target to
6023 fileio_handles_invalidate_target (target
);
6027 remote_unpush_and_throw (remote_target
*target
)
6029 remote_unpush_target (target
);
6030 throw_error (TARGET_CLOSE_ERROR
, _("Disconnected from target."));
6034 remote_target::open_1 (const char *name
, int from_tty
, int extended_p
)
6036 remote_target
*curr_remote
= get_current_remote_target ();
6039 error (_("To open a remote debug connection, you need to specify what\n"
6040 "serial device is attached to the remote system\n"
6041 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6043 /* If we're connected to a running target, target_preopen will kill it.
6044 Ask this question first, before target_preopen has a chance to kill
6046 if (curr_remote
!= NULL
&& !target_has_execution ())
6049 && !query (_("Already connected to a remote target. Disconnect? ")))
6050 error (_("Still connected."));
6053 /* Here the possibly existing remote target gets unpushed. */
6054 target_preopen (from_tty
);
6056 remote_fileio_reset ();
6057 reopen_exec_file ();
6058 reread_symbols (from_tty
);
6060 remote_target
*remote
6061 = (extended_p
? new extended_remote_target () : new remote_target ());
6062 target_ops_up
target_holder (remote
);
6064 remote_state
*rs
= remote
->get_remote_state ();
6066 /* See FIXME above. */
6067 if (!target_async_permitted
)
6068 rs
->wait_forever_enabled_p
= true;
6070 rs
->remote_desc
= remote_serial_open (name
);
6071 if (!rs
->remote_desc
)
6072 perror_with_name (name
);
6074 if (baud_rate
!= -1)
6076 if (serial_setbaudrate (rs
->remote_desc
, baud_rate
))
6078 /* The requested speed could not be set. Error out to
6079 top level after closing remote_desc. Take care to
6080 set remote_desc to NULL to avoid closing remote_desc
6082 serial_close (rs
->remote_desc
);
6083 rs
->remote_desc
= NULL
;
6084 perror_with_name (name
);
6088 serial_setparity (rs
->remote_desc
, serial_parity
);
6089 serial_raw (rs
->remote_desc
);
6091 /* If there is something sitting in the buffer we might take it as a
6092 response to a command, which would be bad. */
6093 serial_flush_input (rs
->remote_desc
);
6097 gdb_puts ("Remote debugging using ");
6102 /* Switch to using the remote target now. */
6103 current_inferior ()->push_target (std::move (target_holder
));
6105 /* Register extra event sources in the event loop. */
6106 rs
->create_async_event_handler ();
6108 rs
->notif_state
= remote_notif_state_allocate (remote
);
6110 /* Reset the target state; these things will be queried either by
6111 remote_query_supported or as they are needed. */
6112 remote
->m_features
.reset_all_packet_configs_support ();
6113 rs
->explicit_packet_size
= 0;
6115 rs
->extended
= extended_p
;
6116 rs
->waiting_for_stop_reply
= 0;
6117 rs
->ctrlc_pending_p
= 0;
6118 rs
->got_ctrlc_during_io
= 0;
6120 rs
->general_thread
= not_sent_ptid
;
6121 rs
->continue_thread
= not_sent_ptid
;
6122 rs
->remote_traceframe_number
= -1;
6124 rs
->last_resume_exec_dir
= EXEC_FORWARD
;
6126 /* Probe for ability to use "ThreadInfo" query, as required. */
6127 rs
->use_threadinfo_query
= 1;
6128 rs
->use_threadextra_query
= 1;
6130 rs
->readahead_cache
.invalidate ();
6132 if (target_async_permitted
)
6134 /* FIXME: cagney/1999-09-23: During the initial connection it is
6135 assumed that the target is already ready and able to respond to
6136 requests. Unfortunately remote_start_remote() eventually calls
6137 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6138 around this. Eventually a mechanism that allows
6139 wait_for_inferior() to expect/get timeouts will be
6141 rs
->wait_forever_enabled_p
= false;
6144 /* First delete any symbols previously loaded from shared libraries. */
6145 no_shared_libraries (NULL
, 0);
6147 /* Start the remote connection. If error() or QUIT, discard this
6148 target (we'd otherwise be in an inconsistent state) and then
6149 propogate the error on up the exception chain. This ensures that
6150 the caller doesn't stumble along blindly assuming that the
6151 function succeeded. The CLI doesn't have this problem but other
6152 UI's, such as MI do.
6154 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6155 this function should return an error indication letting the
6156 caller restore the previous state. Unfortunately the command
6157 ``target remote'' is directly wired to this function making that
6158 impossible. On a positive note, the CLI side of this problem has
6159 been fixed - the function set_cmd_context() makes it possible for
6160 all the ``target ....'' commands to share a common callback
6161 function. See cli-dump.c. */
6166 remote
->start_remote (from_tty
, extended_p
);
6168 catch (const gdb_exception
&ex
)
6170 /* Pop the partially set up target - unless something else did
6171 already before throwing the exception. */
6172 if (ex
.error
!= TARGET_CLOSE_ERROR
)
6173 remote_unpush_target (remote
);
6178 remote_btrace_reset (rs
);
6180 if (target_async_permitted
)
6181 rs
->wait_forever_enabled_p
= true;
6184 /* Determine if WS represents a fork status. */
6187 is_fork_status (target_waitkind kind
)
6189 return (kind
== TARGET_WAITKIND_FORKED
6190 || kind
== TARGET_WAITKIND_VFORKED
);
6193 /* Return a reference to the field where a pending child status, if
6194 there's one, is recorded. If there's no child event pending, the
6195 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6197 static const target_waitstatus
&
6198 thread_pending_status (struct thread_info
*thread
)
6200 return (thread
->has_pending_waitstatus ()
6201 ? thread
->pending_waitstatus ()
6202 : thread
->pending_follow
);
6205 /* Return THREAD's pending status if it is a pending fork/vfork (but
6206 not clone) parent, else return nullptr. */
6208 static const target_waitstatus
*
6209 thread_pending_fork_status (struct thread_info
*thread
)
6211 const target_waitstatus
&ws
= thread_pending_status (thread
);
6213 if (!is_fork_status (ws
.kind ()))
6219 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6220 event, else return nullptr. */
6222 static const target_waitstatus
*
6223 thread_pending_child_status (thread_info
*thread
)
6225 const target_waitstatus
&ws
= thread_pending_status (thread
);
6227 if (!is_new_child_status (ws
.kind ()))
6233 /* Detach the specified process. */
6236 remote_target::remote_detach_pid (int pid
)
6238 struct remote_state
*rs
= get_remote_state ();
6240 /* This should not be necessary, but the handling for D;PID in
6241 GDBserver versions prior to 8.2 incorrectly assumes that the
6242 selected process points to the same process we're detaching,
6243 leading to misbehavior (and possibly GDBserver crashing) when it
6244 does not. Since it's easy and cheap, work around it by forcing
6245 GDBserver to select GDB's current process. */
6246 set_general_process ();
6248 if (m_features
.remote_multi_process_p ())
6249 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "D;%x", pid
);
6251 strcpy (rs
->buf
.data (), "D");
6256 if (rs
->buf
[0] == 'O' && rs
->buf
[1] == 'K')
6258 else if (rs
->buf
[0] == '\0')
6259 error (_("Remote doesn't know how to detach"));
6262 /* It is possible that we have an unprocessed exit event for this
6263 pid. If this is the case then we can ignore the failure to detach
6264 and just pretend that the detach worked, as far as the user is
6265 concerned, the process exited immediately after the detach. */
6266 bool process_has_already_exited
= false;
6267 remote_notif_get_pending_events (¬if_client_stop
);
6268 for (stop_reply_up
&reply
: rs
->stop_reply_queue
)
6270 if (reply
->ptid
.pid () != pid
)
6273 enum target_waitkind kind
= reply
->ws
.kind ();
6274 if (kind
== TARGET_WAITKIND_EXITED
6275 || kind
== TARGET_WAITKIND_SIGNALLED
)
6277 process_has_already_exited
= true;
6279 ("detach failed, but process already exited");
6284 if (!process_has_already_exited
)
6285 error (_("can't detach process: %s"), (char *) rs
->buf
.data ());
6289 /* This detaches a program to which we previously attached, using
6290 inferior_ptid to identify the process. After this is done, GDB
6291 can be used to debug some other program. We better not have left
6292 any breakpoints in the target program or it'll die when it hits
6296 remote_target::remote_detach_1 (inferior
*inf
, int from_tty
)
6298 int pid
= inferior_ptid
.pid ();
6299 struct remote_state
*rs
= get_remote_state ();
6302 if (!target_has_execution ())
6303 error (_("No process to detach from."));
6305 target_announce_detach (from_tty
);
6307 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6309 /* If we're in breakpoints-always-inserted mode, or the inferior
6310 is running, we have to remove breakpoints before detaching.
6311 We don't do this in common code instead because not all
6312 targets support removing breakpoints while the target is
6313 running. The remote target / gdbserver does, though. */
6314 remove_breakpoints_inf (current_inferior ());
6317 /* Tell the remote target to detach. */
6318 remote_detach_pid (pid
);
6320 /* Exit only if this is the only active inferior. */
6321 if (from_tty
&& !rs
->extended
&& number_of_live_inferiors (this) == 1)
6322 gdb_puts (_("Ending remote debugging.\n"));
6324 /* See if any thread of the inferior we are detaching has a pending fork
6325 status. In that case, we must detach from the child resulting from
6327 for (thread_info
*thread
: inf
->non_exited_threads ())
6329 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
6334 remote_detach_pid (ws
->child_ptid ().pid ());
6337 /* Check also for any pending fork events in the stop reply queue. */
6338 remote_notif_get_pending_events (¬if_client_stop
);
6339 for (stop_reply_up
&reply
: rs
->stop_reply_queue
)
6341 if (reply
->ptid
.pid () != pid
)
6344 if (!is_fork_status (reply
->ws
.kind ()))
6347 remote_detach_pid (reply
->ws
.child_ptid ().pid ());
6350 thread_info
*tp
= this->find_thread (inferior_ptid
);
6352 /* Check to see if we are detaching a fork parent. Note that if we
6353 are detaching a fork child, tp == NULL. */
6354 is_fork_parent
= (tp
!= NULL
6355 && tp
->pending_follow
.kind () == TARGET_WAITKIND_FORKED
);
6357 /* If doing detach-on-fork, we don't mourn, because that will delete
6358 breakpoints that should be available for the followed inferior. */
6359 if (!is_fork_parent
)
6361 /* Save the pid as a string before mourning, since that will
6362 unpush the remote target, and we need the string after. */
6363 std::string infpid
= target_pid_to_str (ptid_t (pid
));
6365 target_mourn_inferior (inferior_ptid
);
6366 if (print_inferior_events
)
6367 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6368 inf
->num
, infpid
.c_str ());
6372 switch_to_no_thread ();
6373 detach_inferior (current_inferior ());
6378 remote_target::detach (inferior
*inf
, int from_tty
)
6380 remote_detach_1 (inf
, from_tty
);
6384 extended_remote_target::detach (inferior
*inf
, int from_tty
)
6386 remote_detach_1 (inf
, from_tty
);
6389 /* Target follow-fork function for remote targets. On entry, and
6390 at return, the current inferior is the fork parent.
6392 Note that although this is currently only used for extended-remote,
6393 it is named remote_follow_fork in anticipation of using it for the
6394 remote target as well. */
6397 remote_target::follow_fork (inferior
*child_inf
, ptid_t child_ptid
,
6398 target_waitkind fork_kind
, bool follow_child
,
6401 process_stratum_target::follow_fork (child_inf
, child_ptid
,
6402 fork_kind
, follow_child
, detach_fork
);
6404 if ((fork_kind
== TARGET_WAITKIND_FORKED
6405 && m_features
.remote_fork_event_p ())
6406 || (fork_kind
== TARGET_WAITKIND_VFORKED
6407 && m_features
.remote_vfork_event_p ()))
6409 /* When following the parent and detaching the child, we detach
6410 the child here. For the case of following the child and
6411 detaching the parent, the detach is done in the target-
6412 independent follow fork code in infrun.c. We can't use
6413 target_detach when detaching an unfollowed child because
6414 the client side doesn't know anything about the child. */
6415 if (detach_fork
&& !follow_child
)
6417 /* Detach the fork child. */
6418 remote_detach_pid (child_ptid
.pid ());
6424 remote_target::follow_clone (ptid_t child_ptid
)
6426 remote_add_thread (child_ptid
, false, false, false);
6429 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6430 in the program space of the new inferior. */
6433 remote_target::follow_exec (inferior
*follow_inf
, ptid_t ptid
,
6434 const char *execd_pathname
)
6436 process_stratum_target::follow_exec (follow_inf
, ptid
, execd_pathname
);
6438 /* We know that this is a target file name, so if it has the "target:"
6439 prefix we strip it off before saving it in the program space. */
6440 if (is_target_filename (execd_pathname
))
6441 execd_pathname
+= strlen (TARGET_SYSROOT_PREFIX
);
6443 set_pspace_remote_exec_file (follow_inf
->pspace
, execd_pathname
);
6446 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6449 remote_target::disconnect (const char *args
, int from_tty
)
6452 error (_("Argument given to \"disconnect\" when remotely debugging."));
6454 /* Make sure we unpush even the extended remote targets. Calling
6455 target_mourn_inferior won't unpush, and
6456 remote_target::mourn_inferior won't unpush if there is more than
6457 one inferior left. */
6458 remote_unpush_target (this);
6461 gdb_puts ("Ending remote debugging.\n");
6464 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6465 be chatty about it. */
6468 extended_remote_target::attach (const char *args
, int from_tty
)
6470 struct remote_state
*rs
= get_remote_state ();
6472 char *wait_status
= NULL
;
6474 pid
= parse_pid_to_attach (args
);
6476 /* Remote PID can be freely equal to getpid, do not check it here the same
6477 way as in other targets. */
6479 if (m_features
.packet_support (PACKET_vAttach
) == PACKET_DISABLE
)
6480 error (_("This target does not support attaching to a process"));
6482 target_announce_attach (from_tty
, pid
);
6484 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vAttach;%x", pid
);
6488 switch (m_features
.packet_ok (rs
->buf
, PACKET_vAttach
))
6491 if (!target_is_non_stop_p ())
6493 /* Save the reply for later. */
6494 wait_status
= (char *) alloca (strlen (rs
->buf
.data ()) + 1);
6495 strcpy (wait_status
, rs
->buf
.data ());
6497 else if (strcmp (rs
->buf
.data (), "OK") != 0)
6498 error (_("Attaching to %s failed with: %s"),
6499 target_pid_to_str (ptid_t (pid
)).c_str (),
6502 case PACKET_UNKNOWN
:
6503 error (_("This target does not support attaching to a process"));
6505 error (_("Attaching to %s failed"),
6506 target_pid_to_str (ptid_t (pid
)).c_str ());
6509 switch_to_inferior_no_thread (remote_add_inferior (false, pid
, 1, 0));
6511 inferior_ptid
= ptid_t (pid
);
6513 if (target_is_non_stop_p ())
6515 /* Get list of threads. */
6516 update_thread_list ();
6518 thread_info
*thread
= first_thread_of_inferior (current_inferior ());
6519 if (thread
!= nullptr)
6520 switch_to_thread (thread
);
6522 /* Invalidate our notion of the remote current thread. */
6523 record_currthread (rs
, minus_one_ptid
);
6527 /* Now, if we have thread information, update the main thread's
6529 ptid_t curr_ptid
= remote_current_thread (ptid_t (pid
));
6531 /* Add the main thread to the thread list. We add the thread
6532 silently in this case (the final true parameter). */
6533 thread_info
*thr
= remote_add_thread (curr_ptid
, true, true, true);
6535 switch_to_thread (thr
);
6538 /* Next, if the target can specify a description, read it. We do
6539 this before anything involving memory or registers. */
6540 target_find_description ();
6542 if (!target_is_non_stop_p ())
6544 /* Use the previously fetched status. */
6545 gdb_assert (wait_status
!= NULL
);
6547 struct notif_event
*reply
6548 = remote_notif_parse (this, ¬if_client_stop
, wait_status
);
6550 push_stop_reply ((struct stop_reply
*) reply
);
6554 gdb_assert (wait_status
== NULL
);
6556 gdb_assert (target_can_async_p ());
6560 /* Implementation of the to_post_attach method. */
6563 extended_remote_target::post_attach (int pid
)
6565 /* Get text, data & bss offsets. */
6568 /* In certain cases GDB might not have had the chance to start
6569 symbol lookup up until now. This could happen if the debugged
6570 binary is not using shared libraries, the vsyscall page is not
6571 present (on Linux) and the binary itself hadn't changed since the
6572 debugging process was started. */
6573 if (current_program_space
->symfile_object_file
!= NULL
)
6574 remote_check_symbols();
6578 /* Check for the availability of vCont. This function should also check
6582 remote_target::remote_vcont_probe ()
6584 remote_state
*rs
= get_remote_state ();
6587 strcpy (rs
->buf
.data (), "vCont?");
6590 buf
= rs
->buf
.data ();
6592 /* Make sure that the features we assume are supported. */
6593 if (startswith (buf
, "vCont"))
6596 int support_c
, support_C
;
6598 rs
->supports_vCont
.s
= 0;
6599 rs
->supports_vCont
.S
= 0;
6602 rs
->supports_vCont
.t
= 0;
6603 rs
->supports_vCont
.r
= 0;
6604 while (p
&& *p
== ';')
6607 if (*p
== 's' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6608 rs
->supports_vCont
.s
= 1;
6609 else if (*p
== 'S' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6610 rs
->supports_vCont
.S
= 1;
6611 else if (*p
== 'c' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6613 else if (*p
== 'C' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6615 else if (*p
== 't' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6616 rs
->supports_vCont
.t
= 1;
6617 else if (*p
== 'r' && (*(p
+ 1) == ';' || *(p
+ 1) == 0))
6618 rs
->supports_vCont
.r
= 1;
6620 p
= strchr (p
, ';');
6623 /* If c, and C are not all supported, we can't use vCont. Clearing
6624 BUF will make packet_ok disable the packet. */
6625 if (!support_c
|| !support_C
)
6629 m_features
.packet_ok (rs
->buf
, PACKET_vCont
);
6632 /* Helper function for building "vCont" resumptions. Write a
6633 resumption to P. ENDP points to one-passed-the-end of the buffer
6634 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6635 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6636 resumed thread should be single-stepped and/or signalled. If PTID
6637 equals minus_one_ptid, then all threads are resumed; if PTID
6638 represents a process, then all threads of the process are
6642 remote_target::append_resumption (char *p
, char *endp
,
6643 ptid_t ptid
, int step
, gdb_signal siggnal
)
6645 struct remote_state
*rs
= get_remote_state ();
6647 if (step
&& siggnal
!= GDB_SIGNAL_0
)
6648 p
+= xsnprintf (p
, endp
- p
, ";S%02x", siggnal
);
6650 /* GDB is willing to range step. */
6651 && use_range_stepping
6652 /* Target supports range stepping. */
6653 && rs
->supports_vCont
.r
6654 /* We don't currently support range stepping multiple
6655 threads with a wildcard (though the protocol allows it,
6656 so stubs shouldn't make an active effort to forbid
6658 && !(m_features
.remote_multi_process_p () && ptid
.is_pid ()))
6660 struct thread_info
*tp
;
6662 if (ptid
== minus_one_ptid
)
6664 /* If we don't know about the target thread's tid, then
6665 we're resuming magic_null_ptid (see caller). */
6666 tp
= this->find_thread (magic_null_ptid
);
6669 tp
= this->find_thread (ptid
);
6670 gdb_assert (tp
!= NULL
);
6672 if (tp
->control
.may_range_step
)
6674 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6676 p
+= xsnprintf (p
, endp
- p
, ";r%s,%s",
6677 phex_nz (tp
->control
.step_range_start
,
6679 phex_nz (tp
->control
.step_range_end
,
6683 p
+= xsnprintf (p
, endp
- p
, ";s");
6686 p
+= xsnprintf (p
, endp
- p
, ";s");
6687 else if (siggnal
!= GDB_SIGNAL_0
)
6688 p
+= xsnprintf (p
, endp
- p
, ";C%02x", siggnal
);
6690 p
+= xsnprintf (p
, endp
- p
, ";c");
6692 if (m_features
.remote_multi_process_p () && ptid
.is_pid ())
6696 /* All (-1) threads of process. */
6697 nptid
= ptid_t (ptid
.pid (), -1);
6699 p
+= xsnprintf (p
, endp
- p
, ":");
6700 p
= write_ptid (p
, endp
, nptid
);
6702 else if (ptid
!= minus_one_ptid
)
6704 p
+= xsnprintf (p
, endp
- p
, ":");
6705 p
= write_ptid (p
, endp
, ptid
);
6711 /* Clear the thread's private info on resume. */
6714 resume_clear_thread_private_info (struct thread_info
*thread
)
6716 if (thread
->priv
!= NULL
)
6718 remote_thread_info
*priv
= get_remote_thread_info (thread
);
6720 priv
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
6721 priv
->watch_data_address
= 0;
6725 /* Append a vCont continue-with-signal action for threads that have a
6726 non-zero stop signal. */
6729 remote_target::append_pending_thread_resumptions (char *p
, char *endp
,
6732 for (thread_info
*thread
: all_non_exited_threads (this, ptid
))
6733 if (inferior_ptid
!= thread
->ptid
6734 && thread
->stop_signal () != GDB_SIGNAL_0
)
6736 p
= append_resumption (p
, endp
, thread
->ptid
,
6737 0, thread
->stop_signal ());
6738 thread
->set_stop_signal (GDB_SIGNAL_0
);
6739 resume_clear_thread_private_info (thread
);
6745 /* Set the target running, using the packets that use Hc
6749 remote_target::remote_resume_with_hc (ptid_t ptid
, int step
,
6752 struct remote_state
*rs
= get_remote_state ();
6755 rs
->last_sent_signal
= siggnal
;
6756 rs
->last_sent_step
= step
;
6758 /* The c/s/C/S resume packets use Hc, so set the continue
6760 if (ptid
== minus_one_ptid
)
6761 set_continue_thread (any_thread_ptid
);
6763 set_continue_thread (ptid
);
6765 for (thread_info
*thread
: all_non_exited_threads (this))
6766 resume_clear_thread_private_info (thread
);
6768 buf
= rs
->buf
.data ();
6769 if (::execution_direction
== EXEC_REVERSE
)
6771 /* We don't pass signals to the target in reverse exec mode. */
6772 if (info_verbose
&& siggnal
!= GDB_SIGNAL_0
)
6773 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6776 if (step
&& m_features
.packet_support (PACKET_bs
) == PACKET_DISABLE
)
6777 error (_("Remote reverse-step not supported."));
6778 if (!step
&& m_features
.packet_support (PACKET_bc
) == PACKET_DISABLE
)
6779 error (_("Remote reverse-continue not supported."));
6781 strcpy (buf
, step
? "bs" : "bc");
6783 else if (siggnal
!= GDB_SIGNAL_0
)
6785 buf
[0] = step
? 'S' : 'C';
6786 buf
[1] = tohex (((int) siggnal
>> 4) & 0xf);
6787 buf
[2] = tohex (((int) siggnal
) & 0xf);
6791 strcpy (buf
, step
? "s" : "c");
6796 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6797 STEP, and SIGGNAL have the same meaning as in target_resume. This
6798 function returns non-zero iff it resumes the inferior.
6800 This function issues a strict subset of all possible vCont commands
6804 remote_target::remote_resume_with_vcont (ptid_t scope_ptid
, int step
,
6805 enum gdb_signal siggnal
)
6807 struct remote_state
*rs
= get_remote_state ();
6811 /* No reverse execution actions defined for vCont. */
6812 if (::execution_direction
== EXEC_REVERSE
)
6815 if (m_features
.packet_support (PACKET_vCont
) == PACKET_DISABLE
)
6818 p
= rs
->buf
.data ();
6819 endp
= p
+ get_remote_packet_size ();
6821 /* If we could generate a wider range of packets, we'd have to worry
6822 about overflowing BUF. Should there be a generic
6823 "multi-part-packet" packet? */
6825 p
+= xsnprintf (p
, endp
- p
, "vCont");
6827 if (scope_ptid
== magic_null_ptid
)
6829 /* MAGIC_NULL_PTID means that we don't have any active threads,
6830 so we don't have any TID numbers the inferior will
6831 understand. Make sure to only send forms that do not specify
6833 append_resumption (p
, endp
, minus_one_ptid
, step
, siggnal
);
6835 else if (scope_ptid
== minus_one_ptid
|| scope_ptid
.is_pid ())
6837 /* Resume all threads (of all processes, or of a single
6838 process), with preference for INFERIOR_PTID. This assumes
6839 inferior_ptid belongs to the set of all threads we are about
6841 if (step
|| siggnal
!= GDB_SIGNAL_0
)
6843 /* Step inferior_ptid, with or without signal. */
6844 p
= append_resumption (p
, endp
, inferior_ptid
, step
, siggnal
);
6847 /* Also pass down any pending signaled resumption for other
6848 threads not the current. */
6849 p
= append_pending_thread_resumptions (p
, endp
, scope_ptid
);
6851 /* And continue others without a signal. */
6852 append_resumption (p
, endp
, scope_ptid
, /*step=*/ 0, GDB_SIGNAL_0
);
6856 /* Scheduler locking; resume only SCOPE_PTID. */
6857 append_resumption (p
, endp
, scope_ptid
, step
, siggnal
);
6860 gdb_assert (strlen (rs
->buf
.data ()) < get_remote_packet_size ());
6863 if (target_is_non_stop_p ())
6865 /* In non-stop, the stub replies to vCont with "OK". The stop
6866 reply will be reported asynchronously by means of a `%Stop'
6869 if (strcmp (rs
->buf
.data (), "OK") != 0)
6870 error (_("Unexpected vCont reply in non-stop mode: %s"),
6877 /* Tell the remote machine to resume. */
6880 remote_target::resume (ptid_t scope_ptid
, int step
, enum gdb_signal siggnal
)
6882 struct remote_state
*rs
= get_remote_state ();
6884 /* When connected in non-stop mode, the core resumes threads
6885 individually. Resuming remote threads directly in target_resume
6886 would thus result in sending one packet per thread. Instead, to
6887 minimize roundtrip latency, here we just store the resume
6888 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6889 resumption will be done in remote_target::commit_resume, where we'll be
6890 able to do vCont action coalescing. */
6891 if (target_is_non_stop_p () && ::execution_direction
!= EXEC_REVERSE
)
6893 remote_thread_info
*remote_thr
6894 = get_remote_thread_info (inferior_thread ());
6896 /* We don't expect the core to ask to resume an already resumed (from
6897 its point of view) thread. */
6898 gdb_assert (remote_thr
->get_resume_state () == resume_state::NOT_RESUMED
);
6900 remote_thr
->set_resumed_pending_vcont (step
, siggnal
);
6902 /* There's actually nothing that says that the core can't
6903 request a wildcard resume in non-stop mode, though. It's
6904 just that we know it doesn't currently, so we don't bother
6906 gdb_assert (scope_ptid
== inferior_ptid
);
6910 commit_requested_thread_options ();
6912 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6913 (explained in remote-notif.c:handle_notification) so
6914 remote_notif_process is not called. We need find a place where
6915 it is safe to start a 'vNotif' sequence. It is good to do it
6916 before resuming inferior, because inferior was stopped and no RSP
6917 traffic at that moment. */
6918 if (!target_is_non_stop_p ())
6919 remote_notif_process (rs
->notif_state
, ¬if_client_stop
);
6921 rs
->last_resume_exec_dir
= ::execution_direction
;
6923 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6924 if (!remote_resume_with_vcont (scope_ptid
, step
, siggnal
))
6925 remote_resume_with_hc (scope_ptid
, step
, siggnal
);
6927 /* Update resumed state tracked by the remote target. */
6928 for (thread_info
*tp
: all_non_exited_threads (this, scope_ptid
))
6929 get_remote_thread_info (tp
)->set_resumed ();
6931 /* We've just told the target to resume. The remote server will
6932 wait for the inferior to stop, and then send a stop reply. In
6933 the mean time, we can't start another command/query ourselves
6934 because the stub wouldn't be ready to process it. This applies
6935 only to the base all-stop protocol, however. In non-stop (which
6936 only supports vCont), the stub replies with an "OK", and is
6937 immediate able to process further serial input. */
6938 if (!target_is_non_stop_p ())
6939 rs
->waiting_for_stop_reply
= 1;
6942 /* Private per-inferior info for target remote processes. */
6944 struct remote_inferior
: public private_inferior
6946 /* Whether we can send a wildcard vCont for this process. */
6947 bool may_wildcard_vcont
= true;
6950 /* Get the remote private inferior data associated to INF. */
6952 static remote_inferior
*
6953 get_remote_inferior (inferior
*inf
)
6955 if (inf
->priv
== NULL
)
6956 inf
->priv
.reset (new remote_inferior
);
6958 return gdb::checked_static_cast
<remote_inferior
*> (inf
->priv
.get ());
6961 /* Class used to track the construction of a vCont packet in the
6962 outgoing packet buffer. This is used to send multiple vCont
6963 packets if we have more actions than would fit a single packet. */
6968 explicit vcont_builder (remote_target
*remote
)
6975 void push_action (ptid_t ptid
, bool step
, gdb_signal siggnal
);
6980 /* The remote target. */
6981 remote_target
*m_remote
;
6983 /* Pointer to the first action. P points here if no action has been
6985 char *m_first_action
;
6987 /* Where the next action will be appended. */
6990 /* The end of the buffer. Must never write past this. */
6994 /* Prepare the outgoing buffer for a new vCont packet. */
6997 vcont_builder::restart ()
6999 struct remote_state
*rs
= m_remote
->get_remote_state ();
7001 m_p
= rs
->buf
.data ();
7002 m_endp
= m_p
+ m_remote
->get_remote_packet_size ();
7003 m_p
+= xsnprintf (m_p
, m_endp
- m_p
, "vCont");
7004 m_first_action
= m_p
;
7007 /* If the vCont packet being built has any action, send it to the
7011 vcont_builder::flush ()
7013 struct remote_state
*rs
;
7015 if (m_p
== m_first_action
)
7018 rs
= m_remote
->get_remote_state ();
7019 m_remote
->putpkt (rs
->buf
);
7020 m_remote
->getpkt (&rs
->buf
);
7021 if (strcmp (rs
->buf
.data (), "OK") != 0)
7022 error (_("Unexpected vCont reply in non-stop mode: %s"), rs
->buf
.data ());
7025 /* The largest action is range-stepping, with its two addresses. This
7026 is more than sufficient. If a new, bigger action is created, it'll
7027 quickly trigger a failed assertion in append_resumption (and we'll
7029 #define MAX_ACTION_SIZE 200
7031 /* Append a new vCont action in the outgoing packet being built. If
7032 the action doesn't fit the packet along with previous actions, push
7033 what we've got so far to the remote end and start over a new vCont
7034 packet (with the new action). */
7037 vcont_builder::push_action (ptid_t ptid
, bool step
, gdb_signal siggnal
)
7039 char buf
[MAX_ACTION_SIZE
+ 1];
7041 char *endp
= m_remote
->append_resumption (buf
, buf
+ sizeof (buf
),
7042 ptid
, step
, siggnal
);
7044 /* Check whether this new action would fit in the vCont packet along
7045 with previous actions. If not, send what we've got so far and
7046 start a new vCont packet. */
7047 size_t rsize
= endp
- buf
;
7048 if (rsize
> m_endp
- m_p
)
7053 /* Should now fit. */
7054 gdb_assert (rsize
<= m_endp
- m_p
);
7057 memcpy (m_p
, buf
, rsize
);
7062 /* to_commit_resume implementation. */
7065 remote_target::commit_resumed ()
7067 /* If connected in all-stop mode, we'd send the remote resume
7068 request directly from remote_resume. Likewise if
7069 reverse-debugging, as there are no defined vCont actions for
7070 reverse execution. */
7071 if (!target_is_non_stop_p () || ::execution_direction
== EXEC_REVERSE
)
7074 commit_requested_thread_options ();
7076 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7077 instead of resuming all threads of each process individually.
7078 However, if any thread of a process must remain halted, we can't
7079 send wildcard resumes and must send one action per thread.
7081 Care must be taken to not resume threads/processes the server
7082 side already told us are stopped, but the core doesn't know about
7083 yet, because the events are still in the vStopped notification
7086 #1 => vCont s:p1.1;c
7088 #3 <= %Stopped T05 p1.1
7093 #8 (infrun handles the stop for p1.1 and continues stepping)
7094 #9 => vCont s:p1.1;c
7096 The last vCont above would resume thread p1.2 by mistake, because
7097 the server has no idea that the event for p1.2 had not been
7100 The server side must similarly ignore resume actions for the
7101 thread that has a pending %Stopped notification (and any other
7102 threads with events pending), until GDB acks the notification
7103 with vStopped. Otherwise, e.g., the following case is
7106 #1 => g (or any other packet)
7108 #3 <= %Stopped T05 p1.2
7109 #4 => vCont s:p1.1;c
7112 Above, the server must not resume thread p1.2. GDB can't know
7113 that p1.2 stopped until it acks the %Stopped notification, and
7114 since from GDB's perspective all threads should be running, it
7117 Finally, special care must also be given to handling fork/vfork
7118 events. A (v)fork event actually tells us that two processes
7119 stopped -- the parent and the child. Until we follow the fork,
7120 we must not resume the child. Therefore, if we have a pending
7121 fork follow, we must not send a global wildcard resume action
7122 (vCont;c). We can still send process-wide wildcards though. */
7124 /* Start by assuming a global wildcard (vCont;c) is possible. */
7125 bool may_global_wildcard_vcont
= true;
7127 /* And assume every process is individually wildcard-able too. */
7128 for (inferior
*inf
: all_non_exited_inferiors (this))
7130 remote_inferior
*priv
= get_remote_inferior (inf
);
7132 priv
->may_wildcard_vcont
= true;
7135 /* Check for any pending events (not reported or processed yet) and
7136 disable process and global wildcard resumes appropriately. */
7137 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont
);
7139 bool any_pending_vcont_resume
= false;
7141 for (thread_info
*tp
: all_non_exited_threads (this))
7143 remote_thread_info
*priv
= get_remote_thread_info (tp
);
7145 /* If a thread of a process is not meant to be resumed, then we
7146 can't wildcard that process. */
7147 if (priv
->get_resume_state () == resume_state::NOT_RESUMED
)
7149 get_remote_inferior (tp
->inf
)->may_wildcard_vcont
= false;
7151 /* And if we can't wildcard a process, we can't wildcard
7152 everything either. */
7153 may_global_wildcard_vcont
= false;
7157 if (priv
->get_resume_state () == resume_state::RESUMED_PENDING_VCONT
)
7158 any_pending_vcont_resume
= true;
7160 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7161 then we can't do a global wildcard, as that would resume the
7163 if (thread_pending_child_status (tp
) != nullptr)
7164 may_global_wildcard_vcont
= false;
7167 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7169 if (!any_pending_vcont_resume
)
7172 /* Now let's build the vCont packet(s). Actions must be appended
7173 from narrower to wider scopes (thread -> process -> global). If
7174 we end up with too many actions for a single packet vcont_builder
7175 flushes the current vCont packet to the remote side and starts a
7177 struct vcont_builder
vcont_builder (this);
7179 /* Threads first. */
7180 for (thread_info
*tp
: all_non_exited_threads (this))
7182 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7184 /* If the thread was previously vCont-resumed, no need to send a specific
7185 action for it. If we didn't receive a resume request for it, don't
7186 send an action for it either. */
7187 if (remote_thr
->get_resume_state () != resume_state::RESUMED_PENDING_VCONT
)
7190 gdb_assert (!thread_is_in_step_over_chain (tp
));
7192 /* We should never be commit-resuming a thread that has a stop reply.
7193 Otherwise, we would end up reporting a stop event for a thread while
7194 it is running on the remote target. */
7195 remote_state
*rs
= get_remote_state ();
7196 for (const auto &stop_reply
: rs
->stop_reply_queue
)
7197 gdb_assert (stop_reply
->ptid
!= tp
->ptid
);
7199 const resumed_pending_vcont_info
&info
7200 = remote_thr
->resumed_pending_vcont_info ();
7202 /* Check if we need to send a specific action for this thread. If not,
7203 it will be included in a wildcard resume instead. */
7204 if (info
.step
|| info
.sig
!= GDB_SIGNAL_0
7205 || !get_remote_inferior (tp
->inf
)->may_wildcard_vcont
)
7206 vcont_builder
.push_action (tp
->ptid
, info
.step
, info
.sig
);
7208 remote_thr
->set_resumed ();
7211 /* Now check whether we can send any process-wide wildcard. This is
7212 to avoid sending a global wildcard in the case nothing is
7213 supposed to be resumed. */
7214 bool any_process_wildcard
= false;
7216 for (inferior
*inf
: all_non_exited_inferiors (this))
7218 if (get_remote_inferior (inf
)->may_wildcard_vcont
)
7220 any_process_wildcard
= true;
7225 if (any_process_wildcard
)
7227 /* If all processes are wildcard-able, then send a single "c"
7228 action, otherwise, send an "all (-1) threads of process"
7229 continue action for each running process, if any. */
7230 if (may_global_wildcard_vcont
)
7232 vcont_builder
.push_action (minus_one_ptid
,
7233 false, GDB_SIGNAL_0
);
7237 for (inferior
*inf
: all_non_exited_inferiors (this))
7239 if (get_remote_inferior (inf
)->may_wildcard_vcont
)
7241 vcont_builder
.push_action (ptid_t (inf
->pid
),
7242 false, GDB_SIGNAL_0
);
7248 vcont_builder
.flush ();
7251 /* Implementation of target_has_pending_events. */
7254 remote_target::has_pending_events ()
7256 if (target_can_async_p ())
7258 remote_state
*rs
= get_remote_state ();
7260 if (rs
->async_event_handler_marked ())
7263 /* Note that BUFCNT can be negative, indicating sticky
7265 if (rs
->remote_desc
->bufcnt
!= 0)
7273 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7274 thread, all threads of a remote process, or all threads of all
7278 remote_target::remote_stop_ns (ptid_t ptid
)
7280 struct remote_state
*rs
= get_remote_state ();
7281 char *p
= rs
->buf
.data ();
7282 char *endp
= p
+ get_remote_packet_size ();
7284 /* If any thread that needs to stop was resumed but pending a vCont
7285 resume, generate a phony stop_reply. However, first check
7286 whether the thread wasn't resumed with a signal. Generating a
7287 phony stop in that case would result in losing the signal. */
7288 bool needs_commit
= false;
7289 for (thread_info
*tp
: all_non_exited_threads (this, ptid
))
7291 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7293 if (remote_thr
->get_resume_state ()
7294 == resume_state::RESUMED_PENDING_VCONT
)
7296 const resumed_pending_vcont_info
&info
7297 = remote_thr
->resumed_pending_vcont_info ();
7298 if (info
.sig
!= GDB_SIGNAL_0
)
7300 /* This signal must be forwarded to the inferior. We
7301 could commit-resume just this thread, but its simpler
7302 to just commit-resume everything. */
7303 needs_commit
= true;
7312 for (thread_info
*tp
: all_non_exited_threads (this, ptid
))
7314 remote_thread_info
*remote_thr
= get_remote_thread_info (tp
);
7316 if (remote_thr
->get_resume_state ()
7317 == resume_state::RESUMED_PENDING_VCONT
)
7319 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7320 "vCont-resume (%d, %ld, %s)", tp
->ptid
.pid(),
7322 pulongest (tp
->ptid
.tid ()));
7324 /* Check that the thread wasn't resumed with a signal.
7325 Generating a phony stop would result in losing the
7327 const resumed_pending_vcont_info
&info
7328 = remote_thr
->resumed_pending_vcont_info ();
7329 gdb_assert (info
.sig
== GDB_SIGNAL_0
);
7331 stop_reply
*sr
= new stop_reply ();
7332 sr
->ptid
= tp
->ptid
;
7334 sr
->ws
.set_stopped (GDB_SIGNAL_0
);
7335 sr
->arch
= tp
->inf
->arch ();
7336 sr
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
7337 sr
->watch_data_address
= 0;
7339 this->push_stop_reply (sr
);
7341 /* Pretend that this thread was actually resumed on the
7342 remote target, then stopped. If we leave it in the
7343 RESUMED_PENDING_VCONT state and the commit_resumed
7344 method is called while the stop reply is still in the
7345 queue, we'll end up reporting a stop event to the core
7346 for that thread while it is running on the remote
7347 target... that would be bad. */
7348 remote_thr
->set_resumed ();
7352 if (!rs
->supports_vCont
.t
)
7353 error (_("Remote server does not support stopping threads"));
7355 if (ptid
== minus_one_ptid
7356 || (!m_features
.remote_multi_process_p () && ptid
.is_pid ()))
7357 p
+= xsnprintf (p
, endp
- p
, "vCont;t");
7362 p
+= xsnprintf (p
, endp
- p
, "vCont;t:");
7365 /* All (-1) threads of process. */
7366 nptid
= ptid_t (ptid
.pid (), -1);
7369 /* Small optimization: if we already have a stop reply for
7370 this thread, no use in telling the stub we want this
7372 if (peek_stop_reply (ptid
))
7378 write_ptid (p
, endp
, nptid
);
7381 /* In non-stop, we get an immediate OK reply. The stop reply will
7382 come in asynchronously by notification. */
7385 if (strcmp (rs
->buf
.data (), "OK") != 0)
7386 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid
).c_str (),
7390 /* All-stop version of target_interrupt. Sends a break or a ^C to
7391 interrupt the remote target. It is undefined which thread of which
7392 process reports the interrupt. */
7395 remote_target::remote_interrupt_as ()
7397 struct remote_state
*rs
= get_remote_state ();
7399 rs
->ctrlc_pending_p
= 1;
7401 /* If the inferior is stopped already, but the core didn't know
7402 about it yet, just ignore the request. The pending stop events
7403 will be collected in remote_wait. */
7404 if (stop_reply_queue_length () > 0)
7407 /* Send interrupt_sequence to remote target. */
7408 send_interrupt_sequence ();
7411 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7412 the remote target. It is undefined which thread of which process
7413 reports the interrupt. Throws an error if the packet is not
7414 supported by the server. */
7417 remote_target::remote_interrupt_ns ()
7419 struct remote_state
*rs
= get_remote_state ();
7420 char *p
= rs
->buf
.data ();
7421 char *endp
= p
+ get_remote_packet_size ();
7423 xsnprintf (p
, endp
- p
, "vCtrlC");
7425 /* In non-stop, we get an immediate OK reply. The stop reply will
7426 come in asynchronously by notification. */
7430 switch (m_features
.packet_ok (rs
->buf
, PACKET_vCtrlC
))
7434 case PACKET_UNKNOWN
:
7435 error (_("No support for interrupting the remote target."));
7437 error (_("Interrupting target failed: %s"), rs
->buf
.data ());
7441 /* Implement the to_stop function for the remote targets. */
7444 remote_target::stop (ptid_t ptid
)
7446 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7448 if (target_is_non_stop_p ())
7449 remote_stop_ns (ptid
);
7452 /* We don't currently have a way to transparently pause the
7453 remote target in all-stop mode. Interrupt it instead. */
7454 remote_interrupt_as ();
7458 /* Implement the to_interrupt function for the remote targets. */
7461 remote_target::interrupt ()
7463 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7465 if (target_is_non_stop_p ())
7466 remote_interrupt_ns ();
7468 remote_interrupt_as ();
7471 /* Implement the to_pass_ctrlc function for the remote targets. */
7474 remote_target::pass_ctrlc ()
7476 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
7478 struct remote_state
*rs
= get_remote_state ();
7480 /* If we're starting up, we're not fully synced yet. Quit
7482 if (rs
->starting_up
)
7484 /* If ^C has already been sent once, offer to disconnect. */
7485 else if (rs
->ctrlc_pending_p
)
7488 target_interrupt ();
7491 /* Ask the user what to do when an interrupt is received. */
7494 remote_target::interrupt_query ()
7496 struct remote_state
*rs
= get_remote_state ();
7498 if (rs
->waiting_for_stop_reply
&& rs
->ctrlc_pending_p
)
7500 if (query (_("The target is not responding to interrupt requests.\n"
7501 "Stop debugging it? ")))
7503 remote_unpush_target (this);
7504 throw_error (TARGET_CLOSE_ERROR
, _("Disconnected from target."));
7509 if (query (_("Interrupted while waiting for the program.\n"
7510 "Give up waiting? ")))
7515 /* Enable/disable target terminal ownership. Most targets can use
7516 terminal groups to control terminal ownership. Remote targets are
7517 different in that explicit transfer of ownership to/from GDB/target
7521 remote_target::terminal_inferior ()
7523 /* NOTE: At this point we could also register our selves as the
7524 recipient of all input. Any characters typed could then be
7525 passed on down to the target. */
7529 remote_target::terminal_ours ()
7534 remote_console_output (const char *msg
)
7538 for (p
= msg
; p
[0] && p
[1]; p
+= 2)
7541 char c
= fromhex (p
[0]) * 16 + fromhex (p
[1]);
7545 gdb_stdtarg
->puts (tb
);
7547 gdb_stdtarg
->flush ();
7550 /* Return the length of the stop reply queue. */
7553 remote_target::stop_reply_queue_length ()
7555 remote_state
*rs
= get_remote_state ();
7556 return rs
->stop_reply_queue
.size ();
7560 remote_notif_stop_parse (remote_target
*remote
,
7561 const notif_client
*self
, const char *buf
,
7562 struct notif_event
*event
)
7564 remote
->remote_parse_stop_reply (buf
, (struct stop_reply
*) event
);
7568 remote_notif_stop_ack (remote_target
*remote
,
7569 const notif_client
*self
, const char *buf
,
7570 struct notif_event
*event
)
7572 struct stop_reply
*stop_reply
= (struct stop_reply
*) event
;
7575 putpkt (remote
, self
->ack_command
);
7577 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7578 the notification. It was left in the queue because we need to
7579 acknowledge it and pull the rest of the notifications out. */
7580 if (stop_reply
->ws
.kind () != TARGET_WAITKIND_IGNORE
)
7581 remote
->push_stop_reply (stop_reply
);
7585 remote_notif_stop_can_get_pending_events (remote_target
*remote
,
7586 const notif_client
*self
)
7588 /* We can't get pending events in remote_notif_process for
7589 notification stop, and we have to do this in remote_wait_ns
7590 instead. If we fetch all queued events from stub, remote stub
7591 may exit and we have no chance to process them back in
7593 remote_state
*rs
= remote
->get_remote_state ();
7594 rs
->mark_async_event_handler ();
7598 stop_reply::~stop_reply ()
7600 for (cached_reg_t
®
: regcache
)
7604 static notif_event_up
7605 remote_notif_stop_alloc_reply ()
7607 return notif_event_up (new struct stop_reply ());
7610 /* A client of notification Stop. */
7612 const notif_client notif_client_stop
=
7616 remote_notif_stop_parse
,
7617 remote_notif_stop_ack
,
7618 remote_notif_stop_can_get_pending_events
,
7619 remote_notif_stop_alloc_reply
,
7623 /* If CONTEXT contains any fork/vfork/clone child threads that have
7624 not been reported yet, remove them from the CONTEXT list. If such
7625 a thread exists it is because we are stopped at a fork/vfork/clone
7626 catchpoint and have not yet called follow_fork/follow_clone, which
7627 will set up the host-side data structures for the new child. */
7630 remote_target::remove_new_children (threads_listing_context
*context
)
7632 const notif_client
*notif
= ¬if_client_stop
;
7634 /* For any threads stopped at a (v)fork/clone event, remove the
7635 corresponding child threads from the CONTEXT list. */
7636 for (thread_info
*thread
: all_non_exited_threads (this))
7638 const target_waitstatus
*ws
= thread_pending_child_status (thread
);
7643 context
->remove_thread (ws
->child_ptid ());
7646 /* Check for any pending (v)fork/clone events (not reported or
7647 processed yet) in process PID and remove those child threads from
7648 the CONTEXT list as well. */
7649 remote_notif_get_pending_events (notif
);
7650 for (auto &event
: get_remote_state ()->stop_reply_queue
)
7651 if (is_new_child_status (event
->ws
.kind ()))
7652 context
->remove_thread (event
->ws
.child_ptid ());
7653 else if (event
->ws
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
7654 context
->remove_thread (event
->ptid
);
7657 /* Check whether any event pending in the vStopped queue would prevent a
7658 global or process wildcard vCont action. Set *may_global_wildcard to
7659 false if we can't do a global wildcard (vCont;c), and clear the event
7660 inferior's may_wildcard_vcont flag if we can't do a process-wide
7661 wildcard resume (vCont;c:pPID.-1). */
7664 remote_target::check_pending_events_prevent_wildcard_vcont
7665 (bool *may_global_wildcard
)
7667 const notif_client
*notif
= ¬if_client_stop
;
7669 remote_notif_get_pending_events (notif
);
7670 for (auto &event
: get_remote_state ()->stop_reply_queue
)
7672 if (event
->ws
.kind () == TARGET_WAITKIND_NO_RESUMED
7673 || event
->ws
.kind () == TARGET_WAITKIND_NO_HISTORY
)
7676 if (event
->ws
.kind () == TARGET_WAITKIND_FORKED
7677 || event
->ws
.kind () == TARGET_WAITKIND_VFORKED
)
7678 *may_global_wildcard
= false;
7680 /* This may be the first time we heard about this process.
7681 Regardless, we must not do a global wildcard resume, otherwise
7682 we'd resume this process too. */
7683 *may_global_wildcard
= false;
7684 if (event
->ptid
!= null_ptid
)
7686 inferior
*inf
= find_inferior_ptid (this, event
->ptid
);
7688 get_remote_inferior (inf
)->may_wildcard_vcont
= false;
7693 /* Discard all pending stop replies of inferior INF. */
7696 remote_target::discard_pending_stop_replies (struct inferior
*inf
)
7698 struct stop_reply
*reply
;
7699 struct remote_state
*rs
= get_remote_state ();
7700 struct remote_notif_state
*rns
= rs
->notif_state
;
7702 /* This function can be notified when an inferior exists. When the
7703 target is not remote, the notification state is NULL. */
7704 if (rs
->remote_desc
== NULL
)
7707 reply
= (struct stop_reply
*) rns
->pending_event
[notif_client_stop
.id
];
7709 /* Discard the in-flight notification. */
7710 if (reply
!= NULL
&& reply
->ptid
.pid () == inf
->pid
)
7712 /* Leave the notification pending, since the server expects that
7713 we acknowledge it with vStopped. But clear its contents, so
7714 that later on when we acknowledge it, we also discard it. */
7716 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7717 reply
->ptid
.to_string().c_str(),
7718 reply
->ws
.to_string ().c_str ());
7719 reply
->ws
.set_ignore ();
7722 /* Discard the stop replies we have already pulled with
7724 auto iter
= std::remove_if (rs
->stop_reply_queue
.begin (),
7725 rs
->stop_reply_queue
.end (),
7726 [=] (const stop_reply_up
&event
)
7728 return event
->ptid
.pid () == inf
->pid
;
7730 for (auto it
= iter
; it
!= rs
->stop_reply_queue
.end (); ++it
)
7732 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7733 (*it
)->ptid
.to_string().c_str(),
7734 (*it
)->ws
.to_string ().c_str ());
7735 rs
->stop_reply_queue
.erase (iter
, rs
->stop_reply_queue
.end ());
7738 /* Discard the stop replies for RS in stop_reply_queue. */
7741 remote_target::discard_pending_stop_replies_in_queue ()
7743 remote_state
*rs
= get_remote_state ();
7745 /* Discard the stop replies we have already pulled with
7747 auto iter
= std::remove_if (rs
->stop_reply_queue
.begin (),
7748 rs
->stop_reply_queue
.end (),
7749 [=] (const stop_reply_up
&event
)
7751 return event
->rs
== rs
;
7753 rs
->stop_reply_queue
.erase (iter
, rs
->stop_reply_queue
.end ());
7756 /* Remove the first reply in 'stop_reply_queue' which matches
7760 remote_target::remote_notif_remove_queued_reply (ptid_t ptid
)
7762 remote_state
*rs
= get_remote_state ();
7764 auto iter
= std::find_if (rs
->stop_reply_queue
.begin (),
7765 rs
->stop_reply_queue
.end (),
7766 [=] (const stop_reply_up
&event
)
7768 return event
->ptid
.matches (ptid
);
7770 struct stop_reply
*result
;
7771 if (iter
== rs
->stop_reply_queue
.end ())
7775 result
= iter
->release ();
7776 rs
->stop_reply_queue
.erase (iter
);
7780 gdb_printf (gdb_stdlog
,
7781 "notif: discard queued event: 'Stop' in %s\n",
7782 ptid
.to_string ().c_str ());
7787 /* Look for a queued stop reply belonging to PTID. If one is found,
7788 remove it from the queue, and return it. Returns NULL if none is
7789 found. If there are still queued events left to process, tell the
7790 event loop to get back to target_wait soon. */
7793 remote_target::queued_stop_reply (ptid_t ptid
)
7795 remote_state
*rs
= get_remote_state ();
7796 struct stop_reply
*r
= remote_notif_remove_queued_reply (ptid
);
7798 if (!rs
->stop_reply_queue
.empty () && target_can_async_p ())
7800 /* There's still at least an event left. */
7801 rs
->mark_async_event_handler ();
7807 /* Push a fully parsed stop reply in the stop reply queue. Since we
7808 know that we now have at least one queued event left to pass to the
7809 core side, tell the event loop to get back to target_wait soon. */
7812 remote_target::push_stop_reply (struct stop_reply
*new_event
)
7814 remote_state
*rs
= get_remote_state ();
7815 rs
->stop_reply_queue
.push_back (stop_reply_up (new_event
));
7818 gdb_printf (gdb_stdlog
,
7819 "notif: push 'Stop' %s to queue %d\n",
7820 new_event
->ptid
.to_string ().c_str (),
7821 int (rs
->stop_reply_queue
.size ()));
7823 /* Mark the pending event queue only if async mode is currently enabled.
7824 If async mode is not currently enabled, then, if it later becomes
7825 enabled, and there are events in this queue, we will mark the event
7826 token at that point, see remote_target::async. */
7827 if (target_is_async_p ())
7828 rs
->mark_async_event_handler ();
7831 /* Returns true if we have a stop reply for PTID. */
7834 remote_target::peek_stop_reply (ptid_t ptid
)
7836 remote_state
*rs
= get_remote_state ();
7837 for (auto &event
: rs
->stop_reply_queue
)
7838 if (ptid
== event
->ptid
7839 && event
->ws
.kind () == TARGET_WAITKIND_STOPPED
)
7844 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7845 starting with P and ending with PEND matches PREFIX. */
7848 strprefix (const char *p
, const char *pend
, const char *prefix
)
7850 for ( ; p
< pend
; p
++, prefix
++)
7853 return *prefix
== '\0';
7856 /* Parse the stop reply in BUF. Either the function succeeds, and the
7857 result is stored in EVENT, or throws an error. */
7860 remote_target::remote_parse_stop_reply (const char *buf
, stop_reply
*event
)
7862 remote_arch_state
*rsa
= NULL
;
7867 event
->ptid
= null_ptid
;
7868 event
->rs
= get_remote_state ();
7869 event
->ws
.set_ignore ();
7870 event
->stop_reason
= TARGET_STOPPED_BY_NO_REASON
;
7871 event
->regcache
.clear ();
7876 case 'T': /* Status with PC, SP, FP, ... */
7877 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7878 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7880 n... = register number
7881 r... = register contents
7884 p
= &buf
[3]; /* after Txx */
7890 p1
= strchr (p
, ':');
7892 error (_("Malformed packet(a) (missing colon): %s\n\
7896 error (_("Malformed packet(a) (missing register number): %s\n\
7900 /* Some "registers" are actually extended stop information.
7901 Note if you're adding a new entry here: GDB 7.9 and
7902 earlier assume that all register "numbers" that start
7903 with an hex digit are real register numbers. Make sure
7904 the server only sends such a packet if it knows the
7905 client understands it. */
7907 if (strprefix (p
, p1
, "thread"))
7908 event
->ptid
= read_ptid (++p1
, &p
);
7909 else if (strprefix (p
, p1
, "syscall_entry"))
7913 p
= unpack_varlen_hex (++p1
, &sysno
);
7914 event
->ws
.set_syscall_entry ((int) sysno
);
7916 else if (strprefix (p
, p1
, "syscall_return"))
7920 p
= unpack_varlen_hex (++p1
, &sysno
);
7921 event
->ws
.set_syscall_return ((int) sysno
);
7923 else if (strprefix (p
, p1
, "watch")
7924 || strprefix (p
, p1
, "rwatch")
7925 || strprefix (p
, p1
, "awatch"))
7927 event
->stop_reason
= TARGET_STOPPED_BY_WATCHPOINT
;
7928 p
= unpack_varlen_hex (++p1
, &addr
);
7929 event
->watch_data_address
= (CORE_ADDR
) addr
;
7931 else if (strprefix (p
, p1
, "swbreak"))
7933 event
->stop_reason
= TARGET_STOPPED_BY_SW_BREAKPOINT
;
7935 /* Make sure the stub doesn't forget to indicate support
7937 if (m_features
.packet_support (PACKET_swbreak_feature
)
7939 error (_("Unexpected swbreak stop reason"));
7941 /* The value part is documented as "must be empty",
7942 though we ignore it, in case we ever decide to make
7943 use of it in a backward compatible way. */
7944 p
= strchrnul (p1
+ 1, ';');
7946 else if (strprefix (p
, p1
, "hwbreak"))
7948 event
->stop_reason
= TARGET_STOPPED_BY_HW_BREAKPOINT
;
7950 /* Make sure the stub doesn't forget to indicate support
7952 if (m_features
.packet_support (PACKET_hwbreak_feature
)
7954 error (_("Unexpected hwbreak stop reason"));
7957 p
= strchrnul (p1
+ 1, ';');
7959 else if (strprefix (p
, p1
, "library"))
7961 event
->ws
.set_loaded ();
7962 p
= strchrnul (p1
+ 1, ';');
7964 else if (strprefix (p
, p1
, "replaylog"))
7966 event
->ws
.set_no_history ();
7967 /* p1 will indicate "begin" or "end", but it makes
7968 no difference for now, so ignore it. */
7969 p
= strchrnul (p1
+ 1, ';');
7971 else if (strprefix (p
, p1
, "core"))
7975 p
= unpack_varlen_hex (++p1
, &c
);
7978 else if (strprefix (p
, p1
, "fork"))
7979 event
->ws
.set_forked (read_ptid (++p1
, &p
));
7980 else if (strprefix (p
, p1
, "vfork"))
7981 event
->ws
.set_vforked (read_ptid (++p1
, &p
));
7982 else if (strprefix (p
, p1
, "clone"))
7983 event
->ws
.set_thread_cloned (read_ptid (++p1
, &p
));
7984 else if (strprefix (p
, p1
, "vforkdone"))
7986 event
->ws
.set_vfork_done ();
7987 p
= strchrnul (p1
+ 1, ';');
7989 else if (strprefix (p
, p1
, "exec"))
7994 /* Determine the length of the execd pathname. */
7995 p
= unpack_varlen_hex (++p1
, &ignored
);
7996 pathlen
= (p
- p1
) / 2;
7998 /* Save the pathname for event reporting and for
7999 the next run command. */
8000 gdb::unique_xmalloc_ptr
<char> pathname
8001 ((char *) xmalloc (pathlen
+ 1));
8002 hex2bin (p1
, (gdb_byte
*) pathname
.get (), pathlen
);
8003 pathname
.get ()[pathlen
] = '\0';
8005 /* This is freed during event handling. */
8006 event
->ws
.set_execd (std::move (pathname
));
8008 /* Skip the registers included in this packet, since
8009 they may be for an architecture different from the
8010 one used by the original program. */
8013 else if (strprefix (p
, p1
, "create"))
8015 event
->ws
.set_thread_created ();
8016 p
= strchrnul (p1
+ 1, ';');
8025 p
= strchrnul (p1
+ 1, ';');
8030 /* Maybe a real ``P'' register number. */
8031 p_temp
= unpack_varlen_hex (p
, &pnum
);
8032 /* If the first invalid character is the colon, we got a
8033 register number. Otherwise, it's an unknown stop
8037 /* If we haven't parsed the event's thread yet, find
8038 it now, in order to find the architecture of the
8039 reported expedited registers. */
8040 if (event
->ptid
== null_ptid
)
8042 /* If there is no thread-id information then leave
8043 the event->ptid as null_ptid. Later in
8044 process_stop_reply we will pick a suitable
8046 const char *thr
= strstr (p1
+ 1, ";thread:");
8048 event
->ptid
= read_ptid (thr
+ strlen (";thread:"),
8055 = (event
->ptid
== null_ptid
8057 : find_inferior_ptid (this, event
->ptid
));
8058 /* If this is the first time we learn anything
8059 about this process, skip the registers
8060 included in this packet, since we don't yet
8061 know which architecture to use to parse them.
8062 We'll determine the architecture later when
8063 we process the stop reply and retrieve the
8064 target description, via
8065 remote_notice_new_inferior ->
8066 post_create_inferior. */
8069 p
= strchrnul (p1
+ 1, ';');
8074 event
->arch
= inf
->arch ();
8075 rsa
= event
->rs
->get_remote_arch_state (event
->arch
);
8079 = packet_reg_from_pnum (event
->arch
, rsa
, pnum
);
8080 cached_reg_t cached_reg
;
8083 error (_("Remote sent bad register number %s: %s\n\
8085 hex_string (pnum
), p
, buf
);
8087 cached_reg
.num
= reg
->regnum
;
8088 cached_reg
.data
= (gdb_byte
*)
8089 xmalloc (register_size (event
->arch
, reg
->regnum
));
8092 fieldsize
= hex2bin (p
, cached_reg
.data
,
8093 register_size (event
->arch
, reg
->regnum
));
8095 if (fieldsize
< register_size (event
->arch
, reg
->regnum
))
8096 warning (_("Remote reply is too short: %s"), buf
);
8098 event
->regcache
.push_back (cached_reg
);
8102 /* Not a number. Silently skip unknown optional
8104 p
= strchrnul (p1
+ 1, ';');
8109 error (_("Remote register badly formatted: %s\nhere: %s"),
8114 if (event
->ws
.kind () != TARGET_WAITKIND_IGNORE
)
8118 case 'S': /* Old style status, just signal only. */
8122 sig
= (fromhex (buf
[1]) << 4) + fromhex (buf
[2]);
8123 if (GDB_SIGNAL_FIRST
<= sig
&& sig
< GDB_SIGNAL_LAST
)
8124 event
->ws
.set_stopped ((enum gdb_signal
) sig
);
8126 event
->ws
.set_stopped (GDB_SIGNAL_UNKNOWN
);
8129 case 'w': /* Thread exited. */
8133 p
= unpack_varlen_hex (&buf
[1], &value
);
8134 event
->ws
.set_thread_exited (value
);
8136 error (_("stop reply packet badly formatted: %s"), buf
);
8137 event
->ptid
= read_ptid (++p
, NULL
);
8140 case 'W': /* Target exited. */
8145 /* GDB used to accept only 2 hex chars here. Stubs should
8146 only send more if they detect GDB supports multi-process
8148 p
= unpack_varlen_hex (&buf
[1], &value
);
8152 /* The remote process exited. */
8153 event
->ws
.set_exited (value
);
8157 /* The remote process exited with a signal. */
8158 if (GDB_SIGNAL_FIRST
<= value
&& value
< GDB_SIGNAL_LAST
)
8159 event
->ws
.set_signalled ((enum gdb_signal
) value
);
8161 event
->ws
.set_signalled (GDB_SIGNAL_UNKNOWN
);
8164 /* If no process is specified, return null_ptid, and let the
8165 caller figure out the right process to use. */
8175 else if (startswith (p
, "process:"))
8179 p
+= sizeof ("process:") - 1;
8180 unpack_varlen_hex (p
, &upid
);
8184 error (_("unknown stop reply packet: %s"), buf
);
8187 error (_("unknown stop reply packet: %s"), buf
);
8188 event
->ptid
= ptid_t (pid
);
8192 event
->ws
.set_no_resumed ();
8193 event
->ptid
= minus_one_ptid
;
8198 /* When the stub wants to tell GDB about a new notification reply, it
8199 sends a notification (%Stop, for example). Those can come it at
8200 any time, hence, we have to make sure that any pending
8201 putpkt/getpkt sequence we're making is finished, before querying
8202 the stub for more events with the corresponding ack command
8203 (vStopped, for example). E.g., if we started a vStopped sequence
8204 immediately upon receiving the notification, something like this
8212 1.6) <-- (registers reply to step #1.3)
8214 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8217 To solve this, whenever we parse a %Stop notification successfully,
8218 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8219 doing whatever we were doing:
8225 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8226 2.5) <-- (registers reply to step #2.3)
8228 Eventually after step #2.5, we return to the event loop, which
8229 notices there's an event on the
8230 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8231 associated callback --- the function below. At this point, we're
8232 always safe to start a vStopped sequence. :
8235 2.7) <-- T05 thread:2
8241 remote_target::remote_notif_get_pending_events (const notif_client
*nc
)
8243 struct remote_state
*rs
= get_remote_state ();
8245 if (rs
->notif_state
->pending_event
[nc
->id
] != NULL
)
8248 gdb_printf (gdb_stdlog
,
8249 "notif: process: '%s' ack pending event\n",
8253 nc
->ack (this, nc
, rs
->buf
.data (),
8254 rs
->notif_state
->pending_event
[nc
->id
]);
8255 rs
->notif_state
->pending_event
[nc
->id
] = NULL
;
8260 if (strcmp (rs
->buf
.data (), "OK") == 0)
8263 remote_notif_ack (this, nc
, rs
->buf
.data ());
8269 gdb_printf (gdb_stdlog
,
8270 "notif: process: '%s' no pending reply\n",
8275 /* Wrapper around remote_target::remote_notif_get_pending_events to
8276 avoid having to export the whole remote_target class. */
8279 remote_notif_get_pending_events (remote_target
*remote
, const notif_client
*nc
)
8281 remote
->remote_notif_get_pending_events (nc
);
8284 /* Called from process_stop_reply when the stop packet we are responding
8285 to didn't include a process-id or thread-id. STATUS is the stop event
8286 we are responding to.
8288 It is the task of this function to select a suitable thread (or process)
8289 and return its ptid, this is the thread (or process) we will assume the
8290 stop event came from.
8292 In some cases there isn't really any choice about which thread (or
8293 process) is selected, a basic remote with a single process containing a
8294 single thread might choose not to send any process-id or thread-id in
8295 its stop packets, this function will select and return the one and only
8298 However, if a target supports multiple threads (or processes) and still
8299 doesn't include a thread-id (or process-id) in its stop packet then
8300 first, this is a badly behaving target, and second, we're going to have
8301 to select a thread (or process) at random and use that. This function
8302 will print a warning to the user if it detects that there is the
8303 possibility that GDB is guessing which thread (or process) to
8306 Note that this is called before GDB fetches the updated thread list from the
8307 target. So it's possible for the stop reply to be ambiguous and for GDB to
8308 not realize it. For example, if there's initially one thread, the target
8309 spawns a second thread, and then sends a stop reply without an id that
8310 concerns the first thread. GDB will assume the stop reply is about the
8311 first thread - the only thread it knows about - without printing a warning.
8312 Anyway, if the remote meant for the stop reply to be about the second thread,
8313 then it would be really broken, because GDB doesn't know about that thread
8317 remote_target::select_thread_for_ambiguous_stop_reply
8318 (const target_waitstatus
&status
)
8320 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8322 /* Some stop events apply to all threads in an inferior, while others
8323 only apply to a single thread. */
8324 bool process_wide_stop
8325 = (status
.kind () == TARGET_WAITKIND_EXITED
8326 || status
.kind () == TARGET_WAITKIND_SIGNALLED
);
8328 remote_debug_printf ("process_wide_stop = %d", process_wide_stop
);
8330 thread_info
*first_resumed_thread
= nullptr;
8331 bool ambiguous
= false;
8333 /* Consider all non-exited threads of the target, find the first resumed
8335 for (thread_info
*thr
: all_non_exited_threads (this))
8337 remote_thread_info
*remote_thr
= get_remote_thread_info (thr
);
8339 if (remote_thr
->get_resume_state () != resume_state::RESUMED
)
8342 if (first_resumed_thread
== nullptr)
8343 first_resumed_thread
= thr
;
8344 else if (!process_wide_stop
8345 || first_resumed_thread
->ptid
.pid () != thr
->ptid
.pid ())
8349 gdb_assert (first_resumed_thread
!= nullptr);
8351 remote_debug_printf ("first resumed thread is %s",
8352 pid_to_str (first_resumed_thread
->ptid
).c_str ());
8353 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous
);
8355 /* Warn if the remote target is sending ambiguous stop replies. */
8358 static bool warned
= false;
8362 /* If you are seeing this warning then the remote target has
8363 stopped without specifying a thread-id, but the target
8364 does have multiple threads (or inferiors), and so GDB is
8365 having to guess which thread stopped.
8367 Examples of what might cause this are the target sending
8368 and 'S' stop packet, or a 'T' stop packet and not
8369 including a thread-id.
8371 Additionally, the target might send a 'W' or 'X packet
8372 without including a process-id, when the target has
8373 multiple running inferiors. */
8374 if (process_wide_stop
)
8375 warning (_("multi-inferior target stopped without "
8376 "sending a process-id, using first "
8377 "non-exited inferior"));
8379 warning (_("multi-threaded target stopped without "
8380 "sending a thread-id, using first "
8381 "non-exited thread"));
8386 /* If this is a stop for all threads then don't use a particular threads
8387 ptid, instead create a new ptid where only the pid field is set. */
8388 if (process_wide_stop
)
8389 return ptid_t (first_resumed_thread
->ptid
.pid ());
8391 return first_resumed_thread
->ptid
;
8394 /* Called when it is decided that STOP_REPLY holds the info of the
8395 event that is to be returned to the core. This function always
8396 destroys STOP_REPLY. */
8399 remote_target::process_stop_reply (struct stop_reply
*stop_reply
,
8400 struct target_waitstatus
*status
)
8402 *status
= stop_reply
->ws
;
8403 ptid_t ptid
= stop_reply
->ptid
;
8405 /* If no thread/process was reported by the stub then select a suitable
8407 if (ptid
== null_ptid
)
8408 ptid
= select_thread_for_ambiguous_stop_reply (*status
);
8409 gdb_assert (ptid
!= null_ptid
);
8411 if (status
->kind () != TARGET_WAITKIND_EXITED
8412 && status
->kind () != TARGET_WAITKIND_SIGNALLED
8413 && status
->kind () != TARGET_WAITKIND_NO_RESUMED
)
8415 /* Expedited registers. */
8416 if (!stop_reply
->regcache
.empty ())
8418 /* 'w' stop replies don't cary expedited registers (which
8419 wouldn't make any sense for a thread that is gone
8421 gdb_assert (status
->kind () != TARGET_WAITKIND_THREAD_EXITED
);
8423 struct regcache
*regcache
8424 = get_thread_arch_regcache (this, ptid
, stop_reply
->arch
);
8426 for (cached_reg_t
®
: stop_reply
->regcache
)
8428 regcache
->raw_supply (reg
.num
, reg
.data
);
8432 stop_reply
->regcache
.clear ();
8435 remote_notice_new_inferior (ptid
, false);
8436 remote_thread_info
*remote_thr
= get_remote_thread_info (this, ptid
);
8437 remote_thr
->core
= stop_reply
->core
;
8438 remote_thr
->stop_reason
= stop_reply
->stop_reason
;
8439 remote_thr
->watch_data_address
= stop_reply
->watch_data_address
;
8441 if (target_is_non_stop_p ())
8443 /* If the target works in non-stop mode, a stop-reply indicates that
8444 only this thread stopped. */
8445 remote_thr
->set_not_resumed ();
8449 /* If the target works in all-stop mode, a stop-reply indicates that
8450 all the target's threads stopped. */
8451 for (thread_info
*tp
: all_non_exited_threads (this))
8452 get_remote_thread_info (tp
)->set_not_resumed ();
8460 /* The non-stop mode version of target_wait. */
8463 remote_target::wait_ns (ptid_t ptid
, struct target_waitstatus
*status
,
8464 target_wait_flags options
)
8466 struct remote_state
*rs
= get_remote_state ();
8467 struct stop_reply
*stop_reply
;
8469 bool is_notif
= false;
8471 /* If in non-stop mode, get out of getpkt even if a
8472 notification is received. */
8474 ret
= getpkt (&rs
->buf
, false /* forever */, &is_notif
);
8477 if (ret
!= -1 && !is_notif
)
8480 case 'E': /* Error of some sort. */
8481 /* We're out of sync with the target now. Did it continue
8482 or not? We can't tell which thread it was in non-stop,
8483 so just ignore this. */
8484 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
8486 case 'O': /* Console output. */
8487 remote_console_output (&rs
->buf
[1]);
8490 warning (_("Invalid remote reply: %s"), rs
->buf
.data ());
8494 /* Acknowledge a pending stop reply that may have arrived in the
8496 if (rs
->notif_state
->pending_event
[notif_client_stop
.id
] != NULL
)
8497 remote_notif_get_pending_events (¬if_client_stop
);
8499 /* If indeed we noticed a stop reply, we're done. */
8500 stop_reply
= queued_stop_reply (ptid
);
8501 if (stop_reply
!= NULL
)
8502 return process_stop_reply (stop_reply
, status
);
8504 /* Still no event. If we're just polling for an event, then
8505 return to the event loop. */
8506 if (options
& TARGET_WNOHANG
)
8508 status
->set_ignore ();
8509 return minus_one_ptid
;
8512 /* Otherwise do a blocking wait. */
8513 ret
= getpkt (&rs
->buf
, true /* forever */, &is_notif
);
8517 /* Return the first resumed thread. */
8520 first_remote_resumed_thread (remote_target
*target
)
8522 for (thread_info
*tp
: all_non_exited_threads (target
, minus_one_ptid
))
8528 /* Wait until the remote machine stops, then return, storing status in
8529 STATUS just as `wait' would. */
8532 remote_target::wait_as (ptid_t ptid
, target_waitstatus
*status
,
8533 target_wait_flags options
)
8535 struct remote_state
*rs
= get_remote_state ();
8536 ptid_t event_ptid
= null_ptid
;
8538 struct stop_reply
*stop_reply
;
8542 status
->set_ignore ();
8544 stop_reply
= queued_stop_reply (ptid
);
8545 if (stop_reply
!= NULL
)
8547 /* None of the paths that push a stop reply onto the queue should
8548 have set the waiting_for_stop_reply flag. */
8549 gdb_assert (!rs
->waiting_for_stop_reply
);
8550 event_ptid
= process_stop_reply (stop_reply
, status
);
8554 bool forever
= ((options
& TARGET_WNOHANG
) == 0
8555 && rs
->wait_forever_enabled_p
);
8557 if (!rs
->waiting_for_stop_reply
)
8559 status
->set_no_resumed ();
8560 return minus_one_ptid
;
8563 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8564 _never_ wait for ever -> test on target_is_async_p().
8565 However, before we do that we need to ensure that the caller
8566 knows how to take the target into/out of async mode. */
8568 int ret
= getpkt (&rs
->buf
, forever
, &is_notif
);
8570 /* GDB gets a notification. Return to core as this event is
8572 if (ret
!= -1 && is_notif
)
8573 return minus_one_ptid
;
8575 if (ret
== -1 && (options
& TARGET_WNOHANG
) != 0)
8576 return minus_one_ptid
;
8578 buf
= rs
->buf
.data ();
8580 /* Assume that the target has acknowledged Ctrl-C unless we receive
8581 an 'F' or 'O' packet. */
8582 if (buf
[0] != 'F' && buf
[0] != 'O')
8583 rs
->ctrlc_pending_p
= 0;
8587 case 'E': /* Error of some sort. */
8588 /* We're out of sync with the target now. Did it continue or
8589 not? Not is more likely, so report a stop. */
8590 rs
->waiting_for_stop_reply
= 0;
8592 warning (_("Remote failure reply: %s"), buf
);
8593 status
->set_stopped (GDB_SIGNAL_0
);
8595 case 'F': /* File-I/O request. */
8596 /* GDB may access the inferior memory while handling the File-I/O
8597 request, but we don't want GDB accessing memory while waiting
8598 for a stop reply. See the comments in putpkt_binary. Set
8599 waiting_for_stop_reply to 0 temporarily. */
8600 rs
->waiting_for_stop_reply
= 0;
8601 remote_fileio_request (this, buf
, rs
->ctrlc_pending_p
);
8602 rs
->ctrlc_pending_p
= 0;
8603 /* GDB handled the File-I/O request, and the target is running
8604 again. Keep waiting for events. */
8605 rs
->waiting_for_stop_reply
= 1;
8607 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8609 /* There is a stop reply to handle. */
8610 rs
->waiting_for_stop_reply
= 0;
8613 = (struct stop_reply
*) remote_notif_parse (this,
8617 event_ptid
= process_stop_reply (stop_reply
, status
);
8620 case 'O': /* Console output. */
8621 remote_console_output (buf
+ 1);
8624 if (rs
->last_sent_signal
!= GDB_SIGNAL_0
)
8626 /* Zero length reply means that we tried 'S' or 'C' and the
8627 remote system doesn't support it. */
8628 target_terminal::ours_for_output ();
8630 ("Can't send signals to this remote system. %s not sent.\n",
8631 gdb_signal_to_name (rs
->last_sent_signal
));
8632 rs
->last_sent_signal
= GDB_SIGNAL_0
;
8633 target_terminal::inferior ();
8635 strcpy (buf
, rs
->last_sent_step
? "s" : "c");
8641 warning (_("Invalid remote reply: %s"), buf
);
8646 if (status
->kind () == TARGET_WAITKIND_NO_RESUMED
)
8647 return minus_one_ptid
;
8648 else if (status
->kind () == TARGET_WAITKIND_IGNORE
)
8650 /* Nothing interesting happened. If we're doing a non-blocking
8651 poll, we're done. Otherwise, go back to waiting. */
8652 if (options
& TARGET_WNOHANG
)
8653 return minus_one_ptid
;
8657 else if (status
->kind () != TARGET_WAITKIND_EXITED
8658 && status
->kind () != TARGET_WAITKIND_SIGNALLED
)
8660 if (event_ptid
!= null_ptid
)
8661 record_currthread (rs
, event_ptid
);
8663 event_ptid
= first_remote_resumed_thread (this);
8667 /* A process exit. Invalidate our notion of current thread. */
8668 record_currthread (rs
, minus_one_ptid
);
8669 /* It's possible that the packet did not include a pid. */
8670 if (event_ptid
== null_ptid
)
8671 event_ptid
= first_remote_resumed_thread (this);
8672 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8673 if (event_ptid
== null_ptid
)
8674 event_ptid
= magic_null_ptid
;
8680 /* Wait until the remote machine stops, then return, storing status in
8681 STATUS just as `wait' would. */
8684 remote_target::wait (ptid_t ptid
, struct target_waitstatus
*status
,
8685 target_wait_flags options
)
8687 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8689 remote_state
*rs
= get_remote_state ();
8691 /* Start by clearing the flag that asks for our wait method to be called,
8692 we'll mark it again at the end if needed. If the target is not in
8693 async mode then the async token should not be marked. */
8694 if (target_is_async_p ())
8695 rs
->clear_async_event_handler ();
8697 gdb_assert (!rs
->async_event_handler_marked ());
8701 if (target_is_non_stop_p ())
8702 event_ptid
= wait_ns (ptid
, status
, options
);
8704 event_ptid
= wait_as (ptid
, status
, options
);
8706 if (target_is_async_p ())
8708 /* If there are events left in the queue, or unacknowledged
8709 notifications, then tell the event loop to call us again. */
8710 if (!rs
->stop_reply_queue
.empty ()
8711 || rs
->notif_state
->pending_event
[notif_client_stop
.id
] != nullptr)
8712 rs
->mark_async_event_handler ();
8718 /* Fetch a single register using a 'p' packet. */
8721 remote_target::fetch_register_using_p (struct regcache
*regcache
,
8724 struct gdbarch
*gdbarch
= regcache
->arch ();
8725 struct remote_state
*rs
= get_remote_state ();
8727 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
8730 if (m_features
.packet_support (PACKET_p
) == PACKET_DISABLE
)
8733 if (reg
->pnum
== -1)
8736 p
= rs
->buf
.data ();
8738 p
+= hexnumstr (p
, reg
->pnum
);
8743 buf
= rs
->buf
.data ();
8745 switch (m_features
.packet_ok (rs
->buf
, PACKET_p
))
8749 case PACKET_UNKNOWN
:
8752 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8753 gdbarch_register_name (regcache
->arch (), reg
->regnum
),
8757 /* If this register is unfetchable, tell the regcache. */
8760 regcache
->raw_supply (reg
->regnum
, NULL
);
8764 /* Otherwise, parse and supply the value. */
8770 error (_("fetch_register_using_p: early buf termination"));
8772 regp
[i
++] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8775 regcache
->raw_supply (reg
->regnum
, regp
);
8779 /* Fetch the registers included in the target's 'g' packet. */
8782 remote_target::send_g_packet ()
8784 struct remote_state
*rs
= get_remote_state ();
8787 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "g");
8790 if (packet_check_result (rs
->buf
) == PACKET_ERROR
)
8791 error (_("Could not read registers; remote failure reply '%s'"),
8794 /* We can get out of synch in various cases. If the first character
8795 in the buffer is not a hex character, assume that has happened
8796 and try to fetch another packet to read. */
8797 while ((rs
->buf
[0] < '0' || rs
->buf
[0] > '9')
8798 && (rs
->buf
[0] < 'A' || rs
->buf
[0] > 'F')
8799 && (rs
->buf
[0] < 'a' || rs
->buf
[0] > 'f')
8800 && rs
->buf
[0] != 'x') /* New: unavailable register value. */
8802 remote_debug_printf ("Bad register packet; fetching a new packet");
8806 buf_len
= strlen (rs
->buf
.data ());
8808 /* Sanity check the received packet. */
8809 if (buf_len
% 2 != 0)
8810 error (_("Remote 'g' packet reply is of odd length: %s"), rs
->buf
.data ());
8816 remote_target::process_g_packet (struct regcache
*regcache
)
8818 struct gdbarch
*gdbarch
= regcache
->arch ();
8819 struct remote_state
*rs
= get_remote_state ();
8820 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8825 buf_len
= strlen (rs
->buf
.data ());
8827 /* Further sanity checks, with knowledge of the architecture. */
8828 if (buf_len
> 2 * rsa
->sizeof_g_packet
)
8829 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8831 rsa
->sizeof_g_packet
, buf_len
/ 2,
8834 /* Save the size of the packet sent to us by the target. It is used
8835 as a heuristic when determining the max size of packets that the
8836 target can safely receive. */
8837 if (rsa
->actual_register_packet_size
== 0)
8838 rsa
->actual_register_packet_size
= buf_len
;
8840 /* If this is smaller than we guessed the 'g' packet would be,
8841 update our records. A 'g' reply that doesn't include a register's
8842 value implies either that the register is not available, or that
8843 the 'p' packet must be used. */
8844 if (buf_len
< 2 * rsa
->sizeof_g_packet
)
8846 long sizeof_g_packet
= buf_len
/ 2;
8848 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8850 long offset
= rsa
->regs
[i
].offset
;
8851 long reg_size
= register_size (gdbarch
, i
);
8853 if (rsa
->regs
[i
].pnum
== -1)
8856 if (offset
>= sizeof_g_packet
)
8857 rsa
->regs
[i
].in_g_packet
= 0;
8858 else if (offset
+ reg_size
> sizeof_g_packet
)
8859 error (_("Truncated register %d in remote 'g' packet"), i
);
8861 rsa
->regs
[i
].in_g_packet
= 1;
8864 /* Looks valid enough, we can assume this is the correct length
8865 for a 'g' packet. It's important not to adjust
8866 rsa->sizeof_g_packet if we have truncated registers otherwise
8867 this "if" won't be run the next time the method is called
8868 with a packet of the same size and one of the internal errors
8869 below will trigger instead. */
8870 rsa
->sizeof_g_packet
= sizeof_g_packet
;
8873 regs
= (char *) alloca (rsa
->sizeof_g_packet
);
8875 /* Unimplemented registers read as all bits zero. */
8876 memset (regs
, 0, rsa
->sizeof_g_packet
);
8878 /* Reply describes registers byte by byte, each byte encoded as two
8879 hex characters. Suck them all up, then supply them to the
8880 register cacheing/storage mechanism. */
8882 p
= rs
->buf
.data ();
8883 for (i
= 0; i
< rsa
->sizeof_g_packet
; i
++)
8885 if (p
[0] == 0 || p
[1] == 0)
8886 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8887 internal_error (_("unexpected end of 'g' packet reply"));
8889 if (p
[0] == 'x' && p
[1] == 'x')
8890 regs
[i
] = 0; /* 'x' */
8892 regs
[i
] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8896 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8898 struct packet_reg
*r
= &rsa
->regs
[i
];
8899 long reg_size
= register_size (gdbarch
, i
);
8903 if ((r
->offset
+ reg_size
) * 2 > strlen (rs
->buf
.data ()))
8904 /* This shouldn't happen - we adjusted in_g_packet above. */
8905 internal_error (_("unexpected end of 'g' packet reply"));
8906 else if (rs
->buf
[r
->offset
* 2] == 'x')
8908 gdb_assert (r
->offset
* 2 < strlen (rs
->buf
.data ()));
8909 /* The register isn't available, mark it as such (at
8910 the same time setting the value to zero). */
8911 regcache
->raw_supply (r
->regnum
, NULL
);
8914 regcache
->raw_supply (r
->regnum
, regs
+ r
->offset
);
8920 remote_target::fetch_registers_using_g (struct regcache
*regcache
)
8923 process_g_packet (regcache
);
8926 /* Make the remote selected traceframe match GDB's selected
8930 remote_target::set_remote_traceframe ()
8933 struct remote_state
*rs
= get_remote_state ();
8935 if (rs
->remote_traceframe_number
== get_traceframe_number ())
8938 /* Avoid recursion, remote_trace_find calls us again. */
8939 rs
->remote_traceframe_number
= get_traceframe_number ();
8941 newnum
= target_trace_find (tfind_number
,
8942 get_traceframe_number (), 0, 0, NULL
);
8944 /* Should not happen. If it does, all bets are off. */
8945 if (newnum
!= get_traceframe_number ())
8946 warning (_("could not set remote traceframe"));
8950 remote_target::fetch_registers (struct regcache
*regcache
, int regnum
)
8952 struct gdbarch
*gdbarch
= regcache
->arch ();
8953 struct remote_state
*rs
= get_remote_state ();
8954 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8957 set_remote_traceframe ();
8958 set_general_thread (regcache
->ptid ());
8962 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
8964 gdb_assert (reg
!= NULL
);
8966 /* If this register might be in the 'g' packet, try that first -
8967 we are likely to read more than one register. If this is the
8968 first 'g' packet, we might be overly optimistic about its
8969 contents, so fall back to 'p'. */
8970 if (reg
->in_g_packet
)
8972 fetch_registers_using_g (regcache
);
8973 if (reg
->in_g_packet
)
8977 if (fetch_register_using_p (regcache
, reg
))
8980 /* This register is not available. */
8981 regcache
->raw_supply (reg
->regnum
, NULL
);
8986 fetch_registers_using_g (regcache
);
8988 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8989 if (!rsa
->regs
[i
].in_g_packet
)
8990 if (!fetch_register_using_p (regcache
, &rsa
->regs
[i
]))
8992 /* This register is not available. */
8993 regcache
->raw_supply (i
, NULL
);
8997 /* Prepare to store registers. Since we may send them all (using a
8998 'G' request), we have to read out the ones we don't want to change
9002 remote_target::prepare_to_store (struct regcache
*regcache
)
9004 struct remote_state
*rs
= get_remote_state ();
9005 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9008 /* Make sure the entire registers array is valid. */
9009 switch (m_features
.packet_support (PACKET_P
))
9011 case PACKET_DISABLE
:
9012 case PACKET_SUPPORT_UNKNOWN
:
9013 /* Make sure all the necessary registers are cached. */
9014 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9015 if (rsa
->regs
[i
].in_g_packet
)
9016 regcache
->raw_update (rsa
->regs
[i
].regnum
);
9023 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9024 packet was not recognized. */
9027 remote_target::store_register_using_P (const struct regcache
*regcache
,
9030 struct gdbarch
*gdbarch
= regcache
->arch ();
9031 struct remote_state
*rs
= get_remote_state ();
9032 /* Try storing a single register. */
9033 char *buf
= rs
->buf
.data ();
9034 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
9037 if (m_features
.packet_support (PACKET_P
) == PACKET_DISABLE
)
9040 if (reg
->pnum
== -1)
9043 xsnprintf (buf
, get_remote_packet_size (), "P%s=", phex_nz (reg
->pnum
, 0));
9044 p
= buf
+ strlen (buf
);
9045 regcache
->raw_collect (reg
->regnum
, regp
);
9046 bin2hex (regp
, p
, register_size (gdbarch
, reg
->regnum
));
9050 switch (m_features
.packet_ok (rs
->buf
, PACKET_P
))
9055 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9056 gdbarch_register_name (gdbarch
, reg
->regnum
), rs
->buf
.data ());
9057 case PACKET_UNKNOWN
:
9060 internal_error (_("Bad result from packet_ok"));
9064 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9065 contents of the register cache buffer. FIXME: ignores errors. */
9068 remote_target::store_registers_using_G (const struct regcache
*regcache
)
9070 struct remote_state
*rs
= get_remote_state ();
9071 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9075 /* Extract all the registers in the regcache copying them into a
9080 regs
= (gdb_byte
*) alloca (rsa
->sizeof_g_packet
);
9081 memset (regs
, 0, rsa
->sizeof_g_packet
);
9082 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9084 struct packet_reg
*r
= &rsa
->regs
[i
];
9087 regcache
->raw_collect (r
->regnum
, regs
+ r
->offset
);
9091 /* Command describes registers byte by byte,
9092 each byte encoded as two hex characters. */
9093 p
= rs
->buf
.data ();
9095 bin2hex (regs
, p
, rsa
->sizeof_g_packet
);
9098 if (packet_check_result (rs
->buf
) == PACKET_ERROR
)
9099 error (_("Could not write registers; remote failure reply '%s'"),
9103 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9104 of the register cache buffer. FIXME: ignores errors. */
9107 remote_target::store_registers (struct regcache
*regcache
, int regnum
)
9109 struct gdbarch
*gdbarch
= regcache
->arch ();
9110 struct remote_state
*rs
= get_remote_state ();
9111 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
9114 set_remote_traceframe ();
9115 set_general_thread (regcache
->ptid ());
9119 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
9121 gdb_assert (reg
!= NULL
);
9123 /* Always prefer to store registers using the 'P' packet if
9124 possible; we often change only a small number of registers.
9125 Sometimes we change a larger number; we'd need help from a
9126 higher layer to know to use 'G'. */
9127 if (store_register_using_P (regcache
, reg
))
9130 /* For now, don't complain if we have no way to write the
9131 register. GDB loses track of unavailable registers too
9132 easily. Some day, this may be an error. We don't have
9133 any way to read the register, either... */
9134 if (!reg
->in_g_packet
)
9137 store_registers_using_G (regcache
);
9141 store_registers_using_G (regcache
);
9143 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9144 if (!rsa
->regs
[i
].in_g_packet
)
9145 if (!store_register_using_P (regcache
, &rsa
->regs
[i
]))
9146 /* See above for why we do not issue an error here. */
9151 /* Return the number of hex digits in num. */
9154 hexnumlen (ULONGEST num
)
9158 for (i
= 0; num
!= 0; i
++)
9161 return std::max (i
, 1);
9164 /* Set BUF to the minimum number of hex digits representing NUM. */
9167 hexnumstr (char *buf
, ULONGEST num
)
9169 int len
= hexnumlen (num
);
9171 return hexnumnstr (buf
, num
, len
);
9175 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9178 hexnumnstr (char *buf
, ULONGEST num
, int width
)
9184 for (i
= width
- 1; i
>= 0; i
--)
9186 buf
[i
] = "0123456789abcdef"[(num
& 0xf)];
9193 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9196 remote_address_masked (CORE_ADDR addr
)
9198 unsigned int address_size
= remote_address_size
;
9200 /* If "remoteaddresssize" was not set, default to target address size. */
9202 address_size
= gdbarch_addr_bit (current_inferior ()->arch ());
9204 if (address_size
> 0
9205 && address_size
< (sizeof (ULONGEST
) * 8))
9207 /* Only create a mask when that mask can safely be constructed
9208 in a ULONGEST variable. */
9211 mask
= (mask
<< address_size
) - 1;
9217 /* Determine whether the remote target supports binary downloading.
9218 This is accomplished by sending a no-op memory write of zero length
9219 to the target at the specified address. It does not suffice to send
9220 the whole packet, since many stubs strip the eighth bit and
9221 subsequently compute a wrong checksum, which causes real havoc with
9224 NOTE: This can still lose if the serial line is not eight-bit
9225 clean. In cases like this, the user should clear "remote
9229 remote_target::check_binary_download (CORE_ADDR addr
)
9231 struct remote_state
*rs
= get_remote_state ();
9233 switch (m_features
.packet_support (PACKET_X
))
9235 case PACKET_DISABLE
:
9239 case PACKET_SUPPORT_UNKNOWN
:
9243 p
= rs
->buf
.data ();
9245 p
+= hexnumstr (p
, (ULONGEST
) addr
);
9247 p
+= hexnumstr (p
, (ULONGEST
) 0);
9251 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9254 if (rs
->buf
[0] == '\0')
9256 remote_debug_printf ("binary downloading NOT supported by target");
9257 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_DISABLE
;
9261 remote_debug_printf ("binary downloading supported by target");
9262 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_ENABLE
;
9269 /* Helper function to resize the payload in order to try to get a good
9270 alignment. We try to write an amount of data such that the next write will
9271 start on an address aligned on REMOTE_ALIGN_WRITES. */
9274 align_for_efficient_write (int todo
, CORE_ADDR memaddr
)
9276 return ((memaddr
+ todo
) & ~(REMOTE_ALIGN_WRITES
- 1)) - memaddr
;
9279 /* Write memory data directly to the remote machine.
9280 This does not inform the data cache; the data cache uses this.
9281 HEADER is the starting part of the packet.
9282 MEMADDR is the address in the remote memory space.
9283 MYADDR is the address of the buffer in our space.
9284 LEN_UNITS is the number of addressable units to write.
9285 UNIT_SIZE is the length in bytes of an addressable unit.
9286 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9287 should send data as binary ('X'), or hex-encoded ('M').
9289 The function creates packet of the form
9290 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9292 where encoding of <DATA> is terminated by PACKET_FORMAT.
9294 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9297 Return the transferred status, error or OK (an
9298 'enum target_xfer_status' value). Save the number of addressable units
9299 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9301 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9302 exchange between gdb and the stub could look like (?? in place of the
9308 -> $M1000,3:eeeeffffeeee#??
9312 <- eeeeffffeeeedddd */
9315 remote_target::remote_write_bytes_aux (const char *header
, CORE_ADDR memaddr
,
9316 const gdb_byte
*myaddr
,
9319 ULONGEST
*xfered_len_units
,
9320 char packet_format
, int use_length
)
9322 struct remote_state
*rs
= get_remote_state ();
9328 int payload_capacity_bytes
;
9329 int payload_length_bytes
;
9331 if (packet_format
!= 'X' && packet_format
!= 'M')
9332 internal_error (_("remote_write_bytes_aux: bad packet format"));
9335 return TARGET_XFER_EOF
;
9337 payload_capacity_bytes
= get_memory_write_packet_size ();
9339 /* The packet buffer will be large enough for the payload;
9340 get_memory_packet_size ensures this. */
9343 /* Compute the size of the actual payload by subtracting out the
9344 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9346 payload_capacity_bytes
-= strlen ("$,:#NN");
9348 /* The comma won't be used. */
9349 payload_capacity_bytes
+= 1;
9350 payload_capacity_bytes
-= strlen (header
);
9351 payload_capacity_bytes
-= hexnumlen (memaddr
);
9353 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9355 strcat (rs
->buf
.data (), header
);
9356 p
= rs
->buf
.data () + strlen (header
);
9358 /* Compute a best guess of the number of bytes actually transfered. */
9359 if (packet_format
== 'X')
9361 /* Best guess at number of bytes that will fit. */
9362 todo_units
= std::min (len_units
,
9363 (ULONGEST
) payload_capacity_bytes
/ unit_size
);
9365 payload_capacity_bytes
-= hexnumlen (todo_units
);
9366 todo_units
= std::min (todo_units
, payload_capacity_bytes
/ unit_size
);
9370 /* Number of bytes that will fit. */
9372 = std::min (len_units
,
9373 (ULONGEST
) (payload_capacity_bytes
/ unit_size
) / 2);
9375 payload_capacity_bytes
-= hexnumlen (todo_units
);
9376 todo_units
= std::min (todo_units
,
9377 (payload_capacity_bytes
/ unit_size
) / 2);
9380 if (todo_units
<= 0)
9381 internal_error (_("minimum packet size too small to write data"));
9383 /* If we already need another packet, then try to align the end
9384 of this packet to a useful boundary. */
9385 if (todo_units
> 2 * REMOTE_ALIGN_WRITES
&& todo_units
< len_units
)
9386 todo_units
= align_for_efficient_write (todo_units
, memaddr
);
9388 /* Append "<memaddr>". */
9389 memaddr
= remote_address_masked (memaddr
);
9390 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9397 /* Append the length and retain its location and size. It may need to be
9398 adjusted once the packet body has been created. */
9400 plenlen
= hexnumstr (p
, (ULONGEST
) todo_units
);
9408 /* Append the packet body. */
9409 if (packet_format
== 'X')
9411 /* Binary mode. Send target system values byte by byte, in
9412 increasing byte addresses. Only escape certain critical
9414 payload_length_bytes
=
9415 remote_escape_output (myaddr
, todo_units
, unit_size
, (gdb_byte
*) p
,
9416 &units_written
, payload_capacity_bytes
);
9418 /* If not all TODO units fit, then we'll need another packet. Make
9419 a second try to keep the end of the packet aligned. Don't do
9420 this if the packet is tiny. */
9421 if (units_written
< todo_units
&& units_written
> 2 * REMOTE_ALIGN_WRITES
)
9425 new_todo_units
= align_for_efficient_write (units_written
, memaddr
);
9427 if (new_todo_units
!= units_written
)
9428 payload_length_bytes
=
9429 remote_escape_output (myaddr
, new_todo_units
, unit_size
,
9430 (gdb_byte
*) p
, &units_written
,
9431 payload_capacity_bytes
);
9434 p
+= payload_length_bytes
;
9435 if (use_length
&& units_written
< todo_units
)
9437 /* Escape chars have filled up the buffer prematurely,
9438 and we have actually sent fewer units than planned.
9439 Fix-up the length field of the packet. Use the same
9440 number of characters as before. */
9441 plen
+= hexnumnstr (plen
, (ULONGEST
) units_written
,
9443 *plen
= ':'; /* overwrite \0 from hexnumnstr() */
9448 /* Normal mode: Send target system values byte by byte, in
9449 increasing byte addresses. Each byte is encoded as a two hex
9451 p
+= 2 * bin2hex (myaddr
, p
, todo_units
* unit_size
);
9452 units_written
= todo_units
;
9455 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9458 if (rs
->buf
[0] == 'E')
9459 return TARGET_XFER_E_IO
;
9461 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9462 send fewer units than we'd planned. */
9463 *xfered_len_units
= (ULONGEST
) units_written
;
9464 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9467 /* Write memory data directly to the remote machine.
9468 This does not inform the data cache; the data cache uses this.
9469 MEMADDR is the address in the remote memory space.
9470 MYADDR is the address of the buffer in our space.
9471 LEN is the number of bytes.
9473 Return the transferred status, error or OK (an
9474 'enum target_xfer_status' value). Save the number of bytes
9475 transferred in *XFERED_LEN. Only transfer a single packet. */
9478 remote_target::remote_write_bytes (CORE_ADDR memaddr
, const gdb_byte
*myaddr
,
9479 ULONGEST len
, int unit_size
,
9480 ULONGEST
*xfered_len
)
9482 const char *packet_format
= NULL
;
9484 /* Check whether the target supports binary download. */
9485 check_binary_download (memaddr
);
9487 switch (m_features
.packet_support (PACKET_X
))
9490 packet_format
= "X";
9492 case PACKET_DISABLE
:
9493 packet_format
= "M";
9495 case PACKET_SUPPORT_UNKNOWN
:
9496 internal_error (_("remote_write_bytes: bad internal state"));
9498 internal_error (_("bad switch"));
9501 return remote_write_bytes_aux (packet_format
,
9502 memaddr
, myaddr
, len
, unit_size
, xfered_len
,
9503 packet_format
[0], 1);
9506 /* Read memory data directly from the remote machine.
9507 This does not use the data cache; the data cache uses this.
9508 MEMADDR is the address in the remote memory space.
9509 MYADDR is the address of the buffer in our space.
9510 LEN_UNITS is the number of addressable memory units to read..
9511 UNIT_SIZE is the length in bytes of an addressable unit.
9513 Return the transferred status, error or OK (an
9514 'enum target_xfer_status' value). Save the number of bytes
9515 transferred in *XFERED_LEN_UNITS.
9517 See the comment of remote_write_bytes_aux for an example of
9518 memory read/write exchange between gdb and the stub. */
9521 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr
, gdb_byte
*myaddr
,
9523 int unit_size
, ULONGEST
*xfered_len_units
)
9525 struct remote_state
*rs
= get_remote_state ();
9526 int buf_size_bytes
; /* Max size of packet output buffer. */
9531 buf_size_bytes
= get_memory_read_packet_size ();
9532 /* The packet buffer will be large enough for the payload;
9533 get_memory_packet_size ensures this. */
9535 /* Number of units that will fit. */
9536 todo_units
= std::min (len_units
,
9537 (ULONGEST
) (buf_size_bytes
/ unit_size
) / 2);
9539 /* Construct "m"<memaddr>","<len>". */
9540 memaddr
= remote_address_masked (memaddr
);
9541 p
= rs
->buf
.data ();
9543 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9545 p
+= hexnumstr (p
, (ULONGEST
) todo_units
);
9549 if (rs
->buf
[0] == 'E'
9550 && isxdigit (rs
->buf
[1]) && isxdigit (rs
->buf
[2])
9551 && rs
->buf
[3] == '\0')
9552 return TARGET_XFER_E_IO
;
9553 /* Reply describes memory byte by byte, each byte encoded as two hex
9555 p
= rs
->buf
.data ();
9556 decoded_bytes
= hex2bin (p
, myaddr
, todo_units
* unit_size
);
9557 /* Return what we have. Let higher layers handle partial reads. */
9558 *xfered_len_units
= (ULONGEST
) (decoded_bytes
/ unit_size
);
9559 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9562 /* Using the set of read-only target sections of remote, read live
9565 For interface/parameters/return description see target.h,
9569 remote_target::remote_xfer_live_readonly_partial (gdb_byte
*readbuf
,
9573 ULONGEST
*xfered_len
)
9575 const struct target_section
*secp
;
9577 secp
= target_section_by_addr (this, memaddr
);
9579 && (bfd_section_flags (secp
->the_bfd_section
) & SEC_READONLY
))
9581 ULONGEST memend
= memaddr
+ len
;
9583 const std::vector
<target_section
> *table
9584 = target_get_section_table (this);
9585 for (const target_section
&p
: *table
)
9587 if (memaddr
>= p
.addr
)
9589 if (memend
<= p
.endaddr
)
9591 /* Entire transfer is within this section. */
9592 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9595 else if (memaddr
>= p
.endaddr
)
9597 /* This section ends before the transfer starts. */
9602 /* This section overlaps the transfer. Just do half. */
9603 len
= p
.endaddr
- memaddr
;
9604 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9611 return TARGET_XFER_EOF
;
9614 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9615 first if the requested memory is unavailable in traceframe.
9616 Otherwise, fall back to remote_read_bytes_1. */
9619 remote_target::remote_read_bytes (CORE_ADDR memaddr
,
9620 gdb_byte
*myaddr
, ULONGEST len
, int unit_size
,
9621 ULONGEST
*xfered_len
)
9624 return TARGET_XFER_EOF
;
9626 if (get_traceframe_number () != -1)
9628 std::vector
<mem_range
> available
;
9630 /* If we fail to get the set of available memory, then the
9631 target does not support querying traceframe info, and so we
9632 attempt reading from the traceframe anyway (assuming the
9633 target implements the old QTro packet then). */
9634 if (traceframe_available_memory (&available
, memaddr
, len
))
9636 if (available
.empty () || available
[0].start
!= memaddr
)
9638 enum target_xfer_status res
;
9640 /* Don't read into the traceframe's available
9642 if (!available
.empty ())
9644 LONGEST oldlen
= len
;
9646 len
= available
[0].start
- memaddr
;
9647 gdb_assert (len
<= oldlen
);
9650 /* This goes through the topmost target again. */
9651 res
= remote_xfer_live_readonly_partial (myaddr
, memaddr
,
9652 len
, unit_size
, xfered_len
);
9653 if (res
== TARGET_XFER_OK
)
9654 return TARGET_XFER_OK
;
9657 /* No use trying further, we know some memory starting
9658 at MEMADDR isn't available. */
9660 return (*xfered_len
!= 0) ?
9661 TARGET_XFER_UNAVAILABLE
: TARGET_XFER_EOF
;
9665 /* Don't try to read more than how much is available, in
9666 case the target implements the deprecated QTro packet to
9667 cater for older GDBs (the target's knowledge of read-only
9668 sections may be outdated by now). */
9669 len
= available
[0].length
;
9673 return remote_read_bytes_1 (memaddr
, myaddr
, len
, unit_size
, xfered_len
);
9678 /* Sends a packet with content determined by the printf format string
9679 FORMAT and the remaining arguments, then gets the reply. Returns
9680 whether the packet was a success, a failure, or unknown. */
9683 remote_target::remote_send_printf (const char *format
, ...)
9685 struct remote_state
*rs
= get_remote_state ();
9686 int max_size
= get_remote_packet_size ();
9689 va_start (ap
, format
);
9692 int size
= vsnprintf (rs
->buf
.data (), max_size
, format
, ap
);
9696 if (size
>= max_size
)
9697 internal_error (_("Too long remote packet."));
9699 if (putpkt (rs
->buf
) < 0)
9700 error (_("Communication problem with target."));
9705 return packet_check_result (rs
->buf
);
9708 /* Flash writing can take quite some time. We'll set
9709 effectively infinite timeout for flash operations.
9710 In future, we'll need to decide on a better approach. */
9711 static const int remote_flash_timeout
= 1000;
9714 remote_target::flash_erase (ULONGEST address
, LONGEST length
)
9716 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9717 enum packet_result ret
;
9718 scoped_restore restore_timeout
9719 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9721 ret
= remote_send_printf ("vFlashErase:%s,%s",
9722 phex (address
, addr_size
),
9726 case PACKET_UNKNOWN
:
9727 error (_("Remote target does not support flash erase"));
9729 error (_("Error erasing flash with vFlashErase packet"));
9736 remote_target::remote_flash_write (ULONGEST address
,
9737 ULONGEST length
, ULONGEST
*xfered_len
,
9738 const gdb_byte
*data
)
9740 scoped_restore restore_timeout
9741 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9742 return remote_write_bytes_aux ("vFlashWrite:", address
, data
, length
, 1,
9747 remote_target::flash_done ()
9751 scoped_restore restore_timeout
9752 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9754 ret
= remote_send_printf ("vFlashDone");
9758 case PACKET_UNKNOWN
:
9759 error (_("Remote target does not support vFlashDone"));
9761 error (_("Error finishing flash operation"));
9768 /* Stuff for dealing with the packets which are part of this protocol.
9769 See comment at top of file for details. */
9771 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9772 error to higher layers. Called when a serial error is detected.
9773 The exception message is STRING, followed by a colon and a blank,
9774 the system error message for errno at function entry and final dot
9775 for output compatibility with throw_perror_with_name. */
9778 unpush_and_perror (remote_target
*target
, const char *string
)
9780 int saved_errno
= errno
;
9782 remote_unpush_target (target
);
9783 throw_error (TARGET_CLOSE_ERROR
, "%s: %s.", string
,
9784 safe_strerror (saved_errno
));
9787 /* Read a single character from the remote end. The current quit
9788 handler is overridden to avoid quitting in the middle of packet
9789 sequence, as that would break communication with the remote server.
9790 See remote_serial_quit_handler for more detail. */
9793 remote_target::readchar (int timeout
)
9796 struct remote_state
*rs
= get_remote_state ();
9799 scoped_restore restore_quit_target
9800 = make_scoped_restore (&curr_quit_handler_target
, this);
9801 scoped_restore restore_quit
9802 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
9804 rs
->got_ctrlc_during_io
= 0;
9806 ch
= serial_readchar (rs
->remote_desc
, timeout
);
9808 if (rs
->got_ctrlc_during_io
)
9815 switch ((enum serial_rc
) ch
)
9818 remote_unpush_target (this);
9819 throw_error (TARGET_CLOSE_ERROR
, _("Remote connection closed"));
9822 unpush_and_perror (this, _("Remote communication error. "
9823 "Target disconnected"));
9825 case SERIAL_TIMEOUT
:
9831 /* Wrapper for serial_write that closes the target and throws if
9832 writing fails. The current quit handler is overridden to avoid
9833 quitting in the middle of packet sequence, as that would break
9834 communication with the remote server. See
9835 remote_serial_quit_handler for more detail. */
9838 remote_target::remote_serial_write (const char *str
, int len
)
9840 struct remote_state
*rs
= get_remote_state ();
9842 scoped_restore restore_quit_target
9843 = make_scoped_restore (&curr_quit_handler_target
, this);
9844 scoped_restore restore_quit
9845 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
9847 rs
->got_ctrlc_during_io
= 0;
9849 if (serial_write (rs
->remote_desc
, str
, len
))
9851 unpush_and_perror (this, _("Remote communication error. "
9852 "Target disconnected"));
9855 if (rs
->got_ctrlc_during_io
)
9859 /* Return a string representing an escaped version of BUF, of len N.
9860 E.g. \n is converted to \\n, \t to \\t, etc. */
9863 escape_buffer (const char *buf
, int n
)
9867 stb
.putstrn (buf
, n
, '\\');
9868 return stb
.release ();
9872 remote_target::putpkt (const char *buf
)
9874 return putpkt_binary (buf
, strlen (buf
));
9877 /* Wrapper around remote_target::putpkt to avoid exporting
9881 putpkt (remote_target
*remote
, const char *buf
)
9883 return remote
->putpkt (buf
);
9886 /* Send a packet to the remote machine, with error checking. The data
9887 of the packet is in BUF. The string in BUF can be at most
9888 get_remote_packet_size () - 5 to account for the $, # and checksum,
9889 and for a possible /0 if we are debugging (remote_debug) and want
9890 to print the sent packet as a string. */
9893 remote_target::putpkt_binary (const char *buf
, int cnt
)
9895 struct remote_state
*rs
= get_remote_state ();
9897 unsigned char csum
= 0;
9898 gdb::def_vector
<char> data (cnt
+ 6);
9899 char *buf2
= data
.data ();
9905 /* Catch cases like trying to read memory or listing threads while
9906 we're waiting for a stop reply. The remote server wouldn't be
9907 ready to handle this request, so we'd hang and timeout. We don't
9908 have to worry about this in synchronous mode, because in that
9909 case it's not possible to issue a command while the target is
9910 running. This is not a problem in non-stop mode, because in that
9911 case, the stub is always ready to process serial input. */
9912 if (!target_is_non_stop_p ()
9913 && target_is_async_p ()
9914 && rs
->waiting_for_stop_reply
)
9916 error (_("Cannot execute this command while the target is running.\n"
9917 "Use the \"interrupt\" command to stop the target\n"
9918 "and then try again."));
9921 /* Copy the packet into buffer BUF2, encapsulating it
9922 and giving it a checksum. */
9927 for (i
= 0; i
< cnt
; i
++)
9933 *p
++ = tohex ((csum
>> 4) & 0xf);
9934 *p
++ = tohex (csum
& 0xf);
9936 /* Send it over and over until we get a positive ack. */
9944 int len
= (int) (p
- buf2
);
9947 if (remote_packet_max_chars
< 0)
9950 max_chars
= remote_packet_max_chars
;
9953 = escape_buffer (buf2
, std::min (len
, max_chars
));
9955 if (len
> max_chars
)
9956 remote_debug_printf_nofunc
9957 ("Sending packet: %s [%d bytes omitted]", str
.c_str (),
9960 remote_debug_printf_nofunc ("Sending packet: %s", str
.c_str ());
9962 remote_serial_write (buf2
, p
- buf2
);
9964 /* If this is a no acks version of the remote protocol, send the
9965 packet and move on. */
9969 /* Read until either a timeout occurs (-2) or '+' is read.
9970 Handle any notification that arrives in the mean time. */
9973 ch
= readchar (remote_timeout
);
9978 remote_debug_printf_nofunc ("Received Ack");
9981 remote_debug_printf_nofunc ("Received Nak");
9983 case SERIAL_TIMEOUT
:
9987 break; /* Retransmit buffer. */
9990 remote_debug_printf ("Packet instead of Ack, ignoring it");
9991 /* It's probably an old response sent because an ACK
9992 was lost. Gobble up the packet and ack it so it
9993 doesn't get retransmitted when we resend this
9996 remote_serial_write ("+", 1);
9997 continue; /* Now, go look for +. */
10004 /* If we got a notification, handle it, and go back to looking
10006 /* We've found the start of a notification. Now
10007 collect the data. */
10008 val
= read_frame (&rs
->buf
);
10011 remote_debug_printf_nofunc
10012 (" Notification received: %s",
10013 escape_buffer (rs
->buf
.data (), val
).c_str ());
10015 handle_notification (rs
->notif_state
, rs
->buf
.data ());
10016 /* We're in sync now, rewait for the ack. */
10020 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10026 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10030 break; /* Here to retransmit. */
10034 /* This is wrong. If doing a long backtrace, the user should be
10035 able to get out next time we call QUIT, without anything as
10036 violent as interrupt_query. If we want to provide a way out of
10037 here without getting to the next QUIT, it should be based on
10038 hitting ^C twice as in remote_wait. */
10042 interrupt_query ();
10050 /* Come here after finding the start of a frame when we expected an
10051 ack. Do our best to discard the rest of this packet. */
10054 remote_target::skip_frame ()
10060 c
= readchar (remote_timeout
);
10063 case SERIAL_TIMEOUT
:
10064 /* Nothing we can do. */
10067 /* Discard the two bytes of checksum and stop. */
10068 c
= readchar (remote_timeout
);
10070 c
= readchar (remote_timeout
);
10073 case '*': /* Run length encoding. */
10074 /* Discard the repeat count. */
10075 c
= readchar (remote_timeout
);
10080 /* A regular character. */
10086 /* Come here after finding the start of the frame. Collect the rest
10087 into *BUF, verifying the checksum, length, and handling run-length
10088 compression. NUL terminate the buffer. If there is not enough room,
10091 Returns -1 on error, number of characters in buffer (ignoring the
10092 trailing NULL) on success. (could be extended to return one of the
10093 SERIAL status indications). */
10096 remote_target::read_frame (gdb::char_vector
*buf_p
)
10098 unsigned char csum
;
10101 char *buf
= buf_p
->data ();
10102 struct remote_state
*rs
= get_remote_state ();
10109 c
= readchar (remote_timeout
);
10112 case SERIAL_TIMEOUT
:
10113 remote_debug_printf ("Timeout in mid-packet, retrying");
10117 remote_debug_printf ("Saw new packet start in middle of old one");
10118 return -1; /* Start a new packet, count retries. */
10122 unsigned char pktcsum
;
10128 check_0
= readchar (remote_timeout
);
10130 check_1
= readchar (remote_timeout
);
10132 if (check_0
== SERIAL_TIMEOUT
|| check_1
== SERIAL_TIMEOUT
)
10134 remote_debug_printf ("Timeout in checksum, retrying");
10137 else if (check_0
< 0 || check_1
< 0)
10139 remote_debug_printf ("Communication error in checksum");
10143 /* Don't recompute the checksum; with no ack packets we
10144 don't have any way to indicate a packet retransmission
10146 if (rs
->noack_mode
)
10149 pktcsum
= (fromhex (check_0
) << 4) | fromhex (check_1
);
10150 if (csum
== pktcsum
)
10153 remote_debug_printf
10154 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10155 pktcsum
, csum
, escape_buffer (buf
, bc
).c_str ());
10157 /* Number of characters in buffer ignoring trailing
10161 case '*': /* Run length encoding. */
10166 c
= readchar (remote_timeout
);
10168 repeat
= c
- ' ' + 3; /* Compute repeat count. */
10170 /* The character before ``*'' is repeated. */
10172 if (repeat
> 0 && repeat
<= 255 && bc
> 0)
10174 if (bc
+ repeat
- 1 >= buf_p
->size () - 1)
10176 /* Make some more room in the buffer. */
10177 buf_p
->resize (buf_p
->size () + repeat
);
10178 buf
= buf_p
->data ();
10181 memset (&buf
[bc
], buf
[bc
- 1], repeat
);
10187 gdb_printf (_("Invalid run length encoding: %s\n"), buf
);
10191 if (bc
>= buf_p
->size () - 1)
10193 /* Make some more room in the buffer. */
10194 buf_p
->resize (buf_p
->size () * 2);
10195 buf
= buf_p
->data ();
10205 /* Set this to the maximum number of seconds to wait instead of waiting forever
10206 in target_wait(). If this timer times out, then it generates an error and
10207 the command is aborted. This replaces most of the need for timeouts in the
10208 GDB test suite, and makes it possible to distinguish between a hung target
10209 and one with slow communications. */
10211 static int watchdog
= 0;
10213 show_watchdog (struct ui_file
*file
, int from_tty
,
10214 struct cmd_list_element
*c
, const char *value
)
10216 gdb_printf (file
, _("Watchdog timer is %s.\n"), value
);
10219 /* Read a packet from the remote machine, with error checking, and
10220 store it in *BUF. Resize *BUF if necessary to hold the result. If
10221 FOREVER, wait forever rather than timing out; this is used (in
10222 synchronous mode) to wait for a target that is is executing user
10223 code to stop. If FOREVER == false, this function is allowed to time
10224 out gracefully and return an indication of this to the caller.
10225 Otherwise return the number of bytes read. If IS_NOTIF is not
10226 NULL, then consider receiving a notification enough reason to
10227 return to the caller. In this case, *IS_NOTIF is an output boolean
10228 that indicates whether *BUF holds a notification or not (a regular
10232 remote_target::getpkt (gdb::char_vector
*buf
, bool forever
, bool *is_notif
)
10234 struct remote_state
*rs
= get_remote_state ();
10240 strcpy (buf
->data (), "timeout");
10243 timeout
= watchdog
> 0 ? watchdog
: -1;
10244 else if (is_notif
!= nullptr)
10245 timeout
= 0; /* There should already be a char in the buffer. If
10248 timeout
= remote_timeout
;
10250 #define MAX_TRIES 3
10252 /* Process any number of notifications, and then return when
10253 we get a packet. */
10256 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10258 for (tries
= 1; tries
<= MAX_TRIES
; tries
++)
10260 /* This can loop forever if the remote side sends us
10261 characters continuously, but if it pauses, we'll get
10262 SERIAL_TIMEOUT from readchar because of timeout. Then
10263 we'll count that as a retry.
10265 Note that even when forever is set, we will only wait
10266 forever prior to the start of a packet. After that, we
10267 expect characters to arrive at a brisk pace. They should
10268 show up within remote_timeout intervals. */
10270 c
= readchar (timeout
);
10271 while (c
!= SERIAL_TIMEOUT
&& c
!= '$' && c
!= '%');
10273 if (c
== SERIAL_TIMEOUT
)
10275 if (is_notif
!= nullptr)
10276 return -1; /* Don't complain, it's normal to not get
10277 anything in this case. */
10279 if (forever
) /* Watchdog went off? Kill the target. */
10281 remote_unpush_target (this);
10282 throw_error (TARGET_CLOSE_ERROR
,
10283 _("Watchdog timeout has expired. "
10284 "Target detached."));
10287 remote_debug_printf ("Timed out.");
10291 /* We've found the start of a packet or notification.
10292 Now collect the data. */
10293 val
= read_frame (buf
);
10298 remote_serial_write ("-", 1);
10301 if (tries
> MAX_TRIES
)
10303 /* We have tried hard enough, and just can't receive the
10304 packet/notification. Give up. */
10305 gdb_printf (_("Ignoring packet error, continuing...\n"));
10307 /* Skip the ack char if we're in no-ack mode. */
10308 if (!rs
->noack_mode
)
10309 remote_serial_write ("+", 1);
10313 /* If we got an ordinary packet, return that to our caller. */
10320 if (remote_packet_max_chars
< 0)
10323 max_chars
= remote_packet_max_chars
;
10326 = escape_buffer (buf
->data (),
10327 std::min (val
, max_chars
));
10329 if (val
> max_chars
)
10330 remote_debug_printf_nofunc
10331 ("Packet received: %s [%d bytes omitted]", str
.c_str (),
10334 remote_debug_printf_nofunc ("Packet received: %s",
10338 /* Skip the ack char if we're in no-ack mode. */
10339 if (!rs
->noack_mode
)
10340 remote_serial_write ("+", 1);
10341 if (is_notif
!= NULL
)
10346 /* If we got a notification, handle it, and go back to looking
10350 gdb_assert (c
== '%');
10352 remote_debug_printf_nofunc
10353 (" Notification received: %s",
10354 escape_buffer (buf
->data (), val
).c_str ());
10356 if (is_notif
!= NULL
)
10359 handle_notification (rs
->notif_state
, buf
->data ());
10361 /* Notifications require no acknowledgement. */
10363 if (is_notif
!= nullptr)
10369 /* Kill any new fork children of inferior INF that haven't been
10370 processed by follow_fork. */
10373 remote_target::kill_new_fork_children (inferior
*inf
)
10375 remote_state
*rs
= get_remote_state ();
10376 const notif_client
*notif
= ¬if_client_stop
;
10378 /* Kill the fork child threads of any threads in inferior INF that are stopped
10379 at a fork event. */
10380 for (thread_info
*thread
: inf
->non_exited_threads ())
10382 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
10387 int child_pid
= ws
->child_ptid ().pid ();
10388 int res
= remote_vkill (child_pid
);
10391 error (_("Can't kill fork child process %d"), child_pid
);
10394 /* Check for any pending fork events (not reported or processed yet)
10395 in inferior INF and kill those fork child threads as well. */
10396 remote_notif_get_pending_events (notif
);
10397 for (auto &event
: rs
->stop_reply_queue
)
10399 if (event
->ptid
.pid () != inf
->pid
)
10402 if (!is_fork_status (event
->ws
.kind ()))
10405 int child_pid
= event
->ws
.child_ptid ().pid ();
10406 int res
= remote_vkill (child_pid
);
10409 error (_("Can't kill fork child process %d"), child_pid
);
10414 /* Target hook to kill the current inferior. */
10417 remote_target::kill ()
10420 inferior
*inf
= find_inferior_pid (this, inferior_ptid
.pid ());
10422 gdb_assert (inf
!= nullptr);
10424 if (m_features
.packet_support (PACKET_vKill
) != PACKET_DISABLE
)
10426 /* If we're stopped while forking and we haven't followed yet,
10427 kill the child task. We need to do this before killing the
10428 parent task because if this is a vfork then the parent will
10430 kill_new_fork_children (inf
);
10432 res
= remote_vkill (inf
->pid
);
10435 target_mourn_inferior (inferior_ptid
);
10440 /* If we are in 'target remote' mode and we are killing the only
10441 inferior, then we will tell gdbserver to exit and unpush the
10443 if (res
== -1 && !m_features
.remote_multi_process_p ()
10444 && number_of_live_inferiors (this) == 1)
10448 /* We've killed the remote end, we get to mourn it. If we are
10449 not in extended mode, mourning the inferior also unpushes
10450 remote_ops from the target stack, which closes the remote
10452 target_mourn_inferior (inferior_ptid
);
10457 error (_("Can't kill process"));
10460 /* Send a kill request to the target using the 'vKill' packet. */
10463 remote_target::remote_vkill (int pid
)
10465 if (m_features
.packet_support (PACKET_vKill
) == PACKET_DISABLE
)
10468 remote_state
*rs
= get_remote_state ();
10470 /* Tell the remote target to detach. */
10471 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vKill;%x", pid
);
10475 switch (m_features
.packet_ok (rs
->buf
, PACKET_vKill
))
10481 case PACKET_UNKNOWN
:
10484 internal_error (_("Bad result from packet_ok"));
10488 /* Send a kill request to the target using the 'k' packet. */
10491 remote_target::remote_kill_k ()
10493 /* Catch errors so the user can quit from gdb even when we
10494 aren't on speaking terms with the remote system. */
10499 catch (const gdb_exception_error
&ex
)
10501 if (ex
.error
== TARGET_CLOSE_ERROR
)
10503 /* If we got an (EOF) error that caused the target
10504 to go away, then we're done, that's what we wanted.
10505 "k" is susceptible to cause a premature EOF, given
10506 that the remote server isn't actually required to
10507 reply to "k", and it can happen that it doesn't
10508 even get to reply ACK to the "k". */
10512 /* Otherwise, something went wrong. We didn't actually kill
10513 the target. Just propagate the exception, and let the
10514 user or higher layers decide what to do. */
10520 remote_target::mourn_inferior ()
10522 struct remote_state
*rs
= get_remote_state ();
10524 /* We're no longer interested in notification events of an inferior
10525 that exited or was killed/detached. */
10526 discard_pending_stop_replies (current_inferior ());
10528 /* In 'target remote' mode with one inferior, we close the connection. */
10529 if (!rs
->extended
&& number_of_live_inferiors (this) <= 1)
10531 remote_unpush_target (this);
10535 /* In case we got here due to an error, but we're going to stay
10537 rs
->waiting_for_stop_reply
= 0;
10539 /* If the current general thread belonged to the process we just
10540 detached from or has exited, the remote side current general
10541 thread becomes undefined. Considering a case like this:
10543 - We just got here due to a detach.
10544 - The process that we're detaching from happens to immediately
10545 report a global breakpoint being hit in non-stop mode, in the
10546 same thread we had selected before.
10547 - GDB attaches to this process again.
10548 - This event happens to be the next event we handle.
10550 GDB would consider that the current general thread didn't need to
10551 be set on the stub side (with Hg), since for all it knew,
10552 GENERAL_THREAD hadn't changed.
10554 Notice that although in all-stop mode, the remote server always
10555 sets the current thread to the thread reporting the stop event,
10556 that doesn't happen in non-stop mode; in non-stop, the stub *must
10557 not* change the current thread when reporting a breakpoint hit,
10558 due to the decoupling of event reporting and event handling.
10560 To keep things simple, we always invalidate our notion of the
10562 record_currthread (rs
, minus_one_ptid
);
10564 /* Call common code to mark the inferior as not running. */
10565 generic_mourn_inferior ();
10569 extended_remote_target::supports_disable_randomization ()
10571 return (m_features
.packet_support (PACKET_QDisableRandomization
)
10576 remote_target::extended_remote_disable_randomization (int val
)
10578 struct remote_state
*rs
= get_remote_state ();
10581 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10582 "QDisableRandomization:%x", val
);
10584 reply
= remote_get_noisy_reply ();
10585 if (*reply
== '\0')
10586 error (_("Target does not support QDisableRandomization."));
10587 if (strcmp (reply
, "OK") != 0)
10588 error (_("Bogus QDisableRandomization reply from target: %s"), reply
);
10592 remote_target::extended_remote_run (const std::string
&args
)
10594 struct remote_state
*rs
= get_remote_state ();
10596 const char *remote_exec_file
= get_remote_exec_file ();
10598 /* If the user has disabled vRun support, or we have detected that
10599 support is not available, do not try it. */
10600 if (m_features
.packet_support (PACKET_vRun
) == PACKET_DISABLE
)
10603 strcpy (rs
->buf
.data (), "vRun;");
10604 len
= strlen (rs
->buf
.data ());
10606 if (strlen (remote_exec_file
) * 2 + len
>= get_remote_packet_size ())
10607 error (_("Remote file name too long for run packet"));
10608 len
+= 2 * bin2hex ((gdb_byte
*) remote_exec_file
, rs
->buf
.data () + len
,
10609 strlen (remote_exec_file
));
10611 if (!args
.empty ())
10615 gdb_argv
argv (args
.c_str ());
10616 for (i
= 0; argv
[i
] != NULL
; i
++)
10618 if (strlen (argv
[i
]) * 2 + 1 + len
>= get_remote_packet_size ())
10619 error (_("Argument list too long for run packet"));
10620 rs
->buf
[len
++] = ';';
10621 len
+= 2 * bin2hex ((gdb_byte
*) argv
[i
], rs
->buf
.data () + len
,
10626 rs
->buf
[len
++] = '\0';
10631 switch (m_features
.packet_ok (rs
->buf
, PACKET_vRun
))
10634 /* We have a wait response. All is well. */
10636 case PACKET_UNKNOWN
:
10639 if (remote_exec_file
[0] == '\0')
10640 error (_("Running the default executable on the remote target failed; "
10641 "try \"set remote exec-file\"?"));
10643 error (_("Running \"%s\" on the remote target failed"),
10646 gdb_assert_not_reached ("bad switch");
10650 /* Helper function to send set/unset environment packets. ACTION is
10651 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10652 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10656 remote_target::send_environment_packet (const char *action
,
10657 const char *packet
,
10660 remote_state
*rs
= get_remote_state ();
10662 /* Convert the environment variable to an hex string, which
10663 is the best format to be transmitted over the wire. */
10664 std::string encoded_value
= bin2hex ((const gdb_byte
*) value
,
10667 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10668 "%s:%s", packet
, encoded_value
.c_str ());
10672 if (strcmp (rs
->buf
.data (), "OK") != 0)
10673 warning (_("Unable to %s environment variable '%s' on remote."),
10677 /* Helper function to handle the QEnvironment* packets. */
10680 remote_target::extended_remote_environment_support ()
10682 remote_state
*rs
= get_remote_state ();
10684 if (m_features
.packet_support (PACKET_QEnvironmentReset
) != PACKET_DISABLE
)
10686 putpkt ("QEnvironmentReset");
10688 if (strcmp (rs
->buf
.data (), "OK") != 0)
10689 warning (_("Unable to reset environment on remote."));
10692 gdb_environ
*e
= ¤t_inferior ()->environment
;
10694 if (m_features
.packet_support (PACKET_QEnvironmentHexEncoded
)
10697 for (const std::string
&el
: e
->user_set_env ())
10698 send_environment_packet ("set", "QEnvironmentHexEncoded",
10703 if (m_features
.packet_support (PACKET_QEnvironmentUnset
) != PACKET_DISABLE
)
10704 for (const std::string
&el
: e
->user_unset_env ())
10705 send_environment_packet ("unset", "QEnvironmentUnset", el
.c_str ());
10708 /* Helper function to set the current working directory for the
10709 inferior in the remote target. */
10712 remote_target::extended_remote_set_inferior_cwd ()
10714 if (m_features
.packet_support (PACKET_QSetWorkingDir
) != PACKET_DISABLE
)
10716 const std::string
&inferior_cwd
= current_inferior ()->cwd ();
10717 remote_state
*rs
= get_remote_state ();
10719 if (!inferior_cwd
.empty ())
10721 std::string hexpath
10722 = bin2hex ((const gdb_byte
*) inferior_cwd
.data (),
10723 inferior_cwd
.size ());
10725 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10726 "QSetWorkingDir:%s", hexpath
.c_str ());
10730 /* An empty inferior_cwd means that the user wants us to
10731 reset the remote server's inferior's cwd. */
10732 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10733 "QSetWorkingDir:");
10738 if (m_features
.packet_ok (rs
->buf
, PACKET_QSetWorkingDir
) != PACKET_OK
)
10740 Remote replied unexpectedly while setting the inferior's working\n\
10747 /* In the extended protocol we want to be able to do things like
10748 "run" and have them basically work as expected. So we need
10749 a special create_inferior function. We support changing the
10750 executable file and the command line arguments, but not the
10754 extended_remote_target::create_inferior (const char *exec_file
,
10755 const std::string
&args
,
10756 char **env
, int from_tty
)
10760 struct remote_state
*rs
= get_remote_state ();
10761 const char *remote_exec_file
= get_remote_exec_file ();
10763 /* If running asynchronously, register the target file descriptor
10764 with the event loop. */
10765 if (target_can_async_p ())
10766 target_async (true);
10768 /* Disable address space randomization if requested (and supported). */
10769 if (supports_disable_randomization ())
10770 extended_remote_disable_randomization (disable_randomization
);
10772 /* If startup-with-shell is on, we inform gdbserver to start the
10773 remote inferior using a shell. */
10774 if (m_features
.packet_support (PACKET_QStartupWithShell
) != PACKET_DISABLE
)
10776 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10777 "QStartupWithShell:%d", startup_with_shell
? 1 : 0);
10780 if (strcmp (rs
->buf
.data (), "OK") != 0)
10782 Remote replied unexpectedly while setting startup-with-shell: %s"),
10786 extended_remote_environment_support ();
10788 extended_remote_set_inferior_cwd ();
10790 /* Now restart the remote server. */
10791 run_worked
= extended_remote_run (args
) != -1;
10794 /* vRun was not supported. Fail if we need it to do what the
10796 if (remote_exec_file
[0])
10797 error (_("Remote target does not support \"set remote exec-file\""));
10798 if (!args
.empty ())
10799 error (_("Remote target does not support \"set args\" or run ARGS"));
10801 /* Fall back to "R". */
10802 extended_remote_restart ();
10805 /* vRun's success return is a stop reply. */
10806 stop_reply
= run_worked
? rs
->buf
.data () : NULL
;
10807 add_current_inferior_and_thread (stop_reply
);
10809 /* Get updated offsets, if the stub uses qOffsets. */
10814 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10815 the list of conditions (in agent expression bytecode format), if any, the
10816 target needs to evaluate. The output is placed into the packet buffer
10817 started from BUF and ended at BUF_END. */
10820 remote_add_target_side_condition (struct gdbarch
*gdbarch
,
10821 struct bp_target_info
*bp_tgt
, char *buf
,
10824 if (bp_tgt
->conditions
.empty ())
10827 buf
+= strlen (buf
);
10828 xsnprintf (buf
, buf_end
- buf
, "%s", ";");
10831 /* Send conditions to the target. */
10832 for (agent_expr
*aexpr
: bp_tgt
->conditions
)
10834 xsnprintf (buf
, buf_end
- buf
, "X%x,", (int) aexpr
->buf
.size ());
10835 buf
+= strlen (buf
);
10836 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
10837 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
10844 remote_add_target_side_commands (struct gdbarch
*gdbarch
,
10845 struct bp_target_info
*bp_tgt
, char *buf
)
10847 if (bp_tgt
->tcommands
.empty ())
10850 buf
+= strlen (buf
);
10852 sprintf (buf
, ";cmds:%x,", bp_tgt
->persist
);
10853 buf
+= strlen (buf
);
10855 /* Concatenate all the agent expressions that are commands into the
10857 for (agent_expr
*aexpr
: bp_tgt
->tcommands
)
10859 sprintf (buf
, "X%x,", (int) aexpr
->buf
.size ());
10860 buf
+= strlen (buf
);
10861 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
10862 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
10867 /* Insert a breakpoint. On targets that have software breakpoint
10868 support, we ask the remote target to do the work; on targets
10869 which don't, we insert a traditional memory breakpoint. */
10872 remote_target::insert_breakpoint (struct gdbarch
*gdbarch
,
10873 struct bp_target_info
*bp_tgt
)
10875 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10876 If it succeeds, then set the support to PACKET_ENABLE. If it
10877 fails, and the user has explicitly requested the Z support then
10878 report an error, otherwise, mark it disabled and go on. */
10880 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
10882 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
10883 struct remote_state
*rs
;
10886 /* Make sure the remote is pointing at the right process, if
10888 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10889 set_general_process ();
10891 rs
= get_remote_state ();
10892 p
= rs
->buf
.data ();
10893 endbuf
= p
+ get_remote_packet_size ();
10898 addr
= (ULONGEST
) remote_address_masked (addr
);
10899 p
+= hexnumstr (p
, addr
);
10900 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
10902 if (supports_evaluation_of_breakpoint_conditions ())
10903 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
10905 if (can_run_breakpoint_commands ())
10906 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
10911 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z0
))
10917 case PACKET_UNKNOWN
:
10922 /* If this breakpoint has target-side commands but this stub doesn't
10923 support Z0 packets, throw error. */
10924 if (!bp_tgt
->tcommands
.empty ())
10925 throw_error (NOT_SUPPORTED_ERROR
, _("\
10926 Target doesn't support breakpoints that have target side commands."));
10928 return memory_insert_breakpoint (this, gdbarch
, bp_tgt
);
10932 remote_target::remove_breakpoint (struct gdbarch
*gdbarch
,
10933 struct bp_target_info
*bp_tgt
,
10934 enum remove_bp_reason reason
)
10936 CORE_ADDR addr
= bp_tgt
->placed_address
;
10937 struct remote_state
*rs
= get_remote_state ();
10939 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
10941 char *p
= rs
->buf
.data ();
10942 char *endbuf
= p
+ get_remote_packet_size ();
10944 /* Make sure the remote is pointing at the right process, if
10946 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10947 set_general_process ();
10953 addr
= (ULONGEST
) remote_address_masked (bp_tgt
->placed_address
);
10954 p
+= hexnumstr (p
, addr
);
10955 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
10960 return (rs
->buf
[0] == 'E');
10963 return memory_remove_breakpoint (this, gdbarch
, bp_tgt
, reason
);
10966 static enum Z_packet_type
10967 watchpoint_to_Z_packet (int type
)
10972 return Z_PACKET_WRITE_WP
;
10975 return Z_PACKET_READ_WP
;
10978 return Z_PACKET_ACCESS_WP
;
10981 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type
);
10986 remote_target::insert_watchpoint (CORE_ADDR addr
, int len
,
10987 enum target_hw_bp_type type
, struct expression
*cond
)
10989 struct remote_state
*rs
= get_remote_state ();
10990 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
10992 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
10994 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
10995 + to_underlying (packet
))) == PACKET_DISABLE
)
10998 /* Make sure the remote is pointing at the right process, if
11000 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11001 set_general_process ();
11003 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "Z%x,", packet
);
11004 p
= strchr (rs
->buf
.data (), '\0');
11005 addr
= remote_address_masked (addr
);
11006 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11007 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11012 switch (m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11013 + to_underlying (packet
))))
11017 case PACKET_UNKNOWN
:
11022 internal_error (_("remote_insert_watchpoint: reached end of function"));
11026 remote_target::watchpoint_addr_within_range (CORE_ADDR addr
,
11027 CORE_ADDR start
, int length
)
11029 CORE_ADDR diff
= remote_address_masked (addr
- start
);
11031 return diff
< length
;
11036 remote_target::remove_watchpoint (CORE_ADDR addr
, int len
,
11037 enum target_hw_bp_type type
, struct expression
*cond
)
11039 struct remote_state
*rs
= get_remote_state ();
11040 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
11042 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
11044 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
11045 + to_underlying (packet
))) == PACKET_DISABLE
)
11048 /* Make sure the remote is pointing at the right process, if
11050 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11051 set_general_process ();
11053 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "z%x,", packet
);
11054 p
= strchr (rs
->buf
.data (), '\0');
11055 addr
= remote_address_masked (addr
);
11056 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11057 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11061 switch (m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11062 + to_underlying (packet
))))
11065 case PACKET_UNKNOWN
:
11070 internal_error (_("remote_remove_watchpoint: reached end of function"));
11074 static int remote_hw_watchpoint_limit
= -1;
11075 static int remote_hw_watchpoint_length_limit
= -1;
11076 static int remote_hw_breakpoint_limit
= -1;
11079 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr
, int len
)
11081 if (remote_hw_watchpoint_length_limit
== 0)
11083 else if (remote_hw_watchpoint_length_limit
< 0)
11085 else if (len
<= remote_hw_watchpoint_length_limit
)
11092 remote_target::can_use_hw_breakpoint (enum bptype type
, int cnt
, int ot
)
11094 if (type
== bp_hardware_breakpoint
)
11096 if (remote_hw_breakpoint_limit
== 0)
11098 else if (remote_hw_breakpoint_limit
< 0)
11100 else if (cnt
<= remote_hw_breakpoint_limit
)
11105 if (remote_hw_watchpoint_limit
== 0)
11107 else if (remote_hw_watchpoint_limit
< 0)
11111 else if (cnt
<= remote_hw_watchpoint_limit
)
11117 /* The to_stopped_by_sw_breakpoint method of target remote. */
11120 remote_target::stopped_by_sw_breakpoint ()
11122 struct thread_info
*thread
= inferior_thread ();
11124 return (thread
->priv
!= NULL
11125 && (get_remote_thread_info (thread
)->stop_reason
11126 == TARGET_STOPPED_BY_SW_BREAKPOINT
));
11129 /* The to_supports_stopped_by_sw_breakpoint method of target
11133 remote_target::supports_stopped_by_sw_breakpoint ()
11135 return (m_features
.packet_support (PACKET_swbreak_feature
) == PACKET_ENABLE
);
11138 /* The to_stopped_by_hw_breakpoint method of target remote. */
11141 remote_target::stopped_by_hw_breakpoint ()
11143 struct thread_info
*thread
= inferior_thread ();
11145 return (thread
->priv
!= NULL
11146 && (get_remote_thread_info (thread
)->stop_reason
11147 == TARGET_STOPPED_BY_HW_BREAKPOINT
));
11150 /* The to_supports_stopped_by_hw_breakpoint method of target
11154 remote_target::supports_stopped_by_hw_breakpoint ()
11156 return (m_features
.packet_support (PACKET_hwbreak_feature
) == PACKET_ENABLE
);
11160 remote_target::stopped_by_watchpoint ()
11162 struct thread_info
*thread
= inferior_thread ();
11164 return (thread
->priv
!= NULL
11165 && (get_remote_thread_info (thread
)->stop_reason
11166 == TARGET_STOPPED_BY_WATCHPOINT
));
11170 remote_target::stopped_data_address (CORE_ADDR
*addr_p
)
11172 struct thread_info
*thread
= inferior_thread ();
11174 if (thread
->priv
!= NULL
11175 && (get_remote_thread_info (thread
)->stop_reason
11176 == TARGET_STOPPED_BY_WATCHPOINT
))
11178 *addr_p
= get_remote_thread_info (thread
)->watch_data_address
;
11187 remote_target::insert_hw_breakpoint (struct gdbarch
*gdbarch
,
11188 struct bp_target_info
*bp_tgt
)
11190 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
11191 struct remote_state
*rs
;
11195 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11198 /* Make sure the remote is pointing at the right process, if
11200 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11201 set_general_process ();
11203 rs
= get_remote_state ();
11204 p
= rs
->buf
.data ();
11205 endbuf
= p
+ get_remote_packet_size ();
11211 addr
= remote_address_masked (addr
);
11212 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11213 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11215 if (supports_evaluation_of_breakpoint_conditions ())
11216 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
11218 if (can_run_breakpoint_commands ())
11219 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
11224 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z1
))
11227 if (rs
->buf
[1] == '.')
11229 message
= strchr (&rs
->buf
[2], '.');
11231 error (_("Remote failure reply: %s"), message
+ 1);
11234 case PACKET_UNKNOWN
:
11239 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11244 remote_target::remove_hw_breakpoint (struct gdbarch
*gdbarch
,
11245 struct bp_target_info
*bp_tgt
)
11248 struct remote_state
*rs
= get_remote_state ();
11249 char *p
= rs
->buf
.data ();
11250 char *endbuf
= p
+ get_remote_packet_size ();
11252 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11255 /* Make sure the remote is pointing at the right process, if
11257 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11258 set_general_process ();
11264 addr
= remote_address_masked (bp_tgt
->placed_address
);
11265 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11266 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11271 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z1
))
11274 case PACKET_UNKNOWN
:
11279 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11282 /* Verify memory using the "qCRC:" request. */
11285 remote_target::verify_memory (const gdb_byte
*data
, CORE_ADDR lma
, ULONGEST size
)
11287 struct remote_state
*rs
= get_remote_state ();
11288 unsigned long host_crc
, target_crc
;
11291 /* It doesn't make sense to use qCRC if the remote target is
11292 connected but not running. */
11293 if (target_has_execution ()
11294 && m_features
.packet_support (PACKET_qCRC
) != PACKET_DISABLE
)
11296 enum packet_result result
;
11298 /* Make sure the remote is pointing at the right process. */
11299 set_general_process ();
11301 /* FIXME: assumes lma can fit into long. */
11302 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11303 (long) lma
, (long) size
);
11306 /* Be clever; compute the host_crc before waiting for target
11308 host_crc
= xcrc32 (data
, size
, 0xffffffff);
11312 result
= m_features
.packet_ok (rs
->buf
, PACKET_qCRC
);
11313 if (result
== PACKET_ERROR
)
11315 else if (result
== PACKET_OK
)
11317 for (target_crc
= 0, tmp
= &rs
->buf
[1]; *tmp
; tmp
++)
11318 target_crc
= target_crc
* 16 + fromhex (*tmp
);
11320 return (host_crc
== target_crc
);
11324 return simple_verify_memory (this, data
, lma
, size
);
11327 /* compare-sections command
11329 With no arguments, compares each loadable section in the exec bfd
11330 with the same memory range on the target, and reports mismatches.
11331 Useful for verifying the image on the target against the exec file. */
11334 compare_sections_command (const char *args
, int from_tty
)
11337 const char *sectname
;
11338 bfd_size_type size
;
11341 int mismatched
= 0;
11345 if (!current_program_space
->exec_bfd ())
11346 error (_("command cannot be used without an exec file"));
11348 if (args
!= NULL
&& strcmp (args
, "-r") == 0)
11354 for (s
= current_program_space
->exec_bfd ()->sections
; s
; s
= s
->next
)
11356 if (!(s
->flags
& SEC_LOAD
))
11357 continue; /* Skip non-loadable section. */
11359 if (read_only
&& (s
->flags
& SEC_READONLY
) == 0)
11360 continue; /* Skip writeable sections */
11362 size
= bfd_section_size (s
);
11364 continue; /* Skip zero-length section. */
11366 sectname
= bfd_section_name (s
);
11367 if (args
&& strcmp (args
, sectname
) != 0)
11368 continue; /* Not the section selected by user. */
11370 matched
= 1; /* Do this section. */
11373 gdb::byte_vector
sectdata (size
);
11374 bfd_get_section_contents (current_program_space
->exec_bfd (), s
,
11375 sectdata
.data (), 0, size
);
11377 res
= target_verify_memory (sectdata
.data (), lma
, size
);
11380 error (_("target memory fault, section %s, range %s -- %s"), sectname
,
11381 paddress (current_inferior ()->arch (), lma
),
11382 paddress (current_inferior ()->arch (), lma
+ size
));
11384 gdb_printf ("Section %s, range %s -- %s: ", sectname
,
11385 paddress (current_inferior ()->arch (), lma
),
11386 paddress (current_inferior ()->arch (), lma
+ size
));
11388 gdb_printf ("matched.\n");
11391 gdb_printf ("MIS-MATCHED!\n");
11395 if (mismatched
> 0)
11396 warning (_("One or more sections of the target image does "
11397 "not match the loaded file"));
11398 if (args
&& !matched
)
11399 gdb_printf (_("No loaded section named '%s'.\n"), args
);
11402 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11403 into remote target. The number of bytes written to the remote
11404 target is returned, or -1 for error. */
11407 remote_target::remote_write_qxfer (const char *object_name
,
11408 const char *annex
, const gdb_byte
*writebuf
,
11409 ULONGEST offset
, LONGEST len
,
11410 ULONGEST
*xfered_len
,
11411 const unsigned int which_packet
)
11415 struct remote_state
*rs
= get_remote_state ();
11416 int max_size
= get_memory_write_packet_size ();
11418 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11419 return TARGET_XFER_E_IO
;
11421 /* Insert header. */
11422 i
= snprintf (rs
->buf
.data (), max_size
,
11423 "qXfer:%s:write:%s:%s:",
11424 object_name
, annex
? annex
: "",
11425 phex_nz (offset
, sizeof offset
));
11426 max_size
-= (i
+ 1);
11428 /* Escape as much data as fits into rs->buf. */
11429 buf_len
= remote_escape_output
11430 (writebuf
, len
, 1, (gdb_byte
*) rs
->buf
.data () + i
, &max_size
, max_size
);
11432 if (putpkt_binary (rs
->buf
.data (), i
+ buf_len
) < 0
11433 || getpkt (&rs
->buf
) < 0
11434 || m_features
.packet_ok (rs
->buf
, which_packet
) != PACKET_OK
)
11435 return TARGET_XFER_E_IO
;
11437 unpack_varlen_hex (rs
->buf
.data (), &n
);
11440 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11443 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11444 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11445 number of bytes read is returned, or 0 for EOF, or -1 for error.
11446 The number of bytes read may be less than LEN without indicating an
11447 EOF. PACKET is checked and updated to indicate whether the remote
11448 target supports this object. */
11451 remote_target::remote_read_qxfer (const char *object_name
,
11453 gdb_byte
*readbuf
, ULONGEST offset
,
11455 ULONGEST
*xfered_len
,
11456 const unsigned int which_packet
)
11458 struct remote_state
*rs
= get_remote_state ();
11459 LONGEST i
, n
, packet_len
;
11461 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11462 return TARGET_XFER_E_IO
;
11464 /* Check whether we've cached an end-of-object packet that matches
11466 if (rs
->finished_object
)
11468 if (strcmp (object_name
, rs
->finished_object
) == 0
11469 && strcmp (annex
? annex
: "", rs
->finished_annex
) == 0
11470 && offset
== rs
->finished_offset
)
11471 return TARGET_XFER_EOF
;
11474 /* Otherwise, we're now reading something different. Discard
11476 xfree (rs
->finished_object
);
11477 xfree (rs
->finished_annex
);
11478 rs
->finished_object
= NULL
;
11479 rs
->finished_annex
= NULL
;
11482 /* Request only enough to fit in a single packet. The actual data
11483 may not, since we don't know how much of it will need to be escaped;
11484 the target is free to respond with slightly less data. We subtract
11485 five to account for the response type and the protocol frame. */
11486 n
= std::min
<LONGEST
> (get_remote_packet_size () - 5, len
);
11487 snprintf (rs
->buf
.data (), get_remote_packet_size () - 4,
11488 "qXfer:%s:read:%s:%s,%s",
11489 object_name
, annex
? annex
: "",
11490 phex_nz (offset
, sizeof offset
),
11491 phex_nz (n
, sizeof n
));
11492 i
= putpkt (rs
->buf
);
11494 return TARGET_XFER_E_IO
;
11497 packet_len
= getpkt (&rs
->buf
);
11499 || m_features
.packet_ok (rs
->buf
, which_packet
) != PACKET_OK
)
11500 return TARGET_XFER_E_IO
;
11502 if (rs
->buf
[0] != 'l' && rs
->buf
[0] != 'm')
11503 error (_("Unknown remote qXfer reply: %s"), rs
->buf
.data ());
11505 /* 'm' means there is (or at least might be) more data after this
11506 batch. That does not make sense unless there's at least one byte
11507 of data in this reply. */
11508 if (rs
->buf
[0] == 'm' && packet_len
== 1)
11509 error (_("Remote qXfer reply contained no data."));
11511 /* Got some data. */
11512 i
= remote_unescape_input ((gdb_byte
*) rs
->buf
.data () + 1,
11513 packet_len
- 1, readbuf
, n
);
11515 /* 'l' is an EOF marker, possibly including a final block of data,
11516 or possibly empty. If we have the final block of a non-empty
11517 object, record this fact to bypass a subsequent partial read. */
11518 if (rs
->buf
[0] == 'l' && offset
+ i
> 0)
11520 rs
->finished_object
= xstrdup (object_name
);
11521 rs
->finished_annex
= xstrdup (annex
? annex
: "");
11522 rs
->finished_offset
= offset
+ i
;
11526 return TARGET_XFER_EOF
;
11530 return TARGET_XFER_OK
;
11534 enum target_xfer_status
11535 remote_target::xfer_partial (enum target_object object
,
11536 const char *annex
, gdb_byte
*readbuf
,
11537 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
11538 ULONGEST
*xfered_len
)
11540 struct remote_state
*rs
;
11545 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11547 set_remote_traceframe ();
11548 set_general_thread (inferior_ptid
);
11550 rs
= get_remote_state ();
11552 /* Handle memory using the standard memory routines. */
11553 if (object
== TARGET_OBJECT_MEMORY
)
11555 /* If the remote target is connected but not running, we should
11556 pass this request down to a lower stratum (e.g. the executable
11558 if (!target_has_execution ())
11559 return TARGET_XFER_EOF
;
11561 if (writebuf
!= NULL
)
11562 return remote_write_bytes (offset
, writebuf
, len
, unit_size
,
11565 return remote_read_bytes (offset
, readbuf
, len
, unit_size
,
11569 /* Handle extra signal info using qxfer packets. */
11570 if (object
== TARGET_OBJECT_SIGNAL_INFO
)
11573 return remote_read_qxfer ("siginfo", annex
, readbuf
, offset
, len
,
11574 xfered_len
, PACKET_qXfer_siginfo_read
);
11576 return remote_write_qxfer ("siginfo", annex
, writebuf
, offset
, len
,
11577 xfered_len
, PACKET_qXfer_siginfo_write
);
11580 if (object
== TARGET_OBJECT_STATIC_TRACE_DATA
)
11583 return remote_read_qxfer ("statictrace", annex
,
11584 readbuf
, offset
, len
, xfered_len
,
11585 PACKET_qXfer_statictrace_read
);
11587 return TARGET_XFER_E_IO
;
11590 /* Only handle flash writes. */
11591 if (writebuf
!= NULL
)
11595 case TARGET_OBJECT_FLASH
:
11596 return remote_flash_write (offset
, len
, xfered_len
,
11600 return TARGET_XFER_E_IO
;
11604 /* Map pre-existing objects onto letters. DO NOT do this for new
11605 objects!!! Instead specify new query packets. */
11608 case TARGET_OBJECT_AVR
:
11612 case TARGET_OBJECT_AUXV
:
11613 gdb_assert (annex
== NULL
);
11614 return remote_read_qxfer
11615 ("auxv", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_auxv
);
11617 case TARGET_OBJECT_AVAILABLE_FEATURES
:
11618 return remote_read_qxfer
11619 ("features", annex
, readbuf
, offset
, len
, xfered_len
,
11620 PACKET_qXfer_features
);
11622 case TARGET_OBJECT_LIBRARIES
:
11623 return remote_read_qxfer
11624 ("libraries", annex
, readbuf
, offset
, len
, xfered_len
,
11625 PACKET_qXfer_libraries
);
11627 case TARGET_OBJECT_LIBRARIES_SVR4
:
11628 return remote_read_qxfer
11629 ("libraries-svr4", annex
, readbuf
, offset
, len
, xfered_len
,
11630 PACKET_qXfer_libraries_svr4
);
11632 case TARGET_OBJECT_MEMORY_MAP
:
11633 gdb_assert (annex
== NULL
);
11634 return remote_read_qxfer
11635 ("memory-map", annex
, readbuf
, offset
, len
, xfered_len
,
11636 PACKET_qXfer_memory_map
);
11638 case TARGET_OBJECT_OSDATA
:
11639 /* Should only get here if we're connected. */
11640 gdb_assert (rs
->remote_desc
);
11641 return remote_read_qxfer
11642 ("osdata", annex
, readbuf
, offset
, len
, xfered_len
,
11643 PACKET_qXfer_osdata
);
11645 case TARGET_OBJECT_THREADS
:
11646 gdb_assert (annex
== NULL
);
11647 return remote_read_qxfer
11648 ("threads", annex
, readbuf
, offset
, len
, xfered_len
,
11649 PACKET_qXfer_threads
);
11651 case TARGET_OBJECT_TRACEFRAME_INFO
:
11652 gdb_assert (annex
== NULL
);
11653 return remote_read_qxfer
11654 ("traceframe-info", annex
, readbuf
, offset
, len
, xfered_len
,
11655 PACKET_qXfer_traceframe_info
);
11657 case TARGET_OBJECT_FDPIC
:
11658 return remote_read_qxfer
11659 ("fdpic", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_fdpic
);
11661 case TARGET_OBJECT_OPENVMS_UIB
:
11662 return remote_read_qxfer
11663 ("uib", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_uib
);
11665 case TARGET_OBJECT_BTRACE
:
11666 return remote_read_qxfer
11667 ("btrace", annex
, readbuf
, offset
, len
, xfered_len
,
11668 PACKET_qXfer_btrace
);
11670 case TARGET_OBJECT_BTRACE_CONF
:
11671 return remote_read_qxfer
11672 ("btrace-conf", annex
, readbuf
, offset
, len
, xfered_len
,
11673 PACKET_qXfer_btrace_conf
);
11675 case TARGET_OBJECT_EXEC_FILE
:
11676 return remote_read_qxfer
11677 ("exec-file", annex
, readbuf
, offset
, len
, xfered_len
,
11678 PACKET_qXfer_exec_file
);
11681 return TARGET_XFER_E_IO
;
11684 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11685 large enough let the caller deal with it. */
11686 if (len
< get_remote_packet_size ())
11687 return TARGET_XFER_E_IO
;
11688 len
= get_remote_packet_size ();
11690 /* Except for querying the minimum buffer size, target must be open. */
11691 if (!rs
->remote_desc
)
11692 error (_("remote query is only available after target open"));
11694 gdb_assert (annex
!= NULL
);
11695 gdb_assert (readbuf
!= NULL
);
11697 p2
= rs
->buf
.data ();
11699 *p2
++ = query_type
;
11701 /* We used one buffer char for the remote protocol q command and
11702 another for the query type. As the remote protocol encapsulation
11703 uses 4 chars plus one extra in case we are debugging
11704 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11707 while (annex
[i
] && (i
< (get_remote_packet_size () - 8)))
11709 /* Bad caller may have sent forbidden characters. */
11710 gdb_assert (isprint (annex
[i
]) && annex
[i
] != '$' && annex
[i
] != '#');
11715 gdb_assert (annex
[i
] == '\0');
11717 i
= putpkt (rs
->buf
);
11719 return TARGET_XFER_E_IO
;
11722 strcpy ((char *) readbuf
, rs
->buf
.data ());
11724 *xfered_len
= strlen ((char *) readbuf
);
11725 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11728 /* Implementation of to_get_memory_xfer_limit. */
11731 remote_target::get_memory_xfer_limit ()
11733 return get_memory_write_packet_size ();
11737 remote_target::search_memory (CORE_ADDR start_addr
, ULONGEST search_space_len
,
11738 const gdb_byte
*pattern
, ULONGEST pattern_len
,
11739 CORE_ADDR
*found_addrp
)
11741 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11742 struct remote_state
*rs
= get_remote_state ();
11743 int max_size
= get_memory_write_packet_size ();
11745 /* Number of packet bytes used to encode the pattern;
11746 this could be more than PATTERN_LEN due to escape characters. */
11747 int escaped_pattern_len
;
11748 /* Amount of pattern that was encodable in the packet. */
11749 int used_pattern_len
;
11752 ULONGEST found_addr
;
11754 auto read_memory
= [this] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
11756 return (target_read (this, TARGET_OBJECT_MEMORY
, NULL
, result
, addr
, len
)
11760 /* Don't go to the target if we don't have to. This is done before
11761 checking packet_support to avoid the possibility that a success for this
11762 edge case means the facility works in general. */
11763 if (pattern_len
> search_space_len
)
11765 if (pattern_len
== 0)
11767 *found_addrp
= start_addr
;
11771 /* If we already know the packet isn't supported, fall back to the simple
11772 way of searching memory. */
11774 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
11776 /* Target doesn't provided special support, fall back and use the
11777 standard support (copy memory and do the search here). */
11778 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
11779 pattern
, pattern_len
, found_addrp
);
11782 /* Make sure the remote is pointing at the right process. */
11783 set_general_process ();
11785 /* Insert header. */
11786 i
= snprintf (rs
->buf
.data (), max_size
,
11787 "qSearch:memory:%s;%s;",
11788 phex_nz (start_addr
, addr_size
),
11789 phex_nz (search_space_len
, sizeof (search_space_len
)));
11790 max_size
-= (i
+ 1);
11792 /* Escape as much data as fits into rs->buf. */
11793 escaped_pattern_len
=
11794 remote_escape_output (pattern
, pattern_len
, 1,
11795 (gdb_byte
*) rs
->buf
.data () + i
,
11796 &used_pattern_len
, max_size
);
11798 /* Bail if the pattern is too large. */
11799 if (used_pattern_len
!= pattern_len
)
11800 error (_("Pattern is too large to transmit to remote target."));
11802 if (putpkt_binary (rs
->buf
.data (), i
+ escaped_pattern_len
) < 0
11803 || getpkt (&rs
->buf
) < 0
11804 || m_features
.packet_ok (rs
->buf
, PACKET_qSearch_memory
) != PACKET_OK
)
11806 /* The request may not have worked because the command is not
11807 supported. If so, fall back to the simple way. */
11808 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
11810 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
11811 pattern
, pattern_len
, found_addrp
);
11816 if (rs
->buf
[0] == '0')
11818 else if (rs
->buf
[0] == '1')
11821 if (rs
->buf
[1] != ',')
11822 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
11823 unpack_varlen_hex (&rs
->buf
[2], &found_addr
);
11824 *found_addrp
= found_addr
;
11827 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
11833 remote_target::rcmd (const char *command
, struct ui_file
*outbuf
)
11835 struct remote_state
*rs
= get_remote_state ();
11836 char *p
= rs
->buf
.data ();
11838 if (!rs
->remote_desc
)
11839 error (_("remote rcmd is only available after target open"));
11841 /* Send a NULL command across as an empty command. */
11842 if (command
== NULL
)
11845 /* The query prefix. */
11846 strcpy (rs
->buf
.data (), "qRcmd,");
11847 p
= strchr (rs
->buf
.data (), '\0');
11849 if ((strlen (rs
->buf
.data ()) + strlen (command
) * 2 + 8/*misc*/)
11850 > get_remote_packet_size ())
11851 error (_("\"monitor\" command ``%s'' is too long."), command
);
11853 /* Encode the actual command. */
11854 bin2hex ((const gdb_byte
*) command
, p
, strlen (command
));
11856 if (putpkt (rs
->buf
) < 0)
11857 error (_("Communication problem with target."));
11859 /* get/display the response */
11864 /* XXX - see also remote_get_noisy_reply(). */
11865 QUIT
; /* Allow user to bail out with ^C. */
11867 if (getpkt (&rs
->buf
) == -1)
11869 /* Timeout. Continue to (try to) read responses.
11870 This is better than stopping with an error, assuming the stub
11871 is still executing the (long) monitor command.
11872 If needed, the user can interrupt gdb using C-c, obtaining
11873 an effect similar to stop on timeout. */
11876 buf
= rs
->buf
.data ();
11877 if (buf
[0] == '\0')
11878 error (_("Target does not support this command."));
11879 if (buf
[0] == 'O' && buf
[1] != 'K')
11881 remote_console_output (buf
+ 1); /* 'O' message from stub. */
11884 if (strcmp (buf
, "OK") == 0)
11886 if (strlen (buf
) == 3 && buf
[0] == 'E'
11887 && isxdigit (buf
[1]) && isxdigit (buf
[2]))
11889 error (_("Protocol error with Rcmd"));
11891 for (p
= buf
; p
[0] != '\0' && p
[1] != '\0'; p
+= 2)
11893 char c
= (fromhex (p
[0]) << 4) + fromhex (p
[1]);
11895 gdb_putc (c
, outbuf
);
11901 std::vector
<mem_region
>
11902 remote_target::memory_map ()
11904 std::vector
<mem_region
> result
;
11905 gdb::optional
<gdb::char_vector
> text
11906 = target_read_stralloc (current_inferior ()->top_target (),
11907 TARGET_OBJECT_MEMORY_MAP
, NULL
);
11910 result
= parse_memory_map (text
->data ());
11915 /* Set of callbacks used to implement the 'maint packet' command. */
11917 struct cli_packet_command_callbacks
: public send_remote_packet_callbacks
11919 /* Called before the packet is sent. BUF is the packet content before
11920 the protocol specific prefix, suffix, and escaping is added. */
11922 void sending (gdb::array_view
<const char> &buf
) override
11924 gdb_puts ("sending: ");
11925 print_packet (buf
);
11929 /* Called with BUF, the reply from the remote target. */
11931 void received (gdb::array_view
<const char> &buf
) override
11933 gdb_puts ("received: \"");
11934 print_packet (buf
);
11940 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11941 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11944 print_packet (gdb::array_view
<const char> &buf
)
11948 for (int i
= 0; i
< buf
.size (); ++i
)
11950 gdb_byte c
= buf
[i
];
11952 gdb_putc (c
, &stb
);
11954 gdb_printf (&stb
, "\\x%02x", (unsigned char) c
);
11957 gdb_puts (stb
.string ().c_str ());
11961 /* See remote.h. */
11964 send_remote_packet (gdb::array_view
<const char> &buf
,
11965 send_remote_packet_callbacks
*callbacks
)
11967 if (buf
.size () == 0 || buf
.data ()[0] == '\0')
11968 error (_("a remote packet must not be empty"));
11970 remote_target
*remote
= get_current_remote_target ();
11971 if (remote
== nullptr)
11972 error (_("packets can only be sent to a remote target"));
11974 callbacks
->sending (buf
);
11976 remote
->putpkt_binary (buf
.data (), buf
.size ());
11977 remote_state
*rs
= remote
->get_remote_state ();
11978 int bytes
= remote
->getpkt (&rs
->buf
);
11981 error (_("error while fetching packet from remote target"));
11983 gdb::array_view
<const char> view (&rs
->buf
[0], bytes
);
11984 callbacks
->received (view
);
11987 /* Entry point for the 'maint packet' command. */
11990 cli_packet_command (const char *args
, int from_tty
)
11992 cli_packet_command_callbacks cb
;
11993 gdb::array_view
<const char> view
11994 = gdb::make_array_view (args
, args
== nullptr ? 0 : strlen (args
));
11995 send_remote_packet (view
, &cb
);
11999 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12001 static void display_thread_info (struct gdb_ext_thread_info
*info
);
12003 static void threadset_test_cmd (char *cmd
, int tty
);
12005 static void threadalive_test (char *cmd
, int tty
);
12007 static void threadlist_test_cmd (char *cmd
, int tty
);
12009 int get_and_display_threadinfo (threadref
*ref
);
12011 static void threadinfo_test_cmd (char *cmd
, int tty
);
12013 static int thread_display_step (threadref
*ref
, void *context
);
12015 static void threadlist_update_test_cmd (char *cmd
, int tty
);
12017 static void init_remote_threadtests (void);
12019 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12022 threadset_test_cmd (const char *cmd
, int tty
)
12024 int sample_thread
= SAMPLE_THREAD
;
12026 gdb_printf (_("Remote threadset test\n"));
12027 set_general_thread (sample_thread
);
12032 threadalive_test (const char *cmd
, int tty
)
12034 int sample_thread
= SAMPLE_THREAD
;
12035 int pid
= inferior_ptid
.pid ();
12036 ptid_t ptid
= ptid_t (pid
, sample_thread
, 0);
12038 if (remote_thread_alive (ptid
))
12039 gdb_printf ("PASS: Thread alive test\n");
12041 gdb_printf ("FAIL: Thread alive test\n");
12044 void output_threadid (char *title
, threadref
*ref
);
12047 output_threadid (char *title
, threadref
*ref
)
12051 pack_threadid (&hexid
[0], ref
); /* Convert thread id into hex. */
12053 gdb_printf ("%s %s\n", title
, (&hexid
[0]));
12057 threadlist_test_cmd (const char *cmd
, int tty
)
12060 threadref nextthread
;
12061 int done
, result_count
;
12062 threadref threadlist
[3];
12064 gdb_printf ("Remote Threadlist test\n");
12065 if (!remote_get_threadlist (startflag
, &nextthread
, 3, &done
,
12066 &result_count
, &threadlist
[0]))
12067 gdb_printf ("FAIL: threadlist test\n");
12070 threadref
*scan
= threadlist
;
12071 threadref
*limit
= scan
+ result_count
;
12073 while (scan
< limit
)
12074 output_threadid (" thread ", scan
++);
12079 display_thread_info (struct gdb_ext_thread_info
*info
)
12081 output_threadid ("Threadid: ", &info
->threadid
);
12082 gdb_printf ("Name: %s\n ", info
->shortname
);
12083 gdb_printf ("State: %s\n", info
->display
);
12084 gdb_printf ("other: %s\n\n", info
->more_display
);
12088 get_and_display_threadinfo (threadref
*ref
)
12092 struct gdb_ext_thread_info threadinfo
;
12094 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
12095 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
12096 if (0 != (result
= remote_get_threadinfo (ref
, set
, &threadinfo
)))
12097 display_thread_info (&threadinfo
);
12102 threadinfo_test_cmd (const char *cmd
, int tty
)
12104 int athread
= SAMPLE_THREAD
;
12108 int_to_threadref (&thread
, athread
);
12109 gdb_printf ("Remote Threadinfo test\n");
12110 if (!get_and_display_threadinfo (&thread
))
12111 gdb_printf ("FAIL cannot get thread info\n");
12115 thread_display_step (threadref
*ref
, void *context
)
12117 /* output_threadid(" threadstep ",ref); *//* simple test */
12118 return get_and_display_threadinfo (ref
);
12122 threadlist_update_test_cmd (const char *cmd
, int tty
)
12124 gdb_printf ("Remote Threadlist update test\n");
12125 remote_threadlist_iterator (thread_display_step
, 0, CRAZY_MAX_THREADS
);
12129 init_remote_threadtests (void)
12131 add_com ("tlist", class_obscure
, threadlist_test_cmd
,
12132 _("Fetch and print the remote list of "
12133 "thread identifiers, one pkt only."));
12134 add_com ("tinfo", class_obscure
, threadinfo_test_cmd
,
12135 _("Fetch and display info about one thread."));
12136 add_com ("tset", class_obscure
, threadset_test_cmd
,
12137 _("Test setting to a different thread."));
12138 add_com ("tupd", class_obscure
, threadlist_update_test_cmd
,
12139 _("Iterate through updating all remote thread info."));
12140 add_com ("talive", class_obscure
, threadalive_test
,
12141 _("Remote thread alive test."));
12146 /* Convert a thread ID to a string. */
12149 remote_target::pid_to_str (ptid_t ptid
)
12151 if (ptid
== null_ptid
)
12152 return normal_pid_to_str (ptid
);
12153 else if (ptid
.is_pid ())
12155 /* Printing an inferior target id. */
12157 /* When multi-process extensions are off, there's no way in the
12158 remote protocol to know the remote process id, if there's any
12159 at all. There's one exception --- when we're connected with
12160 target extended-remote, and we manually attached to a process
12161 with "attach PID". We don't record anywhere a flag that
12162 allows us to distinguish that case from the case of
12163 connecting with extended-remote and the stub already being
12164 attached to a process, and reporting yes to qAttached, hence
12165 no smart special casing here. */
12166 if (!m_features
.remote_multi_process_p ())
12167 return "Remote target";
12169 return normal_pid_to_str (ptid
);
12173 if (magic_null_ptid
== ptid
)
12174 return "Thread <main>";
12175 else if (m_features
.remote_multi_process_p ())
12176 if (ptid
.lwp () == 0)
12177 return normal_pid_to_str (ptid
);
12179 return string_printf ("Thread %d.%ld",
12180 ptid
.pid (), ptid
.lwp ());
12182 return string_printf ("Thread %ld", ptid
.lwp ());
12186 /* Get the address of the thread local variable in OBJFILE which is
12187 stored at OFFSET within the thread local storage for thread PTID. */
12190 remote_target::get_thread_local_address (ptid_t ptid
, CORE_ADDR lm
,
12193 if (m_features
.packet_support (PACKET_qGetTLSAddr
) != PACKET_DISABLE
)
12195 struct remote_state
*rs
= get_remote_state ();
12196 char *p
= rs
->buf
.data ();
12197 char *endp
= p
+ get_remote_packet_size ();
12198 enum packet_result result
;
12200 strcpy (p
, "qGetTLSAddr:");
12202 p
= write_ptid (p
, endp
, ptid
);
12204 p
+= hexnumstr (p
, offset
);
12206 p
+= hexnumstr (p
, lm
);
12211 result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTLSAddr
);
12212 if (result
== PACKET_OK
)
12216 unpack_varlen_hex (rs
->buf
.data (), &addr
);
12219 else if (result
== PACKET_UNKNOWN
)
12220 throw_error (TLS_GENERIC_ERROR
,
12221 _("Remote target doesn't support qGetTLSAddr packet"));
12223 throw_error (TLS_GENERIC_ERROR
,
12224 _("Remote target failed to process qGetTLSAddr request"));
12227 throw_error (TLS_GENERIC_ERROR
,
12228 _("TLS not supported or disabled on this target"));
12233 /* Provide thread local base, i.e. Thread Information Block address.
12234 Returns 1 if ptid is found and thread_local_base is non zero. */
12237 remote_target::get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
)
12239 if (m_features
.packet_support (PACKET_qGetTIBAddr
) != PACKET_DISABLE
)
12241 struct remote_state
*rs
= get_remote_state ();
12242 char *p
= rs
->buf
.data ();
12243 char *endp
= p
+ get_remote_packet_size ();
12244 enum packet_result result
;
12246 strcpy (p
, "qGetTIBAddr:");
12248 p
= write_ptid (p
, endp
, ptid
);
12253 result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTIBAddr
);
12254 if (result
== PACKET_OK
)
12257 unpack_varlen_hex (rs
->buf
.data (), &val
);
12259 *addr
= (CORE_ADDR
) val
;
12262 else if (result
== PACKET_UNKNOWN
)
12263 error (_("Remote target doesn't support qGetTIBAddr packet"));
12265 error (_("Remote target failed to process qGetTIBAddr request"));
12268 error (_("qGetTIBAddr not supported or disabled on this target"));
12273 /* Support for inferring a target description based on the current
12274 architecture and the size of a 'g' packet. While the 'g' packet
12275 can have any size (since optional registers can be left off the
12276 end), some sizes are easily recognizable given knowledge of the
12277 approximate architecture. */
12279 struct remote_g_packet_guess
12281 remote_g_packet_guess (int bytes_
, const struct target_desc
*tdesc_
)
12288 const struct target_desc
*tdesc
;
12291 struct remote_g_packet_data
12293 std::vector
<remote_g_packet_guess
> guesses
;
12296 static const registry
<gdbarch
>::key
<struct remote_g_packet_data
>
12297 remote_g_packet_data_handle
;
12299 static struct remote_g_packet_data
*
12300 get_g_packet_data (struct gdbarch
*gdbarch
)
12302 struct remote_g_packet_data
*data
12303 = remote_g_packet_data_handle
.get (gdbarch
);
12304 if (data
== nullptr)
12305 data
= remote_g_packet_data_handle
.emplace (gdbarch
);
12310 register_remote_g_packet_guess (struct gdbarch
*gdbarch
, int bytes
,
12311 const struct target_desc
*tdesc
)
12313 struct remote_g_packet_data
*data
= get_g_packet_data (gdbarch
);
12315 gdb_assert (tdesc
!= NULL
);
12317 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12318 if (guess
.bytes
== bytes
)
12319 internal_error (_("Duplicate g packet description added for size %d"),
12322 data
->guesses
.emplace_back (bytes
, tdesc
);
12325 /* Return true if remote_read_description would do anything on this target
12326 and architecture, false otherwise. */
12329 remote_read_description_p (struct target_ops
*target
)
12331 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12333 return !data
->guesses
.empty ();
12336 const struct target_desc
*
12337 remote_target::read_description ()
12339 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12341 /* Do not try this during initial connection, when we do not know
12342 whether there is a running but stopped thread. */
12343 if (!target_has_execution () || inferior_ptid
== null_ptid
)
12344 return beneath ()->read_description ();
12346 if (!data
->guesses
.empty ())
12348 int bytes
= send_g_packet ();
12350 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12351 if (guess
.bytes
== bytes
)
12352 return guess
.tdesc
;
12354 /* We discard the g packet. A minor optimization would be to
12355 hold on to it, and fill the register cache once we have selected
12356 an architecture, but it's too tricky to do safely. */
12359 return beneath ()->read_description ();
12362 /* Remote file transfer support. This is host-initiated I/O, not
12363 target-initiated; for target-initiated, see remote-fileio.c. */
12365 /* If *LEFT is at least the length of STRING, copy STRING to
12366 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12367 decrease *LEFT. Otherwise raise an error. */
12370 remote_buffer_add_string (char **buffer
, int *left
, const char *string
)
12372 int len
= strlen (string
);
12375 error (_("Packet too long for target."));
12377 memcpy (*buffer
, string
, len
);
12381 /* NUL-terminate the buffer as a convenience, if there is
12387 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
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_bytes (char **buffer
, int *left
, const gdb_byte
*bytes
,
12395 if (2 * len
> *left
)
12396 error (_("Packet too long for target."));
12398 bin2hex (bytes
, *buffer
, len
);
12399 *buffer
+= 2 * len
;
12402 /* NUL-terminate the buffer as a convenience, if there is
12408 /* If *LEFT is large enough, convert VALUE to hex and add it to
12409 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12410 decrease *LEFT. Otherwise raise an error. */
12413 remote_buffer_add_int (char **buffer
, int *left
, ULONGEST value
)
12415 int len
= hexnumlen (value
);
12418 error (_("Packet too long for target."));
12420 hexnumstr (*buffer
, value
);
12424 /* NUL-terminate the buffer as a convenience, if there is
12430 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12431 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12432 was included, and *ATTACHMENT to point to the start of the annex
12433 if any. The length of the packet isn't needed here; there may
12434 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12436 Return 0 if the packet could be parsed, -1 if it could not. If
12437 -1 is returned, the other variables may not be initialized. */
12440 remote_hostio_parse_result (const char *buffer
, int *retcode
,
12441 fileio_error
*remote_errno
, const char **attachment
)
12445 *remote_errno
= FILEIO_SUCCESS
;
12446 *attachment
= NULL
;
12448 if (buffer
[0] != 'F')
12452 *retcode
= strtol (&buffer
[1], &p
, 16);
12453 if (errno
!= 0 || p
== &buffer
[1])
12456 /* Check for ",errno". */
12460 *remote_errno
= (fileio_error
) strtol (p
+ 1, &p2
, 16);
12461 if (errno
!= 0 || p
+ 1 == p2
)
12466 /* Check for ";attachment". If there is no attachment, the
12467 packet should end here. */
12470 *attachment
= p
+ 1;
12473 else if (*p
== '\0')
12479 /* Send a prepared I/O packet to the target and read its response.
12480 The prepared packet is in the global RS->BUF before this function
12481 is called, and the answer is there when we return.
12483 COMMAND_BYTES is the length of the request to send, which may include
12484 binary data. WHICH_PACKET is the packet configuration to check
12485 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12486 is set to the error number and -1 is returned. Otherwise the value
12487 returned by the function is returned.
12489 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12490 attachment is expected; an error will be reported if there's a
12491 mismatch. If one is found, *ATTACHMENT will be set to point into
12492 the packet buffer and *ATTACHMENT_LEN will be set to the
12493 attachment's length. */
12496 remote_target::remote_hostio_send_command (int command_bytes
, int which_packet
,
12497 fileio_error
*remote_errno
, const char **attachment
,
12498 int *attachment_len
)
12500 struct remote_state
*rs
= get_remote_state ();
12501 int ret
, bytes_read
;
12502 const char *attachment_tmp
;
12504 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
12506 *remote_errno
= FILEIO_ENOSYS
;
12510 putpkt_binary (rs
->buf
.data (), command_bytes
);
12511 bytes_read
= getpkt (&rs
->buf
);
12513 /* If it timed out, something is wrong. Don't try to parse the
12515 if (bytes_read
< 0)
12517 *remote_errno
= FILEIO_EINVAL
;
12521 switch (m_features
.packet_ok (rs
->buf
, which_packet
))
12524 *remote_errno
= FILEIO_EINVAL
;
12526 case PACKET_UNKNOWN
:
12527 *remote_errno
= FILEIO_ENOSYS
;
12533 if (remote_hostio_parse_result (rs
->buf
.data (), &ret
, remote_errno
,
12536 *remote_errno
= FILEIO_EINVAL
;
12540 /* Make sure we saw an attachment if and only if we expected one. */
12541 if ((attachment_tmp
== NULL
&& attachment
!= NULL
)
12542 || (attachment_tmp
!= NULL
&& attachment
== NULL
))
12544 *remote_errno
= FILEIO_EINVAL
;
12548 /* If an attachment was found, it must point into the packet buffer;
12549 work out how many bytes there were. */
12550 if (attachment_tmp
!= NULL
)
12552 *attachment
= attachment_tmp
;
12553 *attachment_len
= bytes_read
- (*attachment
- rs
->buf
.data ());
12559 /* See declaration.h. */
12562 readahead_cache::invalidate ()
12567 /* See declaration.h. */
12570 readahead_cache::invalidate_fd (int fd
)
12572 if (this->fd
== fd
)
12576 /* Set the filesystem remote_hostio functions that take FILENAME
12577 arguments will use. Return 0 on success, or -1 if an error
12578 occurs (and set *REMOTE_ERRNO). */
12581 remote_target::remote_hostio_set_filesystem (struct inferior
*inf
,
12582 fileio_error
*remote_errno
)
12584 struct remote_state
*rs
= get_remote_state ();
12585 int required_pid
= (inf
== NULL
|| inf
->fake_pid_p
) ? 0 : inf
->pid
;
12586 char *p
= rs
->buf
.data ();
12587 int left
= get_remote_packet_size () - 1;
12591 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12594 if (rs
->fs_pid
!= -1 && required_pid
== rs
->fs_pid
)
12597 remote_buffer_add_string (&p
, &left
, "vFile:setfs:");
12599 xsnprintf (arg
, sizeof (arg
), "%x", required_pid
);
12600 remote_buffer_add_string (&p
, &left
, arg
);
12602 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_setfs
,
12603 remote_errno
, NULL
, NULL
);
12605 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12609 rs
->fs_pid
= required_pid
;
12614 /* Implementation of to_fileio_open. */
12617 remote_target::remote_hostio_open (inferior
*inf
, const char *filename
,
12618 int flags
, int mode
, int warn_if_slow
,
12619 fileio_error
*remote_errno
)
12621 struct remote_state
*rs
= get_remote_state ();
12622 char *p
= rs
->buf
.data ();
12623 int left
= get_remote_packet_size () - 1;
12627 static int warning_issued
= 0;
12629 gdb_printf (_("Reading %s from remote target...\n"),
12632 if (!warning_issued
)
12634 warning (_("File transfers from remote targets can be slow."
12635 " Use \"set sysroot\" to access files locally"
12637 warning_issued
= 1;
12641 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12644 remote_buffer_add_string (&p
, &left
, "vFile:open:");
12646 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12647 strlen (filename
));
12648 remote_buffer_add_string (&p
, &left
, ",");
12650 remote_buffer_add_int (&p
, &left
, flags
);
12651 remote_buffer_add_string (&p
, &left
, ",");
12653 remote_buffer_add_int (&p
, &left
, mode
);
12655 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_open
,
12656 remote_errno
, NULL
, NULL
);
12660 remote_target::fileio_open (struct inferior
*inf
, const char *filename
,
12661 int flags
, int mode
, int warn_if_slow
,
12662 fileio_error
*remote_errno
)
12664 return remote_hostio_open (inf
, filename
, flags
, mode
, warn_if_slow
,
12668 /* Implementation of to_fileio_pwrite. */
12671 remote_target::remote_hostio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12672 ULONGEST offset
, fileio_error
*remote_errno
)
12674 struct remote_state
*rs
= get_remote_state ();
12675 char *p
= rs
->buf
.data ();
12676 int left
= get_remote_packet_size ();
12679 rs
->readahead_cache
.invalidate_fd (fd
);
12681 remote_buffer_add_string (&p
, &left
, "vFile:pwrite:");
12683 remote_buffer_add_int (&p
, &left
, fd
);
12684 remote_buffer_add_string (&p
, &left
, ",");
12686 remote_buffer_add_int (&p
, &left
, offset
);
12687 remote_buffer_add_string (&p
, &left
, ",");
12689 p
+= remote_escape_output (write_buf
, len
, 1, (gdb_byte
*) p
, &out_len
,
12690 (get_remote_packet_size ()
12691 - (p
- rs
->buf
.data ())));
12693 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pwrite
,
12694 remote_errno
, NULL
, NULL
);
12698 remote_target::fileio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12699 ULONGEST offset
, fileio_error
*remote_errno
)
12701 return remote_hostio_pwrite (fd
, write_buf
, len
, offset
, remote_errno
);
12704 /* Helper for the implementation of to_fileio_pread. Read the file
12705 from the remote side with vFile:pread. */
12708 remote_target::remote_hostio_pread_vFile (int fd
, gdb_byte
*read_buf
, int len
,
12709 ULONGEST offset
, fileio_error
*remote_errno
)
12711 struct remote_state
*rs
= get_remote_state ();
12712 char *p
= rs
->buf
.data ();
12713 const char *attachment
;
12714 int left
= get_remote_packet_size ();
12715 int ret
, attachment_len
;
12718 remote_buffer_add_string (&p
, &left
, "vFile:pread:");
12720 remote_buffer_add_int (&p
, &left
, fd
);
12721 remote_buffer_add_string (&p
, &left
, ",");
12723 remote_buffer_add_int (&p
, &left
, len
);
12724 remote_buffer_add_string (&p
, &left
, ",");
12726 remote_buffer_add_int (&p
, &left
, offset
);
12728 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pread
,
12729 remote_errno
, &attachment
,
12735 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12737 if (read_len
!= ret
)
12738 error (_("Read returned %d, but %d bytes."), ret
, (int) read_len
);
12743 /* See declaration.h. */
12746 readahead_cache::pread (int fd
, gdb_byte
*read_buf
, size_t len
,
12750 && this->offset
<= offset
12751 && offset
< this->offset
+ this->buf
.size ())
12753 ULONGEST max
= this->offset
+ this->buf
.size ();
12755 if (offset
+ len
> max
)
12756 len
= max
- offset
;
12758 memcpy (read_buf
, &this->buf
[offset
- this->offset
], len
);
12765 /* Implementation of to_fileio_pread. */
12768 remote_target::remote_hostio_pread (int fd
, gdb_byte
*read_buf
, int len
,
12769 ULONGEST offset
, fileio_error
*remote_errno
)
12772 struct remote_state
*rs
= get_remote_state ();
12773 readahead_cache
*cache
= &rs
->readahead_cache
;
12775 ret
= cache
->pread (fd
, read_buf
, len
, offset
);
12778 cache
->hit_count
++;
12780 remote_debug_printf ("readahead cache hit %s",
12781 pulongest (cache
->hit_count
));
12785 cache
->miss_count
++;
12787 remote_debug_printf ("readahead cache miss %s",
12788 pulongest (cache
->miss_count
));
12791 cache
->offset
= offset
;
12792 cache
->buf
.resize (get_remote_packet_size ());
12794 ret
= remote_hostio_pread_vFile (cache
->fd
, &cache
->buf
[0],
12795 cache
->buf
.size (),
12796 cache
->offset
, remote_errno
);
12799 cache
->invalidate_fd (fd
);
12803 cache
->buf
.resize (ret
);
12804 return cache
->pread (fd
, read_buf
, len
, offset
);
12808 remote_target::fileio_pread (int fd
, gdb_byte
*read_buf
, int len
,
12809 ULONGEST offset
, fileio_error
*remote_errno
)
12811 return remote_hostio_pread (fd
, read_buf
, len
, offset
, remote_errno
);
12814 /* Implementation of to_fileio_close. */
12817 remote_target::remote_hostio_close (int fd
, fileio_error
*remote_errno
)
12819 struct remote_state
*rs
= get_remote_state ();
12820 char *p
= rs
->buf
.data ();
12821 int left
= get_remote_packet_size () - 1;
12823 rs
->readahead_cache
.invalidate_fd (fd
);
12825 remote_buffer_add_string (&p
, &left
, "vFile:close:");
12827 remote_buffer_add_int (&p
, &left
, fd
);
12829 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_close
,
12830 remote_errno
, NULL
, NULL
);
12834 remote_target::fileio_close (int fd
, fileio_error
*remote_errno
)
12836 return remote_hostio_close (fd
, remote_errno
);
12839 /* Implementation of to_fileio_unlink. */
12842 remote_target::remote_hostio_unlink (inferior
*inf
, const char *filename
,
12843 fileio_error
*remote_errno
)
12845 struct remote_state
*rs
= get_remote_state ();
12846 char *p
= rs
->buf
.data ();
12847 int left
= get_remote_packet_size () - 1;
12849 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12852 remote_buffer_add_string (&p
, &left
, "vFile:unlink:");
12854 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12855 strlen (filename
));
12857 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_unlink
,
12858 remote_errno
, NULL
, NULL
);
12862 remote_target::fileio_unlink (struct inferior
*inf
, const char *filename
,
12863 fileio_error
*remote_errno
)
12865 return remote_hostio_unlink (inf
, filename
, remote_errno
);
12868 /* Implementation of to_fileio_readlink. */
12870 gdb::optional
<std::string
>
12871 remote_target::fileio_readlink (struct inferior
*inf
, const char *filename
,
12872 fileio_error
*remote_errno
)
12874 struct remote_state
*rs
= get_remote_state ();
12875 char *p
= rs
->buf
.data ();
12876 const char *attachment
;
12877 int left
= get_remote_packet_size ();
12878 int len
, attachment_len
;
12881 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12884 remote_buffer_add_string (&p
, &left
, "vFile:readlink:");
12886 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12887 strlen (filename
));
12889 len
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_readlink
,
12890 remote_errno
, &attachment
,
12896 std::string
ret (len
, '\0');
12898 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12899 (gdb_byte
*) &ret
[0], len
);
12900 if (read_len
!= len
)
12901 error (_("Readlink returned %d, but %d bytes."), len
, read_len
);
12906 /* Implementation of to_fileio_fstat. */
12909 remote_target::fileio_fstat (int fd
, struct stat
*st
, fileio_error
*remote_errno
)
12911 struct remote_state
*rs
= get_remote_state ();
12912 char *p
= rs
->buf
.data ();
12913 int left
= get_remote_packet_size ();
12914 int attachment_len
, ret
;
12915 const char *attachment
;
12916 struct fio_stat fst
;
12919 remote_buffer_add_string (&p
, &left
, "vFile:fstat:");
12921 remote_buffer_add_int (&p
, &left
, fd
);
12923 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_fstat
,
12924 remote_errno
, &attachment
,
12928 if (*remote_errno
!= FILEIO_ENOSYS
)
12931 /* Strictly we should return -1, ENOSYS here, but when
12932 "set sysroot remote:" was implemented in August 2008
12933 BFD's need for a stat function was sidestepped with
12934 this hack. This was not remedied until March 2015
12935 so we retain the previous behavior to avoid breaking
12938 Note that the memset is a March 2015 addition; older
12939 GDBs set st_size *and nothing else* so the structure
12940 would have garbage in all other fields. This might
12941 break something but retaining the previous behavior
12942 here would be just too wrong. */
12944 memset (st
, 0, sizeof (struct stat
));
12945 st
->st_size
= INT_MAX
;
12949 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12950 (gdb_byte
*) &fst
, sizeof (fst
));
12952 if (read_len
!= ret
)
12953 error (_("vFile:fstat returned %d, but %d bytes."), ret
, read_len
);
12955 if (read_len
!= sizeof (fst
))
12956 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12957 read_len
, (int) sizeof (fst
));
12959 remote_fileio_to_host_stat (&fst
, st
);
12964 /* Implementation of to_filesystem_is_local. */
12967 remote_target::filesystem_is_local ()
12969 /* Valgrind GDB presents itself as a remote target but works
12970 on the local filesystem: it does not implement remote get
12971 and users are not expected to set a sysroot. To handle
12972 this case we treat the remote filesystem as local if the
12973 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12974 does not support vFile:open. */
12975 if (gdb_sysroot
== TARGET_SYSROOT_PREFIX
)
12977 packet_support ps
= m_features
.packet_support (PACKET_vFile_open
);
12979 if (ps
== PACKET_SUPPORT_UNKNOWN
)
12982 fileio_error remote_errno
;
12984 /* Try opening a file to probe support. The supplied
12985 filename is irrelevant, we only care about whether
12986 the stub recognizes the packet or not. */
12987 fd
= remote_hostio_open (NULL
, "just probing",
12988 FILEIO_O_RDONLY
, 0700, 0,
12992 remote_hostio_close (fd
, &remote_errno
);
12994 ps
= m_features
.packet_support (PACKET_vFile_open
);
12997 if (ps
== PACKET_DISABLE
)
12999 static int warning_issued
= 0;
13001 if (!warning_issued
)
13003 warning (_("remote target does not support file"
13004 " transfer, attempting to access files"
13005 " from local filesystem."));
13006 warning_issued
= 1;
13017 remote_hostio_error (fileio_error errnum
)
13019 int host_error
= fileio_error_to_host (errnum
);
13021 if (host_error
== -1)
13022 error (_("Unknown remote I/O error %d"), errnum
);
13024 error (_("Remote I/O error: %s"), safe_strerror (host_error
));
13027 /* A RAII wrapper around a remote file descriptor. */
13029 class scoped_remote_fd
13032 scoped_remote_fd (remote_target
*remote
, int fd
)
13033 : m_remote (remote
), m_fd (fd
)
13037 ~scoped_remote_fd ()
13043 fileio_error remote_errno
;
13044 m_remote
->remote_hostio_close (m_fd
, &remote_errno
);
13048 /* Swallow exception before it escapes the dtor. If
13049 something goes wrong, likely the connection is gone,
13050 and there's nothing else that can be done. */
13055 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd
);
13057 /* Release ownership of the file descriptor, and return it. */
13058 ATTRIBUTE_UNUSED_RESULT
int release () noexcept
13065 /* Return the owned file descriptor. */
13066 int get () const noexcept
13072 /* The remote target. */
13073 remote_target
*m_remote
;
13075 /* The owned remote I/O file descriptor. */
13080 remote_file_put (const char *local_file
, const char *remote_file
, int from_tty
)
13082 remote_target
*remote
= get_current_remote_target ();
13084 if (remote
== nullptr)
13085 error (_("command can only be used with remote target"));
13087 remote
->remote_file_put (local_file
, remote_file
, from_tty
);
13091 remote_target::remote_file_put (const char *local_file
, const char *remote_file
,
13094 int retcode
, bytes
, io_size
;
13095 fileio_error remote_errno
;
13096 int bytes_in_buffer
;
13100 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "rb");
13102 perror_with_name (local_file
);
13104 scoped_remote_fd fd
13105 (this, remote_hostio_open (NULL
,
13106 remote_file
, (FILEIO_O_WRONLY
| FILEIO_O_CREAT
13108 0700, 0, &remote_errno
));
13109 if (fd
.get () == -1)
13110 remote_hostio_error (remote_errno
);
13112 /* Send up to this many bytes at once. They won't all fit in the
13113 remote packet limit, so we'll transfer slightly fewer. */
13114 io_size
= get_remote_packet_size ();
13115 gdb::byte_vector
buffer (io_size
);
13117 bytes_in_buffer
= 0;
13120 while (bytes_in_buffer
|| !saw_eof
)
13124 bytes
= fread (buffer
.data () + bytes_in_buffer
, 1,
13125 io_size
- bytes_in_buffer
,
13129 if (ferror (file
.get ()))
13130 error (_("Error reading %s."), local_file
);
13133 /* EOF. Unless there is something still in the
13134 buffer from the last iteration, we are done. */
13136 if (bytes_in_buffer
== 0)
13144 bytes
+= bytes_in_buffer
;
13145 bytes_in_buffer
= 0;
13147 retcode
= remote_hostio_pwrite (fd
.get (), buffer
.data (), bytes
,
13148 offset
, &remote_errno
);
13151 remote_hostio_error (remote_errno
);
13152 else if (retcode
== 0)
13153 error (_("Remote write of %d bytes returned 0!"), bytes
);
13154 else if (retcode
< bytes
)
13156 /* Short write. Save the rest of the read data for the next
13158 bytes_in_buffer
= bytes
- retcode
;
13159 memmove (buffer
.data (), buffer
.data () + retcode
, bytes_in_buffer
);
13165 if (remote_hostio_close (fd
.release (), &remote_errno
))
13166 remote_hostio_error (remote_errno
);
13169 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file
);
13173 remote_file_get (const char *remote_file
, const char *local_file
, int from_tty
)
13175 remote_target
*remote
= get_current_remote_target ();
13177 if (remote
== nullptr)
13178 error (_("command can only be used with remote target"));
13180 remote
->remote_file_get (remote_file
, local_file
, from_tty
);
13184 remote_target::remote_file_get (const char *remote_file
, const char *local_file
,
13187 fileio_error remote_errno
;
13188 int bytes
, io_size
;
13191 scoped_remote_fd fd
13192 (this, remote_hostio_open (NULL
,
13193 remote_file
, FILEIO_O_RDONLY
, 0, 0,
13195 if (fd
.get () == -1)
13196 remote_hostio_error (remote_errno
);
13198 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "wb");
13200 perror_with_name (local_file
);
13202 /* Send up to this many bytes at once. They won't all fit in the
13203 remote packet limit, so we'll transfer slightly fewer. */
13204 io_size
= get_remote_packet_size ();
13205 gdb::byte_vector
buffer (io_size
);
13210 bytes
= remote_hostio_pread (fd
.get (), buffer
.data (), io_size
, offset
,
13213 /* Success, but no bytes, means end-of-file. */
13216 remote_hostio_error (remote_errno
);
13220 bytes
= fwrite (buffer
.data (), 1, bytes
, file
.get ());
13222 perror_with_name (local_file
);
13225 if (remote_hostio_close (fd
.release (), &remote_errno
))
13226 remote_hostio_error (remote_errno
);
13229 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file
);
13233 remote_file_delete (const char *remote_file
, int from_tty
)
13235 remote_target
*remote
= get_current_remote_target ();
13237 if (remote
== nullptr)
13238 error (_("command can only be used with remote target"));
13240 remote
->remote_file_delete (remote_file
, from_tty
);
13244 remote_target::remote_file_delete (const char *remote_file
, int from_tty
)
13247 fileio_error remote_errno
;
13249 retcode
= remote_hostio_unlink (NULL
, remote_file
, &remote_errno
);
13251 remote_hostio_error (remote_errno
);
13254 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file
);
13258 remote_put_command (const char *args
, int from_tty
)
13261 error_no_arg (_("file to put"));
13263 gdb_argv
argv (args
);
13264 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13265 error (_("Invalid parameters to remote put"));
13267 remote_file_put (argv
[0], argv
[1], from_tty
);
13271 remote_get_command (const char *args
, int from_tty
)
13274 error_no_arg (_("file to get"));
13276 gdb_argv
argv (args
);
13277 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13278 error (_("Invalid parameters to remote get"));
13280 remote_file_get (argv
[0], argv
[1], from_tty
);
13284 remote_delete_command (const char *args
, int from_tty
)
13287 error_no_arg (_("file to delete"));
13289 gdb_argv
argv (args
);
13290 if (argv
[0] == NULL
|| argv
[1] != NULL
)
13291 error (_("Invalid parameters to remote delete"));
13293 remote_file_delete (argv
[0], from_tty
);
13297 remote_target::can_execute_reverse ()
13299 if (m_features
.packet_support (PACKET_bs
) == PACKET_ENABLE
13300 || m_features
.packet_support (PACKET_bc
) == PACKET_ENABLE
)
13307 remote_target::supports_non_stop ()
13313 remote_target::supports_disable_randomization ()
13315 /* Only supported in extended mode. */
13320 remote_target::supports_multi_process ()
13322 return m_features
.remote_multi_process_p ();
13326 remote_target::remote_supports_cond_tracepoints ()
13328 return (m_features
.packet_support (PACKET_ConditionalTracepoints
)
13333 remote_target::supports_evaluation_of_breakpoint_conditions ()
13335 return (m_features
.packet_support (PACKET_ConditionalBreakpoints
)
13340 remote_target::remote_supports_fast_tracepoints ()
13342 return m_features
.packet_support (PACKET_FastTracepoints
) == PACKET_ENABLE
;
13346 remote_target::remote_supports_static_tracepoints ()
13348 return m_features
.packet_support (PACKET_StaticTracepoints
) == PACKET_ENABLE
;
13352 remote_target::remote_supports_install_in_trace ()
13354 return m_features
.packet_support (PACKET_InstallInTrace
) == PACKET_ENABLE
;
13358 remote_target::supports_enable_disable_tracepoint ()
13360 return (m_features
.packet_support (PACKET_EnableDisableTracepoints_feature
)
13365 remote_target::supports_string_tracing ()
13367 return m_features
.packet_support (PACKET_tracenz_feature
) == PACKET_ENABLE
;
13371 remote_target::can_run_breakpoint_commands ()
13373 return m_features
.packet_support (PACKET_BreakpointCommands
) == PACKET_ENABLE
;
13377 remote_target::trace_init ()
13379 struct remote_state
*rs
= get_remote_state ();
13382 remote_get_noisy_reply ();
13383 if (strcmp (rs
->buf
.data (), "OK") != 0)
13384 error (_("Target does not support this command."));
13387 /* Recursive routine to walk through command list including loops, and
13388 download packets for each command. */
13391 remote_target::remote_download_command_source (int num
, ULONGEST addr
,
13392 struct command_line
*cmds
)
13394 struct remote_state
*rs
= get_remote_state ();
13395 struct command_line
*cmd
;
13397 for (cmd
= cmds
; cmd
; cmd
= cmd
->next
)
13399 QUIT
; /* Allow user to bail out with ^C. */
13400 strcpy (rs
->buf
.data (), "QTDPsrc:");
13401 encode_source_string (num
, addr
, "cmd", cmd
->line
,
13402 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13403 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13405 remote_get_noisy_reply ();
13406 if (strcmp (rs
->buf
.data (), "OK"))
13407 warning (_("Target does not support source download."));
13409 if (cmd
->control_type
== while_control
13410 || cmd
->control_type
== while_stepping_control
)
13412 remote_download_command_source (num
, addr
, cmd
->body_list_0
.get ());
13414 QUIT
; /* Allow user to bail out with ^C. */
13415 strcpy (rs
->buf
.data (), "QTDPsrc:");
13416 encode_source_string (num
, addr
, "cmd", "end",
13417 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13418 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13420 remote_get_noisy_reply ();
13421 if (strcmp (rs
->buf
.data (), "OK"))
13422 warning (_("Target does not support source download."));
13428 remote_target::download_tracepoint (struct bp_location
*loc
)
13432 std::vector
<std::string
> tdp_actions
;
13433 std::vector
<std::string
> stepping_actions
;
13435 struct breakpoint
*b
= loc
->owner
;
13436 tracepoint
*t
= gdb::checked_static_cast
<tracepoint
*> (b
);
13437 struct remote_state
*rs
= get_remote_state ();
13439 const char *err_msg
= _("Tracepoint packet too large for target.");
13442 /* We use a buffer other than rs->buf because we'll build strings
13443 across multiple statements, and other statements in between could
13445 gdb::char_vector
buf (get_remote_packet_size ());
13447 encode_actions_rsp (loc
, &tdp_actions
, &stepping_actions
);
13449 tpaddr
= loc
->address
;
13450 strcpy (addrbuf
, phex (tpaddr
, sizeof (CORE_ADDR
)));
13451 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:%x:%s:%c:%lx:%x",
13452 b
->number
, addrbuf
, /* address */
13453 (b
->enable_state
== bp_enabled
? 'E' : 'D'),
13454 t
->step_count
, t
->pass_count
);
13456 if (ret
< 0 || ret
>= buf
.size ())
13457 error ("%s", err_msg
);
13459 /* Fast tracepoints are mostly handled by the target, but we can
13460 tell the target how big of an instruction block should be moved
13462 if (b
->type
== bp_fast_tracepoint
)
13464 /* Only test for support at download time; we may not know
13465 target capabilities at definition time. */
13466 if (remote_supports_fast_tracepoints ())
13468 if (gdbarch_fast_tracepoint_valid_at (loc
->gdbarch
, tpaddr
,
13471 size_left
= buf
.size () - strlen (buf
.data ());
13472 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13474 gdb_insn_length (loc
->gdbarch
, tpaddr
));
13476 if (ret
< 0 || ret
>= size_left
)
13477 error ("%s", err_msg
);
13480 /* If it passed validation at definition but fails now,
13481 something is very wrong. */
13482 internal_error (_("Fast tracepoint not valid during download"));
13485 /* Fast tracepoints are functionally identical to regular
13486 tracepoints, so don't take lack of support as a reason to
13487 give up on the trace run. */
13488 warning (_("Target does not support fast tracepoints, "
13489 "downloading %d as regular tracepoint"), b
->number
);
13491 else if (b
->type
== bp_static_tracepoint
13492 || b
->type
== bp_static_marker_tracepoint
)
13494 /* Only test for support at download time; we may not know
13495 target capabilities at definition time. */
13496 if (remote_supports_static_tracepoints ())
13498 struct static_tracepoint_marker marker
;
13500 if (target_static_tracepoint_marker_at (tpaddr
, &marker
))
13502 size_left
= buf
.size () - strlen (buf
.data ());
13503 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13506 if (ret
< 0 || ret
>= size_left
)
13507 error ("%s", err_msg
);
13510 error (_("Static tracepoint not valid during download"));
13513 /* Fast tracepoints are functionally identical to regular
13514 tracepoints, so don't take lack of support as a reason
13515 to give up on the trace run. */
13516 error (_("Target does not support static tracepoints"));
13518 /* If the tracepoint has a conditional, make it into an agent
13519 expression and append to the definition. */
13522 /* Only test support at download time, we may not know target
13523 capabilities at definition time. */
13524 if (remote_supports_cond_tracepoints ())
13526 agent_expr_up aexpr
= gen_eval_for_expr (tpaddr
,
13529 size_left
= buf
.size () - strlen (buf
.data ());
13531 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13532 size_left
, ":X%x,", (int) aexpr
->buf
.size ());
13534 if (ret
< 0 || ret
>= size_left
)
13535 error ("%s", err_msg
);
13537 size_left
= buf
.size () - strlen (buf
.data ());
13539 /* Two bytes to encode each aexpr byte, plus the terminating
13541 if (aexpr
->buf
.size () * 2 + 1 > size_left
)
13542 error ("%s", err_msg
);
13544 pkt
= buf
.data () + strlen (buf
.data ());
13546 for (int ndx
= 0; ndx
< aexpr
->buf
.size (); ++ndx
)
13547 pkt
= pack_hex_byte (pkt
, aexpr
->buf
[ndx
]);
13551 warning (_("Target does not support conditional tracepoints, "
13552 "ignoring tp %d cond"), b
->number
);
13555 if (b
->commands
|| !default_collect
.empty ())
13557 size_left
= buf
.size () - strlen (buf
.data ());
13559 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13562 if (ret
< 0 || ret
>= size_left
)
13563 error ("%s", err_msg
);
13566 putpkt (buf
.data ());
13567 remote_get_noisy_reply ();
13568 if (strcmp (rs
->buf
.data (), "OK"))
13569 error (_("Target does not support tracepoints."));
13571 /* do_single_steps (t); */
13572 for (auto action_it
= tdp_actions
.begin ();
13573 action_it
!= tdp_actions
.end (); action_it
++)
13575 QUIT
; /* Allow user to bail out with ^C. */
13577 bool has_more
= ((action_it
+ 1) != tdp_actions
.end ()
13578 || !stepping_actions
.empty ());
13580 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%c",
13581 b
->number
, addrbuf
, /* address */
13582 action_it
->c_str (),
13583 has_more
? '-' : 0);
13585 if (ret
< 0 || ret
>= buf
.size ())
13586 error ("%s", err_msg
);
13588 putpkt (buf
.data ());
13589 remote_get_noisy_reply ();
13590 if (strcmp (rs
->buf
.data (), "OK"))
13591 error (_("Error on target while setting tracepoints."));
13594 for (auto action_it
= stepping_actions
.begin ();
13595 action_it
!= stepping_actions
.end (); action_it
++)
13597 QUIT
; /* Allow user to bail out with ^C. */
13599 bool is_first
= action_it
== stepping_actions
.begin ();
13600 bool has_more
= (action_it
+ 1) != stepping_actions
.end ();
13602 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%s%s",
13603 b
->number
, addrbuf
, /* address */
13604 is_first
? "S" : "",
13605 action_it
->c_str (),
13606 has_more
? "-" : "");
13608 if (ret
< 0 || ret
>= buf
.size ())
13609 error ("%s", err_msg
);
13611 putpkt (buf
.data ());
13612 remote_get_noisy_reply ();
13613 if (strcmp (rs
->buf
.data (), "OK"))
13614 error (_("Error on target while setting tracepoints."));
13617 if (m_features
.packet_support (PACKET_TracepointSource
) == PACKET_ENABLE
)
13619 if (b
->locspec
!= nullptr)
13621 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13623 if (ret
< 0 || ret
>= buf
.size ())
13624 error ("%s", err_msg
);
13626 const char *str
= b
->locspec
->to_string ();
13627 encode_source_string (b
->number
, loc
->address
, "at", str
,
13628 buf
.data () + strlen (buf
.data ()),
13629 buf
.size () - strlen (buf
.data ()));
13630 putpkt (buf
.data ());
13631 remote_get_noisy_reply ();
13632 if (strcmp (rs
->buf
.data (), "OK"))
13633 warning (_("Target does not support source download."));
13635 if (b
->cond_string
)
13637 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13639 if (ret
< 0 || ret
>= buf
.size ())
13640 error ("%s", err_msg
);
13642 encode_source_string (b
->number
, loc
->address
,
13643 "cond", b
->cond_string
.get (),
13644 buf
.data () + strlen (buf
.data ()),
13645 buf
.size () - strlen (buf
.data ()));
13646 putpkt (buf
.data ());
13647 remote_get_noisy_reply ();
13648 if (strcmp (rs
->buf
.data (), "OK"))
13649 warning (_("Target does not support source download."));
13651 remote_download_command_source (b
->number
, loc
->address
,
13652 breakpoint_commands (b
));
13657 remote_target::can_download_tracepoint ()
13659 struct remote_state
*rs
= get_remote_state ();
13660 struct trace_status
*ts
;
13663 /* Don't try to install tracepoints until we've relocated our
13664 symbols, and fetched and merged the target's tracepoint list with
13666 if (rs
->starting_up
)
13669 ts
= current_trace_status ();
13670 status
= get_trace_status (ts
);
13672 if (status
== -1 || !ts
->running_known
|| !ts
->running
)
13675 /* If we are in a tracing experiment, but remote stub doesn't support
13676 installing tracepoint in trace, we have to return. */
13677 if (!remote_supports_install_in_trace ())
13685 remote_target::download_trace_state_variable (const trace_state_variable
&tsv
)
13687 struct remote_state
*rs
= get_remote_state ();
13690 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13691 tsv
.number
, phex ((ULONGEST
) tsv
.initial_value
, 8),
13693 p
= rs
->buf
.data () + strlen (rs
->buf
.data ());
13694 if ((p
- rs
->buf
.data ()) + tsv
.name
.length () * 2
13695 >= get_remote_packet_size ())
13696 error (_("Trace state variable name too long for tsv definition packet"));
13697 p
+= 2 * bin2hex ((gdb_byte
*) (tsv
.name
.data ()), p
, tsv
.name
.length ());
13700 remote_get_noisy_reply ();
13701 if (rs
->buf
[0] == '\0')
13702 error (_("Target does not support this command."));
13703 if (strcmp (rs
->buf
.data (), "OK") != 0)
13704 error (_("Error on target while downloading trace state variable."));
13708 remote_target::enable_tracepoint (struct bp_location
*location
)
13710 struct remote_state
*rs
= get_remote_state ();
13712 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13713 location
->owner
->number
,
13714 phex (location
->address
, sizeof (CORE_ADDR
)));
13716 remote_get_noisy_reply ();
13717 if (rs
->buf
[0] == '\0')
13718 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13719 if (strcmp (rs
->buf
.data (), "OK") != 0)
13720 error (_("Error on target while enabling tracepoint."));
13724 remote_target::disable_tracepoint (struct bp_location
*location
)
13726 struct remote_state
*rs
= get_remote_state ();
13728 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13729 location
->owner
->number
,
13730 phex (location
->address
, sizeof (CORE_ADDR
)));
13732 remote_get_noisy_reply ();
13733 if (rs
->buf
[0] == '\0')
13734 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13735 if (strcmp (rs
->buf
.data (), "OK") != 0)
13736 error (_("Error on target while disabling tracepoint."));
13740 remote_target::trace_set_readonly_regions ()
13743 bfd_size_type size
;
13747 bfd
*abfd
= current_program_space
->exec_bfd ();
13750 return; /* No information to give. */
13752 struct remote_state
*rs
= get_remote_state ();
13754 strcpy (rs
->buf
.data (), "QTro");
13755 offset
= strlen (rs
->buf
.data ());
13756 for (s
= abfd
->sections
; s
; s
= s
->next
)
13758 char tmp1
[40], tmp2
[40];
13761 if ((s
->flags
& SEC_LOAD
) == 0
13762 /* || (s->flags & SEC_CODE) == 0 */
13763 || (s
->flags
& SEC_READONLY
) == 0)
13767 vma
= bfd_section_vma (s
);
13768 size
= bfd_section_size (s
);
13769 bfd_sprintf_vma (abfd
, tmp1
, vma
);
13770 bfd_sprintf_vma (abfd
, tmp2
, vma
+ size
);
13771 sec_length
= 1 + strlen (tmp1
) + 1 + strlen (tmp2
);
13772 if (offset
+ sec_length
+ 1 > rs
->buf
.size ())
13774 if (m_features
.packet_support (PACKET_qXfer_traceframe_info
)
13777 Too many sections for read-only sections definition packet."));
13780 xsnprintf (rs
->buf
.data () + offset
, rs
->buf
.size () - offset
, ":%s,%s",
13782 offset
+= sec_length
;
13792 remote_target::trace_start ()
13794 struct remote_state
*rs
= get_remote_state ();
13796 putpkt ("QTStart");
13797 remote_get_noisy_reply ();
13798 if (rs
->buf
[0] == '\0')
13799 error (_("Target does not support this command."));
13800 if (strcmp (rs
->buf
.data (), "OK") != 0)
13801 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
13805 remote_target::get_trace_status (struct trace_status
*ts
)
13807 /* Initialize it just to avoid a GCC false warning. */
13809 enum packet_result result
;
13810 struct remote_state
*rs
= get_remote_state ();
13812 if (m_features
.packet_support (PACKET_qTStatus
) == PACKET_DISABLE
)
13815 /* FIXME we need to get register block size some other way. */
13816 trace_regblock_size
13817 = rs
->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet
;
13819 putpkt ("qTStatus");
13823 p
= remote_get_noisy_reply ();
13825 catch (const gdb_exception_error
&ex
)
13827 if (ex
.error
!= TARGET_CLOSE_ERROR
)
13829 exception_fprintf (gdb_stderr
, ex
, "qTStatus: ");
13835 result
= m_features
.packet_ok (p
, PACKET_qTStatus
);
13837 /* If the remote target doesn't do tracing, flag it. */
13838 if (result
== PACKET_UNKNOWN
)
13841 /* We're working with a live target. */
13842 ts
->filename
= NULL
;
13845 error (_("Bogus trace status reply from target: %s"), rs
->buf
.data ());
13847 /* Function 'parse_trace_status' sets default value of each field of
13848 'ts' at first, so we don't have to do it here. */
13849 parse_trace_status (p
, ts
);
13851 return ts
->running
;
13855 remote_target::get_tracepoint_status (tracepoint
*tp
,
13856 struct uploaded_tp
*utp
)
13858 struct remote_state
*rs
= get_remote_state ();
13860 size_t size
= get_remote_packet_size ();
13865 tp
->traceframe_usage
= 0;
13866 for (bp_location
&loc
: tp
->locations ())
13868 /* If the tracepoint was never downloaded, don't go asking for
13870 if (tp
->number_on_target
== 0)
13872 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", tp
->number_on_target
,
13873 phex_nz (loc
.address
, 0));
13875 reply
= remote_get_noisy_reply ();
13876 if (reply
&& *reply
)
13879 parse_tracepoint_status (reply
+ 1, tp
, utp
);
13885 utp
->hit_count
= 0;
13886 utp
->traceframe_usage
= 0;
13887 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", utp
->number
,
13888 phex_nz (utp
->addr
, 0));
13890 reply
= remote_get_noisy_reply ();
13891 if (reply
&& *reply
)
13894 parse_tracepoint_status (reply
+ 1, tp
, utp
);
13900 remote_target::trace_stop ()
13902 struct remote_state
*rs
= get_remote_state ();
13905 remote_get_noisy_reply ();
13906 if (rs
->buf
[0] == '\0')
13907 error (_("Target does not support this command."));
13908 if (strcmp (rs
->buf
.data (), "OK") != 0)
13909 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
13913 remote_target::trace_find (enum trace_find_type type
, int num
,
13914 CORE_ADDR addr1
, CORE_ADDR addr2
,
13917 struct remote_state
*rs
= get_remote_state ();
13918 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
13920 int target_frameno
= -1, target_tracept
= -1;
13922 /* Lookups other than by absolute frame number depend on the current
13923 trace selected, so make sure it is correct on the remote end
13925 if (type
!= tfind_number
)
13926 set_remote_traceframe ();
13928 p
= rs
->buf
.data ();
13929 strcpy (p
, "QTFrame:");
13930 p
= strchr (p
, '\0');
13934 xsnprintf (p
, endbuf
- p
, "%x", num
);
13937 xsnprintf (p
, endbuf
- p
, "pc:%s", phex_nz (addr1
, 0));
13940 xsnprintf (p
, endbuf
- p
, "tdp:%x", num
);
13943 xsnprintf (p
, endbuf
- p
, "range:%s:%s", phex_nz (addr1
, 0),
13944 phex_nz (addr2
, 0));
13946 case tfind_outside
:
13947 xsnprintf (p
, endbuf
- p
, "outside:%s:%s", phex_nz (addr1
, 0),
13948 phex_nz (addr2
, 0));
13951 error (_("Unknown trace find type %d"), type
);
13955 reply
= remote_get_noisy_reply ();
13956 if (*reply
== '\0')
13957 error (_("Target does not support this command."));
13959 while (reply
&& *reply
)
13964 target_frameno
= (int) strtol (p
, &reply
, 16);
13966 error (_("Unable to parse trace frame number"));
13967 /* Don't update our remote traceframe number cache on failure
13968 to select a remote traceframe. */
13969 if (target_frameno
== -1)
13974 target_tracept
= (int) strtol (p
, &reply
, 16);
13976 error (_("Unable to parse tracepoint number"));
13978 case 'O': /* "OK"? */
13979 if (reply
[1] == 'K' && reply
[2] == '\0')
13982 error (_("Bogus reply from target: %s"), reply
);
13985 error (_("Bogus reply from target: %s"), reply
);
13988 *tpp
= target_tracept
;
13990 rs
->remote_traceframe_number
= target_frameno
;
13991 return target_frameno
;
13995 remote_target::get_trace_state_variable_value (int tsvnum
, LONGEST
*val
)
13997 struct remote_state
*rs
= get_remote_state ();
14001 set_remote_traceframe ();
14003 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTV:%x", tsvnum
);
14005 reply
= remote_get_noisy_reply ();
14006 if (reply
&& *reply
)
14010 unpack_varlen_hex (reply
+ 1, &uval
);
14011 *val
= (LONGEST
) uval
;
14019 remote_target::save_trace_data (const char *filename
)
14021 struct remote_state
*rs
= get_remote_state ();
14024 p
= rs
->buf
.data ();
14025 strcpy (p
, "QTSave:");
14027 if ((p
- rs
->buf
.data ()) + strlen (filename
) * 2
14028 >= get_remote_packet_size ())
14029 error (_("Remote file name too long for trace save packet"));
14030 p
+= 2 * bin2hex ((gdb_byte
*) filename
, p
, strlen (filename
));
14033 reply
= remote_get_noisy_reply ();
14034 if (*reply
== '\0')
14035 error (_("Target does not support this command."));
14036 if (strcmp (reply
, "OK") != 0)
14037 error (_("Bogus reply from target: %s"), reply
);
14041 /* This is basically a memory transfer, but needs to be its own packet
14042 because we don't know how the target actually organizes its trace
14043 memory, plus we want to be able to ask for as much as possible, but
14044 not be unhappy if we don't get as much as we ask for. */
14047 remote_target::get_raw_trace_data (gdb_byte
*buf
, ULONGEST offset
, LONGEST len
)
14049 struct remote_state
*rs
= get_remote_state ();
14054 p
= rs
->buf
.data ();
14055 strcpy (p
, "qTBuffer:");
14057 p
+= hexnumstr (p
, offset
);
14059 p
+= hexnumstr (p
, len
);
14063 reply
= remote_get_noisy_reply ();
14064 if (reply
&& *reply
)
14066 /* 'l' by itself means we're at the end of the buffer and
14067 there is nothing more to get. */
14071 /* Convert the reply into binary. Limit the number of bytes to
14072 convert according to our passed-in buffer size, rather than
14073 what was returned in the packet; if the target is
14074 unexpectedly generous and gives us a bigger reply than we
14075 asked for, we don't want to crash. */
14076 rslt
= hex2bin (reply
, buf
, len
);
14080 /* Something went wrong, flag as an error. */
14085 remote_target::set_disconnected_tracing (int val
)
14087 struct remote_state
*rs
= get_remote_state ();
14089 if (m_features
.packet_support (PACKET_DisconnectedTracing_feature
)
14094 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14095 "QTDisconnected:%x", val
);
14097 reply
= remote_get_noisy_reply ();
14098 if (*reply
== '\0')
14099 error (_("Target does not support this command."));
14100 if (strcmp (reply
, "OK") != 0)
14101 error (_("Bogus reply from target: %s"), reply
);
14104 warning (_("Target does not support disconnected tracing."));
14108 remote_target::core_of_thread (ptid_t ptid
)
14110 thread_info
*info
= this->find_thread (ptid
);
14112 if (info
!= NULL
&& info
->priv
!= NULL
)
14113 return get_remote_thread_info (info
)->core
;
14119 remote_target::set_circular_trace_buffer (int val
)
14121 struct remote_state
*rs
= get_remote_state ();
14124 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14125 "QTBuffer:circular:%x", val
);
14127 reply
= remote_get_noisy_reply ();
14128 if (*reply
== '\0')
14129 error (_("Target does not support this command."));
14130 if (strcmp (reply
, "OK") != 0)
14131 error (_("Bogus reply from target: %s"), reply
);
14135 remote_target::traceframe_info ()
14137 gdb::optional
<gdb::char_vector
> text
14138 = target_read_stralloc (current_inferior ()->top_target (),
14139 TARGET_OBJECT_TRACEFRAME_INFO
,
14142 return parse_traceframe_info (text
->data ());
14147 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14148 instruction on which a fast tracepoint may be placed. Returns -1
14149 if the packet is not supported, and 0 if the minimum instruction
14150 length is unknown. */
14153 remote_target::get_min_fast_tracepoint_insn_len ()
14155 struct remote_state
*rs
= get_remote_state ();
14158 /* If we're not debugging a process yet, the IPA can't be
14160 if (!target_has_execution ())
14163 /* Make sure the remote is pointing at the right process. */
14164 set_general_process ();
14166 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTMinFTPILen");
14168 reply
= remote_get_noisy_reply ();
14169 if (*reply
== '\0')
14173 ULONGEST min_insn_len
;
14175 unpack_varlen_hex (reply
, &min_insn_len
);
14177 return (int) min_insn_len
;
14182 remote_target::set_trace_buffer_size (LONGEST val
)
14184 if (m_features
.packet_support (PACKET_QTBuffer_size
) != PACKET_DISABLE
)
14186 struct remote_state
*rs
= get_remote_state ();
14187 char *buf
= rs
->buf
.data ();
14188 char *endbuf
= buf
+ get_remote_packet_size ();
14189 enum packet_result result
;
14191 gdb_assert (val
>= 0 || val
== -1);
14192 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTBuffer:size:");
14193 /* Send -1 as literal "-1" to avoid host size dependency. */
14197 buf
+= hexnumstr (buf
, (ULONGEST
) -val
);
14200 buf
+= hexnumstr (buf
, (ULONGEST
) val
);
14203 remote_get_noisy_reply ();
14204 result
= m_features
.packet_ok (rs
->buf
, PACKET_QTBuffer_size
);
14206 if (result
!= PACKET_OK
)
14207 warning (_("Bogus reply from target: %s"), rs
->buf
.data ());
14212 remote_target::set_trace_notes (const char *user
, const char *notes
,
14213 const char *stop_notes
)
14215 struct remote_state
*rs
= get_remote_state ();
14217 char *buf
= rs
->buf
.data ();
14218 char *endbuf
= buf
+ get_remote_packet_size ();
14221 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTNotes:");
14224 buf
+= xsnprintf (buf
, endbuf
- buf
, "user:");
14225 nbytes
= bin2hex ((gdb_byte
*) user
, buf
, strlen (user
));
14231 buf
+= xsnprintf (buf
, endbuf
- buf
, "notes:");
14232 nbytes
= bin2hex ((gdb_byte
*) notes
, buf
, strlen (notes
));
14238 buf
+= xsnprintf (buf
, endbuf
- buf
, "tstop:");
14239 nbytes
= bin2hex ((gdb_byte
*) stop_notes
, buf
, strlen (stop_notes
));
14243 /* Ensure the buffer is terminated. */
14247 reply
= remote_get_noisy_reply ();
14248 if (*reply
== '\0')
14251 if (strcmp (reply
, "OK") != 0)
14252 error (_("Bogus reply from target: %s"), reply
);
14258 remote_target::use_agent (bool use
)
14260 if (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
)
14262 struct remote_state
*rs
= get_remote_state ();
14264 /* If the stub supports QAgent. */
14265 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAgent:%d", use
);
14269 if (strcmp (rs
->buf
.data (), "OK") == 0)
14280 remote_target::can_use_agent ()
14282 return (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
);
14285 #if defined (HAVE_LIBEXPAT)
14287 /* Check the btrace document version. */
14290 check_xml_btrace_version (struct gdb_xml_parser
*parser
,
14291 const struct gdb_xml_element
*element
,
14293 std::vector
<gdb_xml_value
> &attributes
)
14295 const char *version
14296 = (const char *) xml_find_attribute (attributes
, "version")->value
.get ();
14298 if (strcmp (version
, "1.0") != 0)
14299 gdb_xml_error (parser
, _("Unsupported btrace version: \"%s\""), version
);
14302 /* Parse a btrace "block" xml record. */
14305 parse_xml_btrace_block (struct gdb_xml_parser
*parser
,
14306 const struct gdb_xml_element
*element
,
14308 std::vector
<gdb_xml_value
> &attributes
)
14310 struct btrace_data
*btrace
;
14311 ULONGEST
*begin
, *end
;
14313 btrace
= (struct btrace_data
*) user_data
;
14315 switch (btrace
->format
)
14317 case BTRACE_FORMAT_BTS
:
14320 case BTRACE_FORMAT_NONE
:
14321 btrace
->format
= BTRACE_FORMAT_BTS
;
14322 btrace
->variant
.bts
.blocks
= new std::vector
<btrace_block
>;
14326 gdb_xml_error (parser
, _("Btrace format error."));
14329 begin
= (ULONGEST
*) xml_find_attribute (attributes
, "begin")->value
.get ();
14330 end
= (ULONGEST
*) xml_find_attribute (attributes
, "end")->value
.get ();
14331 btrace
->variant
.bts
.blocks
->emplace_back (*begin
, *end
);
14334 /* Parse a "raw" xml record. */
14337 parse_xml_raw (struct gdb_xml_parser
*parser
, const char *body_text
,
14338 gdb_byte
**pdata
, size_t *psize
)
14343 len
= strlen (body_text
);
14345 gdb_xml_error (parser
, _("Bad raw data size."));
14349 gdb::unique_xmalloc_ptr
<gdb_byte
> data ((gdb_byte
*) xmalloc (size
));
14352 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14360 if (hi
== 0 || lo
== 0)
14361 gdb_xml_error (parser
, _("Bad hex encoding."));
14363 *bin
++ = fromhex (hi
) * 16 + fromhex (lo
);
14367 *pdata
= data
.release ();
14371 /* Parse a btrace pt-config "cpu" xml record. */
14374 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser
*parser
,
14375 const struct gdb_xml_element
*element
,
14377 std::vector
<gdb_xml_value
> &attributes
)
14379 struct btrace_data
*btrace
;
14380 const char *vendor
;
14381 ULONGEST
*family
, *model
, *stepping
;
14384 = (const char *) xml_find_attribute (attributes
, "vendor")->value
.get ();
14386 = (ULONGEST
*) xml_find_attribute (attributes
, "family")->value
.get ();
14388 = (ULONGEST
*) xml_find_attribute (attributes
, "model")->value
.get ();
14390 = (ULONGEST
*) xml_find_attribute (attributes
, "stepping")->value
.get ();
14392 btrace
= (struct btrace_data
*) user_data
;
14394 if (strcmp (vendor
, "GenuineIntel") == 0)
14395 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_INTEL
;
14397 btrace
->variant
.pt
.config
.cpu
.family
= *family
;
14398 btrace
->variant
.pt
.config
.cpu
.model
= *model
;
14399 btrace
->variant
.pt
.config
.cpu
.stepping
= *stepping
;
14402 /* Parse a btrace pt "raw" xml record. */
14405 parse_xml_btrace_pt_raw (struct gdb_xml_parser
*parser
,
14406 const struct gdb_xml_element
*element
,
14407 void *user_data
, const char *body_text
)
14409 struct btrace_data
*btrace
;
14411 btrace
= (struct btrace_data
*) user_data
;
14412 parse_xml_raw (parser
, body_text
, &btrace
->variant
.pt
.data
,
14413 &btrace
->variant
.pt
.size
);
14416 /* Parse a btrace "pt" xml record. */
14419 parse_xml_btrace_pt (struct gdb_xml_parser
*parser
,
14420 const struct gdb_xml_element
*element
,
14422 std::vector
<gdb_xml_value
> &attributes
)
14424 struct btrace_data
*btrace
;
14426 btrace
= (struct btrace_data
*) user_data
;
14427 btrace
->format
= BTRACE_FORMAT_PT
;
14428 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_UNKNOWN
;
14429 btrace
->variant
.pt
.data
= NULL
;
14430 btrace
->variant
.pt
.size
= 0;
14433 static const struct gdb_xml_attribute block_attributes
[] = {
14434 { "begin", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14435 { "end", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14436 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14439 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes
[] = {
14440 { "vendor", GDB_XML_AF_NONE
, NULL
, NULL
},
14441 { "family", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14442 { "model", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14443 { "stepping", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14444 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14447 static const struct gdb_xml_element btrace_pt_config_children
[] = {
14448 { "cpu", btrace_pt_config_cpu_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14449 parse_xml_btrace_pt_config_cpu
, NULL
},
14450 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14453 static const struct gdb_xml_element btrace_pt_children
[] = {
14454 { "pt-config", NULL
, btrace_pt_config_children
, GDB_XML_EF_OPTIONAL
, NULL
,
14456 { "raw", NULL
, NULL
, GDB_XML_EF_OPTIONAL
, NULL
, parse_xml_btrace_pt_raw
},
14457 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14460 static const struct gdb_xml_attribute btrace_attributes
[] = {
14461 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14462 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14465 static const struct gdb_xml_element btrace_children
[] = {
14466 { "block", block_attributes
, NULL
,
14467 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
, parse_xml_btrace_block
, NULL
},
14468 { "pt", NULL
, btrace_pt_children
, GDB_XML_EF_OPTIONAL
, parse_xml_btrace_pt
,
14470 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14473 static const struct gdb_xml_element btrace_elements
[] = {
14474 { "btrace", btrace_attributes
, btrace_children
, GDB_XML_EF_NONE
,
14475 check_xml_btrace_version
, NULL
},
14476 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14479 #endif /* defined (HAVE_LIBEXPAT) */
14481 /* Parse a branch trace xml document XML into DATA. */
14484 parse_xml_btrace (struct btrace_data
*btrace
, const char *buffer
)
14486 #if defined (HAVE_LIBEXPAT)
14489 btrace_data result
;
14490 result
.format
= BTRACE_FORMAT_NONE
;
14492 errcode
= gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements
,
14495 error (_("Error parsing branch trace."));
14497 /* Keep parse results. */
14498 *btrace
= std::move (result
);
14500 #else /* !defined (HAVE_LIBEXPAT) */
14502 error (_("Cannot process branch trace. XML support was disabled at "
14505 #endif /* !defined (HAVE_LIBEXPAT) */
14508 #if defined (HAVE_LIBEXPAT)
14510 /* Parse a btrace-conf "bts" xml record. */
14513 parse_xml_btrace_conf_bts (struct gdb_xml_parser
*parser
,
14514 const struct gdb_xml_element
*element
,
14516 std::vector
<gdb_xml_value
> &attributes
)
14518 struct btrace_config
*conf
;
14519 struct gdb_xml_value
*size
;
14521 conf
= (struct btrace_config
*) user_data
;
14522 conf
->format
= BTRACE_FORMAT_BTS
;
14523 conf
->bts
.size
= 0;
14525 size
= xml_find_attribute (attributes
, "size");
14527 conf
->bts
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14530 /* Parse a btrace-conf "pt" xml record. */
14533 parse_xml_btrace_conf_pt (struct gdb_xml_parser
*parser
,
14534 const struct gdb_xml_element
*element
,
14536 std::vector
<gdb_xml_value
> &attributes
)
14538 struct btrace_config
*conf
;
14539 struct gdb_xml_value
*size
;
14541 conf
= (struct btrace_config
*) user_data
;
14542 conf
->format
= BTRACE_FORMAT_PT
;
14545 size
= xml_find_attribute (attributes
, "size");
14547 conf
->pt
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14550 static const struct gdb_xml_attribute btrace_conf_pt_attributes
[] = {
14551 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14552 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14555 static const struct gdb_xml_attribute btrace_conf_bts_attributes
[] = {
14556 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14557 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14560 static const struct gdb_xml_element btrace_conf_children
[] = {
14561 { "bts", btrace_conf_bts_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14562 parse_xml_btrace_conf_bts
, NULL
},
14563 { "pt", btrace_conf_pt_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14564 parse_xml_btrace_conf_pt
, NULL
},
14565 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14568 static const struct gdb_xml_attribute btrace_conf_attributes
[] = {
14569 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14570 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14573 static const struct gdb_xml_element btrace_conf_elements
[] = {
14574 { "btrace-conf", btrace_conf_attributes
, btrace_conf_children
,
14575 GDB_XML_EF_NONE
, NULL
, NULL
},
14576 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14579 #endif /* defined (HAVE_LIBEXPAT) */
14581 /* Parse a branch trace configuration xml document XML into CONF. */
14584 parse_xml_btrace_conf (struct btrace_config
*conf
, const char *xml
)
14586 #if defined (HAVE_LIBEXPAT)
14589 errcode
= gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14590 btrace_conf_elements
, xml
, conf
);
14592 error (_("Error parsing branch trace configuration."));
14594 #else /* !defined (HAVE_LIBEXPAT) */
14596 error (_("Cannot process the branch trace configuration. XML support "
14597 "was disabled at compile time."));
14599 #endif /* !defined (HAVE_LIBEXPAT) */
14602 /* Reset our idea of our target's btrace configuration. */
14605 remote_btrace_reset (remote_state
*rs
)
14607 memset (&rs
->btrace_config
, 0, sizeof (rs
->btrace_config
));
14610 /* Synchronize the configuration with the target. */
14613 remote_target::btrace_sync_conf (const btrace_config
*conf
)
14615 struct remote_state
*rs
;
14616 char *buf
, *pos
, *endbuf
;
14618 rs
= get_remote_state ();
14619 buf
= rs
->buf
.data ();
14620 endbuf
= buf
+ get_remote_packet_size ();
14622 if (m_features
.packet_support (PACKET_Qbtrace_conf_bts_size
) == PACKET_ENABLE
14623 && conf
->bts
.size
!= rs
->btrace_config
.bts
.size
)
14626 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14627 packets_descriptions
[PACKET_Qbtrace_conf_bts_size
].name
,
14633 if (m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_bts_size
)
14636 if (buf
[0] == 'E' && buf
[1] == '.')
14637 error (_("Failed to configure the BTS buffer size: %s"), buf
+ 2);
14639 error (_("Failed to configure the BTS buffer size."));
14642 rs
->btrace_config
.bts
.size
= conf
->bts
.size
;
14645 if (m_features
.packet_support (PACKET_Qbtrace_conf_pt_size
) == PACKET_ENABLE
14646 && conf
->pt
.size
!= rs
->btrace_config
.pt
.size
)
14649 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14650 packets_descriptions
[PACKET_Qbtrace_conf_pt_size
].name
,
14656 if (m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_pt_size
)
14659 if (buf
[0] == 'E' && buf
[1] == '.')
14660 error (_("Failed to configure the trace buffer size: %s"), buf
+ 2);
14662 error (_("Failed to configure the trace buffer size."));
14665 rs
->btrace_config
.pt
.size
= conf
->pt
.size
;
14669 /* Read TP's btrace configuration from the target and store it into CONF. */
14672 btrace_read_config (thread_info
*tp
, btrace_config
*conf
)
14674 /* target_read_stralloc relies on INFERIOR_PTID. */
14675 scoped_restore_current_thread restore_thread
;
14676 switch_to_thread (tp
);
14678 gdb::optional
<gdb::char_vector
> xml
14679 = target_read_stralloc (current_inferior ()->top_target (),
14680 TARGET_OBJECT_BTRACE_CONF
, "");
14682 parse_xml_btrace_conf (conf
, xml
->data ());
14685 /* Maybe reopen target btrace. */
14688 remote_target::remote_btrace_maybe_reopen ()
14690 struct remote_state
*rs
= get_remote_state ();
14691 int btrace_target_pushed
= 0;
14692 #if !defined (HAVE_LIBIPT)
14696 /* Don't bother walking the entirety of the remote thread list when
14697 we know the feature isn't supported by the remote. */
14698 if (m_features
.packet_support (PACKET_qXfer_btrace_conf
) != PACKET_ENABLE
)
14701 for (thread_info
*tp
: all_non_exited_threads (this))
14703 memset (&rs
->btrace_config
, 0x00, sizeof (struct btrace_config
));
14704 btrace_read_config (tp
, &rs
->btrace_config
);
14706 if (rs
->btrace_config
.format
== BTRACE_FORMAT_NONE
)
14709 #if !defined (HAVE_LIBIPT)
14710 if (rs
->btrace_config
.format
== BTRACE_FORMAT_PT
)
14715 warning (_("Target is recording using Intel Processor Trace "
14716 "but support was disabled at compile time."));
14721 #endif /* !defined (HAVE_LIBIPT) */
14723 /* Push target, once, but before anything else happens. This way our
14724 changes to the threads will be cleaned up by unpushing the target
14725 in case btrace_read_config () throws. */
14726 if (!btrace_target_pushed
)
14728 btrace_target_pushed
= 1;
14729 record_btrace_push_target ();
14730 gdb_printf (_("Target is recording using %s.\n"),
14731 btrace_format_string (rs
->btrace_config
.format
));
14735 = new btrace_target_info
{ tp
->ptid
, rs
->btrace_config
};
14739 /* Enable branch tracing. */
14741 struct btrace_target_info
*
14742 remote_target::enable_btrace (thread_info
*tp
,
14743 const struct btrace_config
*conf
)
14745 struct packet_config
*packet
= NULL
;
14746 struct remote_state
*rs
= get_remote_state ();
14747 char *buf
= rs
->buf
.data ();
14748 char *endbuf
= buf
+ get_remote_packet_size ();
14750 unsigned int which_packet
;
14751 switch (conf
->format
)
14753 case BTRACE_FORMAT_BTS
:
14754 which_packet
= PACKET_Qbtrace_bts
;
14756 case BTRACE_FORMAT_PT
:
14757 which_packet
= PACKET_Qbtrace_pt
;
14760 internal_error (_("Bad branch btrace format: %u."),
14761 (unsigned int) conf
->format
);
14764 packet
= &m_features
.m_protocol_packets
[which_packet
];
14765 if (packet
== NULL
|| packet_config_support (packet
) != PACKET_ENABLE
)
14766 error (_("Target does not support branch tracing."));
14768 btrace_sync_conf (conf
);
14770 ptid_t ptid
= tp
->ptid
;
14771 set_general_thread (ptid
);
14773 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
14774 packets_descriptions
[which_packet
].name
);
14778 if (m_features
.packet_ok (rs
->buf
, which_packet
) == PACKET_ERROR
)
14780 if (rs
->buf
[0] == 'E' && rs
->buf
[1] == '.')
14781 error (_("Could not enable branch tracing for %s: %s"),
14782 target_pid_to_str (ptid
).c_str (), &rs
->buf
[2]);
14784 error (_("Could not enable branch tracing for %s."),
14785 target_pid_to_str (ptid
).c_str ());
14788 btrace_target_info
*tinfo
= new btrace_target_info
{ ptid
};
14790 /* If we fail to read the configuration, we lose some information, but the
14791 tracing itself is not impacted. */
14794 btrace_read_config (tp
, &tinfo
->conf
);
14796 catch (const gdb_exception_error
&err
)
14798 if (err
.message
!= NULL
)
14799 warning ("%s", err
.what ());
14805 /* Disable branch tracing. */
14808 remote_target::disable_btrace (struct btrace_target_info
*tinfo
)
14810 struct remote_state
*rs
= get_remote_state ();
14811 char *buf
= rs
->buf
.data ();
14812 char *endbuf
= buf
+ get_remote_packet_size ();
14814 if (m_features
.packet_support (PACKET_Qbtrace_off
) != PACKET_ENABLE
)
14815 error (_("Target does not support branch tracing."));
14817 set_general_thread (tinfo
->ptid
);
14819 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
14820 packets_descriptions
[PACKET_Qbtrace_off
].name
);
14824 if (m_features
.packet_ok (rs
->buf
, PACKET_Qbtrace_off
) == PACKET_ERROR
)
14826 if (rs
->buf
[0] == 'E' && rs
->buf
[1] == '.')
14827 error (_("Could not disable branch tracing for %s: %s"),
14828 target_pid_to_str (tinfo
->ptid
).c_str (), &rs
->buf
[2]);
14830 error (_("Could not disable branch tracing for %s."),
14831 target_pid_to_str (tinfo
->ptid
).c_str ());
14837 /* Teardown branch tracing. */
14840 remote_target::teardown_btrace (struct btrace_target_info
*tinfo
)
14842 /* We must not talk to the target during teardown. */
14846 /* Read the branch trace. */
14849 remote_target::read_btrace (struct btrace_data
*btrace
,
14850 struct btrace_target_info
*tinfo
,
14851 enum btrace_read_type type
)
14855 if (m_features
.packet_support (PACKET_qXfer_btrace
) != PACKET_ENABLE
)
14856 error (_("Target does not support branch tracing."));
14858 #if !defined(HAVE_LIBEXPAT)
14859 error (_("Cannot process branch tracing result. XML parsing not supported."));
14864 case BTRACE_READ_ALL
:
14867 case BTRACE_READ_NEW
:
14870 case BTRACE_READ_DELTA
:
14874 internal_error (_("Bad branch tracing read type: %u."),
14875 (unsigned int) type
);
14878 gdb::optional
<gdb::char_vector
> xml
14879 = target_read_stralloc (current_inferior ()->top_target (),
14880 TARGET_OBJECT_BTRACE
, annex
);
14882 return BTRACE_ERR_UNKNOWN
;
14884 parse_xml_btrace (btrace
, xml
->data ());
14886 return BTRACE_ERR_NONE
;
14889 const struct btrace_config
*
14890 remote_target::btrace_conf (const struct btrace_target_info
*tinfo
)
14892 return &tinfo
->conf
;
14896 remote_target::augmented_libraries_svr4_read ()
14899 (m_features
.packet_support (PACKET_augmented_libraries_svr4_read_feature
)
14903 /* Implementation of to_load. */
14906 remote_target::load (const char *name
, int from_tty
)
14908 generic_load (name
, from_tty
);
14911 /* Accepts an integer PID; returns a string representing a file that
14912 can be opened on the remote side to get the symbols for the child
14913 process. Returns NULL if the operation is not supported. */
14916 remote_target::pid_to_exec_file (int pid
)
14918 static gdb::optional
<gdb::char_vector
> filename
;
14919 char *annex
= NULL
;
14921 if (m_features
.packet_support (PACKET_qXfer_exec_file
) != PACKET_ENABLE
)
14924 inferior
*inf
= find_inferior_pid (this, pid
);
14926 internal_error (_("not currently attached to process %d"), pid
);
14928 if (!inf
->fake_pid_p
)
14930 const int annex_size
= 9;
14932 annex
= (char *) alloca (annex_size
);
14933 xsnprintf (annex
, annex_size
, "%x", pid
);
14936 filename
= target_read_stralloc (current_inferior ()->top_target (),
14937 TARGET_OBJECT_EXEC_FILE
, annex
);
14939 return filename
? filename
->data () : nullptr;
14942 /* Implement the to_can_do_single_step target_ops method. */
14945 remote_target::can_do_single_step ()
14947 /* We can only tell whether target supports single step or not by
14948 supported s and S vCont actions if the stub supports vContSupported
14949 feature. If the stub doesn't support vContSupported feature,
14950 we have conservatively to think target doesn't supports single
14952 if (m_features
.packet_support (PACKET_vContSupported
) == PACKET_ENABLE
)
14954 struct remote_state
*rs
= get_remote_state ();
14956 return rs
->supports_vCont
.s
&& rs
->supports_vCont
.S
;
14962 /* Implementation of the to_execution_direction method for the remote
14965 enum exec_direction_kind
14966 remote_target::execution_direction ()
14968 struct remote_state
*rs
= get_remote_state ();
14970 return rs
->last_resume_exec_dir
;
14973 /* Return pointer to the thread_info struct which corresponds to
14974 THREAD_HANDLE (having length HANDLE_LEN). */
14977 remote_target::thread_handle_to_thread_info (const gdb_byte
*thread_handle
,
14981 for (thread_info
*tp
: all_non_exited_threads (this))
14983 remote_thread_info
*priv
= get_remote_thread_info (tp
);
14985 if (tp
->inf
== inf
&& priv
!= NULL
)
14987 if (handle_len
!= priv
->thread_handle
.size ())
14988 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14989 handle_len
, priv
->thread_handle
.size ());
14990 if (memcmp (thread_handle
, priv
->thread_handle
.data (),
14999 gdb::array_view
<const gdb_byte
>
15000 remote_target::thread_info_to_thread_handle (struct thread_info
*tp
)
15002 remote_thread_info
*priv
= get_remote_thread_info (tp
);
15003 return priv
->thread_handle
;
15007 remote_target::can_async_p ()
15009 /* This flag should be checked in the common target.c code. */
15010 gdb_assert (target_async_permitted
);
15012 /* We're async whenever the serial device can. */
15013 return get_remote_state ()->can_async_p ();
15017 remote_target::is_async_p ()
15019 /* We're async whenever the serial device is. */
15020 return get_remote_state ()->is_async_p ();
15023 /* Pass the SERIAL event on and up to the client. One day this code
15024 will be able to delay notifying the client of an event until the
15025 point where an entire packet has been received. */
15027 static serial_event_ftype remote_async_serial_handler
;
15030 remote_async_serial_handler (struct serial
*scb
, void *context
)
15032 /* Don't propogate error information up to the client. Instead let
15033 the client find out about the error by querying the target. */
15034 inferior_event_handler (INF_REG_EVENT
);
15038 remote_target::async_wait_fd ()
15040 struct remote_state
*rs
= get_remote_state ();
15041 return rs
->remote_desc
->fd
;
15045 remote_target::async (bool enable
)
15047 struct remote_state
*rs
= get_remote_state ();
15051 serial_async (rs
->remote_desc
, remote_async_serial_handler
, rs
);
15053 /* If there are pending events in the stop reply queue tell the
15054 event loop to process them. */
15055 if (!rs
->stop_reply_queue
.empty ())
15056 rs
->mark_async_event_handler ();
15058 /* For simplicity, below we clear the pending events token
15059 without remembering whether it is marked, so here we always
15060 mark it. If there's actually no pending notification to
15061 process, this ends up being a no-op (other than a spurious
15062 event-loop wakeup). */
15063 if (target_is_non_stop_p ())
15064 mark_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15068 serial_async (rs
->remote_desc
, NULL
, NULL
);
15069 /* If the core is disabling async, it doesn't want to be
15070 disturbed with target events. Clear all async event sources
15072 rs
->clear_async_event_handler ();
15074 if (target_is_non_stop_p ())
15075 clear_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15079 /* Implementation of the to_thread_events method. */
15082 remote_target::thread_events (int enable
)
15084 struct remote_state
*rs
= get_remote_state ();
15085 size_t size
= get_remote_packet_size ();
15087 if (m_features
.packet_support (PACKET_QThreadEvents
) == PACKET_DISABLE
)
15090 if (rs
->last_thread_events
== enable
)
15093 xsnprintf (rs
->buf
.data (), size
, "QThreadEvents:%x", enable
? 1 : 0);
15097 switch (m_features
.packet_ok (rs
->buf
, PACKET_QThreadEvents
))
15100 if (strcmp (rs
->buf
.data (), "OK") != 0)
15101 error (_("Remote refused setting thread events: %s"), rs
->buf
.data ());
15102 rs
->last_thread_events
= enable
;
15105 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
15107 case PACKET_UNKNOWN
:
15112 /* Implementation of the supports_set_thread_options target
15116 remote_target::supports_set_thread_options (gdb_thread_options options
)
15118 remote_state
*rs
= get_remote_state ();
15119 return (m_features
.packet_support (PACKET_QThreadOptions
) == PACKET_ENABLE
15120 && (rs
->supported_thread_options
& options
) == options
);
15123 /* For coalescing reasons, actually sending the options to the target
15124 happens at resume time, via this function. See target_resume for
15125 all-stop, and target_commit_resumed for non-stop. */
15128 remote_target::commit_requested_thread_options ()
15130 struct remote_state
*rs
= get_remote_state ();
15132 if (m_features
.packet_support (PACKET_QThreadOptions
) != PACKET_ENABLE
)
15135 char *p
= rs
->buf
.data ();
15136 char *endp
= p
+ get_remote_packet_size ();
15138 /* Clear options for all threads by default. Note that unlike
15139 vCont, the rightmost options that match a thread apply, so we
15140 don't have to worry about whether we can use wildcard ptids. */
15141 strcpy (p
, "QThreadOptions;0");
15144 /* Send the QThreadOptions packet stored in P. */
15145 auto flush
= [&] ()
15150 getpkt (&rs
->buf
, 0);
15152 switch (m_features
.packet_ok (rs
->buf
, PACKET_QThreadOptions
))
15155 if (strcmp (rs
->buf
.data (), "OK") != 0)
15156 error (_("Remote refused setting thread options: %s"), rs
->buf
.data ());
15159 error (_("Remote failure reply: %s"), rs
->buf
.data ());
15160 case PACKET_UNKNOWN
:
15161 gdb_assert_not_reached ("PACKET_UNKNOWN");
15166 /* Prepare P for another QThreadOptions packet. */
15167 auto restart
= [&] ()
15169 p
= rs
->buf
.data ();
15170 strcpy (p
, "QThreadOptions");
15174 /* Now set non-zero options for threads that need them. We don't
15175 bother with the case of all threads of a process wanting the same
15176 non-zero options as that's not an expected scenario. */
15177 for (thread_info
*tp
: all_non_exited_threads (this))
15179 gdb_thread_options options
= tp
->thread_options ();
15184 /* It might be possible to we have more threads with options
15185 than can fit a single QThreadOptions packet. So build each
15186 options/thread pair in this separate buffer to make sure it
15188 constexpr size_t max_options_size
= 100;
15189 char obuf
[max_options_size
];
15190 char *obuf_p
= obuf
;
15191 char *obuf_endp
= obuf
+ max_options_size
;
15194 obuf_p
+= xsnprintf (obuf_p
, obuf_endp
- obuf_p
, "%s",
15195 phex_nz (options
, sizeof (options
)));
15196 if (tp
->ptid
!= magic_null_ptid
)
15199 obuf_p
= write_ptid (obuf_p
, obuf_endp
, tp
->ptid
);
15202 size_t osize
= obuf_p
- obuf
;
15203 if (osize
> endp
- p
)
15205 /* This new options/thread pair doesn't fit the packet
15206 buffer. Send what we have already. */
15210 /* Should now fit. */
15211 gdb_assert (osize
<= endp
- p
);
15214 memcpy (p
, obuf
, osize
);
15222 show_remote_cmd (const char *args
, int from_tty
)
15224 /* We can't just use cmd_show_list here, because we want to skip
15225 the redundant "show remote Z-packet" and the legacy aliases. */
15226 struct cmd_list_element
*list
= remote_show_cmdlist
;
15227 struct ui_out
*uiout
= current_uiout
;
15229 ui_out_emit_tuple
tuple_emitter (uiout
, "showlist");
15230 for (; list
!= NULL
; list
= list
->next
)
15231 if (strcmp (list
->name
, "Z-packet") == 0)
15233 else if (list
->type
== not_set_cmd
)
15234 /* Alias commands are exactly like the original, except they
15235 don't have the normal type. */
15239 ui_out_emit_tuple
option_emitter (uiout
, "option");
15241 uiout
->field_string ("name", list
->name
);
15242 uiout
->text (": ");
15243 if (list
->type
== show_cmd
)
15244 do_show_command (NULL
, from_tty
, list
);
15246 cmd_func (list
, NULL
, from_tty
);
15250 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15251 offer all inferiors using that program space a change to look up symbols. */
15254 remote_objfile_changed_check_symbols (program_space
*pspace
)
15256 /* The affected program space is possibly shared by multiple inferiors.
15257 Consider sending a qSymbol packet for each of the inferiors using that
15259 for (inferior
*inf
: all_inferiors ())
15261 if (inf
->pspace
!= pspace
)
15264 /* Check whether the inferior's process target is a remote target. */
15265 remote_target
*remote
= as_remote_target (inf
->process_target ());
15266 if (remote
== nullptr)
15269 /* When we are attaching or handling a fork child and the shared library
15270 subsystem reads the list of loaded libraries, we receive new objfile
15271 events in between each found library. The libraries are read in an
15272 undefined order, so if we gave the remote side a chance to look up
15273 symbols between each objfile, we might give it an inconsistent picture
15274 of the inferior. It could appear that a library A appears loaded but
15275 a library B does not, even though library A requires library B. That
15276 would present a state that couldn't normally exist in the inferior.
15278 So, skip these events, we'll give the remote a chance to look up
15279 symbols once all the loaded libraries and their symbols are known to
15281 if (inf
->in_initial_library_scan
)
15284 if (!remote
->has_execution (inf
))
15287 /* Need to switch to a specific thread, because remote_check_symbols will
15288 set the general thread using INFERIOR_PTID.
15290 It's possible to have inferiors with no thread here, because we are
15291 called very early in the connection process, while the inferior is
15292 being set up, before threads are added. Just skip it, start_remote_1
15293 also calls remote_check_symbols when it's done setting things up. */
15294 thread_info
*thread
= any_thread_of_inferior (inf
);
15295 if (thread
!= nullptr)
15297 scoped_restore_current_thread restore_thread
;
15298 switch_to_thread (thread
);
15299 remote
->remote_check_symbols ();
15304 /* Function to be called whenever a new objfile (shlib) is detected. */
15307 remote_new_objfile (struct objfile
*objfile
)
15309 remote_objfile_changed_check_symbols (objfile
->pspace
);
15312 /* Pull all the tracepoints defined on the target and create local
15313 data structures representing them. We don't want to create real
15314 tracepoints yet, we don't want to mess up the user's existing
15318 remote_target::upload_tracepoints (struct uploaded_tp
**utpp
)
15320 struct remote_state
*rs
= get_remote_state ();
15323 /* Ask for a first packet of tracepoint definition. */
15326 p
= rs
->buf
.data ();
15327 while (*p
&& *p
!= 'l')
15329 parse_tracepoint_definition (p
, utpp
);
15330 /* Ask for another packet of tracepoint definition. */
15333 p
= rs
->buf
.data ();
15339 remote_target::upload_trace_state_variables (struct uploaded_tsv
**utsvp
)
15341 struct remote_state
*rs
= get_remote_state ();
15344 /* Ask for a first packet of variable definition. */
15347 p
= rs
->buf
.data ();
15348 while (*p
&& *p
!= 'l')
15350 parse_tsv_definition (p
, utsvp
);
15351 /* Ask for another packet of variable definition. */
15354 p
= rs
->buf
.data ();
15359 /* The "set/show range-stepping" show hook. */
15362 show_range_stepping (struct ui_file
*file
, int from_tty
,
15363 struct cmd_list_element
*c
,
15367 _("Debugger's willingness to use range stepping "
15368 "is %s.\n"), value
);
15371 /* Return true if the vCont;r action is supported by the remote
15375 remote_target::vcont_r_supported ()
15377 return (m_features
.packet_support (PACKET_vCont
) == PACKET_ENABLE
15378 && get_remote_state ()->supports_vCont
.r
);
15381 /* The "set/show range-stepping" set hook. */
15384 set_range_stepping (const char *ignore_args
, int from_tty
,
15385 struct cmd_list_element
*c
)
15387 /* When enabling, check whether range stepping is actually supported
15388 by the target, and warn if not. */
15389 if (use_range_stepping
)
15391 remote_target
*remote
= get_current_remote_target ();
15393 || !remote
->vcont_r_supported ())
15394 warning (_("Range stepping is not supported by the current target"));
15399 show_remote_debug (struct ui_file
*file
, int from_tty
,
15400 struct cmd_list_element
*c
, const char *value
)
15402 gdb_printf (file
, _("Debugging of remote protocol is %s.\n"),
15407 show_remote_timeout (struct ui_file
*file
, int from_tty
,
15408 struct cmd_list_element
*c
, const char *value
)
15411 _("Timeout limit to wait for target to respond is %s.\n"),
15415 /* Implement the "supports_memory_tagging" target_ops method. */
15418 remote_target::supports_memory_tagging ()
15420 return m_features
.remote_memory_tagging_p ();
15423 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15426 create_fetch_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15427 size_t len
, int type
)
15429 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15431 std::string request
= string_printf ("qMemTags:%s,%s:%s",
15432 phex_nz (address
, addr_size
),
15433 phex_nz (len
, sizeof (len
)),
15434 phex_nz (type
, sizeof (type
)));
15436 strcpy (packet
.data (), request
.c_str ());
15439 /* Parse the qMemTags packet reply into TAGS.
15441 Return true if successful, false otherwise. */
15444 parse_fetch_memtags_reply (const gdb::char_vector
&reply
,
15445 gdb::byte_vector
&tags
)
15447 if (reply
.empty () || reply
[0] == 'E' || reply
[0] != 'm')
15450 /* Copy the tag data. */
15451 tags
= hex2bin (reply
.data () + 1);
15456 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15459 create_store_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15460 size_t len
, int type
,
15461 const gdb::byte_vector
&tags
)
15463 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15465 /* Put together the main packet, address and length. */
15466 std::string request
= string_printf ("QMemTags:%s,%s:%s:",
15467 phex_nz (address
, addr_size
),
15468 phex_nz (len
, sizeof (len
)),
15469 phex_nz (type
, sizeof (type
)));
15470 request
+= bin2hex (tags
.data (), tags
.size ());
15472 /* Check if we have exceeded the maximum packet size. */
15473 if (packet
.size () < request
.length ())
15474 error (_("Contents too big for packet QMemTags."));
15476 strcpy (packet
.data (), request
.c_str ());
15479 /* Implement the "fetch_memtags" target_ops method. */
15482 remote_target::fetch_memtags (CORE_ADDR address
, size_t len
,
15483 gdb::byte_vector
&tags
, int type
)
15485 /* Make sure the qMemTags packet is supported. */
15486 if (!m_features
.remote_memory_tagging_p ())
15487 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15489 struct remote_state
*rs
= get_remote_state ();
15491 create_fetch_memtags_request (rs
->buf
, address
, len
, type
);
15496 return parse_fetch_memtags_reply (rs
->buf
, tags
);
15499 /* Implement the "store_memtags" target_ops method. */
15502 remote_target::store_memtags (CORE_ADDR address
, size_t len
,
15503 const gdb::byte_vector
&tags
, int type
)
15505 /* Make sure the QMemTags packet is supported. */
15506 if (!m_features
.remote_memory_tagging_p ())
15507 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15509 struct remote_state
*rs
= get_remote_state ();
15511 create_store_memtags_request (rs
->buf
, address
, len
, type
, tags
);
15516 /* Verify if the request was successful. */
15517 return packet_check_result (rs
->buf
.data ()) == PACKET_OK
;
15520 /* Return true if remote target T is non-stop. */
15523 remote_target_is_non_stop_p (remote_target
*t
)
15525 scoped_restore_current_thread restore_thread
;
15526 switch_to_target_no_thread (t
);
15528 return target_is_non_stop_p ();
15533 namespace selftests
{
15536 test_memory_tagging_functions ()
15538 remote_target remote
;
15540 struct packet_config
*config
15541 = &remote
.m_features
.m_protocol_packets
[PACKET_memory_tagging_feature
];
15543 scoped_restore restore_memtag_support_
15544 = make_scoped_restore (&config
->support
);
15546 /* Test memory tagging packet support. */
15547 config
->support
= PACKET_SUPPORT_UNKNOWN
;
15548 SELF_CHECK (remote
.supports_memory_tagging () == false);
15549 config
->support
= PACKET_DISABLE
;
15550 SELF_CHECK (remote
.supports_memory_tagging () == false);
15551 config
->support
= PACKET_ENABLE
;
15552 SELF_CHECK (remote
.supports_memory_tagging () == true);
15554 /* Setup testing. */
15555 gdb::char_vector packet
;
15556 gdb::byte_vector tags
, bv
;
15557 std::string expected
, reply
;
15558 packet
.resize (32000);
15560 /* Test creating a qMemTags request. */
15562 expected
= "qMemTags:0,0:0";
15563 create_fetch_memtags_request (packet
, 0x0, 0x0, 0);
15564 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
15566 expected
= "qMemTags:deadbeef,10:1";
15567 create_fetch_memtags_request (packet
, 0xdeadbeef, 16, 1);
15568 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
15570 /* Test parsing a qMemTags reply. */
15572 /* Error reply, tags vector unmodified. */
15574 strcpy (packet
.data (), reply
.c_str ());
15576 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == false);
15577 SELF_CHECK (tags
.size () == 0);
15579 /* Valid reply, tags vector updated. */
15583 for (int i
= 0; i
< 5; i
++)
15586 reply
= "m" + bin2hex (bv
.data (), bv
.size ());
15587 strcpy (packet
.data (), reply
.c_str ());
15589 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == true);
15590 SELF_CHECK (tags
.size () == 5);
15592 for (int i
= 0; i
< 5; i
++)
15593 SELF_CHECK (tags
[i
] == i
);
15595 /* Test creating a QMemTags request. */
15597 /* Empty tag data. */
15599 expected
= "QMemTags:0,0:0:";
15600 create_store_memtags_request (packet
, 0x0, 0x0, 0, tags
);
15601 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
15602 expected
.length ()) == 0);
15604 /* Non-empty tag data. */
15606 for (int i
= 0; i
< 5; i
++)
15607 tags
.push_back (i
);
15608 expected
= "QMemTags:deadbeef,ff:1:0001020304";
15609 create_store_memtags_request (packet
, 0xdeadbeef, 255, 1, tags
);
15610 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
15611 expected
.length ()) == 0);
15614 } // namespace selftests
15615 #endif /* GDB_SELF_TEST */
15617 void _initialize_remote ();
15619 _initialize_remote ()
15621 add_target (remote_target_info
, remote_target::open
);
15622 add_target (extended_remote_target_info
, extended_remote_target::open
);
15624 /* Hook into new objfile notification. */
15625 gdb::observers::new_objfile
.attach (remote_new_objfile
, "remote");
15626 gdb::observers::all_objfiles_removed
.attach
15627 (remote_objfile_changed_check_symbols
, "remote");
15630 init_remote_threadtests ();
15633 /* set/show remote ... */
15635 add_basic_prefix_cmd ("remote", class_maintenance
, _("\
15636 Remote protocol specific variables.\n\
15637 Configure various remote-protocol specific variables such as\n\
15638 the packets being used."),
15639 &remote_set_cmdlist
,
15640 0 /* allow-unknown */, &setlist
);
15641 add_prefix_cmd ("remote", class_maintenance
, show_remote_cmd
, _("\
15642 Remote protocol specific variables.\n\
15643 Configure various remote-protocol specific variables such as\n\
15644 the packets being used."),
15645 &remote_show_cmdlist
,
15646 0 /* allow-unknown */, &showlist
);
15648 add_cmd ("compare-sections", class_obscure
, compare_sections_command
, _("\
15649 Compare section data on target to the exec file.\n\
15650 Argument is a single section name (default: all loaded sections).\n\
15651 To compare only read-only loaded sections, specify the -r option."),
15654 add_cmd ("packet", class_maintenance
, cli_packet_command
, _("\
15655 Send an arbitrary packet to a remote target.\n\
15656 maintenance packet TEXT\n\
15657 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15658 this command sends the string TEXT to the inferior, and displays the\n\
15659 response packet. GDB supplies the initial `$' character, and the\n\
15660 terminating `#' character and checksum."),
15663 set_show_commands remotebreak_cmds
15664 = add_setshow_boolean_cmd ("remotebreak", no_class
, &remote_break
, _("\
15665 Set whether to send break if interrupted."), _("\
15666 Show whether to send break if interrupted."), _("\
15667 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15668 set_remotebreak
, show_remotebreak
,
15669 &setlist
, &showlist
);
15670 deprecate_cmd (remotebreak_cmds
.set
, "set remote interrupt-sequence");
15671 deprecate_cmd (remotebreak_cmds
.show
, "show remote interrupt-sequence");
15673 add_setshow_enum_cmd ("interrupt-sequence", class_support
,
15674 interrupt_sequence_modes
, &interrupt_sequence_mode
,
15676 Set interrupt sequence to remote target."), _("\
15677 Show interrupt sequence to remote target."), _("\
15678 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15679 NULL
, show_interrupt_sequence
,
15680 &remote_set_cmdlist
,
15681 &remote_show_cmdlist
);
15683 add_setshow_boolean_cmd ("interrupt-on-connect", class_support
,
15684 &interrupt_on_connect
, _("\
15685 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15686 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15687 If set, interrupt sequence is sent to remote target."),
15689 &remote_set_cmdlist
, &remote_show_cmdlist
);
15691 /* Install commands for configuring memory read/write packets. */
15693 add_cmd ("remotewritesize", no_class
, set_memory_write_packet_size
, _("\
15694 Set the maximum number of bytes per memory write packet (deprecated)."),
15696 add_cmd ("remotewritesize", no_class
, show_memory_write_packet_size
, _("\
15697 Show the maximum number of bytes per memory write packet (deprecated)."),
15699 add_cmd ("memory-write-packet-size", no_class
,
15700 set_memory_write_packet_size
, _("\
15701 Set the maximum number of bytes per memory-write packet.\n\
15702 Specify the number of bytes in a packet or 0 (zero) for the\n\
15703 default packet size. The actual limit is further reduced\n\
15704 dependent on the target. Specify \"fixed\" to disable the\n\
15705 further restriction and \"limit\" to enable that restriction."),
15706 &remote_set_cmdlist
);
15707 add_cmd ("memory-read-packet-size", no_class
,
15708 set_memory_read_packet_size
, _("\
15709 Set the maximum number of bytes per memory-read packet.\n\
15710 Specify the number of bytes in a packet or 0 (zero) for the\n\
15711 default packet size. The actual limit is further reduced\n\
15712 dependent on the target. Specify \"fixed\" to disable the\n\
15713 further restriction and \"limit\" to enable that restriction."),
15714 &remote_set_cmdlist
);
15715 add_cmd ("memory-write-packet-size", no_class
,
15716 show_memory_write_packet_size
,
15717 _("Show the maximum number of bytes per memory-write packet."),
15718 &remote_show_cmdlist
);
15719 add_cmd ("memory-read-packet-size", no_class
,
15720 show_memory_read_packet_size
,
15721 _("Show the maximum number of bytes per memory-read packet."),
15722 &remote_show_cmdlist
);
15724 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class
,
15725 &remote_hw_watchpoint_limit
, _("\
15726 Set the maximum number of target hardware watchpoints."), _("\
15727 Show the maximum number of target hardware watchpoints."), _("\
15728 Specify \"unlimited\" for unlimited hardware watchpoints."),
15729 NULL
, show_hardware_watchpoint_limit
,
15730 &remote_set_cmdlist
,
15731 &remote_show_cmdlist
);
15732 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15734 &remote_hw_watchpoint_length_limit
, _("\
15735 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15736 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15737 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15738 NULL
, show_hardware_watchpoint_length_limit
,
15739 &remote_set_cmdlist
, &remote_show_cmdlist
);
15740 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class
,
15741 &remote_hw_breakpoint_limit
, _("\
15742 Set the maximum number of target hardware breakpoints."), _("\
15743 Show the maximum number of target hardware breakpoints."), _("\
15744 Specify \"unlimited\" for unlimited hardware breakpoints."),
15745 NULL
, show_hardware_breakpoint_limit
,
15746 &remote_set_cmdlist
, &remote_show_cmdlist
);
15748 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure
,
15749 &remote_address_size
, _("\
15750 Set the maximum size of the address (in bits) in a memory packet."), _("\
15751 Show the maximum size of the address (in bits) in a memory packet."), NULL
,
15753 NULL
, /* FIXME: i18n: */
15754 &setlist
, &showlist
);
15756 init_all_packet_configs ();
15758 add_packet_config_cmd (PACKET_X
, "X", "binary-download", 1);
15760 add_packet_config_cmd (PACKET_vCont
, "vCont", "verbose-resume", 0);
15762 add_packet_config_cmd (PACKET_QPassSignals
, "QPassSignals", "pass-signals",
15765 add_packet_config_cmd (PACKET_QCatchSyscalls
, "QCatchSyscalls",
15766 "catch-syscalls", 0);
15768 add_packet_config_cmd (PACKET_QProgramSignals
, "QProgramSignals",
15769 "program-signals", 0);
15771 add_packet_config_cmd (PACKET_QSetWorkingDir
, "QSetWorkingDir",
15772 "set-working-dir", 0);
15774 add_packet_config_cmd (PACKET_QStartupWithShell
, "QStartupWithShell",
15775 "startup-with-shell", 0);
15777 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded
,"QEnvironmentHexEncoded",
15778 "environment-hex-encoded", 0);
15780 add_packet_config_cmd (PACKET_QEnvironmentReset
, "QEnvironmentReset",
15781 "environment-reset", 0);
15783 add_packet_config_cmd (PACKET_QEnvironmentUnset
, "QEnvironmentUnset",
15784 "environment-unset", 0);
15786 add_packet_config_cmd (PACKET_qSymbol
, "qSymbol", "symbol-lookup", 0);
15788 add_packet_config_cmd (PACKET_P
, "P", "set-register", 1);
15790 add_packet_config_cmd (PACKET_p
, "p", "fetch-register", 1);
15792 add_packet_config_cmd (PACKET_Z0
, "Z0", "software-breakpoint", 0);
15794 add_packet_config_cmd (PACKET_Z1
, "Z1", "hardware-breakpoint", 0);
15796 add_packet_config_cmd (PACKET_Z2
, "Z2", "write-watchpoint", 0);
15798 add_packet_config_cmd (PACKET_Z3
, "Z3", "read-watchpoint", 0);
15800 add_packet_config_cmd (PACKET_Z4
, "Z4", "access-watchpoint", 0);
15802 add_packet_config_cmd (PACKET_qXfer_auxv
, "qXfer:auxv:read",
15803 "read-aux-vector", 0);
15805 add_packet_config_cmd (PACKET_qXfer_exec_file
, "qXfer:exec-file:read",
15806 "pid-to-exec-file", 0);
15808 add_packet_config_cmd (PACKET_qXfer_features
,
15809 "qXfer:features:read", "target-features", 0);
15811 add_packet_config_cmd (PACKET_qXfer_libraries
, "qXfer:libraries:read",
15812 "library-info", 0);
15814 add_packet_config_cmd (PACKET_qXfer_libraries_svr4
,
15815 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15817 add_packet_config_cmd (PACKET_qXfer_memory_map
, "qXfer:memory-map:read",
15820 add_packet_config_cmd (PACKET_qXfer_osdata
, "qXfer:osdata:read", "osdata", 0);
15822 add_packet_config_cmd (PACKET_qXfer_threads
, "qXfer:threads:read", "threads",
15825 add_packet_config_cmd (PACKET_qXfer_siginfo_read
, "qXfer:siginfo:read",
15826 "read-siginfo-object", 0);
15828 add_packet_config_cmd (PACKET_qXfer_siginfo_write
, "qXfer:siginfo:write",
15829 "write-siginfo-object", 0);
15831 add_packet_config_cmd (PACKET_qXfer_traceframe_info
,
15832 "qXfer:traceframe-info:read", "traceframe-info", 0);
15834 add_packet_config_cmd (PACKET_qXfer_uib
, "qXfer:uib:read",
15835 "unwind-info-block", 0);
15837 add_packet_config_cmd (PACKET_qGetTLSAddr
, "qGetTLSAddr",
15838 "get-thread-local-storage-address", 0);
15840 add_packet_config_cmd (PACKET_qGetTIBAddr
, "qGetTIBAddr",
15841 "get-thread-information-block-address", 0);
15843 add_packet_config_cmd (PACKET_bc
, "bc", "reverse-continue", 0);
15845 add_packet_config_cmd (PACKET_bs
, "bs", "reverse-step", 0);
15847 add_packet_config_cmd (PACKET_qSupported
, "qSupported", "supported-packets",
15850 add_packet_config_cmd (PACKET_qSearch_memory
, "qSearch:memory",
15851 "search-memory", 0);
15853 add_packet_config_cmd (PACKET_qTStatus
, "qTStatus", "trace-status", 0);
15855 add_packet_config_cmd (PACKET_vFile_setfs
, "vFile:setfs", "hostio-setfs", 0);
15857 add_packet_config_cmd (PACKET_vFile_open
, "vFile:open", "hostio-open", 0);
15859 add_packet_config_cmd (PACKET_vFile_pread
, "vFile:pread", "hostio-pread", 0);
15861 add_packet_config_cmd (PACKET_vFile_pwrite
, "vFile:pwrite", "hostio-pwrite",
15864 add_packet_config_cmd (PACKET_vFile_close
, "vFile:close", "hostio-close", 0);
15866 add_packet_config_cmd (PACKET_vFile_unlink
, "vFile:unlink", "hostio-unlink",
15869 add_packet_config_cmd (PACKET_vFile_readlink
, "vFile:readlink",
15870 "hostio-readlink", 0);
15872 add_packet_config_cmd (PACKET_vFile_fstat
, "vFile:fstat", "hostio-fstat", 0);
15874 add_packet_config_cmd (PACKET_vAttach
, "vAttach", "attach", 0);
15876 add_packet_config_cmd (PACKET_vRun
, "vRun", "run", 0);
15878 add_packet_config_cmd (PACKET_QStartNoAckMode
, "QStartNoAckMode", "noack", 0);
15880 add_packet_config_cmd (PACKET_vKill
, "vKill", "kill", 0);
15882 add_packet_config_cmd (PACKET_qAttached
, "qAttached", "query-attached", 0);
15884 add_packet_config_cmd (PACKET_ConditionalTracepoints
,
15885 "ConditionalTracepoints", "conditional-tracepoints",
15888 add_packet_config_cmd (PACKET_ConditionalBreakpoints
,
15889 "ConditionalBreakpoints", "conditional-breakpoints",
15892 add_packet_config_cmd (PACKET_BreakpointCommands
, "BreakpointCommands",
15893 "breakpoint-commands", 0);
15895 add_packet_config_cmd (PACKET_FastTracepoints
, "FastTracepoints",
15896 "fast-tracepoints", 0);
15898 add_packet_config_cmd (PACKET_TracepointSource
, "TracepointSource",
15899 "TracepointSource", 0);
15901 add_packet_config_cmd (PACKET_QAllow
, "QAllow", "allow", 0);
15903 add_packet_config_cmd (PACKET_StaticTracepoints
, "StaticTracepoints",
15904 "static-tracepoints", 0);
15906 add_packet_config_cmd (PACKET_InstallInTrace
, "InstallInTrace",
15907 "install-in-trace", 0);
15909 add_packet_config_cmd (PACKET_qXfer_statictrace_read
,
15910 "qXfer:statictrace:read", "read-sdata-object", 0);
15912 add_packet_config_cmd (PACKET_qXfer_fdpic
, "qXfer:fdpic:read",
15913 "read-fdpic-loadmap", 0);
15915 add_packet_config_cmd (PACKET_QDisableRandomization
, "QDisableRandomization",
15916 "disable-randomization", 0);
15918 add_packet_config_cmd (PACKET_QAgent
, "QAgent", "agent", 0);
15920 add_packet_config_cmd (PACKET_QTBuffer_size
, "QTBuffer:size",
15921 "trace-buffer-size", 0);
15923 add_packet_config_cmd (PACKET_Qbtrace_off
, "Qbtrace:off", "disable-btrace",
15926 add_packet_config_cmd (PACKET_Qbtrace_bts
, "Qbtrace:bts", "enable-btrace-bts",
15929 add_packet_config_cmd (PACKET_Qbtrace_pt
, "Qbtrace:pt", "enable-btrace-pt",
15932 add_packet_config_cmd (PACKET_qXfer_btrace
, "qXfer:btrace", "read-btrace", 0);
15934 add_packet_config_cmd (PACKET_qXfer_btrace_conf
, "qXfer:btrace-conf",
15935 "read-btrace-conf", 0);
15937 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size
, "Qbtrace-conf:bts:size",
15938 "btrace-conf-bts-size", 0);
15940 add_packet_config_cmd (PACKET_multiprocess_feature
, "multiprocess-feature",
15941 "multiprocess-feature", 0);
15943 add_packet_config_cmd (PACKET_swbreak_feature
, "swbreak-feature",
15944 "swbreak-feature", 0);
15946 add_packet_config_cmd (PACKET_hwbreak_feature
, "hwbreak-feature",
15947 "hwbreak-feature", 0);
15949 add_packet_config_cmd (PACKET_fork_event_feature
, "fork-event-feature",
15950 "fork-event-feature", 0);
15952 add_packet_config_cmd (PACKET_vfork_event_feature
, "vfork-event-feature",
15953 "vfork-event-feature", 0);
15955 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size
, "Qbtrace-conf:pt:size",
15956 "btrace-conf-pt-size", 0);
15958 add_packet_config_cmd (PACKET_vContSupported
, "vContSupported",
15959 "verbose-resume-supported", 0);
15961 add_packet_config_cmd (PACKET_exec_event_feature
, "exec-event-feature",
15962 "exec-event-feature", 0);
15964 add_packet_config_cmd (PACKET_vCtrlC
, "vCtrlC", "ctrl-c", 0);
15966 add_packet_config_cmd (PACKET_QThreadEvents
, "QThreadEvents", "thread-events",
15969 add_packet_config_cmd (PACKET_QThreadOptions
, "QThreadOptions",
15970 "thread-options", 0);
15972 add_packet_config_cmd (PACKET_no_resumed
, "N stop reply",
15973 "no-resumed-stop-reply", 0);
15975 add_packet_config_cmd (PACKET_memory_tagging_feature
,
15976 "memory-tagging-feature", "memory-tagging-feature", 0);
15978 /* Assert that we've registered "set remote foo-packet" commands
15979 for all packet configs. */
15983 for (i
= 0; i
< PACKET_MAX
; i
++)
15985 /* Ideally all configs would have a command associated. Some
15986 still don't though. */
15991 case PACKET_QNonStop
:
15992 case PACKET_EnableDisableTracepoints_feature
:
15993 case PACKET_tracenz_feature
:
15994 case PACKET_DisconnectedTracing_feature
:
15995 case PACKET_augmented_libraries_svr4_read_feature
:
15997 /* Additions to this list need to be well justified:
15998 pre-existing packets are OK; new packets are not. */
16006 /* This catches both forgetting to add a config command, and
16007 forgetting to remove a packet from the exception list. */
16008 gdb_assert (excepted
== (packets_descriptions
[i
].name
== NULL
));
16012 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16013 Z sub-packet has its own set and show commands, but users may
16014 have sets to this variable in their .gdbinit files (or in their
16016 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure
,
16017 &remote_Z_packet_detect
, _("\
16018 Set use of remote protocol `Z' packets."), _("\
16019 Show use of remote protocol `Z' packets."), _("\
16020 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16022 set_remote_protocol_Z_packet_cmd
,
16023 show_remote_protocol_Z_packet_cmd
,
16024 /* FIXME: i18n: Use of remote protocol
16025 `Z' packets is %s. */
16026 &remote_set_cmdlist
, &remote_show_cmdlist
);
16028 add_basic_prefix_cmd ("remote", class_files
, _("\
16029 Manipulate files on the remote system.\n\
16030 Transfer files to and from the remote target system."),
16032 0 /* allow-unknown */, &cmdlist
);
16034 add_cmd ("put", class_files
, remote_put_command
,
16035 _("Copy a local file to the remote system."),
16038 add_cmd ("get", class_files
, remote_get_command
,
16039 _("Copy a remote file to the local system."),
16042 add_cmd ("delete", class_files
, remote_delete_command
,
16043 _("Delete a remote file."),
16046 add_setshow_string_noescape_cmd ("exec-file", class_files
,
16047 &remote_exec_file_var
, _("\
16048 Set the remote pathname for \"run\"."), _("\
16049 Show the remote pathname for \"run\"."), NULL
,
16050 set_remote_exec_file
,
16051 show_remote_exec_file
,
16052 &remote_set_cmdlist
,
16053 &remote_show_cmdlist
);
16055 add_setshow_boolean_cmd ("range-stepping", class_run
,
16056 &use_range_stepping
, _("\
16057 Enable or disable range stepping."), _("\
16058 Show whether target-assisted range stepping is enabled."), _("\
16059 If on, and the target supports it, when stepping a source line, GDB\n\
16060 tells the target to step the corresponding range of addresses itself instead\n\
16061 of issuing multiple single-steps. This speeds up source level\n\
16062 stepping. If off, GDB always issues single-steps, even if range\n\
16063 stepping is supported by the target. The default is on."),
16064 set_range_stepping
,
16065 show_range_stepping
,
16069 add_setshow_zinteger_cmd ("watchdog", class_maintenance
, &watchdog
, _("\
16070 Set watchdog timer."), _("\
16071 Show watchdog timer."), _("\
16072 When non-zero, this timeout is used instead of waiting forever for a target\n\
16073 to finish a low-level step or continue operation. If the specified amount\n\
16074 of time passes without a response from the target, an error occurs."),
16077 &setlist
, &showlist
);
16079 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class
,
16080 &remote_packet_max_chars
, _("\
16081 Set the maximum number of characters to display for each remote packet."), _("\
16082 Show the maximum number of characters to display for each remote packet."), _("\
16083 Specify \"unlimited\" to display all the characters."),
16084 NULL
, show_remote_packet_max_chars
,
16085 &setdebuglist
, &showdebuglist
);
16087 add_setshow_boolean_cmd ("remote", no_class
, &remote_debug
,
16088 _("Set debugging of remote protocol."),
16089 _("Show debugging of remote protocol."),
16091 When enabled, each packet sent or received with the remote target\n\
16095 &setdebuglist
, &showdebuglist
);
16097 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class
,
16098 &remote_timeout
, _("\
16099 Set timeout limit to wait for target to respond."), _("\
16100 Show timeout limit to wait for target to respond."), _("\
16101 This value is used to set the time limit for gdb to wait for a response\n\
16102 from the target."),
16104 show_remote_timeout
,
16105 &setlist
, &showlist
);
16107 /* Eventually initialize fileio. See fileio.c */
16108 initialize_remote_fileio (&remote_set_cmdlist
, &remote_show_cmdlist
);
16111 selftests::register_test ("remote_memory_tagging",
16112 selftests::test_memory_tagging_functions
);