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 struct regcache
*regcache
8419 = get_thread_arch_regcache (this, ptid
, stop_reply
->arch
);
8421 for (cached_reg_t
®
: stop_reply
->regcache
)
8423 regcache
->raw_supply (reg
.num
, reg
.data
);
8427 stop_reply
->regcache
.clear ();
8430 remote_notice_new_inferior (ptid
, false);
8431 remote_thread_info
*remote_thr
= get_remote_thread_info (this, ptid
);
8432 remote_thr
->core
= stop_reply
->core
;
8433 remote_thr
->stop_reason
= stop_reply
->stop_reason
;
8434 remote_thr
->watch_data_address
= stop_reply
->watch_data_address
;
8436 if (target_is_non_stop_p ())
8438 /* If the target works in non-stop mode, a stop-reply indicates that
8439 only this thread stopped. */
8440 remote_thr
->set_not_resumed ();
8444 /* If the target works in all-stop mode, a stop-reply indicates that
8445 all the target's threads stopped. */
8446 for (thread_info
*tp
: all_non_exited_threads (this))
8447 get_remote_thread_info (tp
)->set_not_resumed ();
8455 /* The non-stop mode version of target_wait. */
8458 remote_target::wait_ns (ptid_t ptid
, struct target_waitstatus
*status
,
8459 target_wait_flags options
)
8461 struct remote_state
*rs
= get_remote_state ();
8462 struct stop_reply
*stop_reply
;
8464 bool is_notif
= false;
8466 /* If in non-stop mode, get out of getpkt even if a
8467 notification is received. */
8469 ret
= getpkt (&rs
->buf
, false /* forever */, &is_notif
);
8472 if (ret
!= -1 && !is_notif
)
8475 case 'E': /* Error of some sort. */
8476 /* We're out of sync with the target now. Did it continue
8477 or not? We can't tell which thread it was in non-stop,
8478 so just ignore this. */
8479 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
8481 case 'O': /* Console output. */
8482 remote_console_output (&rs
->buf
[1]);
8485 warning (_("Invalid remote reply: %s"), rs
->buf
.data ());
8489 /* Acknowledge a pending stop reply that may have arrived in the
8491 if (rs
->notif_state
->pending_event
[notif_client_stop
.id
] != NULL
)
8492 remote_notif_get_pending_events (¬if_client_stop
);
8494 /* If indeed we noticed a stop reply, we're done. */
8495 stop_reply
= queued_stop_reply (ptid
);
8496 if (stop_reply
!= NULL
)
8497 return process_stop_reply (stop_reply
, status
);
8499 /* Still no event. If we're just polling for an event, then
8500 return to the event loop. */
8501 if (options
& TARGET_WNOHANG
)
8503 status
->set_ignore ();
8504 return minus_one_ptid
;
8507 /* Otherwise do a blocking wait. */
8508 ret
= getpkt (&rs
->buf
, true /* forever */, &is_notif
);
8512 /* Return the first resumed thread. */
8515 first_remote_resumed_thread (remote_target
*target
)
8517 for (thread_info
*tp
: all_non_exited_threads (target
, minus_one_ptid
))
8523 /* Wait until the remote machine stops, then return, storing status in
8524 STATUS just as `wait' would. */
8527 remote_target::wait_as (ptid_t ptid
, target_waitstatus
*status
,
8528 target_wait_flags options
)
8530 struct remote_state
*rs
= get_remote_state ();
8531 ptid_t event_ptid
= null_ptid
;
8533 struct stop_reply
*stop_reply
;
8537 status
->set_ignore ();
8539 stop_reply
= queued_stop_reply (ptid
);
8540 if (stop_reply
!= NULL
)
8542 /* None of the paths that push a stop reply onto the queue should
8543 have set the waiting_for_stop_reply flag. */
8544 gdb_assert (!rs
->waiting_for_stop_reply
);
8545 event_ptid
= process_stop_reply (stop_reply
, status
);
8549 bool forever
= ((options
& TARGET_WNOHANG
) == 0
8550 && rs
->wait_forever_enabled_p
);
8552 if (!rs
->waiting_for_stop_reply
)
8554 status
->set_no_resumed ();
8555 return minus_one_ptid
;
8558 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8559 _never_ wait for ever -> test on target_is_async_p().
8560 However, before we do that we need to ensure that the caller
8561 knows how to take the target into/out of async mode. */
8563 int ret
= getpkt (&rs
->buf
, forever
, &is_notif
);
8565 /* GDB gets a notification. Return to core as this event is
8567 if (ret
!= -1 && is_notif
)
8568 return minus_one_ptid
;
8570 if (ret
== -1 && (options
& TARGET_WNOHANG
) != 0)
8571 return minus_one_ptid
;
8573 buf
= rs
->buf
.data ();
8575 /* Assume that the target has acknowledged Ctrl-C unless we receive
8576 an 'F' or 'O' packet. */
8577 if (buf
[0] != 'F' && buf
[0] != 'O')
8578 rs
->ctrlc_pending_p
= 0;
8582 case 'E': /* Error of some sort. */
8583 /* We're out of sync with the target now. Did it continue or
8584 not? Not is more likely, so report a stop. */
8585 rs
->waiting_for_stop_reply
= 0;
8587 warning (_("Remote failure reply: %s"), buf
);
8588 status
->set_stopped (GDB_SIGNAL_0
);
8590 case 'F': /* File-I/O request. */
8591 /* GDB may access the inferior memory while handling the File-I/O
8592 request, but we don't want GDB accessing memory while waiting
8593 for a stop reply. See the comments in putpkt_binary. Set
8594 waiting_for_stop_reply to 0 temporarily. */
8595 rs
->waiting_for_stop_reply
= 0;
8596 remote_fileio_request (this, buf
, rs
->ctrlc_pending_p
);
8597 rs
->ctrlc_pending_p
= 0;
8598 /* GDB handled the File-I/O request, and the target is running
8599 again. Keep waiting for events. */
8600 rs
->waiting_for_stop_reply
= 1;
8602 case 'N': case 'T': case 'S': case 'X': case 'W':
8604 /* There is a stop reply to handle. */
8605 rs
->waiting_for_stop_reply
= 0;
8608 = (struct stop_reply
*) remote_notif_parse (this,
8612 event_ptid
= process_stop_reply (stop_reply
, status
);
8615 case 'O': /* Console output. */
8616 remote_console_output (buf
+ 1);
8619 if (rs
->last_sent_signal
!= GDB_SIGNAL_0
)
8621 /* Zero length reply means that we tried 'S' or 'C' and the
8622 remote system doesn't support it. */
8623 target_terminal::ours_for_output ();
8625 ("Can't send signals to this remote system. %s not sent.\n",
8626 gdb_signal_to_name (rs
->last_sent_signal
));
8627 rs
->last_sent_signal
= GDB_SIGNAL_0
;
8628 target_terminal::inferior ();
8630 strcpy (buf
, rs
->last_sent_step
? "s" : "c");
8636 warning (_("Invalid remote reply: %s"), buf
);
8641 if (status
->kind () == TARGET_WAITKIND_NO_RESUMED
)
8642 return minus_one_ptid
;
8643 else if (status
->kind () == TARGET_WAITKIND_IGNORE
)
8645 /* Nothing interesting happened. If we're doing a non-blocking
8646 poll, we're done. Otherwise, go back to waiting. */
8647 if (options
& TARGET_WNOHANG
)
8648 return minus_one_ptid
;
8652 else if (status
->kind () != TARGET_WAITKIND_EXITED
8653 && status
->kind () != TARGET_WAITKIND_SIGNALLED
)
8655 if (event_ptid
!= null_ptid
)
8656 record_currthread (rs
, event_ptid
);
8658 event_ptid
= first_remote_resumed_thread (this);
8662 /* A process exit. Invalidate our notion of current thread. */
8663 record_currthread (rs
, minus_one_ptid
);
8664 /* It's possible that the packet did not include a pid. */
8665 if (event_ptid
== null_ptid
)
8666 event_ptid
= first_remote_resumed_thread (this);
8667 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8668 if (event_ptid
== null_ptid
)
8669 event_ptid
= magic_null_ptid
;
8675 /* Wait until the remote machine stops, then return, storing status in
8676 STATUS just as `wait' would. */
8679 remote_target::wait (ptid_t ptid
, struct target_waitstatus
*status
,
8680 target_wait_flags options
)
8682 REMOTE_SCOPED_DEBUG_ENTER_EXIT
;
8684 remote_state
*rs
= get_remote_state ();
8686 /* Start by clearing the flag that asks for our wait method to be called,
8687 we'll mark it again at the end if needed. If the target is not in
8688 async mode then the async token should not be marked. */
8689 if (target_is_async_p ())
8690 rs
->clear_async_event_handler ();
8692 gdb_assert (!rs
->async_event_handler_marked ());
8696 if (target_is_non_stop_p ())
8697 event_ptid
= wait_ns (ptid
, status
, options
);
8699 event_ptid
= wait_as (ptid
, status
, options
);
8701 if (target_is_async_p ())
8703 /* If there are events left in the queue, or unacknowledged
8704 notifications, then tell the event loop to call us again. */
8705 if (!rs
->stop_reply_queue
.empty ()
8706 || rs
->notif_state
->pending_event
[notif_client_stop
.id
] != nullptr)
8707 rs
->mark_async_event_handler ();
8713 /* Fetch a single register using a 'p' packet. */
8716 remote_target::fetch_register_using_p (struct regcache
*regcache
,
8719 struct gdbarch
*gdbarch
= regcache
->arch ();
8720 struct remote_state
*rs
= get_remote_state ();
8722 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
8725 if (m_features
.packet_support (PACKET_p
) == PACKET_DISABLE
)
8728 if (reg
->pnum
== -1)
8731 p
= rs
->buf
.data ();
8733 p
+= hexnumstr (p
, reg
->pnum
);
8738 buf
= rs
->buf
.data ();
8740 switch (m_features
.packet_ok (rs
->buf
, PACKET_p
))
8744 case PACKET_UNKNOWN
:
8747 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8748 gdbarch_register_name (regcache
->arch (), reg
->regnum
),
8752 /* If this register is unfetchable, tell the regcache. */
8755 regcache
->raw_supply (reg
->regnum
, NULL
);
8759 /* Otherwise, parse and supply the value. */
8765 error (_("fetch_register_using_p: early buf termination"));
8767 regp
[i
++] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8770 regcache
->raw_supply (reg
->regnum
, regp
);
8774 /* Fetch the registers included in the target's 'g' packet. */
8777 remote_target::send_g_packet ()
8779 struct remote_state
*rs
= get_remote_state ();
8782 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "g");
8785 if (packet_check_result (rs
->buf
) == PACKET_ERROR
)
8786 error (_("Could not read registers; remote failure reply '%s'"),
8789 /* We can get out of synch in various cases. If the first character
8790 in the buffer is not a hex character, assume that has happened
8791 and try to fetch another packet to read. */
8792 while ((rs
->buf
[0] < '0' || rs
->buf
[0] > '9')
8793 && (rs
->buf
[0] < 'A' || rs
->buf
[0] > 'F')
8794 && (rs
->buf
[0] < 'a' || rs
->buf
[0] > 'f')
8795 && rs
->buf
[0] != 'x') /* New: unavailable register value. */
8797 remote_debug_printf ("Bad register packet; fetching a new packet");
8801 buf_len
= strlen (rs
->buf
.data ());
8803 /* Sanity check the received packet. */
8804 if (buf_len
% 2 != 0)
8805 error (_("Remote 'g' packet reply is of odd length: %s"), rs
->buf
.data ());
8811 remote_target::process_g_packet (struct regcache
*regcache
)
8813 struct gdbarch
*gdbarch
= regcache
->arch ();
8814 struct remote_state
*rs
= get_remote_state ();
8815 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8820 buf_len
= strlen (rs
->buf
.data ());
8822 /* Further sanity checks, with knowledge of the architecture. */
8823 if (buf_len
> 2 * rsa
->sizeof_g_packet
)
8824 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8826 rsa
->sizeof_g_packet
, buf_len
/ 2,
8829 /* Save the size of the packet sent to us by the target. It is used
8830 as a heuristic when determining the max size of packets that the
8831 target can safely receive. */
8832 if (rsa
->actual_register_packet_size
== 0)
8833 rsa
->actual_register_packet_size
= buf_len
;
8835 /* If this is smaller than we guessed the 'g' packet would be,
8836 update our records. A 'g' reply that doesn't include a register's
8837 value implies either that the register is not available, or that
8838 the 'p' packet must be used. */
8839 if (buf_len
< 2 * rsa
->sizeof_g_packet
)
8841 long sizeof_g_packet
= buf_len
/ 2;
8843 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8845 long offset
= rsa
->regs
[i
].offset
;
8846 long reg_size
= register_size (gdbarch
, i
);
8848 if (rsa
->regs
[i
].pnum
== -1)
8851 if (offset
>= sizeof_g_packet
)
8852 rsa
->regs
[i
].in_g_packet
= 0;
8853 else if (offset
+ reg_size
> sizeof_g_packet
)
8854 error (_("Truncated register %d in remote 'g' packet"), i
);
8856 rsa
->regs
[i
].in_g_packet
= 1;
8859 /* Looks valid enough, we can assume this is the correct length
8860 for a 'g' packet. It's important not to adjust
8861 rsa->sizeof_g_packet if we have truncated registers otherwise
8862 this "if" won't be run the next time the method is called
8863 with a packet of the same size and one of the internal errors
8864 below will trigger instead. */
8865 rsa
->sizeof_g_packet
= sizeof_g_packet
;
8868 regs
= (char *) alloca (rsa
->sizeof_g_packet
);
8870 /* Unimplemented registers read as all bits zero. */
8871 memset (regs
, 0, rsa
->sizeof_g_packet
);
8873 /* Reply describes registers byte by byte, each byte encoded as two
8874 hex characters. Suck them all up, then supply them to the
8875 register cacheing/storage mechanism. */
8877 p
= rs
->buf
.data ();
8878 for (i
= 0; i
< rsa
->sizeof_g_packet
; i
++)
8880 if (p
[0] == 0 || p
[1] == 0)
8881 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8882 internal_error (_("unexpected end of 'g' packet reply"));
8884 if (p
[0] == 'x' && p
[1] == 'x')
8885 regs
[i
] = 0; /* 'x' */
8887 regs
[i
] = fromhex (p
[0]) * 16 + fromhex (p
[1]);
8891 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8893 struct packet_reg
*r
= &rsa
->regs
[i
];
8894 long reg_size
= register_size (gdbarch
, i
);
8898 if ((r
->offset
+ reg_size
) * 2 > strlen (rs
->buf
.data ()))
8899 /* This shouldn't happen - we adjusted in_g_packet above. */
8900 internal_error (_("unexpected end of 'g' packet reply"));
8901 else if (rs
->buf
[r
->offset
* 2] == 'x')
8903 gdb_assert (r
->offset
* 2 < strlen (rs
->buf
.data ()));
8904 /* The register isn't available, mark it as such (at
8905 the same time setting the value to zero). */
8906 regcache
->raw_supply (r
->regnum
, NULL
);
8909 regcache
->raw_supply (r
->regnum
, regs
+ r
->offset
);
8915 remote_target::fetch_registers_using_g (struct regcache
*regcache
)
8918 process_g_packet (regcache
);
8921 /* Make the remote selected traceframe match GDB's selected
8925 remote_target::set_remote_traceframe ()
8928 struct remote_state
*rs
= get_remote_state ();
8930 if (rs
->remote_traceframe_number
== get_traceframe_number ())
8933 /* Avoid recursion, remote_trace_find calls us again. */
8934 rs
->remote_traceframe_number
= get_traceframe_number ();
8936 newnum
= target_trace_find (tfind_number
,
8937 get_traceframe_number (), 0, 0, NULL
);
8939 /* Should not happen. If it does, all bets are off. */
8940 if (newnum
!= get_traceframe_number ())
8941 warning (_("could not set remote traceframe"));
8945 remote_target::fetch_registers (struct regcache
*regcache
, int regnum
)
8947 struct gdbarch
*gdbarch
= regcache
->arch ();
8948 struct remote_state
*rs
= get_remote_state ();
8949 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
8952 set_remote_traceframe ();
8953 set_general_thread (regcache
->ptid ());
8957 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
8959 gdb_assert (reg
!= NULL
);
8961 /* If this register might be in the 'g' packet, try that first -
8962 we are likely to read more than one register. If this is the
8963 first 'g' packet, we might be overly optimistic about its
8964 contents, so fall back to 'p'. */
8965 if (reg
->in_g_packet
)
8967 fetch_registers_using_g (regcache
);
8968 if (reg
->in_g_packet
)
8972 if (fetch_register_using_p (regcache
, reg
))
8975 /* This register is not available. */
8976 regcache
->raw_supply (reg
->regnum
, NULL
);
8981 fetch_registers_using_g (regcache
);
8983 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
8984 if (!rsa
->regs
[i
].in_g_packet
)
8985 if (!fetch_register_using_p (regcache
, &rsa
->regs
[i
]))
8987 /* This register is not available. */
8988 regcache
->raw_supply (i
, NULL
);
8992 /* Prepare to store registers. Since we may send them all (using a
8993 'G' request), we have to read out the ones we don't want to change
8997 remote_target::prepare_to_store (struct regcache
*regcache
)
8999 struct remote_state
*rs
= get_remote_state ();
9000 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9003 /* Make sure the entire registers array is valid. */
9004 switch (m_features
.packet_support (PACKET_P
))
9006 case PACKET_DISABLE
:
9007 case PACKET_SUPPORT_UNKNOWN
:
9008 /* Make sure all the necessary registers are cached. */
9009 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9010 if (rsa
->regs
[i
].in_g_packet
)
9011 regcache
->raw_update (rsa
->regs
[i
].regnum
);
9018 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9019 packet was not recognized. */
9022 remote_target::store_register_using_P (const struct regcache
*regcache
,
9025 struct gdbarch
*gdbarch
= regcache
->arch ();
9026 struct remote_state
*rs
= get_remote_state ();
9027 /* Try storing a single register. */
9028 char *buf
= rs
->buf
.data ();
9029 gdb_byte
*regp
= (gdb_byte
*) alloca (register_size (gdbarch
, reg
->regnum
));
9032 if (m_features
.packet_support (PACKET_P
) == PACKET_DISABLE
)
9035 if (reg
->pnum
== -1)
9038 xsnprintf (buf
, get_remote_packet_size (), "P%s=", phex_nz (reg
->pnum
, 0));
9039 p
= buf
+ strlen (buf
);
9040 regcache
->raw_collect (reg
->regnum
, regp
);
9041 bin2hex (regp
, p
, register_size (gdbarch
, reg
->regnum
));
9045 switch (m_features
.packet_ok (rs
->buf
, PACKET_P
))
9050 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9051 gdbarch_register_name (gdbarch
, reg
->regnum
), rs
->buf
.data ());
9052 case PACKET_UNKNOWN
:
9055 internal_error (_("Bad result from packet_ok"));
9059 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9060 contents of the register cache buffer. FIXME: ignores errors. */
9063 remote_target::store_registers_using_G (const struct regcache
*regcache
)
9065 struct remote_state
*rs
= get_remote_state ();
9066 remote_arch_state
*rsa
= rs
->get_remote_arch_state (regcache
->arch ());
9070 /* Extract all the registers in the regcache copying them into a
9075 regs
= (gdb_byte
*) alloca (rsa
->sizeof_g_packet
);
9076 memset (regs
, 0, rsa
->sizeof_g_packet
);
9077 for (i
= 0; i
< gdbarch_num_regs (regcache
->arch ()); i
++)
9079 struct packet_reg
*r
= &rsa
->regs
[i
];
9082 regcache
->raw_collect (r
->regnum
, regs
+ r
->offset
);
9086 /* Command describes registers byte by byte,
9087 each byte encoded as two hex characters. */
9088 p
= rs
->buf
.data ();
9090 bin2hex (regs
, p
, rsa
->sizeof_g_packet
);
9093 if (packet_check_result (rs
->buf
) == PACKET_ERROR
)
9094 error (_("Could not write registers; remote failure reply '%s'"),
9098 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9099 of the register cache buffer. FIXME: ignores errors. */
9102 remote_target::store_registers (struct regcache
*regcache
, int regnum
)
9104 struct gdbarch
*gdbarch
= regcache
->arch ();
9105 struct remote_state
*rs
= get_remote_state ();
9106 remote_arch_state
*rsa
= rs
->get_remote_arch_state (gdbarch
);
9109 set_remote_traceframe ();
9110 set_general_thread (regcache
->ptid ());
9114 packet_reg
*reg
= packet_reg_from_regnum (gdbarch
, rsa
, regnum
);
9116 gdb_assert (reg
!= NULL
);
9118 /* Always prefer to store registers using the 'P' packet if
9119 possible; we often change only a small number of registers.
9120 Sometimes we change a larger number; we'd need help from a
9121 higher layer to know to use 'G'. */
9122 if (store_register_using_P (regcache
, reg
))
9125 /* For now, don't complain if we have no way to write the
9126 register. GDB loses track of unavailable registers too
9127 easily. Some day, this may be an error. We don't have
9128 any way to read the register, either... */
9129 if (!reg
->in_g_packet
)
9132 store_registers_using_G (regcache
);
9136 store_registers_using_G (regcache
);
9138 for (i
= 0; i
< gdbarch_num_regs (gdbarch
); i
++)
9139 if (!rsa
->regs
[i
].in_g_packet
)
9140 if (!store_register_using_P (regcache
, &rsa
->regs
[i
]))
9141 /* See above for why we do not issue an error here. */
9146 /* Return the number of hex digits in num. */
9149 hexnumlen (ULONGEST num
)
9153 for (i
= 0; num
!= 0; i
++)
9156 return std::max (i
, 1);
9159 /* Set BUF to the minimum number of hex digits representing NUM. */
9162 hexnumstr (char *buf
, ULONGEST num
)
9164 int len
= hexnumlen (num
);
9166 return hexnumnstr (buf
, num
, len
);
9170 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9173 hexnumnstr (char *buf
, ULONGEST num
, int width
)
9179 for (i
= width
- 1; i
>= 0; i
--)
9181 buf
[i
] = "0123456789abcdef"[(num
& 0xf)];
9188 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9191 remote_address_masked (CORE_ADDR addr
)
9193 unsigned int address_size
= remote_address_size
;
9195 /* If "remoteaddresssize" was not set, default to target address size. */
9197 address_size
= gdbarch_addr_bit (current_inferior ()->arch ());
9199 if (address_size
> 0
9200 && address_size
< (sizeof (ULONGEST
) * 8))
9202 /* Only create a mask when that mask can safely be constructed
9203 in a ULONGEST variable. */
9206 mask
= (mask
<< address_size
) - 1;
9212 /* Determine whether the remote target supports binary downloading.
9213 This is accomplished by sending a no-op memory write of zero length
9214 to the target at the specified address. It does not suffice to send
9215 the whole packet, since many stubs strip the eighth bit and
9216 subsequently compute a wrong checksum, which causes real havoc with
9219 NOTE: This can still lose if the serial line is not eight-bit
9220 clean. In cases like this, the user should clear "remote
9224 remote_target::check_binary_download (CORE_ADDR addr
)
9226 struct remote_state
*rs
= get_remote_state ();
9228 switch (m_features
.packet_support (PACKET_X
))
9230 case PACKET_DISABLE
:
9234 case PACKET_SUPPORT_UNKNOWN
:
9238 p
= rs
->buf
.data ();
9240 p
+= hexnumstr (p
, (ULONGEST
) addr
);
9242 p
+= hexnumstr (p
, (ULONGEST
) 0);
9246 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9249 if (rs
->buf
[0] == '\0')
9251 remote_debug_printf ("binary downloading NOT supported by target");
9252 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_DISABLE
;
9256 remote_debug_printf ("binary downloading supported by target");
9257 m_features
.m_protocol_packets
[PACKET_X
].support
= PACKET_ENABLE
;
9264 /* Helper function to resize the payload in order to try to get a good
9265 alignment. We try to write an amount of data such that the next write will
9266 start on an address aligned on REMOTE_ALIGN_WRITES. */
9269 align_for_efficient_write (int todo
, CORE_ADDR memaddr
)
9271 return ((memaddr
+ todo
) & ~(REMOTE_ALIGN_WRITES
- 1)) - memaddr
;
9274 /* Write memory data directly to the remote machine.
9275 This does not inform the data cache; the data cache uses this.
9276 HEADER is the starting part of the packet.
9277 MEMADDR is the address in the remote memory space.
9278 MYADDR is the address of the buffer in our space.
9279 LEN_UNITS is the number of addressable units to write.
9280 UNIT_SIZE is the length in bytes of an addressable unit.
9281 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9282 should send data as binary ('X'), or hex-encoded ('M').
9284 The function creates packet of the form
9285 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9287 where encoding of <DATA> is terminated by PACKET_FORMAT.
9289 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9292 Return the transferred status, error or OK (an
9293 'enum target_xfer_status' value). Save the number of addressable units
9294 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9296 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9297 exchange between gdb and the stub could look like (?? in place of the
9303 -> $M1000,3:eeeeffffeeee#??
9307 <- eeeeffffeeeedddd */
9310 remote_target::remote_write_bytes_aux (const char *header
, CORE_ADDR memaddr
,
9311 const gdb_byte
*myaddr
,
9314 ULONGEST
*xfered_len_units
,
9315 char packet_format
, int use_length
)
9317 struct remote_state
*rs
= get_remote_state ();
9323 int payload_capacity_bytes
;
9324 int payload_length_bytes
;
9326 if (packet_format
!= 'X' && packet_format
!= 'M')
9327 internal_error (_("remote_write_bytes_aux: bad packet format"));
9330 return TARGET_XFER_EOF
;
9332 payload_capacity_bytes
= get_memory_write_packet_size ();
9334 /* The packet buffer will be large enough for the payload;
9335 get_memory_packet_size ensures this. */
9338 /* Compute the size of the actual payload by subtracting out the
9339 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9341 payload_capacity_bytes
-= strlen ("$,:#NN");
9343 /* The comma won't be used. */
9344 payload_capacity_bytes
+= 1;
9345 payload_capacity_bytes
-= strlen (header
);
9346 payload_capacity_bytes
-= hexnumlen (memaddr
);
9348 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9350 strcat (rs
->buf
.data (), header
);
9351 p
= rs
->buf
.data () + strlen (header
);
9353 /* Compute a best guess of the number of bytes actually transfered. */
9354 if (packet_format
== 'X')
9356 /* Best guess at number of bytes that will fit. */
9357 todo_units
= std::min (len_units
,
9358 (ULONGEST
) payload_capacity_bytes
/ unit_size
);
9360 payload_capacity_bytes
-= hexnumlen (todo_units
);
9361 todo_units
= std::min (todo_units
, payload_capacity_bytes
/ unit_size
);
9365 /* Number of bytes that will fit. */
9367 = std::min (len_units
,
9368 (ULONGEST
) (payload_capacity_bytes
/ unit_size
) / 2);
9370 payload_capacity_bytes
-= hexnumlen (todo_units
);
9371 todo_units
= std::min (todo_units
,
9372 (payload_capacity_bytes
/ unit_size
) / 2);
9375 if (todo_units
<= 0)
9376 internal_error (_("minimum packet size too small to write data"));
9378 /* If we already need another packet, then try to align the end
9379 of this packet to a useful boundary. */
9380 if (todo_units
> 2 * REMOTE_ALIGN_WRITES
&& todo_units
< len_units
)
9381 todo_units
= align_for_efficient_write (todo_units
, memaddr
);
9383 /* Append "<memaddr>". */
9384 memaddr
= remote_address_masked (memaddr
);
9385 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9392 /* Append the length and retain its location and size. It may need to be
9393 adjusted once the packet body has been created. */
9395 plenlen
= hexnumstr (p
, (ULONGEST
) todo_units
);
9403 /* Append the packet body. */
9404 if (packet_format
== 'X')
9406 /* Binary mode. Send target system values byte by byte, in
9407 increasing byte addresses. Only escape certain critical
9409 payload_length_bytes
=
9410 remote_escape_output (myaddr
, todo_units
, unit_size
, (gdb_byte
*) p
,
9411 &units_written
, payload_capacity_bytes
);
9413 /* If not all TODO units fit, then we'll need another packet. Make
9414 a second try to keep the end of the packet aligned. Don't do
9415 this if the packet is tiny. */
9416 if (units_written
< todo_units
&& units_written
> 2 * REMOTE_ALIGN_WRITES
)
9420 new_todo_units
= align_for_efficient_write (units_written
, memaddr
);
9422 if (new_todo_units
!= units_written
)
9423 payload_length_bytes
=
9424 remote_escape_output (myaddr
, new_todo_units
, unit_size
,
9425 (gdb_byte
*) p
, &units_written
,
9426 payload_capacity_bytes
);
9429 p
+= payload_length_bytes
;
9430 if (use_length
&& units_written
< todo_units
)
9432 /* Escape chars have filled up the buffer prematurely,
9433 and we have actually sent fewer units than planned.
9434 Fix-up the length field of the packet. Use the same
9435 number of characters as before. */
9436 plen
+= hexnumnstr (plen
, (ULONGEST
) units_written
,
9438 *plen
= ':'; /* overwrite \0 from hexnumnstr() */
9443 /* Normal mode: Send target system values byte by byte, in
9444 increasing byte addresses. Each byte is encoded as a two hex
9446 p
+= 2 * bin2hex (myaddr
, p
, todo_units
* unit_size
);
9447 units_written
= todo_units
;
9450 putpkt_binary (rs
->buf
.data (), (int) (p
- rs
->buf
.data ()));
9453 if (rs
->buf
[0] == 'E')
9454 return TARGET_XFER_E_IO
;
9456 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9457 send fewer units than we'd planned. */
9458 *xfered_len_units
= (ULONGEST
) units_written
;
9459 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9462 /* Write memory data directly to the remote machine.
9463 This does not inform the data cache; the data cache uses this.
9464 MEMADDR is the address in the remote memory space.
9465 MYADDR is the address of the buffer in our space.
9466 LEN is the number of bytes.
9468 Return the transferred status, error or OK (an
9469 'enum target_xfer_status' value). Save the number of bytes
9470 transferred in *XFERED_LEN. Only transfer a single packet. */
9473 remote_target::remote_write_bytes (CORE_ADDR memaddr
, const gdb_byte
*myaddr
,
9474 ULONGEST len
, int unit_size
,
9475 ULONGEST
*xfered_len
)
9477 const char *packet_format
= NULL
;
9479 /* Check whether the target supports binary download. */
9480 check_binary_download (memaddr
);
9482 switch (m_features
.packet_support (PACKET_X
))
9485 packet_format
= "X";
9487 case PACKET_DISABLE
:
9488 packet_format
= "M";
9490 case PACKET_SUPPORT_UNKNOWN
:
9491 internal_error (_("remote_write_bytes: bad internal state"));
9493 internal_error (_("bad switch"));
9496 return remote_write_bytes_aux (packet_format
,
9497 memaddr
, myaddr
, len
, unit_size
, xfered_len
,
9498 packet_format
[0], 1);
9501 /* Read memory data directly from the remote machine.
9502 This does not use the data cache; the data cache uses this.
9503 MEMADDR is the address in the remote memory space.
9504 MYADDR is the address of the buffer in our space.
9505 LEN_UNITS is the number of addressable memory units to read..
9506 UNIT_SIZE is the length in bytes of an addressable unit.
9508 Return the transferred status, error or OK (an
9509 'enum target_xfer_status' value). Save the number of bytes
9510 transferred in *XFERED_LEN_UNITS.
9512 See the comment of remote_write_bytes_aux for an example of
9513 memory read/write exchange between gdb and the stub. */
9516 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr
, gdb_byte
*myaddr
,
9518 int unit_size
, ULONGEST
*xfered_len_units
)
9520 struct remote_state
*rs
= get_remote_state ();
9521 int buf_size_bytes
; /* Max size of packet output buffer. */
9526 buf_size_bytes
= get_memory_read_packet_size ();
9527 /* The packet buffer will be large enough for the payload;
9528 get_memory_packet_size ensures this. */
9530 /* Number of units that will fit. */
9531 todo_units
= std::min (len_units
,
9532 (ULONGEST
) (buf_size_bytes
/ unit_size
) / 2);
9534 /* Construct "m"<memaddr>","<len>". */
9535 memaddr
= remote_address_masked (memaddr
);
9536 p
= rs
->buf
.data ();
9538 p
+= hexnumstr (p
, (ULONGEST
) memaddr
);
9540 p
+= hexnumstr (p
, (ULONGEST
) todo_units
);
9544 if (rs
->buf
[0] == 'E'
9545 && isxdigit (rs
->buf
[1]) && isxdigit (rs
->buf
[2])
9546 && rs
->buf
[3] == '\0')
9547 return TARGET_XFER_E_IO
;
9548 /* Reply describes memory byte by byte, each byte encoded as two hex
9550 p
= rs
->buf
.data ();
9551 decoded_bytes
= hex2bin (p
, myaddr
, todo_units
* unit_size
);
9552 /* Return what we have. Let higher layers handle partial reads. */
9553 *xfered_len_units
= (ULONGEST
) (decoded_bytes
/ unit_size
);
9554 return (*xfered_len_units
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
9557 /* Using the set of read-only target sections of remote, read live
9560 For interface/parameters/return description see target.h,
9564 remote_target::remote_xfer_live_readonly_partial (gdb_byte
*readbuf
,
9568 ULONGEST
*xfered_len
)
9570 const struct target_section
*secp
;
9572 secp
= target_section_by_addr (this, memaddr
);
9574 && (bfd_section_flags (secp
->the_bfd_section
) & SEC_READONLY
))
9576 ULONGEST memend
= memaddr
+ len
;
9578 const std::vector
<target_section
> *table
9579 = target_get_section_table (this);
9580 for (const target_section
&p
: *table
)
9582 if (memaddr
>= p
.addr
)
9584 if (memend
<= p
.endaddr
)
9586 /* Entire transfer is within this section. */
9587 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9590 else if (memaddr
>= p
.endaddr
)
9592 /* This section ends before the transfer starts. */
9597 /* This section overlaps the transfer. Just do half. */
9598 len
= p
.endaddr
- memaddr
;
9599 return remote_read_bytes_1 (memaddr
, readbuf
, len
, unit_size
,
9606 return TARGET_XFER_EOF
;
9609 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9610 first if the requested memory is unavailable in traceframe.
9611 Otherwise, fall back to remote_read_bytes_1. */
9614 remote_target::remote_read_bytes (CORE_ADDR memaddr
,
9615 gdb_byte
*myaddr
, ULONGEST len
, int unit_size
,
9616 ULONGEST
*xfered_len
)
9619 return TARGET_XFER_EOF
;
9621 if (get_traceframe_number () != -1)
9623 std::vector
<mem_range
> available
;
9625 /* If we fail to get the set of available memory, then the
9626 target does not support querying traceframe info, and so we
9627 attempt reading from the traceframe anyway (assuming the
9628 target implements the old QTro packet then). */
9629 if (traceframe_available_memory (&available
, memaddr
, len
))
9631 if (available
.empty () || available
[0].start
!= memaddr
)
9633 enum target_xfer_status res
;
9635 /* Don't read into the traceframe's available
9637 if (!available
.empty ())
9639 LONGEST oldlen
= len
;
9641 len
= available
[0].start
- memaddr
;
9642 gdb_assert (len
<= oldlen
);
9645 /* This goes through the topmost target again. */
9646 res
= remote_xfer_live_readonly_partial (myaddr
, memaddr
,
9647 len
, unit_size
, xfered_len
);
9648 if (res
== TARGET_XFER_OK
)
9649 return TARGET_XFER_OK
;
9652 /* No use trying further, we know some memory starting
9653 at MEMADDR isn't available. */
9655 return (*xfered_len
!= 0) ?
9656 TARGET_XFER_UNAVAILABLE
: TARGET_XFER_EOF
;
9660 /* Don't try to read more than how much is available, in
9661 case the target implements the deprecated QTro packet to
9662 cater for older GDBs (the target's knowledge of read-only
9663 sections may be outdated by now). */
9664 len
= available
[0].length
;
9668 return remote_read_bytes_1 (memaddr
, myaddr
, len
, unit_size
, xfered_len
);
9673 /* Sends a packet with content determined by the printf format string
9674 FORMAT and the remaining arguments, then gets the reply. Returns
9675 whether the packet was a success, a failure, or unknown. */
9678 remote_target::remote_send_printf (const char *format
, ...)
9680 struct remote_state
*rs
= get_remote_state ();
9681 int max_size
= get_remote_packet_size ();
9684 va_start (ap
, format
);
9687 int size
= vsnprintf (rs
->buf
.data (), max_size
, format
, ap
);
9691 if (size
>= max_size
)
9692 internal_error (_("Too long remote packet."));
9694 if (putpkt (rs
->buf
) < 0)
9695 error (_("Communication problem with target."));
9700 return packet_check_result (rs
->buf
);
9703 /* Flash writing can take quite some time. We'll set
9704 effectively infinite timeout for flash operations.
9705 In future, we'll need to decide on a better approach. */
9706 static const int remote_flash_timeout
= 1000;
9709 remote_target::flash_erase (ULONGEST address
, LONGEST length
)
9711 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9712 enum packet_result ret
;
9713 scoped_restore restore_timeout
9714 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9716 ret
= remote_send_printf ("vFlashErase:%s,%s",
9717 phex (address
, addr_size
),
9721 case PACKET_UNKNOWN
:
9722 error (_("Remote target does not support flash erase"));
9724 error (_("Error erasing flash with vFlashErase packet"));
9731 remote_target::remote_flash_write (ULONGEST address
,
9732 ULONGEST length
, ULONGEST
*xfered_len
,
9733 const gdb_byte
*data
)
9735 scoped_restore restore_timeout
9736 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9737 return remote_write_bytes_aux ("vFlashWrite:", address
, data
, length
, 1,
9742 remote_target::flash_done ()
9746 scoped_restore restore_timeout
9747 = make_scoped_restore (&remote_timeout
, remote_flash_timeout
);
9749 ret
= remote_send_printf ("vFlashDone");
9753 case PACKET_UNKNOWN
:
9754 error (_("Remote target does not support vFlashDone"));
9756 error (_("Error finishing flash operation"));
9763 /* Stuff for dealing with the packets which are part of this protocol.
9764 See comment at top of file for details. */
9766 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9767 error to higher layers. Called when a serial error is detected.
9768 The exception message is STRING, followed by a colon and a blank,
9769 the system error message for errno at function entry and final dot
9770 for output compatibility with throw_perror_with_name. */
9773 unpush_and_perror (remote_target
*target
, const char *string
)
9775 int saved_errno
= errno
;
9777 remote_unpush_target (target
);
9778 throw_error (TARGET_CLOSE_ERROR
, "%s: %s.", string
,
9779 safe_strerror (saved_errno
));
9782 /* Read a single character from the remote end. The current quit
9783 handler is overridden to avoid quitting in the middle of packet
9784 sequence, as that would break communication with the remote server.
9785 See remote_serial_quit_handler for more detail. */
9788 remote_target::readchar (int timeout
)
9791 struct remote_state
*rs
= get_remote_state ();
9794 scoped_restore restore_quit_target
9795 = make_scoped_restore (&curr_quit_handler_target
, this);
9796 scoped_restore restore_quit
9797 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
9799 rs
->got_ctrlc_during_io
= 0;
9801 ch
= serial_readchar (rs
->remote_desc
, timeout
);
9803 if (rs
->got_ctrlc_during_io
)
9810 switch ((enum serial_rc
) ch
)
9813 remote_unpush_target (this);
9814 throw_error (TARGET_CLOSE_ERROR
, _("Remote connection closed"));
9817 unpush_and_perror (this, _("Remote communication error. "
9818 "Target disconnected"));
9820 case SERIAL_TIMEOUT
:
9826 /* Wrapper for serial_write that closes the target and throws if
9827 writing fails. The current quit handler is overridden to avoid
9828 quitting in the middle of packet sequence, as that would break
9829 communication with the remote server. See
9830 remote_serial_quit_handler for more detail. */
9833 remote_target::remote_serial_write (const char *str
, int len
)
9835 struct remote_state
*rs
= get_remote_state ();
9837 scoped_restore restore_quit_target
9838 = make_scoped_restore (&curr_quit_handler_target
, this);
9839 scoped_restore restore_quit
9840 = make_scoped_restore (&quit_handler
, ::remote_serial_quit_handler
);
9842 rs
->got_ctrlc_during_io
= 0;
9844 if (serial_write (rs
->remote_desc
, str
, len
))
9846 unpush_and_perror (this, _("Remote communication error. "
9847 "Target disconnected"));
9850 if (rs
->got_ctrlc_during_io
)
9854 /* Return a string representing an escaped version of BUF, of len N.
9855 E.g. \n is converted to \\n, \t to \\t, etc. */
9858 escape_buffer (const char *buf
, int n
)
9862 stb
.putstrn (buf
, n
, '\\');
9863 return stb
.release ();
9867 remote_target::putpkt (const char *buf
)
9869 return putpkt_binary (buf
, strlen (buf
));
9872 /* Wrapper around remote_target::putpkt to avoid exporting
9876 putpkt (remote_target
*remote
, const char *buf
)
9878 return remote
->putpkt (buf
);
9881 /* Send a packet to the remote machine, with error checking. The data
9882 of the packet is in BUF. The string in BUF can be at most
9883 get_remote_packet_size () - 5 to account for the $, # and checksum,
9884 and for a possible /0 if we are debugging (remote_debug) and want
9885 to print the sent packet as a string. */
9888 remote_target::putpkt_binary (const char *buf
, int cnt
)
9890 struct remote_state
*rs
= get_remote_state ();
9892 unsigned char csum
= 0;
9893 gdb::def_vector
<char> data (cnt
+ 6);
9894 char *buf2
= data
.data ();
9900 /* Catch cases like trying to read memory or listing threads while
9901 we're waiting for a stop reply. The remote server wouldn't be
9902 ready to handle this request, so we'd hang and timeout. We don't
9903 have to worry about this in synchronous mode, because in that
9904 case it's not possible to issue a command while the target is
9905 running. This is not a problem in non-stop mode, because in that
9906 case, the stub is always ready to process serial input. */
9907 if (!target_is_non_stop_p ()
9908 && target_is_async_p ()
9909 && rs
->waiting_for_stop_reply
)
9911 error (_("Cannot execute this command while the target is running.\n"
9912 "Use the \"interrupt\" command to stop the target\n"
9913 "and then try again."));
9916 /* Copy the packet into buffer BUF2, encapsulating it
9917 and giving it a checksum. */
9922 for (i
= 0; i
< cnt
; i
++)
9928 *p
++ = tohex ((csum
>> 4) & 0xf);
9929 *p
++ = tohex (csum
& 0xf);
9931 /* Send it over and over until we get a positive ack. */
9939 int len
= (int) (p
- buf2
);
9942 if (remote_packet_max_chars
< 0)
9945 max_chars
= remote_packet_max_chars
;
9948 = escape_buffer (buf2
, std::min (len
, max_chars
));
9950 if (len
> max_chars
)
9951 remote_debug_printf_nofunc
9952 ("Sending packet: %s [%d bytes omitted]", str
.c_str (),
9955 remote_debug_printf_nofunc ("Sending packet: %s", str
.c_str ());
9957 remote_serial_write (buf2
, p
- buf2
);
9959 /* If this is a no acks version of the remote protocol, send the
9960 packet and move on. */
9964 /* Read until either a timeout occurs (-2) or '+' is read.
9965 Handle any notification that arrives in the mean time. */
9968 ch
= readchar (remote_timeout
);
9973 remote_debug_printf_nofunc ("Received Ack");
9976 remote_debug_printf_nofunc ("Received Nak");
9978 case SERIAL_TIMEOUT
:
9982 break; /* Retransmit buffer. */
9985 remote_debug_printf ("Packet instead of Ack, ignoring it");
9986 /* It's probably an old response sent because an ACK
9987 was lost. Gobble up the packet and ack it so it
9988 doesn't get retransmitted when we resend this
9991 remote_serial_write ("+", 1);
9992 continue; /* Now, go look for +. */
9999 /* If we got a notification, handle it, and go back to looking
10001 /* We've found the start of a notification. Now
10002 collect the data. */
10003 val
= read_frame (&rs
->buf
);
10006 remote_debug_printf_nofunc
10007 (" Notification received: %s",
10008 escape_buffer (rs
->buf
.data (), val
).c_str ());
10010 handle_notification (rs
->notif_state
, rs
->buf
.data ());
10011 /* We're in sync now, rewait for the ack. */
10015 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10021 remote_debug_printf_nofunc ("Junk: %c%s", ch
& 0177,
10025 break; /* Here to retransmit. */
10029 /* This is wrong. If doing a long backtrace, the user should be
10030 able to get out next time we call QUIT, without anything as
10031 violent as interrupt_query. If we want to provide a way out of
10032 here without getting to the next QUIT, it should be based on
10033 hitting ^C twice as in remote_wait. */
10037 interrupt_query ();
10045 /* Come here after finding the start of a frame when we expected an
10046 ack. Do our best to discard the rest of this packet. */
10049 remote_target::skip_frame ()
10055 c
= readchar (remote_timeout
);
10058 case SERIAL_TIMEOUT
:
10059 /* Nothing we can do. */
10062 /* Discard the two bytes of checksum and stop. */
10063 c
= readchar (remote_timeout
);
10065 c
= readchar (remote_timeout
);
10068 case '*': /* Run length encoding. */
10069 /* Discard the repeat count. */
10070 c
= readchar (remote_timeout
);
10075 /* A regular character. */
10081 /* Come here after finding the start of the frame. Collect the rest
10082 into *BUF, verifying the checksum, length, and handling run-length
10083 compression. NUL terminate the buffer. If there is not enough room,
10086 Returns -1 on error, number of characters in buffer (ignoring the
10087 trailing NULL) on success. (could be extended to return one of the
10088 SERIAL status indications). */
10091 remote_target::read_frame (gdb::char_vector
*buf_p
)
10093 unsigned char csum
;
10096 char *buf
= buf_p
->data ();
10097 struct remote_state
*rs
= get_remote_state ();
10104 c
= readchar (remote_timeout
);
10107 case SERIAL_TIMEOUT
:
10108 remote_debug_printf ("Timeout in mid-packet, retrying");
10112 remote_debug_printf ("Saw new packet start in middle of old one");
10113 return -1; /* Start a new packet, count retries. */
10117 unsigned char pktcsum
;
10123 check_0
= readchar (remote_timeout
);
10125 check_1
= readchar (remote_timeout
);
10127 if (check_0
== SERIAL_TIMEOUT
|| check_1
== SERIAL_TIMEOUT
)
10129 remote_debug_printf ("Timeout in checksum, retrying");
10132 else if (check_0
< 0 || check_1
< 0)
10134 remote_debug_printf ("Communication error in checksum");
10138 /* Don't recompute the checksum; with no ack packets we
10139 don't have any way to indicate a packet retransmission
10141 if (rs
->noack_mode
)
10144 pktcsum
= (fromhex (check_0
) << 4) | fromhex (check_1
);
10145 if (csum
== pktcsum
)
10148 remote_debug_printf
10149 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10150 pktcsum
, csum
, escape_buffer (buf
, bc
).c_str ());
10152 /* Number of characters in buffer ignoring trailing
10156 case '*': /* Run length encoding. */
10161 c
= readchar (remote_timeout
);
10163 repeat
= c
- ' ' + 3; /* Compute repeat count. */
10165 /* The character before ``*'' is repeated. */
10167 if (repeat
> 0 && repeat
<= 255 && bc
> 0)
10169 if (bc
+ repeat
- 1 >= buf_p
->size () - 1)
10171 /* Make some more room in the buffer. */
10172 buf_p
->resize (buf_p
->size () + repeat
);
10173 buf
= buf_p
->data ();
10176 memset (&buf
[bc
], buf
[bc
- 1], repeat
);
10182 gdb_printf (_("Invalid run length encoding: %s\n"), buf
);
10186 if (bc
>= buf_p
->size () - 1)
10188 /* Make some more room in the buffer. */
10189 buf_p
->resize (buf_p
->size () * 2);
10190 buf
= buf_p
->data ();
10200 /* Set this to the maximum number of seconds to wait instead of waiting forever
10201 in target_wait(). If this timer times out, then it generates an error and
10202 the command is aborted. This replaces most of the need for timeouts in the
10203 GDB test suite, and makes it possible to distinguish between a hung target
10204 and one with slow communications. */
10206 static int watchdog
= 0;
10208 show_watchdog (struct ui_file
*file
, int from_tty
,
10209 struct cmd_list_element
*c
, const char *value
)
10211 gdb_printf (file
, _("Watchdog timer is %s.\n"), value
);
10214 /* Read a packet from the remote machine, with error checking, and
10215 store it in *BUF. Resize *BUF if necessary to hold the result. If
10216 FOREVER, wait forever rather than timing out; this is used (in
10217 synchronous mode) to wait for a target that is is executing user
10218 code to stop. If FOREVER == false, this function is allowed to time
10219 out gracefully and return an indication of this to the caller.
10220 Otherwise return the number of bytes read. If IS_NOTIF is not
10221 NULL, then consider receiving a notification enough reason to
10222 return to the caller. In this case, *IS_NOTIF is an output boolean
10223 that indicates whether *BUF holds a notification or not (a regular
10227 remote_target::getpkt (gdb::char_vector
*buf
, bool forever
, bool *is_notif
)
10229 struct remote_state
*rs
= get_remote_state ();
10235 strcpy (buf
->data (), "timeout");
10238 timeout
= watchdog
> 0 ? watchdog
: -1;
10239 else if (is_notif
!= nullptr)
10240 timeout
= 0; /* There should already be a char in the buffer. If
10243 timeout
= remote_timeout
;
10245 #define MAX_TRIES 3
10247 /* Process any number of notifications, and then return when
10248 we get a packet. */
10251 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10253 for (tries
= 1; tries
<= MAX_TRIES
; tries
++)
10255 /* This can loop forever if the remote side sends us
10256 characters continuously, but if it pauses, we'll get
10257 SERIAL_TIMEOUT from readchar because of timeout. Then
10258 we'll count that as a retry.
10260 Note that even when forever is set, we will only wait
10261 forever prior to the start of a packet. After that, we
10262 expect characters to arrive at a brisk pace. They should
10263 show up within remote_timeout intervals. */
10265 c
= readchar (timeout
);
10266 while (c
!= SERIAL_TIMEOUT
&& c
!= '$' && c
!= '%');
10268 if (c
== SERIAL_TIMEOUT
)
10270 if (is_notif
!= nullptr)
10271 return -1; /* Don't complain, it's normal to not get
10272 anything in this case. */
10274 if (forever
) /* Watchdog went off? Kill the target. */
10276 remote_unpush_target (this);
10277 throw_error (TARGET_CLOSE_ERROR
,
10278 _("Watchdog timeout has expired. "
10279 "Target detached."));
10282 remote_debug_printf ("Timed out.");
10286 /* We've found the start of a packet or notification.
10287 Now collect the data. */
10288 val
= read_frame (buf
);
10293 remote_serial_write ("-", 1);
10296 if (tries
> MAX_TRIES
)
10298 /* We have tried hard enough, and just can't receive the
10299 packet/notification. Give up. */
10300 gdb_printf (_("Ignoring packet error, continuing...\n"));
10302 /* Skip the ack char if we're in no-ack mode. */
10303 if (!rs
->noack_mode
)
10304 remote_serial_write ("+", 1);
10308 /* If we got an ordinary packet, return that to our caller. */
10315 if (remote_packet_max_chars
< 0)
10318 max_chars
= remote_packet_max_chars
;
10321 = escape_buffer (buf
->data (),
10322 std::min (val
, max_chars
));
10324 if (val
> max_chars
)
10325 remote_debug_printf_nofunc
10326 ("Packet received: %s [%d bytes omitted]", str
.c_str (),
10329 remote_debug_printf_nofunc ("Packet received: %s",
10333 /* Skip the ack char if we're in no-ack mode. */
10334 if (!rs
->noack_mode
)
10335 remote_serial_write ("+", 1);
10336 if (is_notif
!= NULL
)
10341 /* If we got a notification, handle it, and go back to looking
10345 gdb_assert (c
== '%');
10347 remote_debug_printf_nofunc
10348 (" Notification received: %s",
10349 escape_buffer (buf
->data (), val
).c_str ());
10351 if (is_notif
!= NULL
)
10354 handle_notification (rs
->notif_state
, buf
->data ());
10356 /* Notifications require no acknowledgement. */
10358 if (is_notif
!= nullptr)
10364 /* Kill any new fork children of inferior INF that haven't been
10365 processed by follow_fork. */
10368 remote_target::kill_new_fork_children (inferior
*inf
)
10370 remote_state
*rs
= get_remote_state ();
10371 const notif_client
*notif
= ¬if_client_stop
;
10373 /* Kill the fork child threads of any threads in inferior INF that are stopped
10374 at a fork event. */
10375 for (thread_info
*thread
: inf
->non_exited_threads ())
10377 const target_waitstatus
*ws
= thread_pending_fork_status (thread
);
10382 int child_pid
= ws
->child_ptid ().pid ();
10383 int res
= remote_vkill (child_pid
);
10386 error (_("Can't kill fork child process %d"), child_pid
);
10389 /* Check for any pending fork events (not reported or processed yet)
10390 in inferior INF and kill those fork child threads as well. */
10391 remote_notif_get_pending_events (notif
);
10392 for (auto &event
: rs
->stop_reply_queue
)
10394 if (event
->ptid
.pid () != inf
->pid
)
10397 if (!is_fork_status (event
->ws
.kind ()))
10400 int child_pid
= event
->ws
.child_ptid ().pid ();
10401 int res
= remote_vkill (child_pid
);
10404 error (_("Can't kill fork child process %d"), child_pid
);
10409 /* Target hook to kill the current inferior. */
10412 remote_target::kill ()
10415 inferior
*inf
= find_inferior_pid (this, inferior_ptid
.pid ());
10417 gdb_assert (inf
!= nullptr);
10419 if (m_features
.packet_support (PACKET_vKill
) != PACKET_DISABLE
)
10421 /* If we're stopped while forking and we haven't followed yet,
10422 kill the child task. We need to do this before killing the
10423 parent task because if this is a vfork then the parent will
10425 kill_new_fork_children (inf
);
10427 res
= remote_vkill (inf
->pid
);
10430 target_mourn_inferior (inferior_ptid
);
10435 /* If we are in 'target remote' mode and we are killing the only
10436 inferior, then we will tell gdbserver to exit and unpush the
10438 if (res
== -1 && !m_features
.remote_multi_process_p ()
10439 && number_of_live_inferiors (this) == 1)
10443 /* We've killed the remote end, we get to mourn it. If we are
10444 not in extended mode, mourning the inferior also unpushes
10445 remote_ops from the target stack, which closes the remote
10447 target_mourn_inferior (inferior_ptid
);
10452 error (_("Can't kill process"));
10455 /* Send a kill request to the target using the 'vKill' packet. */
10458 remote_target::remote_vkill (int pid
)
10460 if (m_features
.packet_support (PACKET_vKill
) == PACKET_DISABLE
)
10463 remote_state
*rs
= get_remote_state ();
10465 /* Tell the remote target to detach. */
10466 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "vKill;%x", pid
);
10470 switch (m_features
.packet_ok (rs
->buf
, PACKET_vKill
))
10476 case PACKET_UNKNOWN
:
10479 internal_error (_("Bad result from packet_ok"));
10483 /* Send a kill request to the target using the 'k' packet. */
10486 remote_target::remote_kill_k ()
10488 /* Catch errors so the user can quit from gdb even when we
10489 aren't on speaking terms with the remote system. */
10494 catch (const gdb_exception_error
&ex
)
10496 if (ex
.error
== TARGET_CLOSE_ERROR
)
10498 /* If we got an (EOF) error that caused the target
10499 to go away, then we're done, that's what we wanted.
10500 "k" is susceptible to cause a premature EOF, given
10501 that the remote server isn't actually required to
10502 reply to "k", and it can happen that it doesn't
10503 even get to reply ACK to the "k". */
10507 /* Otherwise, something went wrong. We didn't actually kill
10508 the target. Just propagate the exception, and let the
10509 user or higher layers decide what to do. */
10515 remote_target::mourn_inferior ()
10517 struct remote_state
*rs
= get_remote_state ();
10519 /* We're no longer interested in notification events of an inferior
10520 that exited or was killed/detached. */
10521 discard_pending_stop_replies (current_inferior ());
10523 /* In 'target remote' mode with one inferior, we close the connection. */
10524 if (!rs
->extended
&& number_of_live_inferiors (this) <= 1)
10526 remote_unpush_target (this);
10530 /* In case we got here due to an error, but we're going to stay
10532 rs
->waiting_for_stop_reply
= 0;
10534 /* If the current general thread belonged to the process we just
10535 detached from or has exited, the remote side current general
10536 thread becomes undefined. Considering a case like this:
10538 - We just got here due to a detach.
10539 - The process that we're detaching from happens to immediately
10540 report a global breakpoint being hit in non-stop mode, in the
10541 same thread we had selected before.
10542 - GDB attaches to this process again.
10543 - This event happens to be the next event we handle.
10545 GDB would consider that the current general thread didn't need to
10546 be set on the stub side (with Hg), since for all it knew,
10547 GENERAL_THREAD hadn't changed.
10549 Notice that although in all-stop mode, the remote server always
10550 sets the current thread to the thread reporting the stop event,
10551 that doesn't happen in non-stop mode; in non-stop, the stub *must
10552 not* change the current thread when reporting a breakpoint hit,
10553 due to the decoupling of event reporting and event handling.
10555 To keep things simple, we always invalidate our notion of the
10557 record_currthread (rs
, minus_one_ptid
);
10559 /* Call common code to mark the inferior as not running. */
10560 generic_mourn_inferior ();
10564 extended_remote_target::supports_disable_randomization ()
10566 return (m_features
.packet_support (PACKET_QDisableRandomization
)
10571 remote_target::extended_remote_disable_randomization (int val
)
10573 struct remote_state
*rs
= get_remote_state ();
10576 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10577 "QDisableRandomization:%x", val
);
10579 reply
= remote_get_noisy_reply ();
10580 if (*reply
== '\0')
10581 error (_("Target does not support QDisableRandomization."));
10582 if (strcmp (reply
, "OK") != 0)
10583 error (_("Bogus QDisableRandomization reply from target: %s"), reply
);
10587 remote_target::extended_remote_run (const std::string
&args
)
10589 struct remote_state
*rs
= get_remote_state ();
10591 const char *remote_exec_file
= get_remote_exec_file ();
10593 /* If the user has disabled vRun support, or we have detected that
10594 support is not available, do not try it. */
10595 if (m_features
.packet_support (PACKET_vRun
) == PACKET_DISABLE
)
10598 strcpy (rs
->buf
.data (), "vRun;");
10599 len
= strlen (rs
->buf
.data ());
10601 if (strlen (remote_exec_file
) * 2 + len
>= get_remote_packet_size ())
10602 error (_("Remote file name too long for run packet"));
10603 len
+= 2 * bin2hex ((gdb_byte
*) remote_exec_file
, rs
->buf
.data () + len
,
10604 strlen (remote_exec_file
));
10606 if (!args
.empty ())
10610 gdb_argv
argv (args
.c_str ());
10611 for (i
= 0; argv
[i
] != NULL
; i
++)
10613 if (strlen (argv
[i
]) * 2 + 1 + len
>= get_remote_packet_size ())
10614 error (_("Argument list too long for run packet"));
10615 rs
->buf
[len
++] = ';';
10616 len
+= 2 * bin2hex ((gdb_byte
*) argv
[i
], rs
->buf
.data () + len
,
10621 rs
->buf
[len
++] = '\0';
10626 switch (m_features
.packet_ok (rs
->buf
, PACKET_vRun
))
10629 /* We have a wait response. All is well. */
10631 case PACKET_UNKNOWN
:
10634 if (remote_exec_file
[0] == '\0')
10635 error (_("Running the default executable on the remote target failed; "
10636 "try \"set remote exec-file\"?"));
10638 error (_("Running \"%s\" on the remote target failed"),
10641 gdb_assert_not_reached ("bad switch");
10645 /* Helper function to send set/unset environment packets. ACTION is
10646 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10647 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10651 remote_target::send_environment_packet (const char *action
,
10652 const char *packet
,
10655 remote_state
*rs
= get_remote_state ();
10657 /* Convert the environment variable to an hex string, which
10658 is the best format to be transmitted over the wire. */
10659 std::string encoded_value
= bin2hex ((const gdb_byte
*) value
,
10662 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10663 "%s:%s", packet
, encoded_value
.c_str ());
10667 if (strcmp (rs
->buf
.data (), "OK") != 0)
10668 warning (_("Unable to %s environment variable '%s' on remote."),
10672 /* Helper function to handle the QEnvironment* packets. */
10675 remote_target::extended_remote_environment_support ()
10677 remote_state
*rs
= get_remote_state ();
10679 if (m_features
.packet_support (PACKET_QEnvironmentReset
) != PACKET_DISABLE
)
10681 putpkt ("QEnvironmentReset");
10683 if (strcmp (rs
->buf
.data (), "OK") != 0)
10684 warning (_("Unable to reset environment on remote."));
10687 gdb_environ
*e
= ¤t_inferior ()->environment
;
10689 if (m_features
.packet_support (PACKET_QEnvironmentHexEncoded
)
10692 for (const std::string
&el
: e
->user_set_env ())
10693 send_environment_packet ("set", "QEnvironmentHexEncoded",
10698 if (m_features
.packet_support (PACKET_QEnvironmentUnset
) != PACKET_DISABLE
)
10699 for (const std::string
&el
: e
->user_unset_env ())
10700 send_environment_packet ("unset", "QEnvironmentUnset", el
.c_str ());
10703 /* Helper function to set the current working directory for the
10704 inferior in the remote target. */
10707 remote_target::extended_remote_set_inferior_cwd ()
10709 if (m_features
.packet_support (PACKET_QSetWorkingDir
) != PACKET_DISABLE
)
10711 const std::string
&inferior_cwd
= current_inferior ()->cwd ();
10712 remote_state
*rs
= get_remote_state ();
10714 if (!inferior_cwd
.empty ())
10716 std::string hexpath
10717 = bin2hex ((const gdb_byte
*) inferior_cwd
.data (),
10718 inferior_cwd
.size ());
10720 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10721 "QSetWorkingDir:%s", hexpath
.c_str ());
10725 /* An empty inferior_cwd means that the user wants us to
10726 reset the remote server's inferior's cwd. */
10727 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10728 "QSetWorkingDir:");
10733 if (m_features
.packet_ok (rs
->buf
, PACKET_QSetWorkingDir
) != PACKET_OK
)
10735 Remote replied unexpectedly while setting the inferior's working\n\
10742 /* In the extended protocol we want to be able to do things like
10743 "run" and have them basically work as expected. So we need
10744 a special create_inferior function. We support changing the
10745 executable file and the command line arguments, but not the
10749 extended_remote_target::create_inferior (const char *exec_file
,
10750 const std::string
&args
,
10751 char **env
, int from_tty
)
10755 struct remote_state
*rs
= get_remote_state ();
10756 const char *remote_exec_file
= get_remote_exec_file ();
10758 /* If running asynchronously, register the target file descriptor
10759 with the event loop. */
10760 if (target_can_async_p ())
10761 target_async (true);
10763 /* Disable address space randomization if requested (and supported). */
10764 if (supports_disable_randomization ())
10765 extended_remote_disable_randomization (disable_randomization
);
10767 /* If startup-with-shell is on, we inform gdbserver to start the
10768 remote inferior using a shell. */
10769 if (m_features
.packet_support (PACKET_QStartupWithShell
) != PACKET_DISABLE
)
10771 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
10772 "QStartupWithShell:%d", startup_with_shell
? 1 : 0);
10775 if (strcmp (rs
->buf
.data (), "OK") != 0)
10777 Remote replied unexpectedly while setting startup-with-shell: %s"),
10781 extended_remote_environment_support ();
10783 extended_remote_set_inferior_cwd ();
10785 /* Now restart the remote server. */
10786 run_worked
= extended_remote_run (args
) != -1;
10789 /* vRun was not supported. Fail if we need it to do what the
10791 if (remote_exec_file
[0])
10792 error (_("Remote target does not support \"set remote exec-file\""));
10793 if (!args
.empty ())
10794 error (_("Remote target does not support \"set args\" or run ARGS"));
10796 /* Fall back to "R". */
10797 extended_remote_restart ();
10800 /* vRun's success return is a stop reply. */
10801 stop_reply
= run_worked
? rs
->buf
.data () : NULL
;
10802 add_current_inferior_and_thread (stop_reply
);
10804 /* Get updated offsets, if the stub uses qOffsets. */
10809 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10810 the list of conditions (in agent expression bytecode format), if any, the
10811 target needs to evaluate. The output is placed into the packet buffer
10812 started from BUF and ended at BUF_END. */
10815 remote_add_target_side_condition (struct gdbarch
*gdbarch
,
10816 struct bp_target_info
*bp_tgt
, char *buf
,
10819 if (bp_tgt
->conditions
.empty ())
10822 buf
+= strlen (buf
);
10823 xsnprintf (buf
, buf_end
- buf
, "%s", ";");
10826 /* Send conditions to the target. */
10827 for (agent_expr
*aexpr
: bp_tgt
->conditions
)
10829 xsnprintf (buf
, buf_end
- buf
, "X%x,", (int) aexpr
->buf
.size ());
10830 buf
+= strlen (buf
);
10831 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
10832 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
10839 remote_add_target_side_commands (struct gdbarch
*gdbarch
,
10840 struct bp_target_info
*bp_tgt
, char *buf
)
10842 if (bp_tgt
->tcommands
.empty ())
10845 buf
+= strlen (buf
);
10847 sprintf (buf
, ";cmds:%x,", bp_tgt
->persist
);
10848 buf
+= strlen (buf
);
10850 /* Concatenate all the agent expressions that are commands into the
10852 for (agent_expr
*aexpr
: bp_tgt
->tcommands
)
10854 sprintf (buf
, "X%x,", (int) aexpr
->buf
.size ());
10855 buf
+= strlen (buf
);
10856 for (int i
= 0; i
< aexpr
->buf
.size (); ++i
)
10857 buf
= pack_hex_byte (buf
, aexpr
->buf
[i
]);
10862 /* Insert a breakpoint. On targets that have software breakpoint
10863 support, we ask the remote target to do the work; on targets
10864 which don't, we insert a traditional memory breakpoint. */
10867 remote_target::insert_breakpoint (struct gdbarch
*gdbarch
,
10868 struct bp_target_info
*bp_tgt
)
10870 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10871 If it succeeds, then set the support to PACKET_ENABLE. If it
10872 fails, and the user has explicitly requested the Z support then
10873 report an error, otherwise, mark it disabled and go on. */
10875 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
10877 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
10878 struct remote_state
*rs
;
10881 /* Make sure the remote is pointing at the right process, if
10883 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10884 set_general_process ();
10886 rs
= get_remote_state ();
10887 p
= rs
->buf
.data ();
10888 endbuf
= p
+ get_remote_packet_size ();
10893 addr
= (ULONGEST
) remote_address_masked (addr
);
10894 p
+= hexnumstr (p
, addr
);
10895 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
10897 if (supports_evaluation_of_breakpoint_conditions ())
10898 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
10900 if (can_run_breakpoint_commands ())
10901 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
10906 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z0
))
10912 case PACKET_UNKNOWN
:
10917 /* If this breakpoint has target-side commands but this stub doesn't
10918 support Z0 packets, throw error. */
10919 if (!bp_tgt
->tcommands
.empty ())
10920 throw_error (NOT_SUPPORTED_ERROR
, _("\
10921 Target doesn't support breakpoints that have target side commands."));
10923 return memory_insert_breakpoint (this, gdbarch
, bp_tgt
);
10927 remote_target::remove_breakpoint (struct gdbarch
*gdbarch
,
10928 struct bp_target_info
*bp_tgt
,
10929 enum remove_bp_reason reason
)
10931 CORE_ADDR addr
= bp_tgt
->placed_address
;
10932 struct remote_state
*rs
= get_remote_state ();
10934 if (m_features
.packet_support (PACKET_Z0
) != PACKET_DISABLE
)
10936 char *p
= rs
->buf
.data ();
10937 char *endbuf
= p
+ get_remote_packet_size ();
10939 /* Make sure the remote is pointing at the right process, if
10941 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10942 set_general_process ();
10948 addr
= (ULONGEST
) remote_address_masked (bp_tgt
->placed_address
);
10949 p
+= hexnumstr (p
, addr
);
10950 xsnprintf (p
, endbuf
- p
, ",%d", bp_tgt
->kind
);
10955 return (rs
->buf
[0] == 'E');
10958 return memory_remove_breakpoint (this, gdbarch
, bp_tgt
, reason
);
10961 static enum Z_packet_type
10962 watchpoint_to_Z_packet (int type
)
10967 return Z_PACKET_WRITE_WP
;
10970 return Z_PACKET_READ_WP
;
10973 return Z_PACKET_ACCESS_WP
;
10976 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type
);
10981 remote_target::insert_watchpoint (CORE_ADDR addr
, int len
,
10982 enum target_hw_bp_type type
, struct expression
*cond
)
10984 struct remote_state
*rs
= get_remote_state ();
10985 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
10987 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
10989 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
10990 + to_underlying (packet
))) == PACKET_DISABLE
)
10993 /* Make sure the remote is pointing at the right process, if
10995 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10996 set_general_process ();
10998 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "Z%x,", packet
);
10999 p
= strchr (rs
->buf
.data (), '\0');
11000 addr
= remote_address_masked (addr
);
11001 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11002 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11007 switch (m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11008 + to_underlying (packet
))))
11012 case PACKET_UNKNOWN
:
11017 internal_error (_("remote_insert_watchpoint: reached end of function"));
11021 remote_target::watchpoint_addr_within_range (CORE_ADDR addr
,
11022 CORE_ADDR start
, int length
)
11024 CORE_ADDR diff
= remote_address_masked (addr
- start
);
11026 return diff
< length
;
11031 remote_target::remove_watchpoint (CORE_ADDR addr
, int len
,
11032 enum target_hw_bp_type type
, struct expression
*cond
)
11034 struct remote_state
*rs
= get_remote_state ();
11035 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
11037 enum Z_packet_type packet
= watchpoint_to_Z_packet (type
);
11039 if (m_features
.packet_support ((to_underlying (PACKET_Z0
)
11040 + to_underlying (packet
))) == PACKET_DISABLE
)
11043 /* Make sure the remote is pointing at the right process, if
11045 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11046 set_general_process ();
11048 xsnprintf (rs
->buf
.data (), endbuf
- rs
->buf
.data (), "z%x,", packet
);
11049 p
= strchr (rs
->buf
.data (), '\0');
11050 addr
= remote_address_masked (addr
);
11051 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11052 xsnprintf (p
, endbuf
- p
, ",%x", len
);
11056 switch (m_features
.packet_ok (rs
->buf
, (to_underlying (PACKET_Z0
)
11057 + to_underlying (packet
))))
11060 case PACKET_UNKNOWN
:
11065 internal_error (_("remote_remove_watchpoint: reached end of function"));
11069 static int remote_hw_watchpoint_limit
= -1;
11070 static int remote_hw_watchpoint_length_limit
= -1;
11071 static int remote_hw_breakpoint_limit
= -1;
11074 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr
, int len
)
11076 if (remote_hw_watchpoint_length_limit
== 0)
11078 else if (remote_hw_watchpoint_length_limit
< 0)
11080 else if (len
<= remote_hw_watchpoint_length_limit
)
11087 remote_target::can_use_hw_breakpoint (enum bptype type
, int cnt
, int ot
)
11089 if (type
== bp_hardware_breakpoint
)
11091 if (remote_hw_breakpoint_limit
== 0)
11093 else if (remote_hw_breakpoint_limit
< 0)
11095 else if (cnt
<= remote_hw_breakpoint_limit
)
11100 if (remote_hw_watchpoint_limit
== 0)
11102 else if (remote_hw_watchpoint_limit
< 0)
11106 else if (cnt
<= remote_hw_watchpoint_limit
)
11112 /* The to_stopped_by_sw_breakpoint method of target remote. */
11115 remote_target::stopped_by_sw_breakpoint ()
11117 struct thread_info
*thread
= inferior_thread ();
11119 return (thread
->priv
!= NULL
11120 && (get_remote_thread_info (thread
)->stop_reason
11121 == TARGET_STOPPED_BY_SW_BREAKPOINT
));
11124 /* The to_supports_stopped_by_sw_breakpoint method of target
11128 remote_target::supports_stopped_by_sw_breakpoint ()
11130 return (m_features
.packet_support (PACKET_swbreak_feature
) == PACKET_ENABLE
);
11133 /* The to_stopped_by_hw_breakpoint method of target remote. */
11136 remote_target::stopped_by_hw_breakpoint ()
11138 struct thread_info
*thread
= inferior_thread ();
11140 return (thread
->priv
!= NULL
11141 && (get_remote_thread_info (thread
)->stop_reason
11142 == TARGET_STOPPED_BY_HW_BREAKPOINT
));
11145 /* The to_supports_stopped_by_hw_breakpoint method of target
11149 remote_target::supports_stopped_by_hw_breakpoint ()
11151 return (m_features
.packet_support (PACKET_hwbreak_feature
) == PACKET_ENABLE
);
11155 remote_target::stopped_by_watchpoint ()
11157 struct thread_info
*thread
= inferior_thread ();
11159 return (thread
->priv
!= NULL
11160 && (get_remote_thread_info (thread
)->stop_reason
11161 == TARGET_STOPPED_BY_WATCHPOINT
));
11165 remote_target::stopped_data_address (CORE_ADDR
*addr_p
)
11167 struct thread_info
*thread
= inferior_thread ();
11169 if (thread
->priv
!= NULL
11170 && (get_remote_thread_info (thread
)->stop_reason
11171 == TARGET_STOPPED_BY_WATCHPOINT
))
11173 *addr_p
= get_remote_thread_info (thread
)->watch_data_address
;
11182 remote_target::insert_hw_breakpoint (struct gdbarch
*gdbarch
,
11183 struct bp_target_info
*bp_tgt
)
11185 CORE_ADDR addr
= bp_tgt
->reqstd_address
;
11186 struct remote_state
*rs
;
11190 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11193 /* Make sure the remote is pointing at the right process, if
11195 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11196 set_general_process ();
11198 rs
= get_remote_state ();
11199 p
= rs
->buf
.data ();
11200 endbuf
= p
+ get_remote_packet_size ();
11206 addr
= remote_address_masked (addr
);
11207 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11208 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11210 if (supports_evaluation_of_breakpoint_conditions ())
11211 remote_add_target_side_condition (gdbarch
, bp_tgt
, p
, endbuf
);
11213 if (can_run_breakpoint_commands ())
11214 remote_add_target_side_commands (gdbarch
, bp_tgt
, p
);
11219 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z1
))
11222 if (rs
->buf
[1] == '.')
11224 message
= strchr (&rs
->buf
[2], '.');
11226 error (_("Remote failure reply: %s"), message
+ 1);
11229 case PACKET_UNKNOWN
:
11234 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11239 remote_target::remove_hw_breakpoint (struct gdbarch
*gdbarch
,
11240 struct bp_target_info
*bp_tgt
)
11243 struct remote_state
*rs
= get_remote_state ();
11244 char *p
= rs
->buf
.data ();
11245 char *endbuf
= p
+ get_remote_packet_size ();
11247 if (m_features
.packet_support (PACKET_Z1
) == PACKET_DISABLE
)
11250 /* Make sure the remote is pointing at the right process, if
11252 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11253 set_general_process ();
11259 addr
= remote_address_masked (bp_tgt
->placed_address
);
11260 p
+= hexnumstr (p
, (ULONGEST
) addr
);
11261 xsnprintf (p
, endbuf
- p
, ",%x", bp_tgt
->kind
);
11266 switch (m_features
.packet_ok (rs
->buf
, PACKET_Z1
))
11269 case PACKET_UNKNOWN
:
11274 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11277 /* Verify memory using the "qCRC:" request. */
11280 remote_target::verify_memory (const gdb_byte
*data
, CORE_ADDR lma
, ULONGEST size
)
11282 struct remote_state
*rs
= get_remote_state ();
11283 unsigned long host_crc
, target_crc
;
11286 /* It doesn't make sense to use qCRC if the remote target is
11287 connected but not running. */
11288 if (target_has_execution ()
11289 && m_features
.packet_support (PACKET_qCRC
) != PACKET_DISABLE
)
11291 enum packet_result result
;
11293 /* Make sure the remote is pointing at the right process. */
11294 set_general_process ();
11296 /* FIXME: assumes lma can fit into long. */
11297 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11298 (long) lma
, (long) size
);
11301 /* Be clever; compute the host_crc before waiting for target
11303 host_crc
= xcrc32 (data
, size
, 0xffffffff);
11307 result
= m_features
.packet_ok (rs
->buf
, PACKET_qCRC
);
11308 if (result
== PACKET_ERROR
)
11310 else if (result
== PACKET_OK
)
11312 for (target_crc
= 0, tmp
= &rs
->buf
[1]; *tmp
; tmp
++)
11313 target_crc
= target_crc
* 16 + fromhex (*tmp
);
11315 return (host_crc
== target_crc
);
11319 return simple_verify_memory (this, data
, lma
, size
);
11322 /* compare-sections command
11324 With no arguments, compares each loadable section in the exec bfd
11325 with the same memory range on the target, and reports mismatches.
11326 Useful for verifying the image on the target against the exec file. */
11329 compare_sections_command (const char *args
, int from_tty
)
11332 const char *sectname
;
11333 bfd_size_type size
;
11336 int mismatched
= 0;
11340 if (!current_program_space
->exec_bfd ())
11341 error (_("command cannot be used without an exec file"));
11343 if (args
!= NULL
&& strcmp (args
, "-r") == 0)
11349 for (s
= current_program_space
->exec_bfd ()->sections
; s
; s
= s
->next
)
11351 if (!(s
->flags
& SEC_LOAD
))
11352 continue; /* Skip non-loadable section. */
11354 if (read_only
&& (s
->flags
& SEC_READONLY
) == 0)
11355 continue; /* Skip writeable sections */
11357 size
= bfd_section_size (s
);
11359 continue; /* Skip zero-length section. */
11361 sectname
= bfd_section_name (s
);
11362 if (args
&& strcmp (args
, sectname
) != 0)
11363 continue; /* Not the section selected by user. */
11365 matched
= 1; /* Do this section. */
11368 gdb::byte_vector
sectdata (size
);
11369 bfd_get_section_contents (current_program_space
->exec_bfd (), s
,
11370 sectdata
.data (), 0, size
);
11372 res
= target_verify_memory (sectdata
.data (), lma
, size
);
11375 error (_("target memory fault, section %s, range %s -- %s"), sectname
,
11376 paddress (current_inferior ()->arch (), lma
),
11377 paddress (current_inferior ()->arch (), lma
+ size
));
11379 gdb_printf ("Section %s, range %s -- %s: ", sectname
,
11380 paddress (current_inferior ()->arch (), lma
),
11381 paddress (current_inferior ()->arch (), lma
+ size
));
11383 gdb_printf ("matched.\n");
11386 gdb_printf ("MIS-MATCHED!\n");
11390 if (mismatched
> 0)
11391 warning (_("One or more sections of the target image does "
11392 "not match the loaded file"));
11393 if (args
&& !matched
)
11394 gdb_printf (_("No loaded section named '%s'.\n"), args
);
11397 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11398 into remote target. The number of bytes written to the remote
11399 target is returned, or -1 for error. */
11402 remote_target::remote_write_qxfer (const char *object_name
,
11403 const char *annex
, const gdb_byte
*writebuf
,
11404 ULONGEST offset
, LONGEST len
,
11405 ULONGEST
*xfered_len
,
11406 const unsigned int which_packet
)
11410 struct remote_state
*rs
= get_remote_state ();
11411 int max_size
= get_memory_write_packet_size ();
11413 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11414 return TARGET_XFER_E_IO
;
11416 /* Insert header. */
11417 i
= snprintf (rs
->buf
.data (), max_size
,
11418 "qXfer:%s:write:%s:%s:",
11419 object_name
, annex
? annex
: "",
11420 phex_nz (offset
, sizeof offset
));
11421 max_size
-= (i
+ 1);
11423 /* Escape as much data as fits into rs->buf. */
11424 buf_len
= remote_escape_output
11425 (writebuf
, len
, 1, (gdb_byte
*) rs
->buf
.data () + i
, &max_size
, max_size
);
11427 if (putpkt_binary (rs
->buf
.data (), i
+ buf_len
) < 0
11428 || getpkt (&rs
->buf
) < 0
11429 || m_features
.packet_ok (rs
->buf
, which_packet
) != PACKET_OK
)
11430 return TARGET_XFER_E_IO
;
11432 unpack_varlen_hex (rs
->buf
.data (), &n
);
11435 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11438 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11439 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11440 number of bytes read is returned, or 0 for EOF, or -1 for error.
11441 The number of bytes read may be less than LEN without indicating an
11442 EOF. PACKET is checked and updated to indicate whether the remote
11443 target supports this object. */
11446 remote_target::remote_read_qxfer (const char *object_name
,
11448 gdb_byte
*readbuf
, ULONGEST offset
,
11450 ULONGEST
*xfered_len
,
11451 const unsigned int which_packet
)
11453 struct remote_state
*rs
= get_remote_state ();
11454 LONGEST i
, n
, packet_len
;
11456 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
11457 return TARGET_XFER_E_IO
;
11459 /* Check whether we've cached an end-of-object packet that matches
11461 if (rs
->finished_object
)
11463 if (strcmp (object_name
, rs
->finished_object
) == 0
11464 && strcmp (annex
? annex
: "", rs
->finished_annex
) == 0
11465 && offset
== rs
->finished_offset
)
11466 return TARGET_XFER_EOF
;
11469 /* Otherwise, we're now reading something different. Discard
11471 xfree (rs
->finished_object
);
11472 xfree (rs
->finished_annex
);
11473 rs
->finished_object
= NULL
;
11474 rs
->finished_annex
= NULL
;
11477 /* Request only enough to fit in a single packet. The actual data
11478 may not, since we don't know how much of it will need to be escaped;
11479 the target is free to respond with slightly less data. We subtract
11480 five to account for the response type and the protocol frame. */
11481 n
= std::min
<LONGEST
> (get_remote_packet_size () - 5, len
);
11482 snprintf (rs
->buf
.data (), get_remote_packet_size () - 4,
11483 "qXfer:%s:read:%s:%s,%s",
11484 object_name
, annex
? annex
: "",
11485 phex_nz (offset
, sizeof offset
),
11486 phex_nz (n
, sizeof n
));
11487 i
= putpkt (rs
->buf
);
11489 return TARGET_XFER_E_IO
;
11492 packet_len
= getpkt (&rs
->buf
);
11494 || m_features
.packet_ok (rs
->buf
, which_packet
) != PACKET_OK
)
11495 return TARGET_XFER_E_IO
;
11497 if (rs
->buf
[0] != 'l' && rs
->buf
[0] != 'm')
11498 error (_("Unknown remote qXfer reply: %s"), rs
->buf
.data ());
11500 /* 'm' means there is (or at least might be) more data after this
11501 batch. That does not make sense unless there's at least one byte
11502 of data in this reply. */
11503 if (rs
->buf
[0] == 'm' && packet_len
== 1)
11504 error (_("Remote qXfer reply contained no data."));
11506 /* Got some data. */
11507 i
= remote_unescape_input ((gdb_byte
*) rs
->buf
.data () + 1,
11508 packet_len
- 1, readbuf
, n
);
11510 /* 'l' is an EOF marker, possibly including a final block of data,
11511 or possibly empty. If we have the final block of a non-empty
11512 object, record this fact to bypass a subsequent partial read. */
11513 if (rs
->buf
[0] == 'l' && offset
+ i
> 0)
11515 rs
->finished_object
= xstrdup (object_name
);
11516 rs
->finished_annex
= xstrdup (annex
? annex
: "");
11517 rs
->finished_offset
= offset
+ i
;
11521 return TARGET_XFER_EOF
;
11525 return TARGET_XFER_OK
;
11529 enum target_xfer_status
11530 remote_target::xfer_partial (enum target_object object
,
11531 const char *annex
, gdb_byte
*readbuf
,
11532 const gdb_byte
*writebuf
, ULONGEST offset
, ULONGEST len
,
11533 ULONGEST
*xfered_len
)
11535 struct remote_state
*rs
;
11540 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11542 set_remote_traceframe ();
11543 set_general_thread (inferior_ptid
);
11545 rs
= get_remote_state ();
11547 /* Handle memory using the standard memory routines. */
11548 if (object
== TARGET_OBJECT_MEMORY
)
11550 /* If the remote target is connected but not running, we should
11551 pass this request down to a lower stratum (e.g. the executable
11553 if (!target_has_execution ())
11554 return TARGET_XFER_EOF
;
11556 if (writebuf
!= NULL
)
11557 return remote_write_bytes (offset
, writebuf
, len
, unit_size
,
11560 return remote_read_bytes (offset
, readbuf
, len
, unit_size
,
11564 /* Handle extra signal info using qxfer packets. */
11565 if (object
== TARGET_OBJECT_SIGNAL_INFO
)
11568 return remote_read_qxfer ("siginfo", annex
, readbuf
, offset
, len
,
11569 xfered_len
, PACKET_qXfer_siginfo_read
);
11571 return remote_write_qxfer ("siginfo", annex
, writebuf
, offset
, len
,
11572 xfered_len
, PACKET_qXfer_siginfo_write
);
11575 if (object
== TARGET_OBJECT_STATIC_TRACE_DATA
)
11578 return remote_read_qxfer ("statictrace", annex
,
11579 readbuf
, offset
, len
, xfered_len
,
11580 PACKET_qXfer_statictrace_read
);
11582 return TARGET_XFER_E_IO
;
11585 /* Only handle flash writes. */
11586 if (writebuf
!= NULL
)
11590 case TARGET_OBJECT_FLASH
:
11591 return remote_flash_write (offset
, len
, xfered_len
,
11595 return TARGET_XFER_E_IO
;
11599 /* Map pre-existing objects onto letters. DO NOT do this for new
11600 objects!!! Instead specify new query packets. */
11603 case TARGET_OBJECT_AVR
:
11607 case TARGET_OBJECT_AUXV
:
11608 gdb_assert (annex
== NULL
);
11609 return remote_read_qxfer
11610 ("auxv", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_auxv
);
11612 case TARGET_OBJECT_AVAILABLE_FEATURES
:
11613 return remote_read_qxfer
11614 ("features", annex
, readbuf
, offset
, len
, xfered_len
,
11615 PACKET_qXfer_features
);
11617 case TARGET_OBJECT_LIBRARIES
:
11618 return remote_read_qxfer
11619 ("libraries", annex
, readbuf
, offset
, len
, xfered_len
,
11620 PACKET_qXfer_libraries
);
11622 case TARGET_OBJECT_LIBRARIES_SVR4
:
11623 return remote_read_qxfer
11624 ("libraries-svr4", annex
, readbuf
, offset
, len
, xfered_len
,
11625 PACKET_qXfer_libraries_svr4
);
11627 case TARGET_OBJECT_MEMORY_MAP
:
11628 gdb_assert (annex
== NULL
);
11629 return remote_read_qxfer
11630 ("memory-map", annex
, readbuf
, offset
, len
, xfered_len
,
11631 PACKET_qXfer_memory_map
);
11633 case TARGET_OBJECT_OSDATA
:
11634 /* Should only get here if we're connected. */
11635 gdb_assert (rs
->remote_desc
);
11636 return remote_read_qxfer
11637 ("osdata", annex
, readbuf
, offset
, len
, xfered_len
,
11638 PACKET_qXfer_osdata
);
11640 case TARGET_OBJECT_THREADS
:
11641 gdb_assert (annex
== NULL
);
11642 return remote_read_qxfer
11643 ("threads", annex
, readbuf
, offset
, len
, xfered_len
,
11644 PACKET_qXfer_threads
);
11646 case TARGET_OBJECT_TRACEFRAME_INFO
:
11647 gdb_assert (annex
== NULL
);
11648 return remote_read_qxfer
11649 ("traceframe-info", annex
, readbuf
, offset
, len
, xfered_len
,
11650 PACKET_qXfer_traceframe_info
);
11652 case TARGET_OBJECT_FDPIC
:
11653 return remote_read_qxfer
11654 ("fdpic", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_fdpic
);
11656 case TARGET_OBJECT_OPENVMS_UIB
:
11657 return remote_read_qxfer
11658 ("uib", annex
, readbuf
, offset
, len
, xfered_len
, PACKET_qXfer_uib
);
11660 case TARGET_OBJECT_BTRACE
:
11661 return remote_read_qxfer
11662 ("btrace", annex
, readbuf
, offset
, len
, xfered_len
,
11663 PACKET_qXfer_btrace
);
11665 case TARGET_OBJECT_BTRACE_CONF
:
11666 return remote_read_qxfer
11667 ("btrace-conf", annex
, readbuf
, offset
, len
, xfered_len
,
11668 PACKET_qXfer_btrace_conf
);
11670 case TARGET_OBJECT_EXEC_FILE
:
11671 return remote_read_qxfer
11672 ("exec-file", annex
, readbuf
, offset
, len
, xfered_len
,
11673 PACKET_qXfer_exec_file
);
11676 return TARGET_XFER_E_IO
;
11679 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11680 large enough let the caller deal with it. */
11681 if (len
< get_remote_packet_size ())
11682 return TARGET_XFER_E_IO
;
11683 len
= get_remote_packet_size ();
11685 /* Except for querying the minimum buffer size, target must be open. */
11686 if (!rs
->remote_desc
)
11687 error (_("remote query is only available after target open"));
11689 gdb_assert (annex
!= NULL
);
11690 gdb_assert (readbuf
!= NULL
);
11692 p2
= rs
->buf
.data ();
11694 *p2
++ = query_type
;
11696 /* We used one buffer char for the remote protocol q command and
11697 another for the query type. As the remote protocol encapsulation
11698 uses 4 chars plus one extra in case we are debugging
11699 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11702 while (annex
[i
] && (i
< (get_remote_packet_size () - 8)))
11704 /* Bad caller may have sent forbidden characters. */
11705 gdb_assert (isprint (annex
[i
]) && annex
[i
] != '$' && annex
[i
] != '#');
11710 gdb_assert (annex
[i
] == '\0');
11712 i
= putpkt (rs
->buf
);
11714 return TARGET_XFER_E_IO
;
11717 strcpy ((char *) readbuf
, rs
->buf
.data ());
11719 *xfered_len
= strlen ((char *) readbuf
);
11720 return (*xfered_len
!= 0) ? TARGET_XFER_OK
: TARGET_XFER_EOF
;
11723 /* Implementation of to_get_memory_xfer_limit. */
11726 remote_target::get_memory_xfer_limit ()
11728 return get_memory_write_packet_size ();
11732 remote_target::search_memory (CORE_ADDR start_addr
, ULONGEST search_space_len
,
11733 const gdb_byte
*pattern
, ULONGEST pattern_len
,
11734 CORE_ADDR
*found_addrp
)
11736 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11737 struct remote_state
*rs
= get_remote_state ();
11738 int max_size
= get_memory_write_packet_size ();
11740 /* Number of packet bytes used to encode the pattern;
11741 this could be more than PATTERN_LEN due to escape characters. */
11742 int escaped_pattern_len
;
11743 /* Amount of pattern that was encodable in the packet. */
11744 int used_pattern_len
;
11747 ULONGEST found_addr
;
11749 auto read_memory
= [this] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
11751 return (target_read (this, TARGET_OBJECT_MEMORY
, NULL
, result
, addr
, len
)
11755 /* Don't go to the target if we don't have to. This is done before
11756 checking packet_support to avoid the possibility that a success for this
11757 edge case means the facility works in general. */
11758 if (pattern_len
> search_space_len
)
11760 if (pattern_len
== 0)
11762 *found_addrp
= start_addr
;
11766 /* If we already know the packet isn't supported, fall back to the simple
11767 way of searching memory. */
11769 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
11771 /* Target doesn't provided special support, fall back and use the
11772 standard support (copy memory and do the search here). */
11773 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
11774 pattern
, pattern_len
, found_addrp
);
11777 /* Make sure the remote is pointing at the right process. */
11778 set_general_process ();
11780 /* Insert header. */
11781 i
= snprintf (rs
->buf
.data (), max_size
,
11782 "qSearch:memory:%s;%s;",
11783 phex_nz (start_addr
, addr_size
),
11784 phex_nz (search_space_len
, sizeof (search_space_len
)));
11785 max_size
-= (i
+ 1);
11787 /* Escape as much data as fits into rs->buf. */
11788 escaped_pattern_len
=
11789 remote_escape_output (pattern
, pattern_len
, 1,
11790 (gdb_byte
*) rs
->buf
.data () + i
,
11791 &used_pattern_len
, max_size
);
11793 /* Bail if the pattern is too large. */
11794 if (used_pattern_len
!= pattern_len
)
11795 error (_("Pattern is too large to transmit to remote target."));
11797 if (putpkt_binary (rs
->buf
.data (), i
+ escaped_pattern_len
) < 0
11798 || getpkt (&rs
->buf
) < 0
11799 || m_features
.packet_ok (rs
->buf
, PACKET_qSearch_memory
) != PACKET_OK
)
11801 /* The request may not have worked because the command is not
11802 supported. If so, fall back to the simple way. */
11803 if (m_features
.packet_support (PACKET_qSearch_memory
) == PACKET_DISABLE
)
11805 return simple_search_memory (read_memory
, start_addr
, search_space_len
,
11806 pattern
, pattern_len
, found_addrp
);
11811 if (rs
->buf
[0] == '0')
11813 else if (rs
->buf
[0] == '1')
11816 if (rs
->buf
[1] != ',')
11817 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
11818 unpack_varlen_hex (&rs
->buf
[2], &found_addr
);
11819 *found_addrp
= found_addr
;
11822 error (_("Unknown qSearch:memory reply: %s"), rs
->buf
.data ());
11828 remote_target::rcmd (const char *command
, struct ui_file
*outbuf
)
11830 struct remote_state
*rs
= get_remote_state ();
11831 char *p
= rs
->buf
.data ();
11833 if (!rs
->remote_desc
)
11834 error (_("remote rcmd is only available after target open"));
11836 /* Send a NULL command across as an empty command. */
11837 if (command
== NULL
)
11840 /* The query prefix. */
11841 strcpy (rs
->buf
.data (), "qRcmd,");
11842 p
= strchr (rs
->buf
.data (), '\0');
11844 if ((strlen (rs
->buf
.data ()) + strlen (command
) * 2 + 8/*misc*/)
11845 > get_remote_packet_size ())
11846 error (_("\"monitor\" command ``%s'' is too long."), command
);
11848 /* Encode the actual command. */
11849 bin2hex ((const gdb_byte
*) command
, p
, strlen (command
));
11851 if (putpkt (rs
->buf
) < 0)
11852 error (_("Communication problem with target."));
11854 /* get/display the response */
11859 /* XXX - see also remote_get_noisy_reply(). */
11860 QUIT
; /* Allow user to bail out with ^C. */
11862 if (getpkt (&rs
->buf
) == -1)
11864 /* Timeout. Continue to (try to) read responses.
11865 This is better than stopping with an error, assuming the stub
11866 is still executing the (long) monitor command.
11867 If needed, the user can interrupt gdb using C-c, obtaining
11868 an effect similar to stop on timeout. */
11871 buf
= rs
->buf
.data ();
11872 if (buf
[0] == '\0')
11873 error (_("Target does not support this command."));
11874 if (buf
[0] == 'O' && buf
[1] != 'K')
11876 remote_console_output (buf
+ 1); /* 'O' message from stub. */
11879 if (strcmp (buf
, "OK") == 0)
11881 if (strlen (buf
) == 3 && buf
[0] == 'E'
11882 && isxdigit (buf
[1]) && isxdigit (buf
[2]))
11884 error (_("Protocol error with Rcmd"));
11886 for (p
= buf
; p
[0] != '\0' && p
[1] != '\0'; p
+= 2)
11888 char c
= (fromhex (p
[0]) << 4) + fromhex (p
[1]);
11890 gdb_putc (c
, outbuf
);
11896 std::vector
<mem_region
>
11897 remote_target::memory_map ()
11899 std::vector
<mem_region
> result
;
11900 gdb::optional
<gdb::char_vector
> text
11901 = target_read_stralloc (current_inferior ()->top_target (),
11902 TARGET_OBJECT_MEMORY_MAP
, NULL
);
11905 result
= parse_memory_map (text
->data ());
11910 /* Set of callbacks used to implement the 'maint packet' command. */
11912 struct cli_packet_command_callbacks
: public send_remote_packet_callbacks
11914 /* Called before the packet is sent. BUF is the packet content before
11915 the protocol specific prefix, suffix, and escaping is added. */
11917 void sending (gdb::array_view
<const char> &buf
) override
11919 gdb_puts ("sending: ");
11920 print_packet (buf
);
11924 /* Called with BUF, the reply from the remote target. */
11926 void received (gdb::array_view
<const char> &buf
) override
11928 gdb_puts ("received: \"");
11929 print_packet (buf
);
11935 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11936 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11939 print_packet (gdb::array_view
<const char> &buf
)
11943 for (int i
= 0; i
< buf
.size (); ++i
)
11945 gdb_byte c
= buf
[i
];
11947 gdb_putc (c
, &stb
);
11949 gdb_printf (&stb
, "\\x%02x", (unsigned char) c
);
11952 gdb_puts (stb
.string ().c_str ());
11956 /* See remote.h. */
11959 send_remote_packet (gdb::array_view
<const char> &buf
,
11960 send_remote_packet_callbacks
*callbacks
)
11962 if (buf
.size () == 0 || buf
.data ()[0] == '\0')
11963 error (_("a remote packet must not be empty"));
11965 remote_target
*remote
= get_current_remote_target ();
11966 if (remote
== nullptr)
11967 error (_("packets can only be sent to a remote target"));
11969 callbacks
->sending (buf
);
11971 remote
->putpkt_binary (buf
.data (), buf
.size ());
11972 remote_state
*rs
= remote
->get_remote_state ();
11973 int bytes
= remote
->getpkt (&rs
->buf
);
11976 error (_("error while fetching packet from remote target"));
11978 gdb::array_view
<const char> view (&rs
->buf
[0], bytes
);
11979 callbacks
->received (view
);
11982 /* Entry point for the 'maint packet' command. */
11985 cli_packet_command (const char *args
, int from_tty
)
11987 cli_packet_command_callbacks cb
;
11988 gdb::array_view
<const char> view
11989 = gdb::make_array_view (args
, args
== nullptr ? 0 : strlen (args
));
11990 send_remote_packet (view
, &cb
);
11994 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11996 static void display_thread_info (struct gdb_ext_thread_info
*info
);
11998 static void threadset_test_cmd (char *cmd
, int tty
);
12000 static void threadalive_test (char *cmd
, int tty
);
12002 static void threadlist_test_cmd (char *cmd
, int tty
);
12004 int get_and_display_threadinfo (threadref
*ref
);
12006 static void threadinfo_test_cmd (char *cmd
, int tty
);
12008 static int thread_display_step (threadref
*ref
, void *context
);
12010 static void threadlist_update_test_cmd (char *cmd
, int tty
);
12012 static void init_remote_threadtests (void);
12014 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12017 threadset_test_cmd (const char *cmd
, int tty
)
12019 int sample_thread
= SAMPLE_THREAD
;
12021 gdb_printf (_("Remote threadset test\n"));
12022 set_general_thread (sample_thread
);
12027 threadalive_test (const char *cmd
, int tty
)
12029 int sample_thread
= SAMPLE_THREAD
;
12030 int pid
= inferior_ptid
.pid ();
12031 ptid_t ptid
= ptid_t (pid
, sample_thread
, 0);
12033 if (remote_thread_alive (ptid
))
12034 gdb_printf ("PASS: Thread alive test\n");
12036 gdb_printf ("FAIL: Thread alive test\n");
12039 void output_threadid (char *title
, threadref
*ref
);
12042 output_threadid (char *title
, threadref
*ref
)
12046 pack_threadid (&hexid
[0], ref
); /* Convert thread id into hex. */
12048 gdb_printf ("%s %s\n", title
, (&hexid
[0]));
12052 threadlist_test_cmd (const char *cmd
, int tty
)
12055 threadref nextthread
;
12056 int done
, result_count
;
12057 threadref threadlist
[3];
12059 gdb_printf ("Remote Threadlist test\n");
12060 if (!remote_get_threadlist (startflag
, &nextthread
, 3, &done
,
12061 &result_count
, &threadlist
[0]))
12062 gdb_printf ("FAIL: threadlist test\n");
12065 threadref
*scan
= threadlist
;
12066 threadref
*limit
= scan
+ result_count
;
12068 while (scan
< limit
)
12069 output_threadid (" thread ", scan
++);
12074 display_thread_info (struct gdb_ext_thread_info
*info
)
12076 output_threadid ("Threadid: ", &info
->threadid
);
12077 gdb_printf ("Name: %s\n ", info
->shortname
);
12078 gdb_printf ("State: %s\n", info
->display
);
12079 gdb_printf ("other: %s\n\n", info
->more_display
);
12083 get_and_display_threadinfo (threadref
*ref
)
12087 struct gdb_ext_thread_info threadinfo
;
12089 set
= TAG_THREADID
| TAG_EXISTS
| TAG_THREADNAME
12090 | TAG_MOREDISPLAY
| TAG_DISPLAY
;
12091 if (0 != (result
= remote_get_threadinfo (ref
, set
, &threadinfo
)))
12092 display_thread_info (&threadinfo
);
12097 threadinfo_test_cmd (const char *cmd
, int tty
)
12099 int athread
= SAMPLE_THREAD
;
12103 int_to_threadref (&thread
, athread
);
12104 gdb_printf ("Remote Threadinfo test\n");
12105 if (!get_and_display_threadinfo (&thread
))
12106 gdb_printf ("FAIL cannot get thread info\n");
12110 thread_display_step (threadref
*ref
, void *context
)
12112 /* output_threadid(" threadstep ",ref); *//* simple test */
12113 return get_and_display_threadinfo (ref
);
12117 threadlist_update_test_cmd (const char *cmd
, int tty
)
12119 gdb_printf ("Remote Threadlist update test\n");
12120 remote_threadlist_iterator (thread_display_step
, 0, CRAZY_MAX_THREADS
);
12124 init_remote_threadtests (void)
12126 add_com ("tlist", class_obscure
, threadlist_test_cmd
,
12127 _("Fetch and print the remote list of "
12128 "thread identifiers, one pkt only."));
12129 add_com ("tinfo", class_obscure
, threadinfo_test_cmd
,
12130 _("Fetch and display info about one thread."));
12131 add_com ("tset", class_obscure
, threadset_test_cmd
,
12132 _("Test setting to a different thread."));
12133 add_com ("tupd", class_obscure
, threadlist_update_test_cmd
,
12134 _("Iterate through updating all remote thread info."));
12135 add_com ("talive", class_obscure
, threadalive_test
,
12136 _("Remote thread alive test."));
12141 /* Convert a thread ID to a string. */
12144 remote_target::pid_to_str (ptid_t ptid
)
12146 if (ptid
== null_ptid
)
12147 return normal_pid_to_str (ptid
);
12148 else if (ptid
.is_pid ())
12150 /* Printing an inferior target id. */
12152 /* When multi-process extensions are off, there's no way in the
12153 remote protocol to know the remote process id, if there's any
12154 at all. There's one exception --- when we're connected with
12155 target extended-remote, and we manually attached to a process
12156 with "attach PID". We don't record anywhere a flag that
12157 allows us to distinguish that case from the case of
12158 connecting with extended-remote and the stub already being
12159 attached to a process, and reporting yes to qAttached, hence
12160 no smart special casing here. */
12161 if (!m_features
.remote_multi_process_p ())
12162 return "Remote target";
12164 return normal_pid_to_str (ptid
);
12168 if (magic_null_ptid
== ptid
)
12169 return "Thread <main>";
12170 else if (m_features
.remote_multi_process_p ())
12171 if (ptid
.lwp () == 0)
12172 return normal_pid_to_str (ptid
);
12174 return string_printf ("Thread %d.%ld",
12175 ptid
.pid (), ptid
.lwp ());
12177 return string_printf ("Thread %ld", ptid
.lwp ());
12181 /* Get the address of the thread local variable in OBJFILE which is
12182 stored at OFFSET within the thread local storage for thread PTID. */
12185 remote_target::get_thread_local_address (ptid_t ptid
, CORE_ADDR lm
,
12188 if (m_features
.packet_support (PACKET_qGetTLSAddr
) != PACKET_DISABLE
)
12190 struct remote_state
*rs
= get_remote_state ();
12191 char *p
= rs
->buf
.data ();
12192 char *endp
= p
+ get_remote_packet_size ();
12193 enum packet_result result
;
12195 strcpy (p
, "qGetTLSAddr:");
12197 p
= write_ptid (p
, endp
, ptid
);
12199 p
+= hexnumstr (p
, offset
);
12201 p
+= hexnumstr (p
, lm
);
12206 result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTLSAddr
);
12207 if (result
== PACKET_OK
)
12211 unpack_varlen_hex (rs
->buf
.data (), &addr
);
12214 else if (result
== PACKET_UNKNOWN
)
12215 throw_error (TLS_GENERIC_ERROR
,
12216 _("Remote target doesn't support qGetTLSAddr packet"));
12218 throw_error (TLS_GENERIC_ERROR
,
12219 _("Remote target failed to process qGetTLSAddr request"));
12222 throw_error (TLS_GENERIC_ERROR
,
12223 _("TLS not supported or disabled on this target"));
12228 /* Provide thread local base, i.e. Thread Information Block address.
12229 Returns 1 if ptid is found and thread_local_base is non zero. */
12232 remote_target::get_tib_address (ptid_t ptid
, CORE_ADDR
*addr
)
12234 if (m_features
.packet_support (PACKET_qGetTIBAddr
) != PACKET_DISABLE
)
12236 struct remote_state
*rs
= get_remote_state ();
12237 char *p
= rs
->buf
.data ();
12238 char *endp
= p
+ get_remote_packet_size ();
12239 enum packet_result result
;
12241 strcpy (p
, "qGetTIBAddr:");
12243 p
= write_ptid (p
, endp
, ptid
);
12248 result
= m_features
.packet_ok (rs
->buf
, PACKET_qGetTIBAddr
);
12249 if (result
== PACKET_OK
)
12252 unpack_varlen_hex (rs
->buf
.data (), &val
);
12254 *addr
= (CORE_ADDR
) val
;
12257 else if (result
== PACKET_UNKNOWN
)
12258 error (_("Remote target doesn't support qGetTIBAddr packet"));
12260 error (_("Remote target failed to process qGetTIBAddr request"));
12263 error (_("qGetTIBAddr not supported or disabled on this target"));
12268 /* Support for inferring a target description based on the current
12269 architecture and the size of a 'g' packet. While the 'g' packet
12270 can have any size (since optional registers can be left off the
12271 end), some sizes are easily recognizable given knowledge of the
12272 approximate architecture. */
12274 struct remote_g_packet_guess
12276 remote_g_packet_guess (int bytes_
, const struct target_desc
*tdesc_
)
12283 const struct target_desc
*tdesc
;
12286 struct remote_g_packet_data
12288 std::vector
<remote_g_packet_guess
> guesses
;
12291 static const registry
<gdbarch
>::key
<struct remote_g_packet_data
>
12292 remote_g_packet_data_handle
;
12294 static struct remote_g_packet_data
*
12295 get_g_packet_data (struct gdbarch
*gdbarch
)
12297 struct remote_g_packet_data
*data
12298 = remote_g_packet_data_handle
.get (gdbarch
);
12299 if (data
== nullptr)
12300 data
= remote_g_packet_data_handle
.emplace (gdbarch
);
12305 register_remote_g_packet_guess (struct gdbarch
*gdbarch
, int bytes
,
12306 const struct target_desc
*tdesc
)
12308 struct remote_g_packet_data
*data
= get_g_packet_data (gdbarch
);
12310 gdb_assert (tdesc
!= NULL
);
12312 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12313 if (guess
.bytes
== bytes
)
12314 internal_error (_("Duplicate g packet description added for size %d"),
12317 data
->guesses
.emplace_back (bytes
, tdesc
);
12320 /* Return true if remote_read_description would do anything on this target
12321 and architecture, false otherwise. */
12324 remote_read_description_p (struct target_ops
*target
)
12326 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12328 return !data
->guesses
.empty ();
12331 const struct target_desc
*
12332 remote_target::read_description ()
12334 remote_g_packet_data
*data
= get_g_packet_data (current_inferior ()->arch ());
12336 /* Do not try this during initial connection, when we do not know
12337 whether there is a running but stopped thread. */
12338 if (!target_has_execution () || inferior_ptid
== null_ptid
)
12339 return beneath ()->read_description ();
12341 if (!data
->guesses
.empty ())
12343 int bytes
= send_g_packet ();
12345 for (const remote_g_packet_guess
&guess
: data
->guesses
)
12346 if (guess
.bytes
== bytes
)
12347 return guess
.tdesc
;
12349 /* We discard the g packet. A minor optimization would be to
12350 hold on to it, and fill the register cache once we have selected
12351 an architecture, but it's too tricky to do safely. */
12354 return beneath ()->read_description ();
12357 /* Remote file transfer support. This is host-initiated I/O, not
12358 target-initiated; for target-initiated, see remote-fileio.c. */
12360 /* If *LEFT is at least the length of STRING, copy STRING to
12361 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12362 decrease *LEFT. Otherwise raise an error. */
12365 remote_buffer_add_string (char **buffer
, int *left
, const char *string
)
12367 int len
= strlen (string
);
12370 error (_("Packet too long for target."));
12372 memcpy (*buffer
, string
, len
);
12376 /* NUL-terminate the buffer as a convenience, if there is
12382 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12383 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12384 decrease *LEFT. Otherwise raise an error. */
12387 remote_buffer_add_bytes (char **buffer
, int *left
, const gdb_byte
*bytes
,
12390 if (2 * len
> *left
)
12391 error (_("Packet too long for target."));
12393 bin2hex (bytes
, *buffer
, len
);
12394 *buffer
+= 2 * len
;
12397 /* NUL-terminate the buffer as a convenience, if there is
12403 /* If *LEFT is large enough, convert VALUE to hex and add it to
12404 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12405 decrease *LEFT. Otherwise raise an error. */
12408 remote_buffer_add_int (char **buffer
, int *left
, ULONGEST value
)
12410 int len
= hexnumlen (value
);
12413 error (_("Packet too long for target."));
12415 hexnumstr (*buffer
, value
);
12419 /* NUL-terminate the buffer as a convenience, if there is
12425 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12426 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12427 was included, and *ATTACHMENT to point to the start of the annex
12428 if any. The length of the packet isn't needed here; there may
12429 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12431 Return 0 if the packet could be parsed, -1 if it could not. If
12432 -1 is returned, the other variables may not be initialized. */
12435 remote_hostio_parse_result (const char *buffer
, int *retcode
,
12436 fileio_error
*remote_errno
, const char **attachment
)
12440 *remote_errno
= FILEIO_SUCCESS
;
12441 *attachment
= NULL
;
12443 if (buffer
[0] != 'F')
12447 *retcode
= strtol (&buffer
[1], &p
, 16);
12448 if (errno
!= 0 || p
== &buffer
[1])
12451 /* Check for ",errno". */
12455 *remote_errno
= (fileio_error
) strtol (p
+ 1, &p2
, 16);
12456 if (errno
!= 0 || p
+ 1 == p2
)
12461 /* Check for ";attachment". If there is no attachment, the
12462 packet should end here. */
12465 *attachment
= p
+ 1;
12468 else if (*p
== '\0')
12474 /* Send a prepared I/O packet to the target and read its response.
12475 The prepared packet is in the global RS->BUF before this function
12476 is called, and the answer is there when we return.
12478 COMMAND_BYTES is the length of the request to send, which may include
12479 binary data. WHICH_PACKET is the packet configuration to check
12480 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12481 is set to the error number and -1 is returned. Otherwise the value
12482 returned by the function is returned.
12484 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12485 attachment is expected; an error will be reported if there's a
12486 mismatch. If one is found, *ATTACHMENT will be set to point into
12487 the packet buffer and *ATTACHMENT_LEN will be set to the
12488 attachment's length. */
12491 remote_target::remote_hostio_send_command (int command_bytes
, int which_packet
,
12492 fileio_error
*remote_errno
, const char **attachment
,
12493 int *attachment_len
)
12495 struct remote_state
*rs
= get_remote_state ();
12496 int ret
, bytes_read
;
12497 const char *attachment_tmp
;
12499 if (m_features
.packet_support (which_packet
) == PACKET_DISABLE
)
12501 *remote_errno
= FILEIO_ENOSYS
;
12505 putpkt_binary (rs
->buf
.data (), command_bytes
);
12506 bytes_read
= getpkt (&rs
->buf
);
12508 /* If it timed out, something is wrong. Don't try to parse the
12510 if (bytes_read
< 0)
12512 *remote_errno
= FILEIO_EINVAL
;
12516 switch (m_features
.packet_ok (rs
->buf
, which_packet
))
12519 *remote_errno
= FILEIO_EINVAL
;
12521 case PACKET_UNKNOWN
:
12522 *remote_errno
= FILEIO_ENOSYS
;
12528 if (remote_hostio_parse_result (rs
->buf
.data (), &ret
, remote_errno
,
12531 *remote_errno
= FILEIO_EINVAL
;
12535 /* Make sure we saw an attachment if and only if we expected one. */
12536 if ((attachment_tmp
== NULL
&& attachment
!= NULL
)
12537 || (attachment_tmp
!= NULL
&& attachment
== NULL
))
12539 *remote_errno
= FILEIO_EINVAL
;
12543 /* If an attachment was found, it must point into the packet buffer;
12544 work out how many bytes there were. */
12545 if (attachment_tmp
!= NULL
)
12547 *attachment
= attachment_tmp
;
12548 *attachment_len
= bytes_read
- (*attachment
- rs
->buf
.data ());
12554 /* See declaration.h. */
12557 readahead_cache::invalidate ()
12562 /* See declaration.h. */
12565 readahead_cache::invalidate_fd (int fd
)
12567 if (this->fd
== fd
)
12571 /* Set the filesystem remote_hostio functions that take FILENAME
12572 arguments will use. Return 0 on success, or -1 if an error
12573 occurs (and set *REMOTE_ERRNO). */
12576 remote_target::remote_hostio_set_filesystem (struct inferior
*inf
,
12577 fileio_error
*remote_errno
)
12579 struct remote_state
*rs
= get_remote_state ();
12580 int required_pid
= (inf
== NULL
|| inf
->fake_pid_p
) ? 0 : inf
->pid
;
12581 char *p
= rs
->buf
.data ();
12582 int left
= get_remote_packet_size () - 1;
12586 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12589 if (rs
->fs_pid
!= -1 && required_pid
== rs
->fs_pid
)
12592 remote_buffer_add_string (&p
, &left
, "vFile:setfs:");
12594 xsnprintf (arg
, sizeof (arg
), "%x", required_pid
);
12595 remote_buffer_add_string (&p
, &left
, arg
);
12597 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_setfs
,
12598 remote_errno
, NULL
, NULL
);
12600 if (m_features
.packet_support (PACKET_vFile_setfs
) == PACKET_DISABLE
)
12604 rs
->fs_pid
= required_pid
;
12609 /* Implementation of to_fileio_open. */
12612 remote_target::remote_hostio_open (inferior
*inf
, const char *filename
,
12613 int flags
, int mode
, int warn_if_slow
,
12614 fileio_error
*remote_errno
)
12616 struct remote_state
*rs
= get_remote_state ();
12617 char *p
= rs
->buf
.data ();
12618 int left
= get_remote_packet_size () - 1;
12622 static int warning_issued
= 0;
12624 gdb_printf (_("Reading %s from remote target...\n"),
12627 if (!warning_issued
)
12629 warning (_("File transfers from remote targets can be slow."
12630 " Use \"set sysroot\" to access files locally"
12632 warning_issued
= 1;
12636 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12639 remote_buffer_add_string (&p
, &left
, "vFile:open:");
12641 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12642 strlen (filename
));
12643 remote_buffer_add_string (&p
, &left
, ",");
12645 remote_buffer_add_int (&p
, &left
, flags
);
12646 remote_buffer_add_string (&p
, &left
, ",");
12648 remote_buffer_add_int (&p
, &left
, mode
);
12650 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_open
,
12651 remote_errno
, NULL
, NULL
);
12655 remote_target::fileio_open (struct inferior
*inf
, const char *filename
,
12656 int flags
, int mode
, int warn_if_slow
,
12657 fileio_error
*remote_errno
)
12659 return remote_hostio_open (inf
, filename
, flags
, mode
, warn_if_slow
,
12663 /* Implementation of to_fileio_pwrite. */
12666 remote_target::remote_hostio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12667 ULONGEST offset
, fileio_error
*remote_errno
)
12669 struct remote_state
*rs
= get_remote_state ();
12670 char *p
= rs
->buf
.data ();
12671 int left
= get_remote_packet_size ();
12674 rs
->readahead_cache
.invalidate_fd (fd
);
12676 remote_buffer_add_string (&p
, &left
, "vFile:pwrite:");
12678 remote_buffer_add_int (&p
, &left
, fd
);
12679 remote_buffer_add_string (&p
, &left
, ",");
12681 remote_buffer_add_int (&p
, &left
, offset
);
12682 remote_buffer_add_string (&p
, &left
, ",");
12684 p
+= remote_escape_output (write_buf
, len
, 1, (gdb_byte
*) p
, &out_len
,
12685 (get_remote_packet_size ()
12686 - (p
- rs
->buf
.data ())));
12688 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pwrite
,
12689 remote_errno
, NULL
, NULL
);
12693 remote_target::fileio_pwrite (int fd
, const gdb_byte
*write_buf
, int len
,
12694 ULONGEST offset
, fileio_error
*remote_errno
)
12696 return remote_hostio_pwrite (fd
, write_buf
, len
, offset
, remote_errno
);
12699 /* Helper for the implementation of to_fileio_pread. Read the file
12700 from the remote side with vFile:pread. */
12703 remote_target::remote_hostio_pread_vFile (int fd
, gdb_byte
*read_buf
, int len
,
12704 ULONGEST offset
, fileio_error
*remote_errno
)
12706 struct remote_state
*rs
= get_remote_state ();
12707 char *p
= rs
->buf
.data ();
12708 const char *attachment
;
12709 int left
= get_remote_packet_size ();
12710 int ret
, attachment_len
;
12713 remote_buffer_add_string (&p
, &left
, "vFile:pread:");
12715 remote_buffer_add_int (&p
, &left
, fd
);
12716 remote_buffer_add_string (&p
, &left
, ",");
12718 remote_buffer_add_int (&p
, &left
, len
);
12719 remote_buffer_add_string (&p
, &left
, ",");
12721 remote_buffer_add_int (&p
, &left
, offset
);
12723 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_pread
,
12724 remote_errno
, &attachment
,
12730 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12732 if (read_len
!= ret
)
12733 error (_("Read returned %d, but %d bytes."), ret
, (int) read_len
);
12738 /* See declaration.h. */
12741 readahead_cache::pread (int fd
, gdb_byte
*read_buf
, size_t len
,
12745 && this->offset
<= offset
12746 && offset
< this->offset
+ this->buf
.size ())
12748 ULONGEST max
= this->offset
+ this->buf
.size ();
12750 if (offset
+ len
> max
)
12751 len
= max
- offset
;
12753 memcpy (read_buf
, &this->buf
[offset
- this->offset
], len
);
12760 /* Implementation of to_fileio_pread. */
12763 remote_target::remote_hostio_pread (int fd
, gdb_byte
*read_buf
, int len
,
12764 ULONGEST offset
, fileio_error
*remote_errno
)
12767 struct remote_state
*rs
= get_remote_state ();
12768 readahead_cache
*cache
= &rs
->readahead_cache
;
12770 ret
= cache
->pread (fd
, read_buf
, len
, offset
);
12773 cache
->hit_count
++;
12775 remote_debug_printf ("readahead cache hit %s",
12776 pulongest (cache
->hit_count
));
12780 cache
->miss_count
++;
12782 remote_debug_printf ("readahead cache miss %s",
12783 pulongest (cache
->miss_count
));
12786 cache
->offset
= offset
;
12787 cache
->buf
.resize (get_remote_packet_size ());
12789 ret
= remote_hostio_pread_vFile (cache
->fd
, &cache
->buf
[0],
12790 cache
->buf
.size (),
12791 cache
->offset
, remote_errno
);
12794 cache
->invalidate_fd (fd
);
12798 cache
->buf
.resize (ret
);
12799 return cache
->pread (fd
, read_buf
, len
, offset
);
12803 remote_target::fileio_pread (int fd
, gdb_byte
*read_buf
, int len
,
12804 ULONGEST offset
, fileio_error
*remote_errno
)
12806 return remote_hostio_pread (fd
, read_buf
, len
, offset
, remote_errno
);
12809 /* Implementation of to_fileio_close. */
12812 remote_target::remote_hostio_close (int fd
, fileio_error
*remote_errno
)
12814 struct remote_state
*rs
= get_remote_state ();
12815 char *p
= rs
->buf
.data ();
12816 int left
= get_remote_packet_size () - 1;
12818 rs
->readahead_cache
.invalidate_fd (fd
);
12820 remote_buffer_add_string (&p
, &left
, "vFile:close:");
12822 remote_buffer_add_int (&p
, &left
, fd
);
12824 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_close
,
12825 remote_errno
, NULL
, NULL
);
12829 remote_target::fileio_close (int fd
, fileio_error
*remote_errno
)
12831 return remote_hostio_close (fd
, remote_errno
);
12834 /* Implementation of to_fileio_unlink. */
12837 remote_target::remote_hostio_unlink (inferior
*inf
, const char *filename
,
12838 fileio_error
*remote_errno
)
12840 struct remote_state
*rs
= get_remote_state ();
12841 char *p
= rs
->buf
.data ();
12842 int left
= get_remote_packet_size () - 1;
12844 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12847 remote_buffer_add_string (&p
, &left
, "vFile:unlink:");
12849 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12850 strlen (filename
));
12852 return remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_unlink
,
12853 remote_errno
, NULL
, NULL
);
12857 remote_target::fileio_unlink (struct inferior
*inf
, const char *filename
,
12858 fileio_error
*remote_errno
)
12860 return remote_hostio_unlink (inf
, filename
, remote_errno
);
12863 /* Implementation of to_fileio_readlink. */
12865 gdb::optional
<std::string
>
12866 remote_target::fileio_readlink (struct inferior
*inf
, const char *filename
,
12867 fileio_error
*remote_errno
)
12869 struct remote_state
*rs
= get_remote_state ();
12870 char *p
= rs
->buf
.data ();
12871 const char *attachment
;
12872 int left
= get_remote_packet_size ();
12873 int len
, attachment_len
;
12876 if (remote_hostio_set_filesystem (inf
, remote_errno
) != 0)
12879 remote_buffer_add_string (&p
, &left
, "vFile:readlink:");
12881 remote_buffer_add_bytes (&p
, &left
, (const gdb_byte
*) filename
,
12882 strlen (filename
));
12884 len
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_readlink
,
12885 remote_errno
, &attachment
,
12891 std::string
ret (len
, '\0');
12893 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12894 (gdb_byte
*) &ret
[0], len
);
12895 if (read_len
!= len
)
12896 error (_("Readlink returned %d, but %d bytes."), len
, read_len
);
12901 /* Implementation of to_fileio_fstat. */
12904 remote_target::fileio_fstat (int fd
, struct stat
*st
, fileio_error
*remote_errno
)
12906 struct remote_state
*rs
= get_remote_state ();
12907 char *p
= rs
->buf
.data ();
12908 int left
= get_remote_packet_size ();
12909 int attachment_len
, ret
;
12910 const char *attachment
;
12911 struct fio_stat fst
;
12914 remote_buffer_add_string (&p
, &left
, "vFile:fstat:");
12916 remote_buffer_add_int (&p
, &left
, fd
);
12918 ret
= remote_hostio_send_command (p
- rs
->buf
.data (), PACKET_vFile_fstat
,
12919 remote_errno
, &attachment
,
12923 if (*remote_errno
!= FILEIO_ENOSYS
)
12926 /* Strictly we should return -1, ENOSYS here, but when
12927 "set sysroot remote:" was implemented in August 2008
12928 BFD's need for a stat function was sidestepped with
12929 this hack. This was not remedied until March 2015
12930 so we retain the previous behavior to avoid breaking
12933 Note that the memset is a March 2015 addition; older
12934 GDBs set st_size *and nothing else* so the structure
12935 would have garbage in all other fields. This might
12936 break something but retaining the previous behavior
12937 here would be just too wrong. */
12939 memset (st
, 0, sizeof (struct stat
));
12940 st
->st_size
= INT_MAX
;
12944 read_len
= remote_unescape_input ((gdb_byte
*) attachment
, attachment_len
,
12945 (gdb_byte
*) &fst
, sizeof (fst
));
12947 if (read_len
!= ret
)
12948 error (_("vFile:fstat returned %d, but %d bytes."), ret
, read_len
);
12950 if (read_len
!= sizeof (fst
))
12951 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12952 read_len
, (int) sizeof (fst
));
12954 remote_fileio_to_host_stat (&fst
, st
);
12959 /* Implementation of to_filesystem_is_local. */
12962 remote_target::filesystem_is_local ()
12964 /* Valgrind GDB presents itself as a remote target but works
12965 on the local filesystem: it does not implement remote get
12966 and users are not expected to set a sysroot. To handle
12967 this case we treat the remote filesystem as local if the
12968 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12969 does not support vFile:open. */
12970 if (gdb_sysroot
== TARGET_SYSROOT_PREFIX
)
12972 packet_support ps
= m_features
.packet_support (PACKET_vFile_open
);
12974 if (ps
== PACKET_SUPPORT_UNKNOWN
)
12977 fileio_error remote_errno
;
12979 /* Try opening a file to probe support. The supplied
12980 filename is irrelevant, we only care about whether
12981 the stub recognizes the packet or not. */
12982 fd
= remote_hostio_open (NULL
, "just probing",
12983 FILEIO_O_RDONLY
, 0700, 0,
12987 remote_hostio_close (fd
, &remote_errno
);
12989 ps
= m_features
.packet_support (PACKET_vFile_open
);
12992 if (ps
== PACKET_DISABLE
)
12994 static int warning_issued
= 0;
12996 if (!warning_issued
)
12998 warning (_("remote target does not support file"
12999 " transfer, attempting to access files"
13000 " from local filesystem."));
13001 warning_issued
= 1;
13012 remote_hostio_error (fileio_error errnum
)
13014 int host_error
= fileio_error_to_host (errnum
);
13016 if (host_error
== -1)
13017 error (_("Unknown remote I/O error %d"), errnum
);
13019 error (_("Remote I/O error: %s"), safe_strerror (host_error
));
13022 /* A RAII wrapper around a remote file descriptor. */
13024 class scoped_remote_fd
13027 scoped_remote_fd (remote_target
*remote
, int fd
)
13028 : m_remote (remote
), m_fd (fd
)
13032 ~scoped_remote_fd ()
13038 fileio_error remote_errno
;
13039 m_remote
->remote_hostio_close (m_fd
, &remote_errno
);
13043 /* Swallow exception before it escapes the dtor. If
13044 something goes wrong, likely the connection is gone,
13045 and there's nothing else that can be done. */
13050 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd
);
13052 /* Release ownership of the file descriptor, and return it. */
13053 ATTRIBUTE_UNUSED_RESULT
int release () noexcept
13060 /* Return the owned file descriptor. */
13061 int get () const noexcept
13067 /* The remote target. */
13068 remote_target
*m_remote
;
13070 /* The owned remote I/O file descriptor. */
13075 remote_file_put (const char *local_file
, const char *remote_file
, int from_tty
)
13077 remote_target
*remote
= get_current_remote_target ();
13079 if (remote
== nullptr)
13080 error (_("command can only be used with remote target"));
13082 remote
->remote_file_put (local_file
, remote_file
, from_tty
);
13086 remote_target::remote_file_put (const char *local_file
, const char *remote_file
,
13089 int retcode
, bytes
, io_size
;
13090 fileio_error remote_errno
;
13091 int bytes_in_buffer
;
13095 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "rb");
13097 perror_with_name (local_file
);
13099 scoped_remote_fd fd
13100 (this, remote_hostio_open (NULL
,
13101 remote_file
, (FILEIO_O_WRONLY
| FILEIO_O_CREAT
13103 0700, 0, &remote_errno
));
13104 if (fd
.get () == -1)
13105 remote_hostio_error (remote_errno
);
13107 /* Send up to this many bytes at once. They won't all fit in the
13108 remote packet limit, so we'll transfer slightly fewer. */
13109 io_size
= get_remote_packet_size ();
13110 gdb::byte_vector
buffer (io_size
);
13112 bytes_in_buffer
= 0;
13115 while (bytes_in_buffer
|| !saw_eof
)
13119 bytes
= fread (buffer
.data () + bytes_in_buffer
, 1,
13120 io_size
- bytes_in_buffer
,
13124 if (ferror (file
.get ()))
13125 error (_("Error reading %s."), local_file
);
13128 /* EOF. Unless there is something still in the
13129 buffer from the last iteration, we are done. */
13131 if (bytes_in_buffer
== 0)
13139 bytes
+= bytes_in_buffer
;
13140 bytes_in_buffer
= 0;
13142 retcode
= remote_hostio_pwrite (fd
.get (), buffer
.data (), bytes
,
13143 offset
, &remote_errno
);
13146 remote_hostio_error (remote_errno
);
13147 else if (retcode
== 0)
13148 error (_("Remote write of %d bytes returned 0!"), bytes
);
13149 else if (retcode
< bytes
)
13151 /* Short write. Save the rest of the read data for the next
13153 bytes_in_buffer
= bytes
- retcode
;
13154 memmove (buffer
.data (), buffer
.data () + retcode
, bytes_in_buffer
);
13160 if (remote_hostio_close (fd
.release (), &remote_errno
))
13161 remote_hostio_error (remote_errno
);
13164 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file
);
13168 remote_file_get (const char *remote_file
, const char *local_file
, int from_tty
)
13170 remote_target
*remote
= get_current_remote_target ();
13172 if (remote
== nullptr)
13173 error (_("command can only be used with remote target"));
13175 remote
->remote_file_get (remote_file
, local_file
, from_tty
);
13179 remote_target::remote_file_get (const char *remote_file
, const char *local_file
,
13182 fileio_error remote_errno
;
13183 int bytes
, io_size
;
13186 scoped_remote_fd fd
13187 (this, remote_hostio_open (NULL
,
13188 remote_file
, FILEIO_O_RDONLY
, 0, 0,
13190 if (fd
.get () == -1)
13191 remote_hostio_error (remote_errno
);
13193 gdb_file_up file
= gdb_fopen_cloexec (local_file
, "wb");
13195 perror_with_name (local_file
);
13197 /* Send up to this many bytes at once. They won't all fit in the
13198 remote packet limit, so we'll transfer slightly fewer. */
13199 io_size
= get_remote_packet_size ();
13200 gdb::byte_vector
buffer (io_size
);
13205 bytes
= remote_hostio_pread (fd
.get (), buffer
.data (), io_size
, offset
,
13208 /* Success, but no bytes, means end-of-file. */
13211 remote_hostio_error (remote_errno
);
13215 bytes
= fwrite (buffer
.data (), 1, bytes
, file
.get ());
13217 perror_with_name (local_file
);
13220 if (remote_hostio_close (fd
.release (), &remote_errno
))
13221 remote_hostio_error (remote_errno
);
13224 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file
);
13228 remote_file_delete (const char *remote_file
, int from_tty
)
13230 remote_target
*remote
= get_current_remote_target ();
13232 if (remote
== nullptr)
13233 error (_("command can only be used with remote target"));
13235 remote
->remote_file_delete (remote_file
, from_tty
);
13239 remote_target::remote_file_delete (const char *remote_file
, int from_tty
)
13242 fileio_error remote_errno
;
13244 retcode
= remote_hostio_unlink (NULL
, remote_file
, &remote_errno
);
13246 remote_hostio_error (remote_errno
);
13249 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file
);
13253 remote_put_command (const char *args
, int from_tty
)
13256 error_no_arg (_("file to put"));
13258 gdb_argv
argv (args
);
13259 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13260 error (_("Invalid parameters to remote put"));
13262 remote_file_put (argv
[0], argv
[1], from_tty
);
13266 remote_get_command (const char *args
, int from_tty
)
13269 error_no_arg (_("file to get"));
13271 gdb_argv
argv (args
);
13272 if (argv
[0] == NULL
|| argv
[1] == NULL
|| argv
[2] != NULL
)
13273 error (_("Invalid parameters to remote get"));
13275 remote_file_get (argv
[0], argv
[1], from_tty
);
13279 remote_delete_command (const char *args
, int from_tty
)
13282 error_no_arg (_("file to delete"));
13284 gdb_argv
argv (args
);
13285 if (argv
[0] == NULL
|| argv
[1] != NULL
)
13286 error (_("Invalid parameters to remote delete"));
13288 remote_file_delete (argv
[0], from_tty
);
13292 remote_target::can_execute_reverse ()
13294 if (m_features
.packet_support (PACKET_bs
) == PACKET_ENABLE
13295 || m_features
.packet_support (PACKET_bc
) == PACKET_ENABLE
)
13302 remote_target::supports_non_stop ()
13308 remote_target::supports_disable_randomization ()
13310 /* Only supported in extended mode. */
13315 remote_target::supports_multi_process ()
13317 return m_features
.remote_multi_process_p ();
13321 remote_target::remote_supports_cond_tracepoints ()
13323 return (m_features
.packet_support (PACKET_ConditionalTracepoints
)
13328 remote_target::supports_evaluation_of_breakpoint_conditions ()
13330 return (m_features
.packet_support (PACKET_ConditionalBreakpoints
)
13335 remote_target::remote_supports_fast_tracepoints ()
13337 return m_features
.packet_support (PACKET_FastTracepoints
) == PACKET_ENABLE
;
13341 remote_target::remote_supports_static_tracepoints ()
13343 return m_features
.packet_support (PACKET_StaticTracepoints
) == PACKET_ENABLE
;
13347 remote_target::remote_supports_install_in_trace ()
13349 return m_features
.packet_support (PACKET_InstallInTrace
) == PACKET_ENABLE
;
13353 remote_target::supports_enable_disable_tracepoint ()
13355 return (m_features
.packet_support (PACKET_EnableDisableTracepoints_feature
)
13360 remote_target::supports_string_tracing ()
13362 return m_features
.packet_support (PACKET_tracenz_feature
) == PACKET_ENABLE
;
13366 remote_target::can_run_breakpoint_commands ()
13368 return m_features
.packet_support (PACKET_BreakpointCommands
) == PACKET_ENABLE
;
13372 remote_target::trace_init ()
13374 struct remote_state
*rs
= get_remote_state ();
13377 remote_get_noisy_reply ();
13378 if (strcmp (rs
->buf
.data (), "OK") != 0)
13379 error (_("Target does not support this command."));
13382 /* Recursive routine to walk through command list including loops, and
13383 download packets for each command. */
13386 remote_target::remote_download_command_source (int num
, ULONGEST addr
,
13387 struct command_line
*cmds
)
13389 struct remote_state
*rs
= get_remote_state ();
13390 struct command_line
*cmd
;
13392 for (cmd
= cmds
; cmd
; cmd
= cmd
->next
)
13394 QUIT
; /* Allow user to bail out with ^C. */
13395 strcpy (rs
->buf
.data (), "QTDPsrc:");
13396 encode_source_string (num
, addr
, "cmd", cmd
->line
,
13397 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13398 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13400 remote_get_noisy_reply ();
13401 if (strcmp (rs
->buf
.data (), "OK"))
13402 warning (_("Target does not support source download."));
13404 if (cmd
->control_type
== while_control
13405 || cmd
->control_type
== while_stepping_control
)
13407 remote_download_command_source (num
, addr
, cmd
->body_list_0
.get ());
13409 QUIT
; /* Allow user to bail out with ^C. */
13410 strcpy (rs
->buf
.data (), "QTDPsrc:");
13411 encode_source_string (num
, addr
, "cmd", "end",
13412 rs
->buf
.data () + strlen (rs
->buf
.data ()),
13413 rs
->buf
.size () - strlen (rs
->buf
.data ()));
13415 remote_get_noisy_reply ();
13416 if (strcmp (rs
->buf
.data (), "OK"))
13417 warning (_("Target does not support source download."));
13423 remote_target::download_tracepoint (struct bp_location
*loc
)
13427 std::vector
<std::string
> tdp_actions
;
13428 std::vector
<std::string
> stepping_actions
;
13430 struct breakpoint
*b
= loc
->owner
;
13431 tracepoint
*t
= gdb::checked_static_cast
<tracepoint
*> (b
);
13432 struct remote_state
*rs
= get_remote_state ();
13434 const char *err_msg
= _("Tracepoint packet too large for target.");
13437 /* We use a buffer other than rs->buf because we'll build strings
13438 across multiple statements, and other statements in between could
13440 gdb::char_vector
buf (get_remote_packet_size ());
13442 encode_actions_rsp (loc
, &tdp_actions
, &stepping_actions
);
13444 tpaddr
= loc
->address
;
13445 strcpy (addrbuf
, phex (tpaddr
, sizeof (CORE_ADDR
)));
13446 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:%x:%s:%c:%lx:%x",
13447 b
->number
, addrbuf
, /* address */
13448 (b
->enable_state
== bp_enabled
? 'E' : 'D'),
13449 t
->step_count
, t
->pass_count
);
13451 if (ret
< 0 || ret
>= buf
.size ())
13452 error ("%s", err_msg
);
13454 /* Fast tracepoints are mostly handled by the target, but we can
13455 tell the target how big of an instruction block should be moved
13457 if (b
->type
== bp_fast_tracepoint
)
13459 /* Only test for support at download time; we may not know
13460 target capabilities at definition time. */
13461 if (remote_supports_fast_tracepoints ())
13463 if (gdbarch_fast_tracepoint_valid_at (loc
->gdbarch
, tpaddr
,
13466 size_left
= buf
.size () - strlen (buf
.data ());
13467 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13469 gdb_insn_length (loc
->gdbarch
, tpaddr
));
13471 if (ret
< 0 || ret
>= size_left
)
13472 error ("%s", err_msg
);
13475 /* If it passed validation at definition but fails now,
13476 something is very wrong. */
13477 internal_error (_("Fast tracepoint not valid during download"));
13480 /* Fast tracepoints are functionally identical to regular
13481 tracepoints, so don't take lack of support as a reason to
13482 give up on the trace run. */
13483 warning (_("Target does not support fast tracepoints, "
13484 "downloading %d as regular tracepoint"), b
->number
);
13486 else if (b
->type
== bp_static_tracepoint
13487 || b
->type
== bp_static_marker_tracepoint
)
13489 /* Only test for support at download time; we may not know
13490 target capabilities at definition time. */
13491 if (remote_supports_static_tracepoints ())
13493 struct static_tracepoint_marker marker
;
13495 if (target_static_tracepoint_marker_at (tpaddr
, &marker
))
13497 size_left
= buf
.size () - strlen (buf
.data ());
13498 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13501 if (ret
< 0 || ret
>= size_left
)
13502 error ("%s", err_msg
);
13505 error (_("Static tracepoint not valid during download"));
13508 /* Fast tracepoints are functionally identical to regular
13509 tracepoints, so don't take lack of support as a reason
13510 to give up on the trace run. */
13511 error (_("Target does not support static tracepoints"));
13513 /* If the tracepoint has a conditional, make it into an agent
13514 expression and append to the definition. */
13517 /* Only test support at download time, we may not know target
13518 capabilities at definition time. */
13519 if (remote_supports_cond_tracepoints ())
13521 agent_expr_up aexpr
= gen_eval_for_expr (tpaddr
,
13524 size_left
= buf
.size () - strlen (buf
.data ());
13526 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13527 size_left
, ":X%x,", (int) aexpr
->buf
.size ());
13529 if (ret
< 0 || ret
>= size_left
)
13530 error ("%s", err_msg
);
13532 size_left
= buf
.size () - strlen (buf
.data ());
13534 /* Two bytes to encode each aexpr byte, plus the terminating
13536 if (aexpr
->buf
.size () * 2 + 1 > size_left
)
13537 error ("%s", err_msg
);
13539 pkt
= buf
.data () + strlen (buf
.data ());
13541 for (int ndx
= 0; ndx
< aexpr
->buf
.size (); ++ndx
)
13542 pkt
= pack_hex_byte (pkt
, aexpr
->buf
[ndx
]);
13546 warning (_("Target does not support conditional tracepoints, "
13547 "ignoring tp %d cond"), b
->number
);
13550 if (b
->commands
|| !default_collect
.empty ())
13552 size_left
= buf
.size () - strlen (buf
.data ());
13554 ret
= snprintf (buf
.data () + strlen (buf
.data ()),
13557 if (ret
< 0 || ret
>= size_left
)
13558 error ("%s", err_msg
);
13561 putpkt (buf
.data ());
13562 remote_get_noisy_reply ();
13563 if (strcmp (rs
->buf
.data (), "OK"))
13564 error (_("Target does not support tracepoints."));
13566 /* do_single_steps (t); */
13567 for (auto action_it
= tdp_actions
.begin ();
13568 action_it
!= tdp_actions
.end (); action_it
++)
13570 QUIT
; /* Allow user to bail out with ^C. */
13572 bool has_more
= ((action_it
+ 1) != tdp_actions
.end ()
13573 || !stepping_actions
.empty ());
13575 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%c",
13576 b
->number
, addrbuf
, /* address */
13577 action_it
->c_str (),
13578 has_more
? '-' : 0);
13580 if (ret
< 0 || ret
>= buf
.size ())
13581 error ("%s", err_msg
);
13583 putpkt (buf
.data ());
13584 remote_get_noisy_reply ();
13585 if (strcmp (rs
->buf
.data (), "OK"))
13586 error (_("Error on target while setting tracepoints."));
13589 for (auto action_it
= stepping_actions
.begin ();
13590 action_it
!= stepping_actions
.end (); action_it
++)
13592 QUIT
; /* Allow user to bail out with ^C. */
13594 bool is_first
= action_it
== stepping_actions
.begin ();
13595 bool has_more
= (action_it
+ 1) != stepping_actions
.end ();
13597 ret
= snprintf (buf
.data (), buf
.size (), "QTDP:-%x:%s:%s%s%s",
13598 b
->number
, addrbuf
, /* address */
13599 is_first
? "S" : "",
13600 action_it
->c_str (),
13601 has_more
? "-" : "");
13603 if (ret
< 0 || ret
>= buf
.size ())
13604 error ("%s", err_msg
);
13606 putpkt (buf
.data ());
13607 remote_get_noisy_reply ();
13608 if (strcmp (rs
->buf
.data (), "OK"))
13609 error (_("Error on target while setting tracepoints."));
13612 if (m_features
.packet_support (PACKET_TracepointSource
) == PACKET_ENABLE
)
13614 if (b
->locspec
!= nullptr)
13616 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13618 if (ret
< 0 || ret
>= buf
.size ())
13619 error ("%s", err_msg
);
13621 const char *str
= b
->locspec
->to_string ();
13622 encode_source_string (b
->number
, loc
->address
, "at", str
,
13623 buf
.data () + strlen (buf
.data ()),
13624 buf
.size () - strlen (buf
.data ()));
13625 putpkt (buf
.data ());
13626 remote_get_noisy_reply ();
13627 if (strcmp (rs
->buf
.data (), "OK"))
13628 warning (_("Target does not support source download."));
13630 if (b
->cond_string
)
13632 ret
= snprintf (buf
.data (), buf
.size (), "QTDPsrc:");
13634 if (ret
< 0 || ret
>= buf
.size ())
13635 error ("%s", err_msg
);
13637 encode_source_string (b
->number
, loc
->address
,
13638 "cond", b
->cond_string
.get (),
13639 buf
.data () + strlen (buf
.data ()),
13640 buf
.size () - strlen (buf
.data ()));
13641 putpkt (buf
.data ());
13642 remote_get_noisy_reply ();
13643 if (strcmp (rs
->buf
.data (), "OK"))
13644 warning (_("Target does not support source download."));
13646 remote_download_command_source (b
->number
, loc
->address
,
13647 breakpoint_commands (b
));
13652 remote_target::can_download_tracepoint ()
13654 struct remote_state
*rs
= get_remote_state ();
13655 struct trace_status
*ts
;
13658 /* Don't try to install tracepoints until we've relocated our
13659 symbols, and fetched and merged the target's tracepoint list with
13661 if (rs
->starting_up
)
13664 ts
= current_trace_status ();
13665 status
= get_trace_status (ts
);
13667 if (status
== -1 || !ts
->running_known
|| !ts
->running
)
13670 /* If we are in a tracing experiment, but remote stub doesn't support
13671 installing tracepoint in trace, we have to return. */
13672 if (!remote_supports_install_in_trace ())
13680 remote_target::download_trace_state_variable (const trace_state_variable
&tsv
)
13682 struct remote_state
*rs
= get_remote_state ();
13685 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13686 tsv
.number
, phex ((ULONGEST
) tsv
.initial_value
, 8),
13688 p
= rs
->buf
.data () + strlen (rs
->buf
.data ());
13689 if ((p
- rs
->buf
.data ()) + tsv
.name
.length () * 2
13690 >= get_remote_packet_size ())
13691 error (_("Trace state variable name too long for tsv definition packet"));
13692 p
+= 2 * bin2hex ((gdb_byte
*) (tsv
.name
.data ()), p
, tsv
.name
.length ());
13695 remote_get_noisy_reply ();
13696 if (rs
->buf
[0] == '\0')
13697 error (_("Target does not support this command."));
13698 if (strcmp (rs
->buf
.data (), "OK") != 0)
13699 error (_("Error on target while downloading trace state variable."));
13703 remote_target::enable_tracepoint (struct bp_location
*location
)
13705 struct remote_state
*rs
= get_remote_state ();
13707 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13708 location
->owner
->number
,
13709 phex (location
->address
, sizeof (CORE_ADDR
)));
13711 remote_get_noisy_reply ();
13712 if (rs
->buf
[0] == '\0')
13713 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13714 if (strcmp (rs
->buf
.data (), "OK") != 0)
13715 error (_("Error on target while enabling tracepoint."));
13719 remote_target::disable_tracepoint (struct bp_location
*location
)
13721 struct remote_state
*rs
= get_remote_state ();
13723 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13724 location
->owner
->number
,
13725 phex (location
->address
, sizeof (CORE_ADDR
)));
13727 remote_get_noisy_reply ();
13728 if (rs
->buf
[0] == '\0')
13729 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13730 if (strcmp (rs
->buf
.data (), "OK") != 0)
13731 error (_("Error on target while disabling tracepoint."));
13735 remote_target::trace_set_readonly_regions ()
13738 bfd_size_type size
;
13742 bfd
*abfd
= current_program_space
->exec_bfd ();
13745 return; /* No information to give. */
13747 struct remote_state
*rs
= get_remote_state ();
13749 strcpy (rs
->buf
.data (), "QTro");
13750 offset
= strlen (rs
->buf
.data ());
13751 for (s
= abfd
->sections
; s
; s
= s
->next
)
13753 char tmp1
[40], tmp2
[40];
13756 if ((s
->flags
& SEC_LOAD
) == 0
13757 /* || (s->flags & SEC_CODE) == 0 */
13758 || (s
->flags
& SEC_READONLY
) == 0)
13762 vma
= bfd_section_vma (s
);
13763 size
= bfd_section_size (s
);
13764 bfd_sprintf_vma (abfd
, tmp1
, vma
);
13765 bfd_sprintf_vma (abfd
, tmp2
, vma
+ size
);
13766 sec_length
= 1 + strlen (tmp1
) + 1 + strlen (tmp2
);
13767 if (offset
+ sec_length
+ 1 > rs
->buf
.size ())
13769 if (m_features
.packet_support (PACKET_qXfer_traceframe_info
)
13772 Too many sections for read-only sections definition packet."));
13775 xsnprintf (rs
->buf
.data () + offset
, rs
->buf
.size () - offset
, ":%s,%s",
13777 offset
+= sec_length
;
13787 remote_target::trace_start ()
13789 struct remote_state
*rs
= get_remote_state ();
13791 putpkt ("QTStart");
13792 remote_get_noisy_reply ();
13793 if (rs
->buf
[0] == '\0')
13794 error (_("Target does not support this command."));
13795 if (strcmp (rs
->buf
.data (), "OK") != 0)
13796 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
13800 remote_target::get_trace_status (struct trace_status
*ts
)
13802 /* Initialize it just to avoid a GCC false warning. */
13804 enum packet_result result
;
13805 struct remote_state
*rs
= get_remote_state ();
13807 if (m_features
.packet_support (PACKET_qTStatus
) == PACKET_DISABLE
)
13810 /* FIXME we need to get register block size some other way. */
13811 trace_regblock_size
13812 = rs
->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet
;
13814 putpkt ("qTStatus");
13818 p
= remote_get_noisy_reply ();
13820 catch (const gdb_exception_error
&ex
)
13822 if (ex
.error
!= TARGET_CLOSE_ERROR
)
13824 exception_fprintf (gdb_stderr
, ex
, "qTStatus: ");
13830 result
= m_features
.packet_ok (p
, PACKET_qTStatus
);
13832 /* If the remote target doesn't do tracing, flag it. */
13833 if (result
== PACKET_UNKNOWN
)
13836 /* We're working with a live target. */
13837 ts
->filename
= NULL
;
13840 error (_("Bogus trace status reply from target: %s"), rs
->buf
.data ());
13842 /* Function 'parse_trace_status' sets default value of each field of
13843 'ts' at first, so we don't have to do it here. */
13844 parse_trace_status (p
, ts
);
13846 return ts
->running
;
13850 remote_target::get_tracepoint_status (tracepoint
*tp
,
13851 struct uploaded_tp
*utp
)
13853 struct remote_state
*rs
= get_remote_state ();
13855 size_t size
= get_remote_packet_size ();
13860 tp
->traceframe_usage
= 0;
13861 for (bp_location
&loc
: tp
->locations ())
13863 /* If the tracepoint was never downloaded, don't go asking for
13865 if (tp
->number_on_target
== 0)
13867 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", tp
->number_on_target
,
13868 phex_nz (loc
.address
, 0));
13870 reply
= remote_get_noisy_reply ();
13871 if (reply
&& *reply
)
13874 parse_tracepoint_status (reply
+ 1, tp
, utp
);
13880 utp
->hit_count
= 0;
13881 utp
->traceframe_usage
= 0;
13882 xsnprintf (rs
->buf
.data (), size
, "qTP:%x:%s", utp
->number
,
13883 phex_nz (utp
->addr
, 0));
13885 reply
= remote_get_noisy_reply ();
13886 if (reply
&& *reply
)
13889 parse_tracepoint_status (reply
+ 1, tp
, utp
);
13895 remote_target::trace_stop ()
13897 struct remote_state
*rs
= get_remote_state ();
13900 remote_get_noisy_reply ();
13901 if (rs
->buf
[0] == '\0')
13902 error (_("Target does not support this command."));
13903 if (strcmp (rs
->buf
.data (), "OK") != 0)
13904 error (_("Bogus reply from target: %s"), rs
->buf
.data ());
13908 remote_target::trace_find (enum trace_find_type type
, int num
,
13909 CORE_ADDR addr1
, CORE_ADDR addr2
,
13912 struct remote_state
*rs
= get_remote_state ();
13913 char *endbuf
= rs
->buf
.data () + get_remote_packet_size ();
13915 int target_frameno
= -1, target_tracept
= -1;
13917 /* Lookups other than by absolute frame number depend on the current
13918 trace selected, so make sure it is correct on the remote end
13920 if (type
!= tfind_number
)
13921 set_remote_traceframe ();
13923 p
= rs
->buf
.data ();
13924 strcpy (p
, "QTFrame:");
13925 p
= strchr (p
, '\0');
13929 xsnprintf (p
, endbuf
- p
, "%x", num
);
13932 xsnprintf (p
, endbuf
- p
, "pc:%s", phex_nz (addr1
, 0));
13935 xsnprintf (p
, endbuf
- p
, "tdp:%x", num
);
13938 xsnprintf (p
, endbuf
- p
, "range:%s:%s", phex_nz (addr1
, 0),
13939 phex_nz (addr2
, 0));
13941 case tfind_outside
:
13942 xsnprintf (p
, endbuf
- p
, "outside:%s:%s", phex_nz (addr1
, 0),
13943 phex_nz (addr2
, 0));
13946 error (_("Unknown trace find type %d"), type
);
13950 reply
= remote_get_noisy_reply ();
13951 if (*reply
== '\0')
13952 error (_("Target does not support this command."));
13954 while (reply
&& *reply
)
13959 target_frameno
= (int) strtol (p
, &reply
, 16);
13961 error (_("Unable to parse trace frame number"));
13962 /* Don't update our remote traceframe number cache on failure
13963 to select a remote traceframe. */
13964 if (target_frameno
== -1)
13969 target_tracept
= (int) strtol (p
, &reply
, 16);
13971 error (_("Unable to parse tracepoint number"));
13973 case 'O': /* "OK"? */
13974 if (reply
[1] == 'K' && reply
[2] == '\0')
13977 error (_("Bogus reply from target: %s"), reply
);
13980 error (_("Bogus reply from target: %s"), reply
);
13983 *tpp
= target_tracept
;
13985 rs
->remote_traceframe_number
= target_frameno
;
13986 return target_frameno
;
13990 remote_target::get_trace_state_variable_value (int tsvnum
, LONGEST
*val
)
13992 struct remote_state
*rs
= get_remote_state ();
13996 set_remote_traceframe ();
13998 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTV:%x", tsvnum
);
14000 reply
= remote_get_noisy_reply ();
14001 if (reply
&& *reply
)
14005 unpack_varlen_hex (reply
+ 1, &uval
);
14006 *val
= (LONGEST
) uval
;
14014 remote_target::save_trace_data (const char *filename
)
14016 struct remote_state
*rs
= get_remote_state ();
14019 p
= rs
->buf
.data ();
14020 strcpy (p
, "QTSave:");
14022 if ((p
- rs
->buf
.data ()) + strlen (filename
) * 2
14023 >= get_remote_packet_size ())
14024 error (_("Remote file name too long for trace save packet"));
14025 p
+= 2 * bin2hex ((gdb_byte
*) filename
, p
, strlen (filename
));
14028 reply
= remote_get_noisy_reply ();
14029 if (*reply
== '\0')
14030 error (_("Target does not support this command."));
14031 if (strcmp (reply
, "OK") != 0)
14032 error (_("Bogus reply from target: %s"), reply
);
14036 /* This is basically a memory transfer, but needs to be its own packet
14037 because we don't know how the target actually organizes its trace
14038 memory, plus we want to be able to ask for as much as possible, but
14039 not be unhappy if we don't get as much as we ask for. */
14042 remote_target::get_raw_trace_data (gdb_byte
*buf
, ULONGEST offset
, LONGEST len
)
14044 struct remote_state
*rs
= get_remote_state ();
14049 p
= rs
->buf
.data ();
14050 strcpy (p
, "qTBuffer:");
14052 p
+= hexnumstr (p
, offset
);
14054 p
+= hexnumstr (p
, len
);
14058 reply
= remote_get_noisy_reply ();
14059 if (reply
&& *reply
)
14061 /* 'l' by itself means we're at the end of the buffer and
14062 there is nothing more to get. */
14066 /* Convert the reply into binary. Limit the number of bytes to
14067 convert according to our passed-in buffer size, rather than
14068 what was returned in the packet; if the target is
14069 unexpectedly generous and gives us a bigger reply than we
14070 asked for, we don't want to crash. */
14071 rslt
= hex2bin (reply
, buf
, len
);
14075 /* Something went wrong, flag as an error. */
14080 remote_target::set_disconnected_tracing (int val
)
14082 struct remote_state
*rs
= get_remote_state ();
14084 if (m_features
.packet_support (PACKET_DisconnectedTracing_feature
)
14089 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14090 "QTDisconnected:%x", val
);
14092 reply
= remote_get_noisy_reply ();
14093 if (*reply
== '\0')
14094 error (_("Target does not support this command."));
14095 if (strcmp (reply
, "OK") != 0)
14096 error (_("Bogus reply from target: %s"), reply
);
14099 warning (_("Target does not support disconnected tracing."));
14103 remote_target::core_of_thread (ptid_t ptid
)
14105 thread_info
*info
= this->find_thread (ptid
);
14107 if (info
!= NULL
&& info
->priv
!= NULL
)
14108 return get_remote_thread_info (info
)->core
;
14114 remote_target::set_circular_trace_buffer (int val
)
14116 struct remote_state
*rs
= get_remote_state ();
14119 xsnprintf (rs
->buf
.data (), get_remote_packet_size (),
14120 "QTBuffer:circular:%x", val
);
14122 reply
= remote_get_noisy_reply ();
14123 if (*reply
== '\0')
14124 error (_("Target does not support this command."));
14125 if (strcmp (reply
, "OK") != 0)
14126 error (_("Bogus reply from target: %s"), reply
);
14130 remote_target::traceframe_info ()
14132 gdb::optional
<gdb::char_vector
> text
14133 = target_read_stralloc (current_inferior ()->top_target (),
14134 TARGET_OBJECT_TRACEFRAME_INFO
,
14137 return parse_traceframe_info (text
->data ());
14142 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14143 instruction on which a fast tracepoint may be placed. Returns -1
14144 if the packet is not supported, and 0 if the minimum instruction
14145 length is unknown. */
14148 remote_target::get_min_fast_tracepoint_insn_len ()
14150 struct remote_state
*rs
= get_remote_state ();
14153 /* If we're not debugging a process yet, the IPA can't be
14155 if (!target_has_execution ())
14158 /* Make sure the remote is pointing at the right process. */
14159 set_general_process ();
14161 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "qTMinFTPILen");
14163 reply
= remote_get_noisy_reply ();
14164 if (*reply
== '\0')
14168 ULONGEST min_insn_len
;
14170 unpack_varlen_hex (reply
, &min_insn_len
);
14172 return (int) min_insn_len
;
14177 remote_target::set_trace_buffer_size (LONGEST val
)
14179 if (m_features
.packet_support (PACKET_QTBuffer_size
) != PACKET_DISABLE
)
14181 struct remote_state
*rs
= get_remote_state ();
14182 char *buf
= rs
->buf
.data ();
14183 char *endbuf
= buf
+ get_remote_packet_size ();
14184 enum packet_result result
;
14186 gdb_assert (val
>= 0 || val
== -1);
14187 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTBuffer:size:");
14188 /* Send -1 as literal "-1" to avoid host size dependency. */
14192 buf
+= hexnumstr (buf
, (ULONGEST
) -val
);
14195 buf
+= hexnumstr (buf
, (ULONGEST
) val
);
14198 remote_get_noisy_reply ();
14199 result
= m_features
.packet_ok (rs
->buf
, PACKET_QTBuffer_size
);
14201 if (result
!= PACKET_OK
)
14202 warning (_("Bogus reply from target: %s"), rs
->buf
.data ());
14207 remote_target::set_trace_notes (const char *user
, const char *notes
,
14208 const char *stop_notes
)
14210 struct remote_state
*rs
= get_remote_state ();
14212 char *buf
= rs
->buf
.data ();
14213 char *endbuf
= buf
+ get_remote_packet_size ();
14216 buf
+= xsnprintf (buf
, endbuf
- buf
, "QTNotes:");
14219 buf
+= xsnprintf (buf
, endbuf
- buf
, "user:");
14220 nbytes
= bin2hex ((gdb_byte
*) user
, buf
, strlen (user
));
14226 buf
+= xsnprintf (buf
, endbuf
- buf
, "notes:");
14227 nbytes
= bin2hex ((gdb_byte
*) notes
, buf
, strlen (notes
));
14233 buf
+= xsnprintf (buf
, endbuf
- buf
, "tstop:");
14234 nbytes
= bin2hex ((gdb_byte
*) stop_notes
, buf
, strlen (stop_notes
));
14238 /* Ensure the buffer is terminated. */
14242 reply
= remote_get_noisy_reply ();
14243 if (*reply
== '\0')
14246 if (strcmp (reply
, "OK") != 0)
14247 error (_("Bogus reply from target: %s"), reply
);
14253 remote_target::use_agent (bool use
)
14255 if (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
)
14257 struct remote_state
*rs
= get_remote_state ();
14259 /* If the stub supports QAgent. */
14260 xsnprintf (rs
->buf
.data (), get_remote_packet_size (), "QAgent:%d", use
);
14264 if (strcmp (rs
->buf
.data (), "OK") == 0)
14275 remote_target::can_use_agent ()
14277 return (m_features
.packet_support (PACKET_QAgent
) != PACKET_DISABLE
);
14280 #if defined (HAVE_LIBEXPAT)
14282 /* Check the btrace document version. */
14285 check_xml_btrace_version (struct gdb_xml_parser
*parser
,
14286 const struct gdb_xml_element
*element
,
14288 std::vector
<gdb_xml_value
> &attributes
)
14290 const char *version
14291 = (const char *) xml_find_attribute (attributes
, "version")->value
.get ();
14293 if (strcmp (version
, "1.0") != 0)
14294 gdb_xml_error (parser
, _("Unsupported btrace version: \"%s\""), version
);
14297 /* Parse a btrace "block" xml record. */
14300 parse_xml_btrace_block (struct gdb_xml_parser
*parser
,
14301 const struct gdb_xml_element
*element
,
14303 std::vector
<gdb_xml_value
> &attributes
)
14305 struct btrace_data
*btrace
;
14306 ULONGEST
*begin
, *end
;
14308 btrace
= (struct btrace_data
*) user_data
;
14310 switch (btrace
->format
)
14312 case BTRACE_FORMAT_BTS
:
14315 case BTRACE_FORMAT_NONE
:
14316 btrace
->format
= BTRACE_FORMAT_BTS
;
14317 btrace
->variant
.bts
.blocks
= new std::vector
<btrace_block
>;
14321 gdb_xml_error (parser
, _("Btrace format error."));
14324 begin
= (ULONGEST
*) xml_find_attribute (attributes
, "begin")->value
.get ();
14325 end
= (ULONGEST
*) xml_find_attribute (attributes
, "end")->value
.get ();
14326 btrace
->variant
.bts
.blocks
->emplace_back (*begin
, *end
);
14329 /* Parse a "raw" xml record. */
14332 parse_xml_raw (struct gdb_xml_parser
*parser
, const char *body_text
,
14333 gdb_byte
**pdata
, size_t *psize
)
14338 len
= strlen (body_text
);
14340 gdb_xml_error (parser
, _("Bad raw data size."));
14344 gdb::unique_xmalloc_ptr
<gdb_byte
> data ((gdb_byte
*) xmalloc (size
));
14347 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14355 if (hi
== 0 || lo
== 0)
14356 gdb_xml_error (parser
, _("Bad hex encoding."));
14358 *bin
++ = fromhex (hi
) * 16 + fromhex (lo
);
14362 *pdata
= data
.release ();
14366 /* Parse a btrace pt-config "cpu" xml record. */
14369 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser
*parser
,
14370 const struct gdb_xml_element
*element
,
14372 std::vector
<gdb_xml_value
> &attributes
)
14374 struct btrace_data
*btrace
;
14375 const char *vendor
;
14376 ULONGEST
*family
, *model
, *stepping
;
14379 = (const char *) xml_find_attribute (attributes
, "vendor")->value
.get ();
14381 = (ULONGEST
*) xml_find_attribute (attributes
, "family")->value
.get ();
14383 = (ULONGEST
*) xml_find_attribute (attributes
, "model")->value
.get ();
14385 = (ULONGEST
*) xml_find_attribute (attributes
, "stepping")->value
.get ();
14387 btrace
= (struct btrace_data
*) user_data
;
14389 if (strcmp (vendor
, "GenuineIntel") == 0)
14390 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_INTEL
;
14392 btrace
->variant
.pt
.config
.cpu
.family
= *family
;
14393 btrace
->variant
.pt
.config
.cpu
.model
= *model
;
14394 btrace
->variant
.pt
.config
.cpu
.stepping
= *stepping
;
14397 /* Parse a btrace pt "raw" xml record. */
14400 parse_xml_btrace_pt_raw (struct gdb_xml_parser
*parser
,
14401 const struct gdb_xml_element
*element
,
14402 void *user_data
, const char *body_text
)
14404 struct btrace_data
*btrace
;
14406 btrace
= (struct btrace_data
*) user_data
;
14407 parse_xml_raw (parser
, body_text
, &btrace
->variant
.pt
.data
,
14408 &btrace
->variant
.pt
.size
);
14411 /* Parse a btrace "pt" xml record. */
14414 parse_xml_btrace_pt (struct gdb_xml_parser
*parser
,
14415 const struct gdb_xml_element
*element
,
14417 std::vector
<gdb_xml_value
> &attributes
)
14419 struct btrace_data
*btrace
;
14421 btrace
= (struct btrace_data
*) user_data
;
14422 btrace
->format
= BTRACE_FORMAT_PT
;
14423 btrace
->variant
.pt
.config
.cpu
.vendor
= CV_UNKNOWN
;
14424 btrace
->variant
.pt
.data
= NULL
;
14425 btrace
->variant
.pt
.size
= 0;
14428 static const struct gdb_xml_attribute block_attributes
[] = {
14429 { "begin", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14430 { "end", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14431 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14434 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes
[] = {
14435 { "vendor", GDB_XML_AF_NONE
, NULL
, NULL
},
14436 { "family", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14437 { "model", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14438 { "stepping", GDB_XML_AF_NONE
, gdb_xml_parse_attr_ulongest
, NULL
},
14439 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14442 static const struct gdb_xml_element btrace_pt_config_children
[] = {
14443 { "cpu", btrace_pt_config_cpu_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14444 parse_xml_btrace_pt_config_cpu
, NULL
},
14445 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14448 static const struct gdb_xml_element btrace_pt_children
[] = {
14449 { "pt-config", NULL
, btrace_pt_config_children
, GDB_XML_EF_OPTIONAL
, NULL
,
14451 { "raw", NULL
, NULL
, GDB_XML_EF_OPTIONAL
, NULL
, parse_xml_btrace_pt_raw
},
14452 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14455 static const struct gdb_xml_attribute btrace_attributes
[] = {
14456 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14457 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14460 static const struct gdb_xml_element btrace_children
[] = {
14461 { "block", block_attributes
, NULL
,
14462 GDB_XML_EF_REPEATABLE
| GDB_XML_EF_OPTIONAL
, parse_xml_btrace_block
, NULL
},
14463 { "pt", NULL
, btrace_pt_children
, GDB_XML_EF_OPTIONAL
, parse_xml_btrace_pt
,
14465 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14468 static const struct gdb_xml_element btrace_elements
[] = {
14469 { "btrace", btrace_attributes
, btrace_children
, GDB_XML_EF_NONE
,
14470 check_xml_btrace_version
, NULL
},
14471 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14474 #endif /* defined (HAVE_LIBEXPAT) */
14476 /* Parse a branch trace xml document XML into DATA. */
14479 parse_xml_btrace (struct btrace_data
*btrace
, const char *buffer
)
14481 #if defined (HAVE_LIBEXPAT)
14484 btrace_data result
;
14485 result
.format
= BTRACE_FORMAT_NONE
;
14487 errcode
= gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements
,
14490 error (_("Error parsing branch trace."));
14492 /* Keep parse results. */
14493 *btrace
= std::move (result
);
14495 #else /* !defined (HAVE_LIBEXPAT) */
14497 error (_("Cannot process branch trace. XML support was disabled at "
14500 #endif /* !defined (HAVE_LIBEXPAT) */
14503 #if defined (HAVE_LIBEXPAT)
14505 /* Parse a btrace-conf "bts" xml record. */
14508 parse_xml_btrace_conf_bts (struct gdb_xml_parser
*parser
,
14509 const struct gdb_xml_element
*element
,
14511 std::vector
<gdb_xml_value
> &attributes
)
14513 struct btrace_config
*conf
;
14514 struct gdb_xml_value
*size
;
14516 conf
= (struct btrace_config
*) user_data
;
14517 conf
->format
= BTRACE_FORMAT_BTS
;
14518 conf
->bts
.size
= 0;
14520 size
= xml_find_attribute (attributes
, "size");
14522 conf
->bts
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14525 /* Parse a btrace-conf "pt" xml record. */
14528 parse_xml_btrace_conf_pt (struct gdb_xml_parser
*parser
,
14529 const struct gdb_xml_element
*element
,
14531 std::vector
<gdb_xml_value
> &attributes
)
14533 struct btrace_config
*conf
;
14534 struct gdb_xml_value
*size
;
14536 conf
= (struct btrace_config
*) user_data
;
14537 conf
->format
= BTRACE_FORMAT_PT
;
14540 size
= xml_find_attribute (attributes
, "size");
14542 conf
->pt
.size
= (unsigned int) *(ULONGEST
*) size
->value
.get ();
14545 static const struct gdb_xml_attribute btrace_conf_pt_attributes
[] = {
14546 { "size", GDB_XML_AF_OPTIONAL
, gdb_xml_parse_attr_ulongest
, NULL
},
14547 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14550 static const struct gdb_xml_attribute btrace_conf_bts_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_element btrace_conf_children
[] = {
14556 { "bts", btrace_conf_bts_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14557 parse_xml_btrace_conf_bts
, NULL
},
14558 { "pt", btrace_conf_pt_attributes
, NULL
, GDB_XML_EF_OPTIONAL
,
14559 parse_xml_btrace_conf_pt
, NULL
},
14560 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14563 static const struct gdb_xml_attribute btrace_conf_attributes
[] = {
14564 { "version", GDB_XML_AF_NONE
, NULL
, NULL
},
14565 { NULL
, GDB_XML_AF_NONE
, NULL
, NULL
}
14568 static const struct gdb_xml_element btrace_conf_elements
[] = {
14569 { "btrace-conf", btrace_conf_attributes
, btrace_conf_children
,
14570 GDB_XML_EF_NONE
, NULL
, NULL
},
14571 { NULL
, NULL
, NULL
, GDB_XML_EF_NONE
, NULL
, NULL
}
14574 #endif /* defined (HAVE_LIBEXPAT) */
14576 /* Parse a branch trace configuration xml document XML into CONF. */
14579 parse_xml_btrace_conf (struct btrace_config
*conf
, const char *xml
)
14581 #if defined (HAVE_LIBEXPAT)
14584 errcode
= gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14585 btrace_conf_elements
, xml
, conf
);
14587 error (_("Error parsing branch trace configuration."));
14589 #else /* !defined (HAVE_LIBEXPAT) */
14591 error (_("Cannot process the branch trace configuration. XML support "
14592 "was disabled at compile time."));
14594 #endif /* !defined (HAVE_LIBEXPAT) */
14597 /* Reset our idea of our target's btrace configuration. */
14600 remote_btrace_reset (remote_state
*rs
)
14602 memset (&rs
->btrace_config
, 0, sizeof (rs
->btrace_config
));
14605 /* Synchronize the configuration with the target. */
14608 remote_target::btrace_sync_conf (const btrace_config
*conf
)
14610 struct remote_state
*rs
;
14611 char *buf
, *pos
, *endbuf
;
14613 rs
= get_remote_state ();
14614 buf
= rs
->buf
.data ();
14615 endbuf
= buf
+ get_remote_packet_size ();
14617 if (m_features
.packet_support (PACKET_Qbtrace_conf_bts_size
) == PACKET_ENABLE
14618 && conf
->bts
.size
!= rs
->btrace_config
.bts
.size
)
14621 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14622 packets_descriptions
[PACKET_Qbtrace_conf_bts_size
].name
,
14628 if (m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_bts_size
)
14631 if (buf
[0] == 'E' && buf
[1] == '.')
14632 error (_("Failed to configure the BTS buffer size: %s"), buf
+ 2);
14634 error (_("Failed to configure the BTS buffer size."));
14637 rs
->btrace_config
.bts
.size
= conf
->bts
.size
;
14640 if (m_features
.packet_support (PACKET_Qbtrace_conf_pt_size
) == PACKET_ENABLE
14641 && conf
->pt
.size
!= rs
->btrace_config
.pt
.size
)
14644 pos
+= xsnprintf (pos
, endbuf
- pos
, "%s=0x%x",
14645 packets_descriptions
[PACKET_Qbtrace_conf_pt_size
].name
,
14651 if (m_features
.packet_ok (buf
, PACKET_Qbtrace_conf_pt_size
)
14654 if (buf
[0] == 'E' && buf
[1] == '.')
14655 error (_("Failed to configure the trace buffer size: %s"), buf
+ 2);
14657 error (_("Failed to configure the trace buffer size."));
14660 rs
->btrace_config
.pt
.size
= conf
->pt
.size
;
14664 /* Read TP's btrace configuration from the target and store it into CONF. */
14667 btrace_read_config (thread_info
*tp
, btrace_config
*conf
)
14669 /* target_read_stralloc relies on INFERIOR_PTID. */
14670 scoped_restore_current_thread restore_thread
;
14671 switch_to_thread (tp
);
14673 gdb::optional
<gdb::char_vector
> xml
14674 = target_read_stralloc (current_inferior ()->top_target (),
14675 TARGET_OBJECT_BTRACE_CONF
, "");
14677 parse_xml_btrace_conf (conf
, xml
->data ());
14680 /* Maybe reopen target btrace. */
14683 remote_target::remote_btrace_maybe_reopen ()
14685 struct remote_state
*rs
= get_remote_state ();
14686 int btrace_target_pushed
= 0;
14687 #if !defined (HAVE_LIBIPT)
14691 /* Don't bother walking the entirety of the remote thread list when
14692 we know the feature isn't supported by the remote. */
14693 if (m_features
.packet_support (PACKET_qXfer_btrace_conf
) != PACKET_ENABLE
)
14696 for (thread_info
*tp
: all_non_exited_threads (this))
14698 memset (&rs
->btrace_config
, 0x00, sizeof (struct btrace_config
));
14699 btrace_read_config (tp
, &rs
->btrace_config
);
14701 if (rs
->btrace_config
.format
== BTRACE_FORMAT_NONE
)
14704 #if !defined (HAVE_LIBIPT)
14705 if (rs
->btrace_config
.format
== BTRACE_FORMAT_PT
)
14710 warning (_("Target is recording using Intel Processor Trace "
14711 "but support was disabled at compile time."));
14716 #endif /* !defined (HAVE_LIBIPT) */
14718 /* Push target, once, but before anything else happens. This way our
14719 changes to the threads will be cleaned up by unpushing the target
14720 in case btrace_read_config () throws. */
14721 if (!btrace_target_pushed
)
14723 btrace_target_pushed
= 1;
14724 record_btrace_push_target ();
14725 gdb_printf (_("Target is recording using %s.\n"),
14726 btrace_format_string (rs
->btrace_config
.format
));
14730 = new btrace_target_info
{ tp
->ptid
, rs
->btrace_config
};
14734 /* Enable branch tracing. */
14736 struct btrace_target_info
*
14737 remote_target::enable_btrace (thread_info
*tp
,
14738 const struct btrace_config
*conf
)
14740 struct packet_config
*packet
= NULL
;
14741 struct remote_state
*rs
= get_remote_state ();
14742 char *buf
= rs
->buf
.data ();
14743 char *endbuf
= buf
+ get_remote_packet_size ();
14745 unsigned int which_packet
;
14746 switch (conf
->format
)
14748 case BTRACE_FORMAT_BTS
:
14749 which_packet
= PACKET_Qbtrace_bts
;
14751 case BTRACE_FORMAT_PT
:
14752 which_packet
= PACKET_Qbtrace_pt
;
14755 internal_error (_("Bad branch btrace format: %u."),
14756 (unsigned int) conf
->format
);
14759 packet
= &m_features
.m_protocol_packets
[which_packet
];
14760 if (packet
== NULL
|| packet_config_support (packet
) != PACKET_ENABLE
)
14761 error (_("Target does not support branch tracing."));
14763 btrace_sync_conf (conf
);
14765 ptid_t ptid
= tp
->ptid
;
14766 set_general_thread (ptid
);
14768 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
14769 packets_descriptions
[which_packet
].name
);
14773 if (m_features
.packet_ok (rs
->buf
, which_packet
) == PACKET_ERROR
)
14775 if (rs
->buf
[0] == 'E' && rs
->buf
[1] == '.')
14776 error (_("Could not enable branch tracing for %s: %s"),
14777 target_pid_to_str (ptid
).c_str (), &rs
->buf
[2]);
14779 error (_("Could not enable branch tracing for %s."),
14780 target_pid_to_str (ptid
).c_str ());
14783 btrace_target_info
*tinfo
= new btrace_target_info
{ ptid
};
14785 /* If we fail to read the configuration, we lose some information, but the
14786 tracing itself is not impacted. */
14789 btrace_read_config (tp
, &tinfo
->conf
);
14791 catch (const gdb_exception_error
&err
)
14793 if (err
.message
!= NULL
)
14794 warning ("%s", err
.what ());
14800 /* Disable branch tracing. */
14803 remote_target::disable_btrace (struct btrace_target_info
*tinfo
)
14805 struct remote_state
*rs
= get_remote_state ();
14806 char *buf
= rs
->buf
.data ();
14807 char *endbuf
= buf
+ get_remote_packet_size ();
14809 if (m_features
.packet_support (PACKET_Qbtrace_off
) != PACKET_ENABLE
)
14810 error (_("Target does not support branch tracing."));
14812 set_general_thread (tinfo
->ptid
);
14814 buf
+= xsnprintf (buf
, endbuf
- buf
, "%s",
14815 packets_descriptions
[PACKET_Qbtrace_off
].name
);
14819 if (m_features
.packet_ok (rs
->buf
, PACKET_Qbtrace_off
) == PACKET_ERROR
)
14821 if (rs
->buf
[0] == 'E' && rs
->buf
[1] == '.')
14822 error (_("Could not disable branch tracing for %s: %s"),
14823 target_pid_to_str (tinfo
->ptid
).c_str (), &rs
->buf
[2]);
14825 error (_("Could not disable branch tracing for %s."),
14826 target_pid_to_str (tinfo
->ptid
).c_str ());
14832 /* Teardown branch tracing. */
14835 remote_target::teardown_btrace (struct btrace_target_info
*tinfo
)
14837 /* We must not talk to the target during teardown. */
14841 /* Read the branch trace. */
14844 remote_target::read_btrace (struct btrace_data
*btrace
,
14845 struct btrace_target_info
*tinfo
,
14846 enum btrace_read_type type
)
14850 if (m_features
.packet_support (PACKET_qXfer_btrace
) != PACKET_ENABLE
)
14851 error (_("Target does not support branch tracing."));
14853 #if !defined(HAVE_LIBEXPAT)
14854 error (_("Cannot process branch tracing result. XML parsing not supported."));
14859 case BTRACE_READ_ALL
:
14862 case BTRACE_READ_NEW
:
14865 case BTRACE_READ_DELTA
:
14869 internal_error (_("Bad branch tracing read type: %u."),
14870 (unsigned int) type
);
14873 gdb::optional
<gdb::char_vector
> xml
14874 = target_read_stralloc (current_inferior ()->top_target (),
14875 TARGET_OBJECT_BTRACE
, annex
);
14877 return BTRACE_ERR_UNKNOWN
;
14879 parse_xml_btrace (btrace
, xml
->data ());
14881 return BTRACE_ERR_NONE
;
14884 const struct btrace_config
*
14885 remote_target::btrace_conf (const struct btrace_target_info
*tinfo
)
14887 return &tinfo
->conf
;
14891 remote_target::augmented_libraries_svr4_read ()
14894 (m_features
.packet_support (PACKET_augmented_libraries_svr4_read_feature
)
14898 /* Implementation of to_load. */
14901 remote_target::load (const char *name
, int from_tty
)
14903 generic_load (name
, from_tty
);
14906 /* Accepts an integer PID; returns a string representing a file that
14907 can be opened on the remote side to get the symbols for the child
14908 process. Returns NULL if the operation is not supported. */
14911 remote_target::pid_to_exec_file (int pid
)
14913 static gdb::optional
<gdb::char_vector
> filename
;
14914 char *annex
= NULL
;
14916 if (m_features
.packet_support (PACKET_qXfer_exec_file
) != PACKET_ENABLE
)
14919 inferior
*inf
= find_inferior_pid (this, pid
);
14921 internal_error (_("not currently attached to process %d"), pid
);
14923 if (!inf
->fake_pid_p
)
14925 const int annex_size
= 9;
14927 annex
= (char *) alloca (annex_size
);
14928 xsnprintf (annex
, annex_size
, "%x", pid
);
14931 filename
= target_read_stralloc (current_inferior ()->top_target (),
14932 TARGET_OBJECT_EXEC_FILE
, annex
);
14934 return filename
? filename
->data () : nullptr;
14937 /* Implement the to_can_do_single_step target_ops method. */
14940 remote_target::can_do_single_step ()
14942 /* We can only tell whether target supports single step or not by
14943 supported s and S vCont actions if the stub supports vContSupported
14944 feature. If the stub doesn't support vContSupported feature,
14945 we have conservatively to think target doesn't supports single
14947 if (m_features
.packet_support (PACKET_vContSupported
) == PACKET_ENABLE
)
14949 struct remote_state
*rs
= get_remote_state ();
14951 return rs
->supports_vCont
.s
&& rs
->supports_vCont
.S
;
14957 /* Implementation of the to_execution_direction method for the remote
14960 enum exec_direction_kind
14961 remote_target::execution_direction ()
14963 struct remote_state
*rs
= get_remote_state ();
14965 return rs
->last_resume_exec_dir
;
14968 /* Return pointer to the thread_info struct which corresponds to
14969 THREAD_HANDLE (having length HANDLE_LEN). */
14972 remote_target::thread_handle_to_thread_info (const gdb_byte
*thread_handle
,
14976 for (thread_info
*tp
: all_non_exited_threads (this))
14978 remote_thread_info
*priv
= get_remote_thread_info (tp
);
14980 if (tp
->inf
== inf
&& priv
!= NULL
)
14982 if (handle_len
!= priv
->thread_handle
.size ())
14983 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14984 handle_len
, priv
->thread_handle
.size ());
14985 if (memcmp (thread_handle
, priv
->thread_handle
.data (),
14994 gdb::array_view
<const gdb_byte
>
14995 remote_target::thread_info_to_thread_handle (struct thread_info
*tp
)
14997 remote_thread_info
*priv
= get_remote_thread_info (tp
);
14998 return priv
->thread_handle
;
15002 remote_target::can_async_p ()
15004 /* This flag should be checked in the common target.c code. */
15005 gdb_assert (target_async_permitted
);
15007 /* We're async whenever the serial device can. */
15008 return get_remote_state ()->can_async_p ();
15012 remote_target::is_async_p ()
15014 /* We're async whenever the serial device is. */
15015 return get_remote_state ()->is_async_p ();
15018 /* Pass the SERIAL event on and up to the client. One day this code
15019 will be able to delay notifying the client of an event until the
15020 point where an entire packet has been received. */
15022 static serial_event_ftype remote_async_serial_handler
;
15025 remote_async_serial_handler (struct serial
*scb
, void *context
)
15027 /* Don't propogate error information up to the client. Instead let
15028 the client find out about the error by querying the target. */
15029 inferior_event_handler (INF_REG_EVENT
);
15033 remote_target::async_wait_fd ()
15035 struct remote_state
*rs
= get_remote_state ();
15036 return rs
->remote_desc
->fd
;
15040 remote_target::async (bool enable
)
15042 struct remote_state
*rs
= get_remote_state ();
15046 serial_async (rs
->remote_desc
, remote_async_serial_handler
, rs
);
15048 /* If there are pending events in the stop reply queue tell the
15049 event loop to process them. */
15050 if (!rs
->stop_reply_queue
.empty ())
15051 rs
->mark_async_event_handler ();
15053 /* For simplicity, below we clear the pending events token
15054 without remembering whether it is marked, so here we always
15055 mark it. If there's actually no pending notification to
15056 process, this ends up being a no-op (other than a spurious
15057 event-loop wakeup). */
15058 if (target_is_non_stop_p ())
15059 mark_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15063 serial_async (rs
->remote_desc
, NULL
, NULL
);
15064 /* If the core is disabling async, it doesn't want to be
15065 disturbed with target events. Clear all async event sources
15067 rs
->clear_async_event_handler ();
15069 if (target_is_non_stop_p ())
15070 clear_async_event_handler (rs
->notif_state
->get_pending_events_token
);
15074 /* Implementation of the to_thread_events method. */
15077 remote_target::thread_events (int enable
)
15079 struct remote_state
*rs
= get_remote_state ();
15080 size_t size
= get_remote_packet_size ();
15082 if (m_features
.packet_support (PACKET_QThreadEvents
) == PACKET_DISABLE
)
15085 if (rs
->last_thread_events
== enable
)
15088 xsnprintf (rs
->buf
.data (), size
, "QThreadEvents:%x", enable
? 1 : 0);
15092 switch (m_features
.packet_ok (rs
->buf
, PACKET_QThreadEvents
))
15095 if (strcmp (rs
->buf
.data (), "OK") != 0)
15096 error (_("Remote refused setting thread events: %s"), rs
->buf
.data ());
15097 rs
->last_thread_events
= enable
;
15100 warning (_("Remote failure reply: %s"), rs
->buf
.data ());
15102 case PACKET_UNKNOWN
:
15107 /* Implementation of the supports_set_thread_options target
15111 remote_target::supports_set_thread_options (gdb_thread_options options
)
15113 remote_state
*rs
= get_remote_state ();
15114 return (m_features
.packet_support (PACKET_QThreadOptions
) == PACKET_ENABLE
15115 && (rs
->supported_thread_options
& options
) == options
);
15118 /* For coalescing reasons, actually sending the options to the target
15119 happens at resume time, via this function. See target_resume for
15120 all-stop, and target_commit_resumed for non-stop. */
15123 remote_target::commit_requested_thread_options ()
15125 struct remote_state
*rs
= get_remote_state ();
15127 if (m_features
.packet_support (PACKET_QThreadOptions
) != PACKET_ENABLE
)
15130 char *p
= rs
->buf
.data ();
15131 char *endp
= p
+ get_remote_packet_size ();
15133 /* Clear options for all threads by default. Note that unlike
15134 vCont, the rightmost options that match a thread apply, so we
15135 don't have to worry about whether we can use wildcard ptids. */
15136 strcpy (p
, "QThreadOptions;0");
15139 /* Send the QThreadOptions packet stored in P. */
15140 auto flush
= [&] ()
15145 getpkt (&rs
->buf
, 0);
15147 switch (m_features
.packet_ok (rs
->buf
, PACKET_QThreadOptions
))
15150 if (strcmp (rs
->buf
.data (), "OK") != 0)
15151 error (_("Remote refused setting thread options: %s"), rs
->buf
.data ());
15154 error (_("Remote failure reply: %s"), rs
->buf
.data ());
15155 case PACKET_UNKNOWN
:
15156 gdb_assert_not_reached ("PACKET_UNKNOWN");
15161 /* Prepare P for another QThreadOptions packet. */
15162 auto restart
= [&] ()
15164 p
= rs
->buf
.data ();
15165 strcpy (p
, "QThreadOptions");
15169 /* Now set non-zero options for threads that need them. We don't
15170 bother with the case of all threads of a process wanting the same
15171 non-zero options as that's not an expected scenario. */
15172 for (thread_info
*tp
: all_non_exited_threads (this))
15174 gdb_thread_options options
= tp
->thread_options ();
15179 /* It might be possible to we have more threads with options
15180 than can fit a single QThreadOptions packet. So build each
15181 options/thread pair in this separate buffer to make sure it
15183 constexpr size_t max_options_size
= 100;
15184 char obuf
[max_options_size
];
15185 char *obuf_p
= obuf
;
15186 char *obuf_endp
= obuf
+ max_options_size
;
15189 obuf_p
+= xsnprintf (obuf_p
, obuf_endp
- obuf_p
, "%s",
15190 phex_nz (options
, sizeof (options
)));
15191 if (tp
->ptid
!= magic_null_ptid
)
15194 obuf_p
= write_ptid (obuf_p
, obuf_endp
, tp
->ptid
);
15197 size_t osize
= obuf_p
- obuf
;
15198 if (osize
> endp
- p
)
15200 /* This new options/thread pair doesn't fit the packet
15201 buffer. Send what we have already. */
15205 /* Should now fit. */
15206 gdb_assert (osize
<= endp
- p
);
15209 memcpy (p
, obuf
, osize
);
15217 show_remote_cmd (const char *args
, int from_tty
)
15219 /* We can't just use cmd_show_list here, because we want to skip
15220 the redundant "show remote Z-packet" and the legacy aliases. */
15221 struct cmd_list_element
*list
= remote_show_cmdlist
;
15222 struct ui_out
*uiout
= current_uiout
;
15224 ui_out_emit_tuple
tuple_emitter (uiout
, "showlist");
15225 for (; list
!= NULL
; list
= list
->next
)
15226 if (strcmp (list
->name
, "Z-packet") == 0)
15228 else if (list
->type
== not_set_cmd
)
15229 /* Alias commands are exactly like the original, except they
15230 don't have the normal type. */
15234 ui_out_emit_tuple
option_emitter (uiout
, "option");
15236 uiout
->field_string ("name", list
->name
);
15237 uiout
->text (": ");
15238 if (list
->type
== show_cmd
)
15239 do_show_command (NULL
, from_tty
, list
);
15241 cmd_func (list
, NULL
, from_tty
);
15245 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15246 offer all inferiors using that program space a change to look up symbols. */
15249 remote_objfile_changed_check_symbols (program_space
*pspace
)
15251 /* The affected program space is possibly shared by multiple inferiors.
15252 Consider sending a qSymbol packet for each of the inferiors using that
15254 for (inferior
*inf
: all_inferiors ())
15256 if (inf
->pspace
!= pspace
)
15259 /* Check whether the inferior's process target is a remote target. */
15260 remote_target
*remote
= as_remote_target (inf
->process_target ());
15261 if (remote
== nullptr)
15264 /* When we are attaching or handling a fork child and the shared library
15265 subsystem reads the list of loaded libraries, we receive new objfile
15266 events in between each found library. The libraries are read in an
15267 undefined order, so if we gave the remote side a chance to look up
15268 symbols between each objfile, we might give it an inconsistent picture
15269 of the inferior. It could appear that a library A appears loaded but
15270 a library B does not, even though library A requires library B. That
15271 would present a state that couldn't normally exist in the inferior.
15273 So, skip these events, we'll give the remote a chance to look up
15274 symbols once all the loaded libraries and their symbols are known to
15276 if (inf
->in_initial_library_scan
)
15279 if (!remote
->has_execution (inf
))
15282 /* Need to switch to a specific thread, because remote_check_symbols will
15283 set the general thread using INFERIOR_PTID.
15285 It's possible to have inferiors with no thread here, because we are
15286 called very early in the connection process, while the inferior is
15287 being set up, before threads are added. Just skip it, start_remote_1
15288 also calls remote_check_symbols when it's done setting things up. */
15289 thread_info
*thread
= any_thread_of_inferior (inf
);
15290 if (thread
!= nullptr)
15292 scoped_restore_current_thread restore_thread
;
15293 switch_to_thread (thread
);
15294 remote
->remote_check_symbols ();
15299 /* Function to be called whenever a new objfile (shlib) is detected. */
15302 remote_new_objfile (struct objfile
*objfile
)
15304 remote_objfile_changed_check_symbols (objfile
->pspace
);
15307 /* Pull all the tracepoints defined on the target and create local
15308 data structures representing them. We don't want to create real
15309 tracepoints yet, we don't want to mess up the user's existing
15313 remote_target::upload_tracepoints (struct uploaded_tp
**utpp
)
15315 struct remote_state
*rs
= get_remote_state ();
15318 /* Ask for a first packet of tracepoint definition. */
15321 p
= rs
->buf
.data ();
15322 while (*p
&& *p
!= 'l')
15324 parse_tracepoint_definition (p
, utpp
);
15325 /* Ask for another packet of tracepoint definition. */
15328 p
= rs
->buf
.data ();
15334 remote_target::upload_trace_state_variables (struct uploaded_tsv
**utsvp
)
15336 struct remote_state
*rs
= get_remote_state ();
15339 /* Ask for a first packet of variable definition. */
15342 p
= rs
->buf
.data ();
15343 while (*p
&& *p
!= 'l')
15345 parse_tsv_definition (p
, utsvp
);
15346 /* Ask for another packet of variable definition. */
15349 p
= rs
->buf
.data ();
15354 /* The "set/show range-stepping" show hook. */
15357 show_range_stepping (struct ui_file
*file
, int from_tty
,
15358 struct cmd_list_element
*c
,
15362 _("Debugger's willingness to use range stepping "
15363 "is %s.\n"), value
);
15366 /* Return true if the vCont;r action is supported by the remote
15370 remote_target::vcont_r_supported ()
15372 return (m_features
.packet_support (PACKET_vCont
) == PACKET_ENABLE
15373 && get_remote_state ()->supports_vCont
.r
);
15376 /* The "set/show range-stepping" set hook. */
15379 set_range_stepping (const char *ignore_args
, int from_tty
,
15380 struct cmd_list_element
*c
)
15382 /* When enabling, check whether range stepping is actually supported
15383 by the target, and warn if not. */
15384 if (use_range_stepping
)
15386 remote_target
*remote
= get_current_remote_target ();
15388 || !remote
->vcont_r_supported ())
15389 warning (_("Range stepping is not supported by the current target"));
15394 show_remote_debug (struct ui_file
*file
, int from_tty
,
15395 struct cmd_list_element
*c
, const char *value
)
15397 gdb_printf (file
, _("Debugging of remote protocol is %s.\n"),
15402 show_remote_timeout (struct ui_file
*file
, int from_tty
,
15403 struct cmd_list_element
*c
, const char *value
)
15406 _("Timeout limit to wait for target to respond is %s.\n"),
15410 /* Implement the "supports_memory_tagging" target_ops method. */
15413 remote_target::supports_memory_tagging ()
15415 return m_features
.remote_memory_tagging_p ();
15418 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15421 create_fetch_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15422 size_t len
, int type
)
15424 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15426 std::string request
= string_printf ("qMemTags:%s,%s:%s",
15427 phex_nz (address
, addr_size
),
15428 phex_nz (len
, sizeof (len
)),
15429 phex_nz (type
, sizeof (type
)));
15431 strcpy (packet
.data (), request
.c_str ());
15434 /* Parse the qMemTags packet reply into TAGS.
15436 Return true if successful, false otherwise. */
15439 parse_fetch_memtags_reply (const gdb::char_vector
&reply
,
15440 gdb::byte_vector
&tags
)
15442 if (reply
.empty () || reply
[0] == 'E' || reply
[0] != 'm')
15445 /* Copy the tag data. */
15446 tags
= hex2bin (reply
.data () + 1);
15451 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15454 create_store_memtags_request (gdb::char_vector
&packet
, CORE_ADDR address
,
15455 size_t len
, int type
,
15456 const gdb::byte_vector
&tags
)
15458 int addr_size
= gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15460 /* Put together the main packet, address and length. */
15461 std::string request
= string_printf ("QMemTags:%s,%s:%s:",
15462 phex_nz (address
, addr_size
),
15463 phex_nz (len
, sizeof (len
)),
15464 phex_nz (type
, sizeof (type
)));
15465 request
+= bin2hex (tags
.data (), tags
.size ());
15467 /* Check if we have exceeded the maximum packet size. */
15468 if (packet
.size () < request
.length ())
15469 error (_("Contents too big for packet QMemTags."));
15471 strcpy (packet
.data (), request
.c_str ());
15474 /* Implement the "fetch_memtags" target_ops method. */
15477 remote_target::fetch_memtags (CORE_ADDR address
, size_t len
,
15478 gdb::byte_vector
&tags
, int type
)
15480 /* Make sure the qMemTags packet is supported. */
15481 if (!m_features
.remote_memory_tagging_p ())
15482 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15484 struct remote_state
*rs
= get_remote_state ();
15486 create_fetch_memtags_request (rs
->buf
, address
, len
, type
);
15491 return parse_fetch_memtags_reply (rs
->buf
, tags
);
15494 /* Implement the "store_memtags" target_ops method. */
15497 remote_target::store_memtags (CORE_ADDR address
, size_t len
,
15498 const gdb::byte_vector
&tags
, int type
)
15500 /* Make sure the QMemTags packet is supported. */
15501 if (!m_features
.remote_memory_tagging_p ())
15502 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15504 struct remote_state
*rs
= get_remote_state ();
15506 create_store_memtags_request (rs
->buf
, address
, len
, type
, tags
);
15511 /* Verify if the request was successful. */
15512 return packet_check_result (rs
->buf
.data ()) == PACKET_OK
;
15515 /* Return true if remote target T is non-stop. */
15518 remote_target_is_non_stop_p (remote_target
*t
)
15520 scoped_restore_current_thread restore_thread
;
15521 switch_to_target_no_thread (t
);
15523 return target_is_non_stop_p ();
15528 namespace selftests
{
15531 test_memory_tagging_functions ()
15533 remote_target remote
;
15535 struct packet_config
*config
15536 = &remote
.m_features
.m_protocol_packets
[PACKET_memory_tagging_feature
];
15538 scoped_restore restore_memtag_support_
15539 = make_scoped_restore (&config
->support
);
15541 /* Test memory tagging packet support. */
15542 config
->support
= PACKET_SUPPORT_UNKNOWN
;
15543 SELF_CHECK (remote
.supports_memory_tagging () == false);
15544 config
->support
= PACKET_DISABLE
;
15545 SELF_CHECK (remote
.supports_memory_tagging () == false);
15546 config
->support
= PACKET_ENABLE
;
15547 SELF_CHECK (remote
.supports_memory_tagging () == true);
15549 /* Setup testing. */
15550 gdb::char_vector packet
;
15551 gdb::byte_vector tags
, bv
;
15552 std::string expected
, reply
;
15553 packet
.resize (32000);
15555 /* Test creating a qMemTags request. */
15557 expected
= "qMemTags:0,0:0";
15558 create_fetch_memtags_request (packet
, 0x0, 0x0, 0);
15559 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
15561 expected
= "qMemTags:deadbeef,10:1";
15562 create_fetch_memtags_request (packet
, 0xdeadbeef, 16, 1);
15563 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
15565 /* Test parsing a qMemTags reply. */
15567 /* Error reply, tags vector unmodified. */
15569 strcpy (packet
.data (), reply
.c_str ());
15571 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == false);
15572 SELF_CHECK (tags
.size () == 0);
15574 /* Valid reply, tags vector updated. */
15578 for (int i
= 0; i
< 5; i
++)
15581 reply
= "m" + bin2hex (bv
.data (), bv
.size ());
15582 strcpy (packet
.data (), reply
.c_str ());
15584 SELF_CHECK (parse_fetch_memtags_reply (packet
, tags
) == true);
15585 SELF_CHECK (tags
.size () == 5);
15587 for (int i
= 0; i
< 5; i
++)
15588 SELF_CHECK (tags
[i
] == i
);
15590 /* Test creating a QMemTags request. */
15592 /* Empty tag data. */
15594 expected
= "QMemTags:0,0:0:";
15595 create_store_memtags_request (packet
, 0x0, 0x0, 0, tags
);
15596 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
15597 expected
.length ()) == 0);
15599 /* Non-empty tag data. */
15601 for (int i
= 0; i
< 5; i
++)
15602 tags
.push_back (i
);
15603 expected
= "QMemTags:deadbeef,ff:1:0001020304";
15604 create_store_memtags_request (packet
, 0xdeadbeef, 255, 1, tags
);
15605 SELF_CHECK (memcmp (packet
.data (), expected
.c_str (),
15606 expected
.length ()) == 0);
15609 } // namespace selftests
15610 #endif /* GDB_SELF_TEST */
15612 void _initialize_remote ();
15614 _initialize_remote ()
15616 add_target (remote_target_info
, remote_target::open
);
15617 add_target (extended_remote_target_info
, extended_remote_target::open
);
15619 /* Hook into new objfile notification. */
15620 gdb::observers::new_objfile
.attach (remote_new_objfile
, "remote");
15621 gdb::observers::all_objfiles_removed
.attach
15622 (remote_objfile_changed_check_symbols
, "remote");
15625 init_remote_threadtests ();
15628 /* set/show remote ... */
15630 add_basic_prefix_cmd ("remote", class_maintenance
, _("\
15631 Remote protocol specific variables.\n\
15632 Configure various remote-protocol specific variables such as\n\
15633 the packets being used."),
15634 &remote_set_cmdlist
,
15635 0 /* allow-unknown */, &setlist
);
15636 add_prefix_cmd ("remote", class_maintenance
, show_remote_cmd
, _("\
15637 Remote protocol specific variables.\n\
15638 Configure various remote-protocol specific variables such as\n\
15639 the packets being used."),
15640 &remote_show_cmdlist
,
15641 0 /* allow-unknown */, &showlist
);
15643 add_cmd ("compare-sections", class_obscure
, compare_sections_command
, _("\
15644 Compare section data on target to the exec file.\n\
15645 Argument is a single section name (default: all loaded sections).\n\
15646 To compare only read-only loaded sections, specify the -r option."),
15649 add_cmd ("packet", class_maintenance
, cli_packet_command
, _("\
15650 Send an arbitrary packet to a remote target.\n\
15651 maintenance packet TEXT\n\
15652 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15653 this command sends the string TEXT to the inferior, and displays the\n\
15654 response packet. GDB supplies the initial `$' character, and the\n\
15655 terminating `#' character and checksum."),
15658 set_show_commands remotebreak_cmds
15659 = add_setshow_boolean_cmd ("remotebreak", no_class
, &remote_break
, _("\
15660 Set whether to send break if interrupted."), _("\
15661 Show whether to send break if interrupted."), _("\
15662 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15663 set_remotebreak
, show_remotebreak
,
15664 &setlist
, &showlist
);
15665 deprecate_cmd (remotebreak_cmds
.set
, "set remote interrupt-sequence");
15666 deprecate_cmd (remotebreak_cmds
.show
, "show remote interrupt-sequence");
15668 add_setshow_enum_cmd ("interrupt-sequence", class_support
,
15669 interrupt_sequence_modes
, &interrupt_sequence_mode
,
15671 Set interrupt sequence to remote target."), _("\
15672 Show interrupt sequence to remote target."), _("\
15673 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15674 NULL
, show_interrupt_sequence
,
15675 &remote_set_cmdlist
,
15676 &remote_show_cmdlist
);
15678 add_setshow_boolean_cmd ("interrupt-on-connect", class_support
,
15679 &interrupt_on_connect
, _("\
15680 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15681 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15682 If set, interrupt sequence is sent to remote target."),
15684 &remote_set_cmdlist
, &remote_show_cmdlist
);
15686 /* Install commands for configuring memory read/write packets. */
15688 add_cmd ("remotewritesize", no_class
, set_memory_write_packet_size
, _("\
15689 Set the maximum number of bytes per memory write packet (deprecated)."),
15691 add_cmd ("remotewritesize", no_class
, show_memory_write_packet_size
, _("\
15692 Show the maximum number of bytes per memory write packet (deprecated)."),
15694 add_cmd ("memory-write-packet-size", no_class
,
15695 set_memory_write_packet_size
, _("\
15696 Set the maximum number of bytes per memory-write packet.\n\
15697 Specify the number of bytes in a packet or 0 (zero) for the\n\
15698 default packet size. The actual limit is further reduced\n\
15699 dependent on the target. Specify \"fixed\" to disable the\n\
15700 further restriction and \"limit\" to enable that restriction."),
15701 &remote_set_cmdlist
);
15702 add_cmd ("memory-read-packet-size", no_class
,
15703 set_memory_read_packet_size
, _("\
15704 Set the maximum number of bytes per memory-read packet.\n\
15705 Specify the number of bytes in a packet or 0 (zero) for the\n\
15706 default packet size. The actual limit is further reduced\n\
15707 dependent on the target. Specify \"fixed\" to disable the\n\
15708 further restriction and \"limit\" to enable that restriction."),
15709 &remote_set_cmdlist
);
15710 add_cmd ("memory-write-packet-size", no_class
,
15711 show_memory_write_packet_size
,
15712 _("Show the maximum number of bytes per memory-write packet."),
15713 &remote_show_cmdlist
);
15714 add_cmd ("memory-read-packet-size", no_class
,
15715 show_memory_read_packet_size
,
15716 _("Show the maximum number of bytes per memory-read packet."),
15717 &remote_show_cmdlist
);
15719 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class
,
15720 &remote_hw_watchpoint_limit
, _("\
15721 Set the maximum number of target hardware watchpoints."), _("\
15722 Show the maximum number of target hardware watchpoints."), _("\
15723 Specify \"unlimited\" for unlimited hardware watchpoints."),
15724 NULL
, show_hardware_watchpoint_limit
,
15725 &remote_set_cmdlist
,
15726 &remote_show_cmdlist
);
15727 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15729 &remote_hw_watchpoint_length_limit
, _("\
15730 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15731 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15732 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15733 NULL
, show_hardware_watchpoint_length_limit
,
15734 &remote_set_cmdlist
, &remote_show_cmdlist
);
15735 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class
,
15736 &remote_hw_breakpoint_limit
, _("\
15737 Set the maximum number of target hardware breakpoints."), _("\
15738 Show the maximum number of target hardware breakpoints."), _("\
15739 Specify \"unlimited\" for unlimited hardware breakpoints."),
15740 NULL
, show_hardware_breakpoint_limit
,
15741 &remote_set_cmdlist
, &remote_show_cmdlist
);
15743 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure
,
15744 &remote_address_size
, _("\
15745 Set the maximum size of the address (in bits) in a memory packet."), _("\
15746 Show the maximum size of the address (in bits) in a memory packet."), NULL
,
15748 NULL
, /* FIXME: i18n: */
15749 &setlist
, &showlist
);
15751 init_all_packet_configs ();
15753 add_packet_config_cmd (PACKET_X
, "X", "binary-download", 1);
15755 add_packet_config_cmd (PACKET_vCont
, "vCont", "verbose-resume", 0);
15757 add_packet_config_cmd (PACKET_QPassSignals
, "QPassSignals", "pass-signals",
15760 add_packet_config_cmd (PACKET_QCatchSyscalls
, "QCatchSyscalls",
15761 "catch-syscalls", 0);
15763 add_packet_config_cmd (PACKET_QProgramSignals
, "QProgramSignals",
15764 "program-signals", 0);
15766 add_packet_config_cmd (PACKET_QSetWorkingDir
, "QSetWorkingDir",
15767 "set-working-dir", 0);
15769 add_packet_config_cmd (PACKET_QStartupWithShell
, "QStartupWithShell",
15770 "startup-with-shell", 0);
15772 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded
,"QEnvironmentHexEncoded",
15773 "environment-hex-encoded", 0);
15775 add_packet_config_cmd (PACKET_QEnvironmentReset
, "QEnvironmentReset",
15776 "environment-reset", 0);
15778 add_packet_config_cmd (PACKET_QEnvironmentUnset
, "QEnvironmentUnset",
15779 "environment-unset", 0);
15781 add_packet_config_cmd (PACKET_qSymbol
, "qSymbol", "symbol-lookup", 0);
15783 add_packet_config_cmd (PACKET_P
, "P", "set-register", 1);
15785 add_packet_config_cmd (PACKET_p
, "p", "fetch-register", 1);
15787 add_packet_config_cmd (PACKET_Z0
, "Z0", "software-breakpoint", 0);
15789 add_packet_config_cmd (PACKET_Z1
, "Z1", "hardware-breakpoint", 0);
15791 add_packet_config_cmd (PACKET_Z2
, "Z2", "write-watchpoint", 0);
15793 add_packet_config_cmd (PACKET_Z3
, "Z3", "read-watchpoint", 0);
15795 add_packet_config_cmd (PACKET_Z4
, "Z4", "access-watchpoint", 0);
15797 add_packet_config_cmd (PACKET_qXfer_auxv
, "qXfer:auxv:read",
15798 "read-aux-vector", 0);
15800 add_packet_config_cmd (PACKET_qXfer_exec_file
, "qXfer:exec-file:read",
15801 "pid-to-exec-file", 0);
15803 add_packet_config_cmd (PACKET_qXfer_features
,
15804 "qXfer:features:read", "target-features", 0);
15806 add_packet_config_cmd (PACKET_qXfer_libraries
, "qXfer:libraries:read",
15807 "library-info", 0);
15809 add_packet_config_cmd (PACKET_qXfer_libraries_svr4
,
15810 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15812 add_packet_config_cmd (PACKET_qXfer_memory_map
, "qXfer:memory-map:read",
15815 add_packet_config_cmd (PACKET_qXfer_osdata
, "qXfer:osdata:read", "osdata", 0);
15817 add_packet_config_cmd (PACKET_qXfer_threads
, "qXfer:threads:read", "threads",
15820 add_packet_config_cmd (PACKET_qXfer_siginfo_read
, "qXfer:siginfo:read",
15821 "read-siginfo-object", 0);
15823 add_packet_config_cmd (PACKET_qXfer_siginfo_write
, "qXfer:siginfo:write",
15824 "write-siginfo-object", 0);
15826 add_packet_config_cmd (PACKET_qXfer_traceframe_info
,
15827 "qXfer:traceframe-info:read", "traceframe-info", 0);
15829 add_packet_config_cmd (PACKET_qXfer_uib
, "qXfer:uib:read",
15830 "unwind-info-block", 0);
15832 add_packet_config_cmd (PACKET_qGetTLSAddr
, "qGetTLSAddr",
15833 "get-thread-local-storage-address", 0);
15835 add_packet_config_cmd (PACKET_qGetTIBAddr
, "qGetTIBAddr",
15836 "get-thread-information-block-address", 0);
15838 add_packet_config_cmd (PACKET_bc
, "bc", "reverse-continue", 0);
15840 add_packet_config_cmd (PACKET_bs
, "bs", "reverse-step", 0);
15842 add_packet_config_cmd (PACKET_qSupported
, "qSupported", "supported-packets",
15845 add_packet_config_cmd (PACKET_qSearch_memory
, "qSearch:memory",
15846 "search-memory", 0);
15848 add_packet_config_cmd (PACKET_qTStatus
, "qTStatus", "trace-status", 0);
15850 add_packet_config_cmd (PACKET_vFile_setfs
, "vFile:setfs", "hostio-setfs", 0);
15852 add_packet_config_cmd (PACKET_vFile_open
, "vFile:open", "hostio-open", 0);
15854 add_packet_config_cmd (PACKET_vFile_pread
, "vFile:pread", "hostio-pread", 0);
15856 add_packet_config_cmd (PACKET_vFile_pwrite
, "vFile:pwrite", "hostio-pwrite",
15859 add_packet_config_cmd (PACKET_vFile_close
, "vFile:close", "hostio-close", 0);
15861 add_packet_config_cmd (PACKET_vFile_unlink
, "vFile:unlink", "hostio-unlink",
15864 add_packet_config_cmd (PACKET_vFile_readlink
, "vFile:readlink",
15865 "hostio-readlink", 0);
15867 add_packet_config_cmd (PACKET_vFile_fstat
, "vFile:fstat", "hostio-fstat", 0);
15869 add_packet_config_cmd (PACKET_vAttach
, "vAttach", "attach", 0);
15871 add_packet_config_cmd (PACKET_vRun
, "vRun", "run", 0);
15873 add_packet_config_cmd (PACKET_QStartNoAckMode
, "QStartNoAckMode", "noack", 0);
15875 add_packet_config_cmd (PACKET_vKill
, "vKill", "kill", 0);
15877 add_packet_config_cmd (PACKET_qAttached
, "qAttached", "query-attached", 0);
15879 add_packet_config_cmd (PACKET_ConditionalTracepoints
,
15880 "ConditionalTracepoints", "conditional-tracepoints",
15883 add_packet_config_cmd (PACKET_ConditionalBreakpoints
,
15884 "ConditionalBreakpoints", "conditional-breakpoints",
15887 add_packet_config_cmd (PACKET_BreakpointCommands
, "BreakpointCommands",
15888 "breakpoint-commands", 0);
15890 add_packet_config_cmd (PACKET_FastTracepoints
, "FastTracepoints",
15891 "fast-tracepoints", 0);
15893 add_packet_config_cmd (PACKET_TracepointSource
, "TracepointSource",
15894 "TracepointSource", 0);
15896 add_packet_config_cmd (PACKET_QAllow
, "QAllow", "allow", 0);
15898 add_packet_config_cmd (PACKET_StaticTracepoints
, "StaticTracepoints",
15899 "static-tracepoints", 0);
15901 add_packet_config_cmd (PACKET_InstallInTrace
, "InstallInTrace",
15902 "install-in-trace", 0);
15904 add_packet_config_cmd (PACKET_qXfer_statictrace_read
,
15905 "qXfer:statictrace:read", "read-sdata-object", 0);
15907 add_packet_config_cmd (PACKET_qXfer_fdpic
, "qXfer:fdpic:read",
15908 "read-fdpic-loadmap", 0);
15910 add_packet_config_cmd (PACKET_QDisableRandomization
, "QDisableRandomization",
15911 "disable-randomization", 0);
15913 add_packet_config_cmd (PACKET_QAgent
, "QAgent", "agent", 0);
15915 add_packet_config_cmd (PACKET_QTBuffer_size
, "QTBuffer:size",
15916 "trace-buffer-size", 0);
15918 add_packet_config_cmd (PACKET_Qbtrace_off
, "Qbtrace:off", "disable-btrace",
15921 add_packet_config_cmd (PACKET_Qbtrace_bts
, "Qbtrace:bts", "enable-btrace-bts",
15924 add_packet_config_cmd (PACKET_Qbtrace_pt
, "Qbtrace:pt", "enable-btrace-pt",
15927 add_packet_config_cmd (PACKET_qXfer_btrace
, "qXfer:btrace", "read-btrace", 0);
15929 add_packet_config_cmd (PACKET_qXfer_btrace_conf
, "qXfer:btrace-conf",
15930 "read-btrace-conf", 0);
15932 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size
, "Qbtrace-conf:bts:size",
15933 "btrace-conf-bts-size", 0);
15935 add_packet_config_cmd (PACKET_multiprocess_feature
, "multiprocess-feature",
15936 "multiprocess-feature", 0);
15938 add_packet_config_cmd (PACKET_swbreak_feature
, "swbreak-feature",
15939 "swbreak-feature", 0);
15941 add_packet_config_cmd (PACKET_hwbreak_feature
, "hwbreak-feature",
15942 "hwbreak-feature", 0);
15944 add_packet_config_cmd (PACKET_fork_event_feature
, "fork-event-feature",
15945 "fork-event-feature", 0);
15947 add_packet_config_cmd (PACKET_vfork_event_feature
, "vfork-event-feature",
15948 "vfork-event-feature", 0);
15950 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size
, "Qbtrace-conf:pt:size",
15951 "btrace-conf-pt-size", 0);
15953 add_packet_config_cmd (PACKET_vContSupported
, "vContSupported",
15954 "verbose-resume-supported", 0);
15956 add_packet_config_cmd (PACKET_exec_event_feature
, "exec-event-feature",
15957 "exec-event-feature", 0);
15959 add_packet_config_cmd (PACKET_vCtrlC
, "vCtrlC", "ctrl-c", 0);
15961 add_packet_config_cmd (PACKET_QThreadEvents
, "QThreadEvents", "thread-events",
15964 add_packet_config_cmd (PACKET_QThreadOptions
, "QThreadOptions",
15965 "thread-options", 0);
15967 add_packet_config_cmd (PACKET_no_resumed
, "N stop reply",
15968 "no-resumed-stop-reply", 0);
15970 add_packet_config_cmd (PACKET_memory_tagging_feature
,
15971 "memory-tagging-feature", "memory-tagging-feature", 0);
15973 /* Assert that we've registered "set remote foo-packet" commands
15974 for all packet configs. */
15978 for (i
= 0; i
< PACKET_MAX
; i
++)
15980 /* Ideally all configs would have a command associated. Some
15981 still don't though. */
15986 case PACKET_QNonStop
:
15987 case PACKET_EnableDisableTracepoints_feature
:
15988 case PACKET_tracenz_feature
:
15989 case PACKET_DisconnectedTracing_feature
:
15990 case PACKET_augmented_libraries_svr4_read_feature
:
15992 /* Additions to this list need to be well justified:
15993 pre-existing packets are OK; new packets are not. */
16001 /* This catches both forgetting to add a config command, and
16002 forgetting to remove a packet from the exception list. */
16003 gdb_assert (excepted
== (packets_descriptions
[i
].name
== NULL
));
16007 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16008 Z sub-packet has its own set and show commands, but users may
16009 have sets to this variable in their .gdbinit files (or in their
16011 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure
,
16012 &remote_Z_packet_detect
, _("\
16013 Set use of remote protocol `Z' packets."), _("\
16014 Show use of remote protocol `Z' packets."), _("\
16015 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16017 set_remote_protocol_Z_packet_cmd
,
16018 show_remote_protocol_Z_packet_cmd
,
16019 /* FIXME: i18n: Use of remote protocol
16020 `Z' packets is %s. */
16021 &remote_set_cmdlist
, &remote_show_cmdlist
);
16023 add_basic_prefix_cmd ("remote", class_files
, _("\
16024 Manipulate files on the remote system.\n\
16025 Transfer files to and from the remote target system."),
16027 0 /* allow-unknown */, &cmdlist
);
16029 add_cmd ("put", class_files
, remote_put_command
,
16030 _("Copy a local file to the remote system."),
16033 add_cmd ("get", class_files
, remote_get_command
,
16034 _("Copy a remote file to the local system."),
16037 add_cmd ("delete", class_files
, remote_delete_command
,
16038 _("Delete a remote file."),
16041 add_setshow_string_noescape_cmd ("exec-file", class_files
,
16042 &remote_exec_file_var
, _("\
16043 Set the remote pathname for \"run\"."), _("\
16044 Show the remote pathname for \"run\"."), NULL
,
16045 set_remote_exec_file
,
16046 show_remote_exec_file
,
16047 &remote_set_cmdlist
,
16048 &remote_show_cmdlist
);
16050 add_setshow_boolean_cmd ("range-stepping", class_run
,
16051 &use_range_stepping
, _("\
16052 Enable or disable range stepping."), _("\
16053 Show whether target-assisted range stepping is enabled."), _("\
16054 If on, and the target supports it, when stepping a source line, GDB\n\
16055 tells the target to step the corresponding range of addresses itself instead\n\
16056 of issuing multiple single-steps. This speeds up source level\n\
16057 stepping. If off, GDB always issues single-steps, even if range\n\
16058 stepping is supported by the target. The default is on."),
16059 set_range_stepping
,
16060 show_range_stepping
,
16064 add_setshow_zinteger_cmd ("watchdog", class_maintenance
, &watchdog
, _("\
16065 Set watchdog timer."), _("\
16066 Show watchdog timer."), _("\
16067 When non-zero, this timeout is used instead of waiting forever for a target\n\
16068 to finish a low-level step or continue operation. If the specified amount\n\
16069 of time passes without a response from the target, an error occurs."),
16072 &setlist
, &showlist
);
16074 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class
,
16075 &remote_packet_max_chars
, _("\
16076 Set the maximum number of characters to display for each remote packet."), _("\
16077 Show the maximum number of characters to display for each remote packet."), _("\
16078 Specify \"unlimited\" to display all the characters."),
16079 NULL
, show_remote_packet_max_chars
,
16080 &setdebuglist
, &showdebuglist
);
16082 add_setshow_boolean_cmd ("remote", no_class
, &remote_debug
,
16083 _("Set debugging of remote protocol."),
16084 _("Show debugging of remote protocol."),
16086 When enabled, each packet sent or received with the remote target\n\
16090 &setdebuglist
, &showdebuglist
);
16092 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class
,
16093 &remote_timeout
, _("\
16094 Set timeout limit to wait for target to respond."), _("\
16095 Show timeout limit to wait for target to respond."), _("\
16096 This value is used to set the time limit for gdb to wait for a response\n\
16097 from the target."),
16099 show_remote_timeout
,
16100 &setlist
, &showlist
);
16102 /* Eventually initialize fileio. See fileio.c */
16103 initialize_remote_fileio (&remote_set_cmdlist
, &remote_show_cmdlist
);
16106 selftests::register_test ("remote_memory_tagging",
16107 selftests::test_memory_tagging_functions
);