Automatic date update in version.in
[binutils-gdb.git] / gdb / remote.c
blob84daa8567b694cc47ef2b016e5d8a82567c6d270
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. */
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdbthread.h"
34 #include "remote.h"
35 #include "remote-notif.h"
36 #include "regcache.h"
37 #include "value.h"
38 #include "observable.h"
39 #include "solib.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "target-descriptions.h"
43 #include "gdb_bfd.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
46 #include "disasm.h"
47 #include "location.h"
49 #include "gdbsupport/gdb_sys_time.h"
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
55 #include <signal.h>
56 #include "serial.h"
58 #include "gdbcore.h"
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
62 #include <sys/stat.h>
63 #include "xml-support.h"
65 #include "memory-map.h"
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70 #include "gdbsupport/agent.h"
71 #include "btrace.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"
77 #include <algorithm>
78 #include <iterator>
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.).");
90 /* See remote.h */
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;
103 struct packet_reg;
105 struct stop_reply;
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. */
112 enum packet_support
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
121 static const char *
122 get_packet_support_name (auto_boolean support)
124 switch (support)
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
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. */
140 static const char *
141 get_target_type_name (bool target_connected)
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
149 /* Analyze a packet's return value and update the packet config
150 accordingly. */
152 enum packet_result
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
159 /* Enumeration of packets for a remote target. */
161 enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
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
229 running. */
230 PACKET_InstallInTrace,
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
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
265 disconnected. */
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. */
299 PACKET_vCtrlC,
301 /* Support TARGET_WAITKIND_NO_RESUMED. */
302 PACKET_no_resumed,
304 /* Support for memory tagging, allocation tag fetch/store
305 packets and the tag violation stop replies. */
306 PACKET_memory_tagging_feature,
308 PACKET_MAX
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
320 /* vCont;t */
321 bool t = false;
323 /* vCont;r */
324 bool r = false;
326 /* vCont;s */
327 bool s = false;
329 /* vCont;S */
330 bool S = false;
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. */
342 void invalidate ();
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
352 cache is invalid. */
353 int fd = -1;
355 /* The offset into the file that the cache buffer corresponds
356 to. */
357 ULONGEST offset = 0;
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. */
369 struct packet_reg
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);
376 at present. */
377 /* char *name; == gdbarch_register_name (arch, regnum);
378 at present. */
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
397 trailers). */
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. */
409 class remote_state
411 public:
413 remote_state ();
414 ~remote_state ();
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);
427 nullptr, "remote");
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);
462 public: /* data */
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
469 packets. */
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
484 reliable. */
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
515 starts. */
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
536 target. */
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. */
574 int fs_pid = -1;
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
599 this can go away. */
600 bool wait_forever_enabled_p = true;
602 /* The set of thread options the target reported it supports, via
603 qSupported. */
604 gdb_thread_options supported_thread_options = 0;
606 private:
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>
615 m_arch_states;
618 static const target_info remote_target_info = {
619 "remote",
620 N_("Remote target using gdb-specific protocol"),
621 remote_doc
624 /* Description of a remote packet. */
626 struct packet_description
628 /* Name of the packet used for gdb output. */
629 const char *name;
631 /* Title of the packet, used by the set/show remote name-packet
632 commands to identify the individual packages and gdb output. */
633 const char *title;
636 /* Configuration of a remote packet. */
638 struct packet_config
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
661 const char *name;
662 long size;
663 int fixed_p;
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
688 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
744 configurations. */
745 packet_config m_protocol_packets[PACKET_MAX];
748 class remote_target : public process_stratum_target
750 public:
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,
840 int handle_len,
841 inferior *inf) override;
843 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
844 override;
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,
853 const char *annex,
854 gdb_byte *readbuf,
855 const gdb_byte *writebuf,
856 ULONGEST offset, ULONGEST len,
857 ULONGEST *xfered_len) override;
859 ULONGEST get_memory_xfer_limit () override;
861 void rcmd (const char *command, struct ui_file *output) override;
863 const char *pid_to_exec_file (int pid) override;
865 void log_command (const char *cmd) override
867 serial_log_command (this, cmd);
870 CORE_ADDR get_thread_local_address (ptid_t ptid,
871 CORE_ADDR load_module_addr,
872 CORE_ADDR offset) override;
874 bool can_execute_reverse () override;
876 std::vector<mem_region> memory_map () override;
878 void flash_erase (ULONGEST address, LONGEST length) override;
880 void flash_done () override;
882 const struct target_desc *read_description () override;
884 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
885 const gdb_byte *pattern, ULONGEST pattern_len,
886 CORE_ADDR *found_addrp) override;
888 bool can_async_p () override;
890 bool is_async_p () override;
892 void async (bool) override;
894 int async_wait_fd () override;
896 void thread_events (int) override;
898 bool supports_set_thread_options (gdb_thread_options) override;
900 int can_do_single_step () override;
902 void terminal_inferior () override;
904 void terminal_ours () override;
906 bool supports_non_stop () override;
908 bool supports_multi_process () override;
910 bool supports_disable_randomization () override;
912 bool filesystem_is_local () override;
915 int fileio_open (struct inferior *inf, const char *filename,
916 int flags, int mode, int warn_if_slow,
917 fileio_error *target_errno) override;
919 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
920 ULONGEST offset, fileio_error *target_errno) override;
922 int fileio_pread (int fd, gdb_byte *read_buf, int len,
923 ULONGEST offset, fileio_error *target_errno) override;
925 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
927 int fileio_close (int fd, fileio_error *target_errno) override;
929 int fileio_unlink (struct inferior *inf,
930 const char *filename,
931 fileio_error *target_errno) override;
933 std::optional<std::string>
934 fileio_readlink (struct inferior *inf,
935 const char *filename,
936 fileio_error *target_errno) override;
938 bool supports_enable_disable_tracepoint () override;
940 bool supports_string_tracing () override;
942 int remote_supports_cond_tracepoints ();
944 bool supports_evaluation_of_breakpoint_conditions () override;
946 int remote_supports_fast_tracepoints ();
948 int remote_supports_static_tracepoints ();
950 int remote_supports_install_in_trace ();
952 bool can_run_breakpoint_commands () override;
954 void trace_init () override;
956 void download_tracepoint (struct bp_location *location) override;
958 bool can_download_tracepoint () override;
960 void download_trace_state_variable (const trace_state_variable &tsv) override;
962 void enable_tracepoint (struct bp_location *location) override;
964 void disable_tracepoint (struct bp_location *location) override;
966 void trace_set_readonly_regions () override;
968 void trace_start () override;
970 int get_trace_status (struct trace_status *ts) override;
972 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
973 override;
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)
1013 override;
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,
1061 int from_tty);
1062 void remote_file_get (const char *remote_file, const char *local_file,
1063 int from_tty);
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,
1096 ptid_t ptid);
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,
1125 bool silent_p);
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,
1152 int try_open_exec);
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,
1172 int *doneflag);
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,
1200 const char *value);
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,
1217 packet_reg *reg);
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,
1222 packet_reg *reg);
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,
1230 CORE_ADDR memaddr,
1231 const gdb_byte *myaddr,
1232 ULONGEST len_units,
1233 int unit_size,
1234 ULONGEST *xfered_len_units,
1235 char packet_format,
1236 int use_length);
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,
1243 ULONGEST len_units,
1244 int unit_size, ULONGEST *xfered_len_units);
1246 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1247 ULONGEST memaddr,
1248 ULONGEST len,
1249 int unit_size,
1250 ULONGEST *xfered_len);
1252 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1253 gdb_byte *myaddr, ULONGEST len,
1254 int unit_size,
1255 ULONGEST *xfered_len);
1257 packet_result remote_send_printf (const char *format, ...)
1258 ATTRIBUTE_PRINTF (2, 3);
1260 target_xfer_status remote_flash_write (ULONGEST address,
1261 ULONGEST length, ULONGEST *xfered_len,
1262 const gdb_byte *data);
1264 int readchar (int timeout);
1266 void remote_serial_write (const char *str, int len);
1267 void remote_serial_send_break ();
1269 int putpkt (const char *buf);
1270 int putpkt_binary (const char *buf, int cnt);
1272 int putpkt (const gdb::char_vector &buf)
1274 return putpkt (buf.data ());
1277 void skip_frame ();
1278 long read_frame (gdb::char_vector *buf_p);
1279 int getpkt (gdb::char_vector *buf, bool forever = false,
1280 bool *is_notif = nullptr);
1281 int remote_vkill (int pid);
1282 void remote_kill_k ();
1284 void extended_remote_disable_randomization (int val);
1285 int extended_remote_run (const std::string &args);
1287 void send_environment_packet (const char *action,
1288 const char *packet,
1289 const char *value);
1291 void extended_remote_environment_support ();
1292 void extended_remote_set_inferior_cwd ();
1294 target_xfer_status remote_write_qxfer (const char *object_name,
1295 const char *annex,
1296 const gdb_byte *writebuf,
1297 ULONGEST offset, LONGEST len,
1298 ULONGEST *xfered_len,
1299 const unsigned int which_packet);
1301 target_xfer_status remote_read_qxfer (const char *object_name,
1302 const char *annex,
1303 gdb_byte *readbuf, ULONGEST offset,
1304 LONGEST len,
1305 ULONGEST *xfered_len,
1306 const unsigned int which_packet);
1308 void push_stop_reply (struct stop_reply *new_event);
1310 bool vcont_r_supported ();
1312 remote_features m_features;
1314 private:
1316 bool start_remote_1 (int from_tty, int extended_p);
1318 /* The remote state. Don't reference this directly. Use the
1319 get_remote_state method instead. */
1320 remote_state m_remote_state;
1323 static const target_info extended_remote_target_info = {
1324 "extended-remote",
1325 N_("Extended remote target using gdb-specific protocol"),
1326 remote_doc
1329 /* Set up the extended remote target by extending the standard remote
1330 target and adding to it. */
1332 class extended_remote_target final : public remote_target
1334 public:
1335 const target_info &info () const override
1336 { return extended_remote_target_info; }
1338 /* Open an extended-remote connection. */
1339 static void open (const char *, int);
1341 bool can_create_inferior () override { return true; }
1342 void create_inferior (const char *, const std::string &,
1343 char **, int) override;
1345 void detach (inferior *, int) override;
1347 bool can_attach () override { return true; }
1348 void attach (const char *, int) override;
1350 void post_attach (int) override;
1351 bool supports_disable_randomization () override;
1354 struct stop_reply : public notif_event
1356 ~stop_reply ();
1358 /* The identifier of the thread about this event */
1359 ptid_t ptid;
1361 /* The remote state this event is associated with. When the remote
1362 connection, represented by a remote_state object, is closed,
1363 all the associated stop_reply events should be released. */
1364 struct remote_state *rs;
1366 struct target_waitstatus ws;
1368 /* The architecture associated with the expedited registers. */
1369 gdbarch *arch;
1371 /* Expedited registers. This makes remote debugging a bit more
1372 efficient for those targets that provide critical registers as
1373 part of their normal status mechanism (as another roundtrip to
1374 fetch them is avoided). */
1375 std::vector<cached_reg_t> regcache;
1377 enum target_stop_reason stop_reason;
1379 CORE_ADDR watch_data_address;
1381 int core;
1384 /* Return TARGET as a remote_target if it is one, else nullptr. */
1386 static remote_target *
1387 as_remote_target (process_stratum_target *target)
1389 return dynamic_cast<remote_target *> (target);
1392 /* See remote.h. */
1394 bool
1395 is_remote_target (process_stratum_target *target)
1397 return as_remote_target (target) != nullptr;
1400 /* Per-program-space data key. */
1401 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1402 remote_pspace_data;
1404 /* The variable registered as the control variable used by the
1405 remote exec-file commands. While the remote exec-file setting is
1406 per-program-space, the set/show machinery uses this as the
1407 location of the remote exec-file value. */
1408 static std::string remote_exec_file_var;
1410 /* The size to align memory write packets, when practical. The protocol
1411 does not guarantee any alignment, and gdb will generate short
1412 writes and unaligned writes, but even as a best-effort attempt this
1413 can improve bulk transfers. For instance, if a write is misaligned
1414 relative to the target's data bus, the stub may need to make an extra
1415 round trip fetching data from the target. This doesn't make a
1416 huge difference, but it's easy to do, so we try to be helpful.
1418 The alignment chosen is arbitrary; usually data bus width is
1419 important here, not the possibly larger cache line size. */
1420 enum { REMOTE_ALIGN_WRITES = 16 };
1422 /* Prototypes for local functions. */
1424 static int hexnumlen (ULONGEST num);
1426 static int stubhex (int ch);
1428 static int hexnumstr (char *, ULONGEST);
1430 static int hexnumnstr (char *, ULONGEST, int);
1432 static CORE_ADDR remote_address_masked (CORE_ADDR);
1434 static int stub_unpack_int (const char *buff, int fieldlength);
1436 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1437 cmd_list_element *c);
1439 static void show_packet_config_cmd (ui_file *file,
1440 const unsigned int which_packet,
1441 remote_target *remote);
1443 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1444 int from_tty,
1445 struct cmd_list_element *c,
1446 const char *value);
1448 static ptid_t read_ptid (const char *buf, const char **obuf);
1450 static bool remote_read_description_p (struct target_ops *target);
1452 static void remote_console_output (const char *msg);
1454 static void remote_btrace_reset (remote_state *rs);
1456 static void remote_unpush_and_throw (remote_target *target);
1458 /* For "remote". */
1460 static struct cmd_list_element *remote_cmdlist;
1462 /* For "set remote" and "show remote". */
1464 static struct cmd_list_element *remote_set_cmdlist;
1465 static struct cmd_list_element *remote_show_cmdlist;
1467 /* Controls whether GDB is willing to use range stepping. */
1469 static bool use_range_stepping = true;
1471 /* From the remote target's point of view, each thread is in one of these three
1472 states. */
1473 enum class resume_state
1475 /* Not resumed - we haven't been asked to resume this thread. */
1476 NOT_RESUMED,
1478 /* We have been asked to resume this thread, but haven't sent a vCont action
1479 for it yet. We'll need to consider it next time commit_resume is
1480 called. */
1481 RESUMED_PENDING_VCONT,
1483 /* We have been asked to resume this thread, and we have sent a vCont action
1484 for it. */
1485 RESUMED,
1488 /* Information about a thread's pending vCont-resume. Used when a thread is in
1489 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1490 stores this information which is then picked up by
1491 remote_target::commit_resume to know which is the proper action for this
1492 thread to include in the vCont packet. */
1493 struct resumed_pending_vcont_info
1495 /* True if the last resume call for this thread was a step request, false
1496 if a continue request. */
1497 bool step;
1499 /* The signal specified in the last resume call for this thread. */
1500 gdb_signal sig;
1503 /* Private data that we'll store in (struct thread_info)->priv. */
1504 struct remote_thread_info : public private_thread_info
1506 std::string extra;
1507 std::string name;
1508 int core = -1;
1510 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1511 sequence of bytes. */
1512 gdb::byte_vector thread_handle;
1514 /* Whether the target stopped for a breakpoint/watchpoint. */
1515 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1517 /* This is set to the data address of the access causing the target
1518 to stop for a watchpoint. */
1519 CORE_ADDR watch_data_address = 0;
1521 /* Get the thread's resume state. */
1522 enum resume_state get_resume_state () const
1524 return m_resume_state;
1527 /* Put the thread in the NOT_RESUMED state. */
1528 void set_not_resumed ()
1530 m_resume_state = resume_state::NOT_RESUMED;
1533 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1534 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1536 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1537 m_resumed_pending_vcont_info.step = step;
1538 m_resumed_pending_vcont_info.sig = sig;
1541 /* Get the information this thread's pending vCont-resumption.
1543 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1544 state. */
1545 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1547 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1549 return m_resumed_pending_vcont_info;
1552 /* Put the thread in the VCONT_RESUMED state. */
1553 void set_resumed ()
1555 m_resume_state = resume_state::RESUMED;
1558 private:
1559 /* Resume state for this thread. This is used to implement vCont action
1560 coalescing (only when the target operates in non-stop mode).
1562 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1563 which notes that this thread must be considered in the next commit_resume
1564 call.
1566 remote_target::commit_resume sends a vCont packet with actions for the
1567 threads in the RESUMED_PENDING_VCONT state and moves them to the
1568 VCONT_RESUMED state.
1570 When reporting a stop to the core for a thread, that thread is moved back
1571 to the NOT_RESUMED state. */
1572 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1574 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1575 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1578 remote_state::remote_state ()
1579 : buf (400)
1583 remote_state::~remote_state ()
1585 xfree (this->last_pass_packet);
1586 xfree (this->last_program_signals_packet);
1587 xfree (this->finished_object);
1588 xfree (this->finished_annex);
1591 /* Utility: generate error from an incoming stub packet. */
1592 static void
1593 trace_error (char *buf)
1595 if (*buf++ != 'E')
1596 return; /* not an error msg */
1597 switch (*buf)
1599 case '1': /* malformed packet error */
1600 if (*++buf == '0') /* general case: */
1601 error (_("remote.c: error in outgoing packet."));
1602 else
1603 error (_("remote.c: error in outgoing packet at field #%ld."),
1604 strtol (buf, NULL, 16));
1605 default:
1606 error (_("Target returns error code '%s'."), buf);
1610 /* Utility: wait for reply from stub, while accepting "O" packets. */
1612 char *
1613 remote_target::remote_get_noisy_reply ()
1615 struct remote_state *rs = get_remote_state ();
1617 do /* Loop on reply from remote stub. */
1619 char *buf;
1621 QUIT; /* Allow user to bail out with ^C. */
1622 getpkt (&rs->buf);
1623 buf = rs->buf.data ();
1624 if (buf[0] == 'E')
1625 trace_error (buf);
1626 else if (startswith (buf, "qRelocInsn:"))
1628 ULONGEST ul;
1629 CORE_ADDR from, to, org_to;
1630 const char *p, *pp;
1631 int adjusted_size = 0;
1632 int relocated = 0;
1634 p = buf + strlen ("qRelocInsn:");
1635 pp = unpack_varlen_hex (p, &ul);
1636 if (*pp != ';')
1637 error (_("invalid qRelocInsn packet: %s"), buf);
1638 from = ul;
1640 p = pp + 1;
1641 unpack_varlen_hex (p, &ul);
1642 to = ul;
1644 org_to = to;
1648 gdbarch_relocate_instruction (current_inferior ()->arch (),
1649 &to, from);
1650 relocated = 1;
1652 catch (const gdb_exception &ex)
1654 if (ex.error == MEMORY_ERROR)
1656 /* Propagate memory errors silently back to the
1657 target. The stub may have limited the range of
1658 addresses we can write to, for example. */
1660 else
1662 /* Something unexpectedly bad happened. Be verbose
1663 so we can tell what, and propagate the error back
1664 to the stub, so it doesn't get stuck waiting for
1665 a response. */
1666 exception_fprintf (gdb_stderr, ex,
1667 _("warning: relocating instruction: "));
1669 putpkt ("E01");
1672 if (relocated)
1674 adjusted_size = to - org_to;
1676 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1677 putpkt (buf);
1680 else if (buf[0] == 'O' && buf[1] != 'K')
1681 remote_console_output (buf + 1); /* 'O' message from stub */
1682 else
1683 return buf; /* Here's the actual reply. */
1685 while (1);
1688 struct remote_arch_state *
1689 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1691 remote_arch_state *rsa;
1693 auto it = this->m_arch_states.find (gdbarch);
1694 if (it == this->m_arch_states.end ())
1696 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1697 std::forward_as_tuple (gdbarch),
1698 std::forward_as_tuple (gdbarch));
1699 rsa = &p.first->second;
1701 /* Make sure that the packet buffer is plenty big enough for
1702 this architecture. */
1703 if (this->buf.size () < rsa->remote_packet_size)
1704 this->buf.resize (2 * rsa->remote_packet_size);
1706 else
1707 rsa = &it->second;
1709 return rsa;
1712 /* Fetch the global remote target state. */
1714 remote_state *
1715 remote_target::get_remote_state ()
1717 /* Make sure that the remote architecture state has been
1718 initialized, because doing so might reallocate rs->buf. Any
1719 function which calls getpkt also needs to be mindful of changes
1720 to rs->buf, but this call limits the number of places which run
1721 into trouble. */
1722 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1724 return &m_remote_state;
1727 /* Fetch the remote exec-file from the current program space. */
1729 static const char *
1730 get_remote_exec_file (void)
1732 char *remote_exec_file;
1734 remote_exec_file = remote_pspace_data.get (current_program_space);
1735 if (remote_exec_file == NULL)
1736 return "";
1738 return remote_exec_file;
1741 /* Set the remote exec file for PSPACE. */
1743 static void
1744 set_pspace_remote_exec_file (struct program_space *pspace,
1745 const char *remote_exec_file)
1747 char *old_file = remote_pspace_data.get (pspace);
1749 xfree (old_file);
1750 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1753 /* The "set/show remote exec-file" set command hook. */
1755 static void
1756 set_remote_exec_file (const char *ignored, int from_tty,
1757 struct cmd_list_element *c)
1759 set_pspace_remote_exec_file (current_program_space,
1760 remote_exec_file_var.c_str ());
1763 /* The "set/show remote exec-file" show command hook. */
1765 static void
1766 show_remote_exec_file (struct ui_file *file, int from_tty,
1767 struct cmd_list_element *cmd, const char *value)
1769 gdb_printf (file, "%s\n", get_remote_exec_file ());
1772 static int
1773 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1775 int regnum, num_remote_regs, offset;
1776 struct packet_reg **remote_regs;
1778 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1780 struct packet_reg *r = &regs[regnum];
1782 if (register_size (gdbarch, regnum) == 0)
1783 /* Do not try to fetch zero-sized (placeholder) registers. */
1784 r->pnum = -1;
1785 else
1786 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1788 r->regnum = regnum;
1791 /* Define the g/G packet format as the contents of each register
1792 with a remote protocol number, in order of ascending protocol
1793 number. */
1795 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1796 for (num_remote_regs = 0, regnum = 0;
1797 regnum < gdbarch_num_regs (gdbarch);
1798 regnum++)
1799 if (regs[regnum].pnum != -1)
1800 remote_regs[num_remote_regs++] = &regs[regnum];
1802 std::sort (remote_regs, remote_regs + num_remote_regs,
1803 [] (const packet_reg *a, const packet_reg *b)
1804 { return a->pnum < b->pnum; });
1806 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1808 remote_regs[regnum]->in_g_packet = 1;
1809 remote_regs[regnum]->offset = offset;
1810 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1813 return offset;
1816 /* Given the architecture described by GDBARCH, return the remote
1817 protocol register's number and the register's offset in the g/G
1818 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1819 If the target does not have a mapping for REGNUM, return false,
1820 otherwise, return true. */
1823 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1824 int *pnum, int *poffset)
1826 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1828 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1830 map_regcache_remote_table (gdbarch, regs.data ());
1832 *pnum = regs[regnum].pnum;
1833 *poffset = regs[regnum].offset;
1835 return *pnum != -1;
1838 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1840 /* Use the architecture to build a regnum<->pnum table, which will be
1841 1:1 unless a feature set specifies otherwise. */
1842 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1844 /* Record the maximum possible size of the g packet - it may turn out
1845 to be smaller. */
1846 this->sizeof_g_packet
1847 = map_regcache_remote_table (gdbarch, this->regs.get ());
1849 /* Default maximum number of characters in a packet body. Many
1850 remote stubs have a hardwired buffer size of 400 bytes
1851 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1852 as the maximum packet-size to ensure that the packet and an extra
1853 NUL character can always fit in the buffer. This stops GDB
1854 trashing stubs that try to squeeze an extra NUL into what is
1855 already a full buffer (As of 1999-12-04 that was most stubs). */
1856 this->remote_packet_size = 400 - 1;
1858 /* This one is filled in when a ``g'' packet is received. */
1859 this->actual_register_packet_size = 0;
1861 /* Should rsa->sizeof_g_packet needs more space than the
1862 default, adjust the size accordingly. Remember that each byte is
1863 encoded as two characters. 32 is the overhead for the packet
1864 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1865 (``$NN:G...#NN'') is a better guess, the below has been padded a
1866 little. */
1867 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1868 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1871 /* Get a pointer to the current remote target. If not connected to a
1872 remote target, return NULL. */
1874 static remote_target *
1875 get_current_remote_target ()
1877 target_ops *proc_target = current_inferior ()->process_target ();
1878 return dynamic_cast<remote_target *> (proc_target);
1881 /* Return the current allowed size of a remote packet. This is
1882 inferred from the current architecture, and should be used to
1883 limit the length of outgoing packets. */
1884 long
1885 remote_target::get_remote_packet_size ()
1887 struct remote_state *rs = get_remote_state ();
1888 remote_arch_state *rsa
1889 = rs->get_remote_arch_state (current_inferior ()->arch ());
1891 if (rs->explicit_packet_size)
1892 return rs->explicit_packet_size;
1894 return rsa->remote_packet_size;
1897 static struct packet_reg *
1898 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1899 long regnum)
1901 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1902 return NULL;
1903 else
1905 struct packet_reg *r = &rsa->regs[regnum];
1907 gdb_assert (r->regnum == regnum);
1908 return r;
1912 static struct packet_reg *
1913 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1914 LONGEST pnum)
1916 int i;
1918 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1920 struct packet_reg *r = &rsa->regs[i];
1922 if (r->pnum == pnum)
1923 return r;
1925 return NULL;
1928 /* Allow the user to specify what sequence to send to the remote
1929 when he requests a program interruption: Although ^C is usually
1930 what remote systems expect (this is the default, here), it is
1931 sometimes preferable to send a break. On other systems such
1932 as the Linux kernel, a break followed by g, which is Magic SysRq g
1933 is required in order to interrupt the execution. */
1934 const char interrupt_sequence_control_c[] = "Ctrl-C";
1935 const char interrupt_sequence_break[] = "BREAK";
1936 const char interrupt_sequence_break_g[] = "BREAK-g";
1937 static const char *const interrupt_sequence_modes[] =
1939 interrupt_sequence_control_c,
1940 interrupt_sequence_break,
1941 interrupt_sequence_break_g,
1942 NULL
1944 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1946 static void
1947 show_interrupt_sequence (struct ui_file *file, int from_tty,
1948 struct cmd_list_element *c,
1949 const char *value)
1951 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1952 gdb_printf (file,
1953 _("Send the ASCII ETX character (Ctrl-c) "
1954 "to the remote target to interrupt the "
1955 "execution of the program.\n"));
1956 else if (interrupt_sequence_mode == interrupt_sequence_break)
1957 gdb_printf (file,
1958 _("send a break signal to the remote target "
1959 "to interrupt the execution of the program.\n"));
1960 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1961 gdb_printf (file,
1962 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1963 "the remote target to interrupt the execution "
1964 "of Linux kernel.\n"));
1965 else
1966 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1967 interrupt_sequence_mode);
1970 /* This boolean variable specifies whether interrupt_sequence is sent
1971 to the remote target when gdb connects to it.
1972 This is mostly needed when you debug the Linux kernel: The Linux kernel
1973 expects BREAK g which is Magic SysRq g for connecting gdb. */
1974 static bool interrupt_on_connect = false;
1976 /* This variable is used to implement the "set/show remotebreak" commands.
1977 Since these commands are now deprecated in favor of "set/show remote
1978 interrupt-sequence", it no longer has any effect on the code. */
1979 static bool remote_break;
1981 static void
1982 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1984 if (remote_break)
1985 interrupt_sequence_mode = interrupt_sequence_break;
1986 else
1987 interrupt_sequence_mode = interrupt_sequence_control_c;
1990 static void
1991 show_remotebreak (struct ui_file *file, int from_tty,
1992 struct cmd_list_element *c,
1993 const char *value)
1997 /* This variable sets the number of bits in an address that are to be
1998 sent in a memory ("M" or "m") packet. Normally, after stripping
1999 leading zeros, the entire address would be sent. This variable
2000 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2001 initial implementation of remote.c restricted the address sent in
2002 memory packets to ``host::sizeof long'' bytes - (typically 32
2003 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2004 address was never sent. Since fixing this bug may cause a break in
2005 some remote targets this variable is principally provided to
2006 facilitate backward compatibility. */
2008 static unsigned int remote_address_size;
2011 /* The default max memory-write-packet-size, when the setting is
2012 "fixed". The 16k is historical. (It came from older GDB's using
2013 alloca for buffers and the knowledge (folklore?) that some hosts
2014 don't cope very well with large alloca calls.) */
2015 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2017 /* The minimum remote packet size for memory transfers. Ensures we
2018 can write at least one byte. */
2019 #define MIN_MEMORY_PACKET_SIZE 20
2021 /* Get the memory packet size, assuming it is fixed. */
2023 static long
2024 get_fixed_memory_packet_size (struct memory_packet_config *config)
2026 gdb_assert (config->fixed_p);
2028 if (config->size <= 0)
2029 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2030 else
2031 return config->size;
2034 /* Compute the current size of a read/write packet. Since this makes
2035 use of ``actual_register_packet_size'' the computation is dynamic. */
2037 long
2038 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2040 struct remote_state *rs = get_remote_state ();
2041 remote_arch_state *rsa
2042 = rs->get_remote_arch_state (current_inferior ()->arch ());
2044 long what_they_get;
2045 if (config->fixed_p)
2046 what_they_get = get_fixed_memory_packet_size (config);
2047 else
2049 what_they_get = get_remote_packet_size ();
2050 /* Limit the packet to the size specified by the user. */
2051 if (config->size > 0
2052 && what_they_get > config->size)
2053 what_they_get = config->size;
2055 /* Limit it to the size of the targets ``g'' response unless we have
2056 permission from the stub to use a larger packet size. */
2057 if (rs->explicit_packet_size == 0
2058 && rsa->actual_register_packet_size > 0
2059 && what_they_get > rsa->actual_register_packet_size)
2060 what_they_get = rsa->actual_register_packet_size;
2062 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2063 what_they_get = MIN_MEMORY_PACKET_SIZE;
2065 /* Make sure there is room in the global buffer for this packet
2066 (including its trailing NUL byte). */
2067 if (rs->buf.size () < what_they_get + 1)
2068 rs->buf.resize (2 * what_they_get);
2070 return what_they_get;
2073 /* Update the size of a read/write packet. If they user wants
2074 something really big then do a sanity check. */
2076 static void
2077 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2078 bool target_connected)
2080 int fixed_p = config->fixed_p;
2081 long size = config->size;
2083 if (args == NULL)
2084 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2085 else if (strcmp (args, "hard") == 0
2086 || strcmp (args, "fixed") == 0)
2087 fixed_p = 1;
2088 else if (strcmp (args, "soft") == 0
2089 || strcmp (args, "limit") == 0)
2090 fixed_p = 0;
2091 else
2093 char *end;
2095 size = strtoul (args, &end, 0);
2096 if (args == end)
2097 error (_("Invalid %s (bad syntax)."), config->name);
2099 /* Instead of explicitly capping the size of a packet to or
2100 disallowing it, the user is allowed to set the size to
2101 something arbitrarily large. */
2104 /* Extra checks? */
2105 if (fixed_p && !config->fixed_p)
2107 /* So that the query shows the correct value. */
2108 long query_size = (size <= 0
2109 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2110 : size);
2112 if (target_connected
2113 && !query (_("The target may not be able to correctly handle a %s\n"
2114 "of %ld bytes. Change the packet size? "),
2115 config->name, query_size))
2116 error (_("Packet size not changed."));
2117 else if (!target_connected
2118 && !query (_("Future remote targets may not be able to "
2119 "correctly handle a %s\nof %ld bytes. Change the "
2120 "packet size for future remote targets? "),
2121 config->name, query_size))
2122 error (_("Packet size not changed."));
2124 /* Update the config. */
2125 config->fixed_p = fixed_p;
2126 config->size = size;
2128 const char *target_type = get_target_type_name (target_connected);
2129 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2130 args);
2134 /* Show the memory-read or write-packet size configuration CONFIG of the
2135 target REMOTE. If REMOTE is nullptr, the default configuration for future
2136 remote targets should be passed in CONFIG. */
2138 static void
2139 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2141 const char *target_type = get_target_type_name (remote != nullptr);
2143 if (config->size == 0)
2144 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2145 else
2146 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2147 config->size);
2149 if (config->fixed_p)
2150 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2151 get_fixed_memory_packet_size (config));
2152 else
2154 if (remote != nullptr)
2155 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2156 remote->get_memory_packet_size (config));
2157 else
2158 gdb_puts ("The actual limit will be further reduced "
2159 "dependent on the target.\n");
2163 /* Configure the memory-write-packet size of the currently selected target. If
2164 no target is available, the default configuration for future remote targets
2165 is configured. */
2167 static void
2168 set_memory_write_packet_size (const char *args, int from_tty)
2170 remote_target *remote = get_current_remote_target ();
2171 if (remote != nullptr)
2173 set_memory_packet_size
2174 (args, &remote->m_features.m_memory_write_packet_config, true);
2176 else
2178 memory_packet_config* config = &memory_write_packet_config;
2179 set_memory_packet_size (args, config, false);
2183 /* Display the memory-write-packet size of the currently selected target. If
2184 no target is available, the default configuration for future remote targets
2185 is shown. */
2187 static void
2188 show_memory_write_packet_size (const char *args, int from_tty)
2190 remote_target *remote = get_current_remote_target ();
2191 if (remote != nullptr)
2192 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2193 remote);
2194 else
2195 show_memory_packet_size (&memory_write_packet_config, nullptr);
2198 /* Show the number of hardware watchpoints that can be used. */
2200 static void
2201 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2202 struct cmd_list_element *c,
2203 const char *value)
2205 gdb_printf (file, _("The maximum number of target hardware "
2206 "watchpoints is %s.\n"), value);
2209 /* Show the length limit (in bytes) for hardware watchpoints. */
2211 static void
2212 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2213 struct cmd_list_element *c,
2214 const char *value)
2216 gdb_printf (file, _("The maximum length (in bytes) of a target "
2217 "hardware watchpoint is %s.\n"), value);
2220 /* Show the number of hardware breakpoints that can be used. */
2222 static void
2223 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2224 struct cmd_list_element *c,
2225 const char *value)
2227 gdb_printf (file, _("The maximum number of target hardware "
2228 "breakpoints is %s.\n"), value);
2231 /* Controls the maximum number of characters to display in the debug output
2232 for each remote packet. The remaining characters are omitted. */
2234 static int remote_packet_max_chars = 512;
2236 /* Show the maximum number of characters to display for each remote packet
2237 when remote debugging is enabled. */
2239 static void
2240 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2241 struct cmd_list_element *c,
2242 const char *value)
2244 gdb_printf (file, _("Number of remote packet characters to "
2245 "display is %s.\n"), value);
2248 long
2249 remote_target::get_memory_write_packet_size ()
2251 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2254 /* Configure the memory-read-packet size of the currently selected target. If
2255 no target is available, the default configuration for future remote targets
2256 is adapted. */
2258 static void
2259 set_memory_read_packet_size (const char *args, int from_tty)
2261 remote_target *remote = get_current_remote_target ();
2262 if (remote != nullptr)
2263 set_memory_packet_size
2264 (args, &remote->m_features.m_memory_read_packet_config, true);
2265 else
2267 memory_packet_config* config = &memory_read_packet_config;
2268 set_memory_packet_size (args, config, false);
2273 /* Display the memory-read-packet size of the currently selected target. If
2274 no target is available, the default configuration for future remote targets
2275 is shown. */
2277 static void
2278 show_memory_read_packet_size (const char *args, int from_tty)
2280 remote_target *remote = get_current_remote_target ();
2281 if (remote != nullptr)
2282 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2283 remote);
2284 else
2285 show_memory_packet_size (&memory_read_packet_config, nullptr);
2288 long
2289 remote_target::get_memory_read_packet_size ()
2291 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2293 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2294 extra buffer size argument before the memory read size can be
2295 increased beyond this. */
2296 if (size > get_remote_packet_size ())
2297 size = get_remote_packet_size ();
2298 return size;
2301 static enum packet_support packet_config_support (const packet_config *config);
2304 static void
2305 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2306 cmd_list_element *c)
2308 remote_target *remote = get_current_remote_target ();
2309 gdb_assert (c->var.has_value ());
2311 auto *default_config = static_cast<packet_config *> (c->context ());
2312 const int packet_idx = std::distance (remote_protocol_packets,
2313 default_config);
2315 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2317 const char *name = packets_descriptions[packet_idx].name;
2318 const auto_boolean value = c->var->get<auto_boolean> ();
2319 const char *support = get_packet_support_name (value);
2320 const char *target_type = get_target_type_name (remote != nullptr);
2322 if (remote != nullptr)
2323 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2324 else
2325 remote_protocol_packets[packet_idx].detect = value;
2327 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2328 target_type, support);
2329 return;
2332 internal_error (_("Could not find config for %s"), c->name);
2335 static void
2336 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2337 remote_target *remote)
2339 const char *support = "internal-error";
2340 const char *target_type = get_target_type_name (remote != nullptr);
2342 packet_config *config;
2343 if (remote != nullptr)
2344 config = &remote->m_features.m_protocol_packets[which_packet];
2345 else
2346 config = &remote_protocol_packets[which_packet];
2348 switch (packet_config_support (config))
2350 case PACKET_ENABLE:
2351 support = "enabled";
2352 break;
2353 case PACKET_DISABLE:
2354 support = "disabled";
2355 break;
2356 case PACKET_SUPPORT_UNKNOWN:
2357 support = "unknown";
2358 break;
2360 switch (config->detect)
2362 case AUTO_BOOLEAN_AUTO:
2363 gdb_printf (file,
2364 _("Support for the '%s' packet %s is \"auto\", "
2365 "currently %s.\n"),
2366 packets_descriptions[which_packet].name, target_type,
2367 support);
2368 break;
2369 case AUTO_BOOLEAN_TRUE:
2370 case AUTO_BOOLEAN_FALSE:
2371 gdb_printf (file,
2372 _("Support for the '%s' packet %s is \"%s\".\n"),
2373 packets_descriptions[which_packet].name, target_type,
2374 get_packet_support_name (config->detect));
2375 break;
2379 static void
2380 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2381 const char *title, int legacy)
2383 packets_descriptions[which_packet].name = name;
2384 packets_descriptions[which_packet].title = title;
2386 packet_config *config = &remote_protocol_packets[which_packet];
2388 gdb::unique_xmalloc_ptr<char> set_doc
2389 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2390 name, title);
2391 gdb::unique_xmalloc_ptr<char> show_doc
2392 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2393 name, title);
2394 /* set/show TITLE-packet {auto,on,off} */
2395 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2396 set_show_commands cmds
2397 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2398 &config->detect, set_doc.get (),
2399 show_doc.get (), NULL, /* help_doc */
2400 set_remote_protocol_packet_cmd,
2401 show_remote_protocol_packet_cmd,
2402 &remote_set_cmdlist, &remote_show_cmdlist);
2403 cmds.show->set_context (config);
2404 cmds.set->set_context (config);
2406 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2407 if (legacy)
2409 /* It's not clear who should take ownership of the LEGACY_NAME string
2410 created below, so, for now, place the string into a static vector
2411 which ensures the strings is released when GDB exits. */
2412 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2413 gdb::unique_xmalloc_ptr<char> legacy_name
2414 = xstrprintf ("%s-packet", name);
2415 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2416 &remote_set_cmdlist);
2417 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2418 &remote_show_cmdlist);
2419 legacy_names.emplace_back (std::move (legacy_name));
2423 static enum packet_result
2424 packet_check_result (const char *buf)
2426 if (buf[0] != '\0')
2428 /* The stub recognized the packet request. Check that the
2429 operation succeeded. */
2430 if (buf[0] == 'E'
2431 && isxdigit (buf[1]) && isxdigit (buf[2])
2432 && buf[3] == '\0')
2433 /* "Enn" - definitely an error. */
2434 return PACKET_ERROR;
2436 /* Always treat "E." as an error. This will be used for
2437 more verbose error messages, such as E.memtypes. */
2438 if (buf[0] == 'E' && buf[1] == '.')
2439 return PACKET_ERROR;
2441 /* The packet may or may not be OK. Just assume it is. */
2442 return PACKET_OK;
2444 else
2445 /* The stub does not support the packet. */
2446 return PACKET_UNKNOWN;
2449 static enum packet_result
2450 packet_check_result (const gdb::char_vector &buf)
2452 return packet_check_result (buf.data ());
2455 packet_result
2456 remote_features::packet_ok (const char *buf, const int which_packet)
2458 packet_config *config = &m_protocol_packets[which_packet];
2459 packet_description *descr = &packets_descriptions[which_packet];
2461 enum packet_result result;
2463 if (config->detect != AUTO_BOOLEAN_TRUE
2464 && config->support == PACKET_DISABLE)
2465 internal_error (_("packet_ok: attempt to use a disabled packet"));
2467 result = packet_check_result (buf);
2468 switch (result)
2470 case PACKET_OK:
2471 case PACKET_ERROR:
2472 /* The stub recognized the packet request. */
2473 if (config->support == PACKET_SUPPORT_UNKNOWN)
2475 remote_debug_printf ("Packet %s (%s) is supported",
2476 descr->name, descr->title);
2477 config->support = PACKET_ENABLE;
2479 break;
2480 case PACKET_UNKNOWN:
2481 /* The stub does not support the packet. */
2482 if (config->detect == AUTO_BOOLEAN_AUTO
2483 && config->support == PACKET_ENABLE)
2485 /* If the stub previously indicated that the packet was
2486 supported then there is a protocol error. */
2487 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2488 descr->name, descr->title);
2490 else if (config->detect == AUTO_BOOLEAN_TRUE)
2492 /* The user set it wrong. */
2493 error (_("Enabled packet %s (%s) not recognized by stub"),
2494 descr->name, descr->title);
2497 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2498 descr->title);
2499 config->support = PACKET_DISABLE;
2500 break;
2503 return result;
2506 packet_result
2507 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2509 return packet_ok (buf.data (), which_packet);
2512 /* Returns whether a given packet or feature is supported. This takes
2513 into account the state of the corresponding "set remote foo-packet"
2514 command, which may be used to bypass auto-detection. */
2516 static enum packet_support
2517 packet_config_support (const packet_config *config)
2519 switch (config->detect)
2521 case AUTO_BOOLEAN_TRUE:
2522 return PACKET_ENABLE;
2523 case AUTO_BOOLEAN_FALSE:
2524 return PACKET_DISABLE;
2525 case AUTO_BOOLEAN_AUTO:
2526 return config->support;
2527 default:
2528 gdb_assert_not_reached ("bad switch");
2532 packet_support
2533 remote_features::packet_support (int packet) const
2535 const packet_config *config = &m_protocol_packets[packet];
2536 return packet_config_support (config);
2539 static void
2540 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2541 struct cmd_list_element *c,
2542 const char *value)
2544 remote_target *remote = get_current_remote_target ();
2545 gdb_assert (c->var.has_value ());
2547 auto *default_config = static_cast<packet_config *> (c->context ());
2548 const int packet_idx = std::distance (remote_protocol_packets,
2549 default_config);
2551 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2553 show_packet_config_cmd (file, packet_idx, remote);
2554 return;
2556 internal_error (_("Could not find config for %s"), c->name);
2559 /* Should we try one of the 'Z' requests? */
2561 enum Z_packet_type
2563 Z_PACKET_SOFTWARE_BP,
2564 Z_PACKET_HARDWARE_BP,
2565 Z_PACKET_WRITE_WP,
2566 Z_PACKET_READ_WP,
2567 Z_PACKET_ACCESS_WP,
2568 NR_Z_PACKET_TYPES
2571 /* For compatibility with older distributions. Provide a ``set remote
2572 Z-packet ...'' command that updates all the Z packet types. */
2574 static enum auto_boolean remote_Z_packet_detect;
2576 static void
2577 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2578 struct cmd_list_element *c)
2580 remote_target *remote = get_current_remote_target ();
2581 int i;
2583 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2585 if (remote != nullptr)
2586 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2587 = remote_Z_packet_detect;
2588 else
2589 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2592 const char *support = get_packet_support_name (remote_Z_packet_detect);
2593 const char *target_type = get_target_type_name (remote != nullptr);
2594 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2595 support);
2599 static void
2600 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2601 struct cmd_list_element *c,
2602 const char *value)
2604 remote_target *remote = get_current_remote_target ();
2605 int i;
2607 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2608 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2611 /* Insert fork catchpoint target routine. If fork events are enabled
2612 then return success, nothing more to do. */
2615 remote_target::insert_fork_catchpoint (int pid)
2617 return !m_features.remote_fork_event_p ();
2620 /* Remove fork catchpoint target routine. Nothing to do, just
2621 return success. */
2624 remote_target::remove_fork_catchpoint (int pid)
2626 return 0;
2629 /* Insert vfork catchpoint target routine. If vfork events are enabled
2630 then return success, nothing more to do. */
2633 remote_target::insert_vfork_catchpoint (int pid)
2635 return !m_features.remote_vfork_event_p ();
2638 /* Remove vfork catchpoint target routine. Nothing to do, just
2639 return success. */
2642 remote_target::remove_vfork_catchpoint (int pid)
2644 return 0;
2647 /* Insert exec catchpoint target routine. If exec events are
2648 enabled, just return success. */
2651 remote_target::insert_exec_catchpoint (int pid)
2653 return !m_features.remote_exec_event_p ();
2656 /* Remove exec catchpoint target routine. Nothing to do, just
2657 return success. */
2660 remote_target::remove_exec_catchpoint (int pid)
2662 return 0;
2667 /* Take advantage of the fact that the TID field is not used, to tag
2668 special ptids with it set to != 0. */
2669 static const ptid_t magic_null_ptid (42000, -1, 1);
2670 static const ptid_t not_sent_ptid (42000, -2, 1);
2671 static const ptid_t any_thread_ptid (42000, 0, 1);
2673 /* Find out if the stub attached to PID (and hence GDB should offer to
2674 detach instead of killing it when bailing out). */
2677 remote_target::remote_query_attached (int pid)
2679 struct remote_state *rs = get_remote_state ();
2680 size_t size = get_remote_packet_size ();
2682 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2683 return 0;
2685 if (m_features.remote_multi_process_p ())
2686 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2687 else
2688 xsnprintf (rs->buf.data (), size, "qAttached");
2690 putpkt (rs->buf);
2691 getpkt (&rs->buf);
2693 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2695 case PACKET_OK:
2696 if (strcmp (rs->buf.data (), "1") == 0)
2697 return 1;
2698 break;
2699 case PACKET_ERROR:
2700 warning (_("Remote failure reply: %s"), rs->buf.data ());
2701 break;
2702 case PACKET_UNKNOWN:
2703 break;
2706 return 0;
2709 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2710 has been invented by GDB, instead of reported by the target. Since
2711 we can be connected to a remote system before before knowing about
2712 any inferior, mark the target with execution when we find the first
2713 inferior. If ATTACHED is 1, then we had just attached to this
2714 inferior. If it is 0, then we just created this inferior. If it
2715 is -1, then try querying the remote stub to find out if it had
2716 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2717 attempt to open this inferior's executable as the main executable
2718 if no main executable is open already. */
2720 inferior *
2721 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2722 int try_open_exec)
2724 struct inferior *inf;
2726 /* Check whether this process we're learning about is to be
2727 considered attached, or if is to be considered to have been
2728 spawned by the stub. */
2729 if (attached == -1)
2730 attached = remote_query_attached (pid);
2732 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2734 /* If the target shares code across all inferiors, then every
2735 attach adds a new inferior. */
2736 inf = add_inferior (pid);
2738 /* ... and every inferior is bound to the same program space.
2739 However, each inferior may still have its own address
2740 space. */
2741 inf->aspace = maybe_new_address_space ();
2742 inf->pspace = current_program_space;
2744 else
2746 /* In the traditional debugging scenario, there's a 1-1 match
2747 between program/address spaces. We simply bind the inferior
2748 to the program space's address space. */
2749 inf = current_inferior ();
2751 /* However, if the current inferior is already bound to a
2752 process, find some other empty inferior. */
2753 if (inf->pid != 0)
2755 inf = nullptr;
2756 for (inferior *it : all_inferiors ())
2757 if (it->pid == 0)
2759 inf = it;
2760 break;
2763 if (inf == nullptr)
2765 /* Since all inferiors were already bound to a process, add
2766 a new inferior. */
2767 inf = add_inferior_with_spaces ();
2769 switch_to_inferior_no_thread (inf);
2770 inf->push_target (this);
2771 inferior_appeared (inf, pid);
2774 inf->attach_flag = attached;
2775 inf->fake_pid_p = fake_pid_p;
2777 /* If no main executable is currently open then attempt to
2778 open the file that was executed to create this inferior. */
2779 if (try_open_exec && get_exec_file (0) == NULL)
2780 exec_file_locate_attach (pid, 0, 1);
2782 /* Check for exec file mismatch, and let the user solve it. */
2783 validate_exec_file (1);
2785 return inf;
2788 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2789 static remote_thread_info *get_remote_thread_info (remote_target *target,
2790 ptid_t ptid);
2792 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2793 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2794 remote_state::starting_up flag) is true then the new thread is added
2795 silently, otherwise the new thread will be announced to the user. */
2797 thread_info *
2798 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2799 bool silent_p)
2801 struct remote_state *rs = get_remote_state ();
2802 struct thread_info *thread;
2804 /* GDB historically didn't pull threads in the initial connection
2805 setup. If the remote target doesn't even have a concept of
2806 threads (e.g., a bare-metal target), even if internally we
2807 consider that a single-threaded target, mentioning a new thread
2808 might be confusing to the user. Be silent then, preserving the
2809 age old behavior. */
2810 if (rs->starting_up || silent_p)
2811 thread = add_thread_silent (this, ptid);
2812 else
2813 thread = add_thread (this, ptid);
2815 if (executing)
2816 get_remote_thread_info (thread)->set_resumed ();
2817 set_executing (this, ptid, executing);
2818 set_running (this, ptid, running);
2820 return thread;
2823 /* Come here when we learn about a thread id from the remote target.
2824 It may be the first time we hear about such thread, so take the
2825 opportunity to add it to GDB's thread list. In case this is the
2826 first time we're noticing its corresponding inferior, add it to
2827 GDB's inferior list as well. EXECUTING indicates whether the
2828 thread is (internally) executing or stopped. */
2830 void
2831 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2833 /* In non-stop mode, we assume new found threads are (externally)
2834 running until proven otherwise with a stop reply. In all-stop,
2835 we can only get here if all threads are stopped. */
2836 bool running = target_is_non_stop_p ();
2838 /* If this is a new thread, add it to GDB's thread list.
2839 If we leave it up to WFI to do this, bad things will happen. */
2841 thread_info *tp = this->find_thread (currthread);
2842 if (tp != NULL && tp->state == THREAD_EXITED)
2844 /* We're seeing an event on a thread id we knew had exited.
2845 This has to be a new thread reusing the old id. Add it. */
2846 remote_add_thread (currthread, running, executing, false);
2847 return;
2850 if (!in_thread_list (this, currthread))
2852 struct inferior *inf = NULL;
2853 int pid = currthread.pid ();
2855 if (inferior_ptid.is_pid ()
2856 && pid == inferior_ptid.pid ())
2858 /* inferior_ptid has no thread member yet. This can happen
2859 with the vAttach -> remote_wait,"TAAthread:" path if the
2860 stub doesn't support qC. This is the first stop reported
2861 after an attach, so this is the main thread. Update the
2862 ptid in the thread list. */
2863 if (in_thread_list (this, ptid_t (pid)))
2864 thread_change_ptid (this, inferior_ptid, currthread);
2865 else
2867 thread_info *thr
2868 = remote_add_thread (currthread, running, executing, false);
2869 switch_to_thread (thr);
2871 return;
2874 if (magic_null_ptid == inferior_ptid)
2876 /* inferior_ptid is not set yet. This can happen with the
2877 vRun -> remote_wait,"TAAthread:" path if the stub
2878 doesn't support qC. This is the first stop reported
2879 after an attach, so this is the main thread. Update the
2880 ptid in the thread list. */
2881 thread_change_ptid (this, inferior_ptid, currthread);
2882 return;
2885 /* When connecting to a target remote, or to a target
2886 extended-remote which already was debugging an inferior, we
2887 may not know about it yet. Add it before adding its child
2888 thread, so notifications are emitted in a sensible order. */
2889 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2891 bool fake_pid_p = !m_features.remote_multi_process_p ();
2893 inf = remote_add_inferior (fake_pid_p,
2894 currthread.pid (), -1, 1);
2897 /* This is really a new thread. Add it. */
2898 thread_info *new_thr
2899 = remote_add_thread (currthread, running, executing, false);
2901 /* If we found a new inferior, let the common code do whatever
2902 it needs to with it (e.g., read shared libraries, insert
2903 breakpoints), unless we're just setting up an all-stop
2904 connection. */
2905 if (inf != NULL)
2907 struct remote_state *rs = get_remote_state ();
2909 if (!rs->starting_up)
2910 notice_new_inferior (new_thr, executing, 0);
2915 /* Return THREAD's private thread data, creating it if necessary. */
2917 static remote_thread_info *
2918 get_remote_thread_info (thread_info *thread)
2920 gdb_assert (thread != NULL);
2922 if (thread->priv == NULL)
2923 thread->priv.reset (new remote_thread_info);
2925 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2928 /* Return PTID's private thread data, creating it if necessary. */
2930 static remote_thread_info *
2931 get_remote_thread_info (remote_target *target, ptid_t ptid)
2933 thread_info *thr = target->find_thread (ptid);
2934 return get_remote_thread_info (thr);
2937 /* Call this function as a result of
2938 1) A halt indication (T packet) containing a thread id
2939 2) A direct query of currthread
2940 3) Successful execution of set thread */
2942 static void
2943 record_currthread (struct remote_state *rs, ptid_t currthread)
2945 rs->general_thread = currthread;
2948 /* If 'QPassSignals' is supported, tell the remote stub what signals
2949 it can simply pass through to the inferior without reporting. */
2951 void
2952 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2954 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2956 char *pass_packet, *p;
2957 int count = 0;
2958 struct remote_state *rs = get_remote_state ();
2960 gdb_assert (pass_signals.size () < 256);
2961 for (size_t i = 0; i < pass_signals.size (); i++)
2963 if (pass_signals[i])
2964 count++;
2966 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2967 strcpy (pass_packet, "QPassSignals:");
2968 p = pass_packet + strlen (pass_packet);
2969 for (size_t i = 0; i < pass_signals.size (); i++)
2971 if (pass_signals[i])
2973 if (i >= 16)
2974 *p++ = tohex (i >> 4);
2975 *p++ = tohex (i & 15);
2976 if (count)
2977 *p++ = ';';
2978 else
2979 break;
2980 count--;
2983 *p = 0;
2984 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2986 putpkt (pass_packet);
2987 getpkt (&rs->buf);
2988 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2989 xfree (rs->last_pass_packet);
2990 rs->last_pass_packet = pass_packet;
2992 else
2993 xfree (pass_packet);
2997 /* If 'QCatchSyscalls' is supported, tell the remote stub
2998 to report syscalls to GDB. */
3001 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3002 gdb::array_view<const int> syscall_counts)
3004 const char *catch_packet;
3005 enum packet_result result;
3006 int n_sysno = 0;
3008 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3010 /* Not supported. */
3011 return 1;
3014 if (needed && any_count == 0)
3016 /* Count how many syscalls are to be caught. */
3017 for (size_t i = 0; i < syscall_counts.size (); i++)
3019 if (syscall_counts[i] != 0)
3020 n_sysno++;
3024 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3025 pid, needed, any_count, n_sysno);
3027 std::string built_packet;
3028 if (needed)
3030 /* Prepare a packet with the sysno list, assuming max 8+1
3031 characters for a sysno. If the resulting packet size is too
3032 big, fallback on the non-selective packet. */
3033 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3034 built_packet.reserve (maxpktsz);
3035 built_packet = "QCatchSyscalls:1";
3036 if (any_count == 0)
3038 /* Add in each syscall to be caught. */
3039 for (size_t i = 0; i < syscall_counts.size (); i++)
3041 if (syscall_counts[i] != 0)
3042 string_appendf (built_packet, ";%zx", i);
3045 if (built_packet.size () > get_remote_packet_size ())
3047 /* catch_packet too big. Fallback to less efficient
3048 non selective mode, with GDB doing the filtering. */
3049 catch_packet = "QCatchSyscalls:1";
3051 else
3052 catch_packet = built_packet.c_str ();
3054 else
3055 catch_packet = "QCatchSyscalls:0";
3057 struct remote_state *rs = get_remote_state ();
3059 putpkt (catch_packet);
3060 getpkt (&rs->buf);
3061 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3062 if (result == PACKET_OK)
3063 return 0;
3064 else
3065 return -1;
3068 /* If 'QProgramSignals' is supported, tell the remote stub what
3069 signals it should pass through to the inferior when detaching. */
3071 void
3072 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3074 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3076 char *packet, *p;
3077 int count = 0;
3078 struct remote_state *rs = get_remote_state ();
3080 gdb_assert (signals.size () < 256);
3081 for (size_t i = 0; i < signals.size (); i++)
3083 if (signals[i])
3084 count++;
3086 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3087 strcpy (packet, "QProgramSignals:");
3088 p = packet + strlen (packet);
3089 for (size_t i = 0; i < signals.size (); i++)
3091 if (signal_pass_state (i))
3093 if (i >= 16)
3094 *p++ = tohex (i >> 4);
3095 *p++ = tohex (i & 15);
3096 if (count)
3097 *p++ = ';';
3098 else
3099 break;
3100 count--;
3103 *p = 0;
3104 if (!rs->last_program_signals_packet
3105 || strcmp (rs->last_program_signals_packet, packet) != 0)
3107 putpkt (packet);
3108 getpkt (&rs->buf);
3109 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3110 xfree (rs->last_program_signals_packet);
3111 rs->last_program_signals_packet = packet;
3113 else
3114 xfree (packet);
3118 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3119 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3120 thread. If GEN is set, set the general thread, if not, then set
3121 the step/continue thread. */
3122 void
3123 remote_target::set_thread (ptid_t ptid, int gen)
3125 struct remote_state *rs = get_remote_state ();
3126 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3127 char *buf = rs->buf.data ();
3128 char *endbuf = buf + get_remote_packet_size ();
3130 if (state == ptid)
3131 return;
3133 *buf++ = 'H';
3134 *buf++ = gen ? 'g' : 'c';
3135 if (ptid == magic_null_ptid)
3136 xsnprintf (buf, endbuf - buf, "0");
3137 else if (ptid == any_thread_ptid)
3138 xsnprintf (buf, endbuf - buf, "0");
3139 else if (ptid == minus_one_ptid)
3140 xsnprintf (buf, endbuf - buf, "-1");
3141 else
3142 write_ptid (buf, endbuf, ptid);
3143 putpkt (rs->buf);
3144 getpkt (&rs->buf);
3145 if (gen)
3146 rs->general_thread = ptid;
3147 else
3148 rs->continue_thread = ptid;
3151 void
3152 remote_target::set_general_thread (ptid_t ptid)
3154 set_thread (ptid, 1);
3157 void
3158 remote_target::set_continue_thread (ptid_t ptid)
3160 set_thread (ptid, 0);
3163 /* Change the remote current process. Which thread within the process
3164 ends up selected isn't important, as long as it is the same process
3165 as what INFERIOR_PTID points to.
3167 This comes from that fact that there is no explicit notion of
3168 "selected process" in the protocol. The selected process for
3169 general operations is the process the selected general thread
3170 belongs to. */
3172 void
3173 remote_target::set_general_process ()
3175 /* If the remote can't handle multiple processes, don't bother. */
3176 if (!m_features.remote_multi_process_p ())
3177 return;
3179 remote_state *rs = get_remote_state ();
3181 /* We only need to change the remote current thread if it's pointing
3182 at some other process. */
3183 if (rs->general_thread.pid () != inferior_ptid.pid ())
3184 set_general_thread (inferior_ptid);
3188 /* Return nonzero if this is the main thread that we made up ourselves
3189 to model non-threaded targets as single-threaded. */
3191 static int
3192 remote_thread_always_alive (ptid_t ptid)
3194 if (ptid == magic_null_ptid)
3195 /* The main thread is always alive. */
3196 return 1;
3198 if (ptid.pid () != 0 && ptid.lwp () == 0)
3199 /* The main thread is always alive. This can happen after a
3200 vAttach, if the remote side doesn't support
3201 multi-threading. */
3202 return 1;
3204 return 0;
3207 /* Return nonzero if the thread PTID is still alive on the remote
3208 system. */
3210 bool
3211 remote_target::thread_alive (ptid_t ptid)
3213 struct remote_state *rs = get_remote_state ();
3214 char *p, *endp;
3216 /* Check if this is a thread that we made up ourselves to model
3217 non-threaded targets as single-threaded. */
3218 if (remote_thread_always_alive (ptid))
3219 return 1;
3221 p = rs->buf.data ();
3222 endp = p + get_remote_packet_size ();
3224 *p++ = 'T';
3225 write_ptid (p, endp, ptid);
3227 putpkt (rs->buf);
3228 getpkt (&rs->buf);
3229 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3232 /* Return a pointer to a thread name if we know it and NULL otherwise.
3233 The thread_info object owns the memory for the name. */
3235 const char *
3236 remote_target::thread_name (struct thread_info *info)
3238 if (info->priv != NULL)
3240 const std::string &name = get_remote_thread_info (info)->name;
3241 return !name.empty () ? name.c_str () : NULL;
3244 return NULL;
3247 /* About these extended threadlist and threadinfo packets. They are
3248 variable length packets but, the fields within them are often fixed
3249 length. They are redundant enough to send over UDP as is the
3250 remote protocol in general. There is a matching unit test module
3251 in libstub. */
3253 /* WARNING: This threadref data structure comes from the remote O.S.,
3254 libstub protocol encoding, and remote.c. It is not particularly
3255 changeable. */
3257 /* Right now, the internal structure is int. We want it to be bigger.
3258 Plan to fix this. */
3260 typedef int gdb_threadref; /* Internal GDB thread reference. */
3262 /* gdb_ext_thread_info is an internal GDB data structure which is
3263 equivalent to the reply of the remote threadinfo packet. */
3265 struct gdb_ext_thread_info
3267 threadref threadid; /* External form of thread reference. */
3268 int active; /* Has state interesting to GDB?
3269 regs, stack. */
3270 char display[256]; /* Brief state display, name,
3271 blocked/suspended. */
3272 char shortname[32]; /* To be used to name threads. */
3273 char more_display[256]; /* Long info, statistics, queue depth,
3274 whatever. */
3277 /* The volume of remote transfers can be limited by submitting
3278 a mask containing bits specifying the desired information.
3279 Use a union of these values as the 'selection' parameter to
3280 get_thread_info. FIXME: Make these TAG names more thread specific. */
3282 #define TAG_THREADID 1
3283 #define TAG_EXISTS 2
3284 #define TAG_DISPLAY 4
3285 #define TAG_THREADNAME 8
3286 #define TAG_MOREDISPLAY 16
3288 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3290 static const char *unpack_nibble (const char *buf, int *val);
3292 static const char *unpack_byte (const char *buf, int *value);
3294 static char *pack_int (char *buf, int value);
3296 static const char *unpack_int (const char *buf, int *value);
3298 static const char *unpack_string (const char *src, char *dest, int length);
3300 static char *pack_threadid (char *pkt, threadref *id);
3302 static const char *unpack_threadid (const char *inbuf, threadref *id);
3304 void int_to_threadref (threadref *id, int value);
3306 static int threadref_to_int (threadref *ref);
3308 static void copy_threadref (threadref *dest, threadref *src);
3310 static int threadmatch (threadref *dest, threadref *src);
3312 static char *pack_threadinfo_request (char *pkt, int mode,
3313 threadref *id);
3315 static char *pack_threadlist_request (char *pkt, int startflag,
3316 int threadcount,
3317 threadref *nextthread);
3319 static int remote_newthread_step (threadref *ref, void *context);
3322 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3323 buffer we're allowed to write to. Returns
3324 BUF+CHARACTERS_WRITTEN. */
3326 char *
3327 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3329 int pid, tid;
3331 if (m_features.remote_multi_process_p ())
3333 pid = ptid.pid ();
3334 if (pid < 0)
3335 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3336 else
3337 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3339 tid = ptid.lwp ();
3340 if (tid < 0)
3341 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3342 else
3343 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3345 return buf;
3348 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3349 last parsed char. Returns null_ptid if no thread id is found, and
3350 throws an error if the thread id has an invalid format. */
3352 static ptid_t
3353 read_ptid (const char *buf, const char **obuf)
3355 const char *p = buf;
3356 const char *pp;
3357 ULONGEST pid = 0, tid = 0;
3359 if (*p == 'p')
3361 /* Multi-process ptid. */
3362 pp = unpack_varlen_hex (p + 1, &pid);
3363 if (*pp != '.')
3364 error (_("invalid remote ptid: %s"), p);
3366 p = pp;
3367 pp = unpack_varlen_hex (p + 1, &tid);
3368 if (obuf)
3369 *obuf = pp;
3370 return ptid_t (pid, tid);
3373 /* No multi-process. Just a tid. */
3374 pp = unpack_varlen_hex (p, &tid);
3376 /* Return null_ptid when no thread id is found. */
3377 if (p == pp)
3379 if (obuf)
3380 *obuf = pp;
3381 return null_ptid;
3384 /* Since the stub is not sending a process id, default to what's
3385 current_inferior, unless it doesn't have a PID yet. If so,
3386 then since there's no way to know the pid of the reported
3387 threads, use the magic number. */
3388 inferior *inf = current_inferior ();
3389 if (inf->pid == 0)
3390 pid = magic_null_ptid.pid ();
3391 else
3392 pid = inf->pid;
3394 if (obuf)
3395 *obuf = pp;
3396 return ptid_t (pid, tid);
3399 static int
3400 stubhex (int ch)
3402 if (ch >= 'a' && ch <= 'f')
3403 return ch - 'a' + 10;
3404 if (ch >= '0' && ch <= '9')
3405 return ch - '0';
3406 if (ch >= 'A' && ch <= 'F')
3407 return ch - 'A' + 10;
3408 return -1;
3411 static int
3412 stub_unpack_int (const char *buff, int fieldlength)
3414 int nibble;
3415 int retval = 0;
3417 while (fieldlength)
3419 nibble = stubhex (*buff++);
3420 retval |= nibble;
3421 fieldlength--;
3422 if (fieldlength)
3423 retval = retval << 4;
3425 return retval;
3428 static const char *
3429 unpack_nibble (const char *buf, int *val)
3431 *val = fromhex (*buf++);
3432 return buf;
3435 static const char *
3436 unpack_byte (const char *buf, int *value)
3438 *value = stub_unpack_int (buf, 2);
3439 return buf + 2;
3442 static char *
3443 pack_int (char *buf, int value)
3445 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3446 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3447 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3448 buf = pack_hex_byte (buf, (value & 0xff));
3449 return buf;
3452 static const char *
3453 unpack_int (const char *buf, int *value)
3455 *value = stub_unpack_int (buf, 8);
3456 return buf + 8;
3459 #if 0 /* Currently unused, uncomment when needed. */
3460 static char *pack_string (char *pkt, char *string);
3462 static char *
3463 pack_string (char *pkt, char *string)
3465 char ch;
3466 int len;
3468 len = strlen (string);
3469 if (len > 200)
3470 len = 200; /* Bigger than most GDB packets, junk??? */
3471 pkt = pack_hex_byte (pkt, len);
3472 while (len-- > 0)
3474 ch = *string++;
3475 if ((ch == '\0') || (ch == '#'))
3476 ch = '*'; /* Protect encapsulation. */
3477 *pkt++ = ch;
3479 return pkt;
3481 #endif /* 0 (unused) */
3483 static const char *
3484 unpack_string (const char *src, char *dest, int length)
3486 while (length--)
3487 *dest++ = *src++;
3488 *dest = '\0';
3489 return src;
3492 static char *
3493 pack_threadid (char *pkt, threadref *id)
3495 char *limit;
3496 unsigned char *altid;
3498 altid = (unsigned char *) id;
3499 limit = pkt + BUF_THREAD_ID_SIZE;
3500 while (pkt < limit)
3501 pkt = pack_hex_byte (pkt, *altid++);
3502 return pkt;
3506 static const char *
3507 unpack_threadid (const char *inbuf, threadref *id)
3509 char *altref;
3510 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3511 int x, y;
3513 altref = (char *) id;
3515 while (inbuf < limit)
3517 x = stubhex (*inbuf++);
3518 y = stubhex (*inbuf++);
3519 *altref++ = (x << 4) | y;
3521 return inbuf;
3524 /* Externally, threadrefs are 64 bits but internally, they are still
3525 ints. This is due to a mismatch of specifications. We would like
3526 to use 64bit thread references internally. This is an adapter
3527 function. */
3529 void
3530 int_to_threadref (threadref *id, int value)
3532 unsigned char *scan;
3534 scan = (unsigned char *) id;
3536 int i = 4;
3537 while (i--)
3538 *scan++ = 0;
3540 *scan++ = (value >> 24) & 0xff;
3541 *scan++ = (value >> 16) & 0xff;
3542 *scan++ = (value >> 8) & 0xff;
3543 *scan++ = (value & 0xff);
3546 static int
3547 threadref_to_int (threadref *ref)
3549 int i, value = 0;
3550 unsigned char *scan;
3552 scan = *ref;
3553 scan += 4;
3554 i = 4;
3555 while (i-- > 0)
3556 value = (value << 8) | ((*scan++) & 0xff);
3557 return value;
3560 static void
3561 copy_threadref (threadref *dest, threadref *src)
3563 int i;
3564 unsigned char *csrc, *cdest;
3566 csrc = (unsigned char *) src;
3567 cdest = (unsigned char *) dest;
3568 i = 8;
3569 while (i--)
3570 *cdest++ = *csrc++;
3573 static int
3574 threadmatch (threadref *dest, threadref *src)
3576 /* Things are broken right now, so just assume we got a match. */
3577 #if 0
3578 unsigned char *srcp, *destp;
3579 int i, result;
3580 srcp = (char *) src;
3581 destp = (char *) dest;
3583 result = 1;
3584 while (i-- > 0)
3585 result &= (*srcp++ == *destp++) ? 1 : 0;
3586 return result;
3587 #endif
3588 return 1;
3592 threadid:1, # always request threadid
3593 context_exists:2,
3594 display:4,
3595 unique_name:8,
3596 more_display:16
3599 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3601 static char *
3602 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3604 *pkt++ = 'q'; /* Info Query */
3605 *pkt++ = 'P'; /* process or thread info */
3606 pkt = pack_int (pkt, mode); /* mode */
3607 pkt = pack_threadid (pkt, id); /* threadid */
3608 *pkt = '\0'; /* terminate */
3609 return pkt;
3612 /* These values tag the fields in a thread info response packet. */
3613 /* Tagging the fields allows us to request specific fields and to
3614 add more fields as time goes by. */
3616 #define TAG_THREADID 1 /* Echo the thread identifier. */
3617 #define TAG_EXISTS 2 /* Is this process defined enough to
3618 fetch registers and its stack? */
3619 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3620 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3621 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3622 the process. */
3625 remote_target::remote_unpack_thread_info_response (const char *pkt,
3626 threadref *expectedref,
3627 gdb_ext_thread_info *info)
3629 struct remote_state *rs = get_remote_state ();
3630 int mask, length;
3631 int tag;
3632 threadref ref;
3633 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3634 int retval = 1;
3636 /* info->threadid = 0; FIXME: implement zero_threadref. */
3637 info->active = 0;
3638 info->display[0] = '\0';
3639 info->shortname[0] = '\0';
3640 info->more_display[0] = '\0';
3642 /* Assume the characters indicating the packet type have been
3643 stripped. */
3644 pkt = unpack_int (pkt, &mask); /* arg mask */
3645 pkt = unpack_threadid (pkt, &ref);
3647 if (mask == 0)
3648 warning (_("Incomplete response to threadinfo request."));
3649 if (!threadmatch (&ref, expectedref))
3650 { /* This is an answer to a different request. */
3651 warning (_("ERROR RMT Thread info mismatch."));
3652 return 0;
3654 copy_threadref (&info->threadid, &ref);
3656 /* Loop on tagged fields , try to bail if something goes wrong. */
3658 /* Packets are terminated with nulls. */
3659 while ((pkt < limit) && mask && *pkt)
3661 pkt = unpack_int (pkt, &tag); /* tag */
3662 pkt = unpack_byte (pkt, &length); /* length */
3663 if (!(tag & mask)) /* Tags out of synch with mask. */
3665 warning (_("ERROR RMT: threadinfo tag mismatch."));
3666 retval = 0;
3667 break;
3669 if (tag == TAG_THREADID)
3671 if (length != 16)
3673 warning (_("ERROR RMT: length of threadid is not 16."));
3674 retval = 0;
3675 break;
3677 pkt = unpack_threadid (pkt, &ref);
3678 mask = mask & ~TAG_THREADID;
3679 continue;
3681 if (tag == TAG_EXISTS)
3683 info->active = stub_unpack_int (pkt, length);
3684 pkt += length;
3685 mask = mask & ~(TAG_EXISTS);
3686 if (length > 8)
3688 warning (_("ERROR RMT: 'exists' length too long."));
3689 retval = 0;
3690 break;
3692 continue;
3694 if (tag == TAG_THREADNAME)
3696 pkt = unpack_string (pkt, &info->shortname[0], length);
3697 mask = mask & ~TAG_THREADNAME;
3698 continue;
3700 if (tag == TAG_DISPLAY)
3702 pkt = unpack_string (pkt, &info->display[0], length);
3703 mask = mask & ~TAG_DISPLAY;
3704 continue;
3706 if (tag == TAG_MOREDISPLAY)
3708 pkt = unpack_string (pkt, &info->more_display[0], length);
3709 mask = mask & ~TAG_MOREDISPLAY;
3710 continue;
3712 warning (_("ERROR RMT: unknown thread info tag."));
3713 break; /* Not a tag we know about. */
3715 return retval;
3719 remote_target::remote_get_threadinfo (threadref *threadid,
3720 int fieldset,
3721 gdb_ext_thread_info *info)
3723 struct remote_state *rs = get_remote_state ();
3724 int result;
3726 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3727 putpkt (rs->buf);
3728 getpkt (&rs->buf);
3730 if (rs->buf[0] == '\0')
3731 return 0;
3733 result = remote_unpack_thread_info_response (&rs->buf[2],
3734 threadid, info);
3735 return result;
3738 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3740 static char *
3741 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3742 threadref *nextthread)
3744 *pkt++ = 'q'; /* info query packet */
3745 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3746 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3747 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3748 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3749 *pkt = '\0';
3750 return pkt;
3753 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3756 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3757 threadref *original_echo,
3758 threadref *resultlist,
3759 int *doneflag)
3761 struct remote_state *rs = get_remote_state ();
3762 int count, resultcount, done;
3764 resultcount = 0;
3765 /* Assume the 'q' and 'M chars have been stripped. */
3766 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3767 /* done parse past here */
3768 pkt = unpack_byte (pkt, &count); /* count field */
3769 pkt = unpack_nibble (pkt, &done);
3770 /* The first threadid is the argument threadid. */
3771 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3772 while ((count-- > 0) && (pkt < limit))
3774 pkt = unpack_threadid (pkt, resultlist++);
3775 if (resultcount++ >= result_limit)
3776 break;
3778 if (doneflag)
3779 *doneflag = done;
3780 return resultcount;
3783 /* Fetch the next batch of threads from the remote. Returns -1 if the
3784 qL packet is not supported, 0 on error and 1 on success. */
3787 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3788 int result_limit, int *done, int *result_count,
3789 threadref *threadlist)
3791 struct remote_state *rs = get_remote_state ();
3792 int result = 1;
3794 /* Truncate result limit to be smaller than the packet size. */
3795 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3796 >= get_remote_packet_size ())
3797 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3799 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3800 nextthread);
3801 putpkt (rs->buf);
3802 getpkt (&rs->buf);
3803 if (rs->buf[0] == '\0')
3805 /* Packet not supported. */
3806 return -1;
3809 *result_count =
3810 parse_threadlist_response (&rs->buf[2], result_limit,
3811 &rs->echo_nextthread, threadlist, done);
3813 if (!threadmatch (&rs->echo_nextthread, nextthread))
3815 /* FIXME: This is a good reason to drop the packet. */
3816 /* Possibly, there is a duplicate response. */
3817 /* Possibilities :
3818 retransmit immediatly - race conditions
3819 retransmit after timeout - yes
3820 exit
3821 wait for packet, then exit
3823 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3824 return 0; /* I choose simply exiting. */
3826 if (*result_count <= 0)
3828 if (*done != 1)
3830 warning (_("RMT ERROR : failed to get remote thread list."));
3831 result = 0;
3833 return result; /* break; */
3835 if (*result_count > result_limit)
3837 *result_count = 0;
3838 warning (_("RMT ERROR: threadlist response longer than requested."));
3839 return 0;
3841 return result;
3844 /* Fetch the list of remote threads, with the qL packet, and call
3845 STEPFUNCTION for each thread found. Stops iterating and returns 1
3846 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3847 STEPFUNCTION returns false. If the packet is not supported,
3848 returns -1. */
3851 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3852 void *context, int looplimit)
3854 struct remote_state *rs = get_remote_state ();
3855 int done, i, result_count;
3856 int startflag = 1;
3857 int result = 1;
3858 int loopcount = 0;
3860 done = 0;
3861 while (!done)
3863 if (loopcount++ > looplimit)
3865 result = 0;
3866 warning (_("Remote fetch threadlist -infinite loop-."));
3867 break;
3869 result = remote_get_threadlist (startflag, &rs->nextthread,
3870 MAXTHREADLISTRESULTS,
3871 &done, &result_count,
3872 rs->resultthreadlist);
3873 if (result <= 0)
3874 break;
3875 /* Clear for later iterations. */
3876 startflag = 0;
3877 /* Setup to resume next batch of thread references, set nextthread. */
3878 if (result_count >= 1)
3879 copy_threadref (&rs->nextthread,
3880 &rs->resultthreadlist[result_count - 1]);
3881 i = 0;
3882 while (result_count--)
3884 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3886 result = 0;
3887 break;
3891 return result;
3894 /* A thread found on the remote target. */
3896 struct thread_item
3898 explicit thread_item (ptid_t ptid_)
3899 : ptid (ptid_)
3902 thread_item (thread_item &&other) = default;
3903 thread_item &operator= (thread_item &&other) = default;
3905 DISABLE_COPY_AND_ASSIGN (thread_item);
3907 /* The thread's PTID. */
3908 ptid_t ptid;
3910 /* The thread's extra info. */
3911 std::string extra;
3913 /* The thread's name. */
3914 std::string name;
3916 /* The core the thread was running on. -1 if not known. */
3917 int core = -1;
3919 /* The thread handle associated with the thread. */
3920 gdb::byte_vector thread_handle;
3923 /* Context passed around to the various methods listing remote
3924 threads. As new threads are found, they're added to the ITEMS
3925 vector. */
3927 struct threads_listing_context
3929 /* Return true if this object contains an entry for a thread with ptid
3930 PTID. */
3932 bool contains_thread (ptid_t ptid) const
3934 auto match_ptid = [&] (const thread_item &item)
3936 return item.ptid == ptid;
3939 auto it = std::find_if (this->items.begin (),
3940 this->items.end (),
3941 match_ptid);
3943 return it != this->items.end ();
3946 /* Remove the thread with ptid PTID. */
3948 void remove_thread (ptid_t ptid)
3950 auto match_ptid = [&] (const thread_item &item)
3952 return item.ptid == ptid;
3955 auto it = std::remove_if (this->items.begin (),
3956 this->items.end (),
3957 match_ptid);
3959 if (it != this->items.end ())
3960 this->items.erase (it);
3963 /* The threads found on the remote target. */
3964 std::vector<thread_item> items;
3967 static int
3968 remote_newthread_step (threadref *ref, void *data)
3970 struct threads_listing_context *context
3971 = (struct threads_listing_context *) data;
3972 int pid = inferior_ptid.pid ();
3973 int lwp = threadref_to_int (ref);
3974 ptid_t ptid (pid, lwp);
3976 context->items.emplace_back (ptid);
3978 return 1; /* continue iterator */
3981 #define CRAZY_MAX_THREADS 1000
3983 ptid_t
3984 remote_target::remote_current_thread (ptid_t oldpid)
3986 struct remote_state *rs = get_remote_state ();
3988 putpkt ("qC");
3989 getpkt (&rs->buf);
3990 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3992 const char *obuf;
3993 ptid_t result;
3995 result = read_ptid (&rs->buf[2], &obuf);
3996 if (*obuf != '\0')
3997 remote_debug_printf ("warning: garbage in qC reply");
3999 return result;
4001 else
4002 return oldpid;
4005 /* List remote threads using the deprecated qL packet. */
4008 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4010 if (remote_threadlist_iterator (remote_newthread_step, context,
4011 CRAZY_MAX_THREADS) >= 0)
4012 return 1;
4014 return 0;
4017 #if defined(HAVE_LIBEXPAT)
4019 static void
4020 start_thread (struct gdb_xml_parser *parser,
4021 const struct gdb_xml_element *element,
4022 void *user_data,
4023 std::vector<gdb_xml_value> &attributes)
4025 struct threads_listing_context *data
4026 = (struct threads_listing_context *) user_data;
4027 struct gdb_xml_value *attr;
4029 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4030 ptid_t ptid = read_ptid (id, NULL);
4032 data->items.emplace_back (ptid);
4033 thread_item &item = data->items.back ();
4035 attr = xml_find_attribute (attributes, "core");
4036 if (attr != NULL)
4037 item.core = *(ULONGEST *) attr->value.get ();
4039 attr = xml_find_attribute (attributes, "name");
4040 if (attr != NULL)
4041 item.name = (const char *) attr->value.get ();
4043 attr = xml_find_attribute (attributes, "handle");
4044 if (attr != NULL)
4045 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4048 static void
4049 end_thread (struct gdb_xml_parser *parser,
4050 const struct gdb_xml_element *element,
4051 void *user_data, const char *body_text)
4053 struct threads_listing_context *data
4054 = (struct threads_listing_context *) user_data;
4056 if (body_text != NULL && *body_text != '\0')
4057 data->items.back ().extra = body_text;
4060 const struct gdb_xml_attribute thread_attributes[] = {
4061 { "id", GDB_XML_AF_NONE, NULL, NULL },
4062 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4063 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4064 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4065 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4068 const struct gdb_xml_element thread_children[] = {
4069 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4072 const struct gdb_xml_element threads_children[] = {
4073 { "thread", thread_attributes, thread_children,
4074 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4075 start_thread, end_thread },
4076 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4079 const struct gdb_xml_element threads_elements[] = {
4080 { "threads", NULL, threads_children,
4081 GDB_XML_EF_NONE, NULL, NULL },
4082 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4085 #endif
4087 /* List remote threads using qXfer:threads:read. */
4090 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4092 #if defined(HAVE_LIBEXPAT)
4093 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4095 std::optional<gdb::char_vector> xml
4096 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4098 if (xml && (*xml)[0] != '\0')
4100 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4101 threads_elements, xml->data (), context);
4104 return 1;
4106 #endif
4108 return 0;
4111 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4114 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4116 struct remote_state *rs = get_remote_state ();
4118 if (rs->use_threadinfo_query)
4120 const char *bufp;
4122 putpkt ("qfThreadInfo");
4123 getpkt (&rs->buf);
4124 bufp = rs->buf.data ();
4125 if (bufp[0] != '\0') /* q packet recognized */
4127 while (*bufp++ == 'm') /* reply contains one or more TID */
4131 ptid_t ptid = read_ptid (bufp, &bufp);
4132 context->items.emplace_back (ptid);
4134 while (*bufp++ == ','); /* comma-separated list */
4135 putpkt ("qsThreadInfo");
4136 getpkt (&rs->buf);
4137 bufp = rs->buf.data ();
4139 return 1;
4141 else
4143 /* Packet not recognized. */
4144 rs->use_threadinfo_query = 0;
4148 return 0;
4151 /* Return true if INF only has one non-exited thread. */
4153 static bool
4154 has_single_non_exited_thread (inferior *inf)
4156 int count = 0;
4157 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4158 if (++count > 1)
4159 break;
4160 return count == 1;
4163 /* Implement the to_update_thread_list function for the remote
4164 targets. */
4166 void
4167 remote_target::update_thread_list ()
4169 struct threads_listing_context context;
4170 int got_list = 0;
4172 /* We have a few different mechanisms to fetch the thread list. Try
4173 them all, starting with the most preferred one first, falling
4174 back to older methods. */
4175 if (remote_get_threads_with_qxfer (&context)
4176 || remote_get_threads_with_qthreadinfo (&context)
4177 || remote_get_threads_with_ql (&context))
4179 got_list = 1;
4181 if (context.items.empty ()
4182 && remote_thread_always_alive (inferior_ptid))
4184 /* Some targets don't really support threads, but still
4185 reply an (empty) thread list in response to the thread
4186 listing packets, instead of replying "packet not
4187 supported". Exit early so we don't delete the main
4188 thread. */
4189 return;
4192 /* CONTEXT now holds the current thread list on the remote
4193 target end. Delete GDB-side threads no longer found on the
4194 target. */
4195 for (thread_info *tp : all_threads_safe ())
4197 if (tp->inf->process_target () != this)
4198 continue;
4200 if (!context.contains_thread (tp->ptid))
4202 /* Do not remove the thread if it is the last thread in
4203 the inferior. This situation happens when we have a
4204 pending exit process status to process. Otherwise we
4205 may end up with a seemingly live inferior (i.e. pid
4206 != 0) that has no threads. */
4207 if (has_single_non_exited_thread (tp->inf))
4208 continue;
4210 /* Do not remove the thread if we've requested to be
4211 notified of its exit. For example, the thread may be
4212 displaced stepping, infrun will need to handle the
4213 exit event, and displaced stepping info is recorded
4214 in the thread object. If we deleted the thread now,
4215 we'd lose that info. */
4216 if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
4217 continue;
4219 /* Not found. */
4220 delete_thread (tp);
4224 /* Remove any unreported fork/vfork/clone child threads from
4225 CONTEXT so that we don't interfere with follow
4226 fork/vfork/clone, which is where creation of such threads is
4227 handled. */
4228 remove_new_children (&context);
4230 /* And now add threads we don't know about yet to our list. */
4231 for (thread_item &item : context.items)
4233 if (item.ptid != null_ptid)
4235 /* In non-stop mode, we assume new found threads are
4236 executing until proven otherwise with a stop reply.
4237 In all-stop, we can only get here if all threads are
4238 stopped. */
4239 bool executing = target_is_non_stop_p ();
4241 remote_notice_new_inferior (item.ptid, executing);
4243 thread_info *tp = this->find_thread (item.ptid);
4244 remote_thread_info *info = get_remote_thread_info (tp);
4245 info->core = item.core;
4246 info->extra = std::move (item.extra);
4247 info->name = std::move (item.name);
4248 info->thread_handle = std::move (item.thread_handle);
4253 if (!got_list)
4255 /* If no thread listing method is supported, then query whether
4256 each known thread is alive, one by one, with the T packet.
4257 If the target doesn't support threads at all, then this is a
4258 no-op. See remote_thread_alive. */
4259 prune_threads ();
4264 * Collect a descriptive string about the given thread.
4265 * The target may say anything it wants to about the thread
4266 * (typically info about its blocked / runnable state, name, etc.).
4267 * This string will appear in the info threads display.
4269 * Optional: targets are not required to implement this function.
4272 const char *
4273 remote_target::extra_thread_info (thread_info *tp)
4275 struct remote_state *rs = get_remote_state ();
4276 int set;
4277 threadref id;
4278 struct gdb_ext_thread_info threadinfo;
4280 if (rs->remote_desc == 0) /* paranoia */
4281 internal_error (_("remote_threads_extra_info"));
4283 if (tp->ptid == magic_null_ptid
4284 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4285 /* This is the main thread which was added by GDB. The remote
4286 server doesn't know about it. */
4287 return NULL;
4289 std::string &extra = get_remote_thread_info (tp)->extra;
4291 /* If already have cached info, use it. */
4292 if (!extra.empty ())
4293 return extra.c_str ();
4295 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4297 /* If we're using qXfer:threads:read, then the extra info is
4298 included in the XML. So if we didn't have anything cached,
4299 it's because there's really no extra info. */
4300 return NULL;
4303 if (rs->use_threadextra_query)
4305 char *b = rs->buf.data ();
4306 char *endb = b + get_remote_packet_size ();
4308 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4309 b += strlen (b);
4310 write_ptid (b, endb, tp->ptid);
4312 putpkt (rs->buf);
4313 getpkt (&rs->buf);
4314 if (rs->buf[0] != 0)
4316 extra.resize (strlen (rs->buf.data ()) / 2);
4317 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4318 return extra.c_str ();
4322 /* If the above query fails, fall back to the old method. */
4323 rs->use_threadextra_query = 0;
4324 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4325 | TAG_MOREDISPLAY | TAG_DISPLAY;
4326 int_to_threadref (&id, tp->ptid.lwp ());
4327 if (remote_get_threadinfo (&id, set, &threadinfo))
4328 if (threadinfo.active)
4330 if (*threadinfo.shortname)
4331 string_appendf (extra, " Name: %s", threadinfo.shortname);
4332 if (*threadinfo.display)
4334 if (!extra.empty ())
4335 extra += ',';
4336 string_appendf (extra, " State: %s", threadinfo.display);
4338 if (*threadinfo.more_display)
4340 if (!extra.empty ())
4341 extra += ',';
4342 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4344 return extra.c_str ();
4346 return NULL;
4350 bool
4351 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4352 struct static_tracepoint_marker *marker)
4354 struct remote_state *rs = get_remote_state ();
4355 char *p = rs->buf.data ();
4357 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4358 p += strlen (p);
4359 p += hexnumstr (p, addr);
4360 putpkt (rs->buf);
4361 getpkt (&rs->buf);
4362 p = rs->buf.data ();
4364 if (*p == 'E')
4365 error (_("Remote failure reply: %s"), p);
4367 if (*p++ == 'm')
4369 parse_static_tracepoint_marker_definition (p, NULL, marker);
4370 return true;
4373 return false;
4376 std::vector<static_tracepoint_marker>
4377 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4379 struct remote_state *rs = get_remote_state ();
4380 std::vector<static_tracepoint_marker> markers;
4381 const char *p;
4382 static_tracepoint_marker marker;
4384 /* Ask for a first packet of static tracepoint marker
4385 definition. */
4386 putpkt ("qTfSTM");
4387 getpkt (&rs->buf);
4388 p = rs->buf.data ();
4389 if (*p == 'E')
4390 error (_("Remote failure reply: %s"), p);
4392 while (*p++ == 'm')
4396 parse_static_tracepoint_marker_definition (p, &p, &marker);
4398 if (strid == NULL || marker.str_id == strid)
4399 markers.push_back (std::move (marker));
4401 while (*p++ == ','); /* comma-separated list */
4402 /* Ask for another packet of static tracepoint definition. */
4403 putpkt ("qTsSTM");
4404 getpkt (&rs->buf);
4405 p = rs->buf.data ();
4408 return markers;
4412 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4414 ptid_t
4415 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4417 return ptid_t (inferior_ptid.pid (), lwp);
4421 /* Restart the remote side; this is an extended protocol operation. */
4423 void
4424 remote_target::extended_remote_restart ()
4426 struct remote_state *rs = get_remote_state ();
4428 /* Send the restart command; for reasons I don't understand the
4429 remote side really expects a number after the "R". */
4430 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4431 putpkt (rs->buf);
4433 remote_fileio_reset ();
4436 /* Clean up connection to a remote debugger. */
4438 void
4439 remote_target::close ()
4441 /* Make sure we leave stdin registered in the event loop. */
4442 terminal_ours ();
4444 trace_reset_local_state ();
4446 delete this;
4449 remote_target::~remote_target ()
4451 struct remote_state *rs = get_remote_state ();
4453 /* Check for NULL because we may get here with a partially
4454 constructed target/connection. */
4455 if (rs->remote_desc == nullptr)
4456 return;
4458 serial_close (rs->remote_desc);
4460 /* We are destroying the remote target, so we should discard
4461 everything of this target. */
4462 discard_pending_stop_replies_in_queue ();
4464 rs->delete_async_event_handler ();
4466 delete rs->notif_state;
4469 /* Query the remote side for the text, data and bss offsets. */
4471 void
4472 remote_target::get_offsets ()
4474 struct remote_state *rs = get_remote_state ();
4475 char *buf;
4476 char *ptr;
4477 int lose, num_segments = 0, do_sections, do_segments;
4478 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4480 if (current_program_space->symfile_object_file == NULL)
4481 return;
4483 putpkt ("qOffsets");
4484 getpkt (&rs->buf);
4485 buf = rs->buf.data ();
4487 if (buf[0] == '\000')
4488 return; /* Return silently. Stub doesn't support
4489 this command. */
4490 if (buf[0] == 'E')
4492 warning (_("Remote failure reply: %s"), buf);
4493 return;
4496 /* Pick up each field in turn. This used to be done with scanf, but
4497 scanf will make trouble if CORE_ADDR size doesn't match
4498 conversion directives correctly. The following code will work
4499 with any size of CORE_ADDR. */
4500 text_addr = data_addr = bss_addr = 0;
4501 ptr = buf;
4502 lose = 0;
4504 if (startswith (ptr, "Text="))
4506 ptr += 5;
4507 /* Don't use strtol, could lose on big values. */
4508 while (*ptr && *ptr != ';')
4509 text_addr = (text_addr << 4) + fromhex (*ptr++);
4511 if (startswith (ptr, ";Data="))
4513 ptr += 6;
4514 while (*ptr && *ptr != ';')
4515 data_addr = (data_addr << 4) + fromhex (*ptr++);
4517 else
4518 lose = 1;
4520 if (!lose && startswith (ptr, ";Bss="))
4522 ptr += 5;
4523 while (*ptr && *ptr != ';')
4524 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4526 if (bss_addr != data_addr)
4527 warning (_("Target reported unsupported offsets: %s"), buf);
4529 else
4530 lose = 1;
4532 else if (startswith (ptr, "TextSeg="))
4534 ptr += 8;
4535 /* Don't use strtol, could lose on big values. */
4536 while (*ptr && *ptr != ';')
4537 text_addr = (text_addr << 4) + fromhex (*ptr++);
4538 num_segments = 1;
4540 if (startswith (ptr, ";DataSeg="))
4542 ptr += 9;
4543 while (*ptr && *ptr != ';')
4544 data_addr = (data_addr << 4) + fromhex (*ptr++);
4545 num_segments++;
4548 else
4549 lose = 1;
4551 if (lose)
4552 error (_("Malformed response to offset query, %s"), buf);
4553 else if (*ptr != '\0')
4554 warning (_("Target reported unsupported offsets: %s"), buf);
4556 objfile *objf = current_program_space->symfile_object_file;
4557 section_offsets offs = objf->section_offsets;
4559 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4560 do_segments = (data != NULL);
4561 do_sections = num_segments == 0;
4563 if (num_segments > 0)
4565 segments[0] = text_addr;
4566 segments[1] = data_addr;
4568 /* If we have two segments, we can still try to relocate everything
4569 by assuming that the .text and .data offsets apply to the whole
4570 text and data segments. Convert the offsets given in the packet
4571 to base addresses for symfile_map_offsets_to_segments. */
4572 else if (data != nullptr && data->segments.size () == 2)
4574 segments[0] = data->segments[0].base + text_addr;
4575 segments[1] = data->segments[1].base + data_addr;
4576 num_segments = 2;
4578 /* If the object file has only one segment, assume that it is text
4579 rather than data; main programs with no writable data are rare,
4580 but programs with no code are useless. Of course the code might
4581 have ended up in the data segment... to detect that we would need
4582 the permissions here. */
4583 else if (data && data->segments.size () == 1)
4585 segments[0] = data->segments[0].base + text_addr;
4586 num_segments = 1;
4588 /* There's no way to relocate by segment. */
4589 else
4590 do_segments = 0;
4592 if (do_segments)
4594 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4595 data.get (), offs,
4596 num_segments, segments);
4598 if (ret == 0 && !do_sections)
4599 error (_("Can not handle qOffsets TextSeg "
4600 "response with this symbol file"));
4602 if (ret > 0)
4603 do_sections = 0;
4606 if (do_sections)
4608 offs[SECT_OFF_TEXT (objf)] = text_addr;
4610 /* This is a temporary kludge to force data and bss to use the
4611 same offsets because that's what nlmconv does now. The real
4612 solution requires changes to the stub and remote.c that I
4613 don't have time to do right now. */
4615 offs[SECT_OFF_DATA (objf)] = data_addr;
4616 offs[SECT_OFF_BSS (objf)] = data_addr;
4619 objfile_relocate (objf, offs);
4622 /* Send interrupt_sequence to remote target. */
4624 void
4625 remote_target::send_interrupt_sequence ()
4627 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4628 remote_serial_write ("\x03", 1);
4629 else if (interrupt_sequence_mode == interrupt_sequence_break)
4630 remote_serial_send_break ();
4631 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4633 remote_serial_send_break ();
4634 remote_serial_write ("g", 1);
4636 else
4637 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4638 interrupt_sequence_mode);
4641 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4642 and extract the PTID. Returns NULL_PTID if not found. */
4644 static ptid_t
4645 stop_reply_extract_thread (const char *stop_reply)
4647 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4649 const char *p;
4651 /* Txx r:val ; r:val (...) */
4652 p = &stop_reply[3];
4654 /* Look for "register" named "thread". */
4655 while (*p != '\0')
4657 const char *p1;
4659 p1 = strchr (p, ':');
4660 if (p1 == NULL)
4661 return null_ptid;
4663 if (strncmp (p, "thread", p1 - p) == 0)
4664 return read_ptid (++p1, &p);
4666 p1 = strchr (p, ';');
4667 if (p1 == NULL)
4668 return null_ptid;
4669 p1++;
4671 p = p1;
4675 return null_ptid;
4678 /* Determine the remote side's current thread. If we have a stop
4679 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4680 "thread" register we can extract the current thread from. If not,
4681 ask the remote which is the current thread with qC. The former
4682 method avoids a roundtrip. */
4684 ptid_t
4685 remote_target::get_current_thread (const char *wait_status)
4687 ptid_t ptid = null_ptid;
4689 /* Note we don't use remote_parse_stop_reply as that makes use of
4690 the target architecture, which we haven't yet fully determined at
4691 this point. */
4692 if (wait_status != NULL)
4693 ptid = stop_reply_extract_thread (wait_status);
4694 if (ptid == null_ptid)
4695 ptid = remote_current_thread (inferior_ptid);
4697 return ptid;
4700 /* Query the remote target for which is the current thread/process,
4701 add it to our tables, and update INFERIOR_PTID. The caller is
4702 responsible for setting the state such that the remote end is ready
4703 to return the current thread.
4705 This function is called after handling the '?' or 'vRun' packets,
4706 whose response is a stop reply from which we can also try
4707 extracting the thread. If the target doesn't support the explicit
4708 qC query, we infer the current thread from that stop reply, passed
4709 in in WAIT_STATUS, which may be NULL.
4711 The function returns pointer to the main thread of the inferior. */
4713 thread_info *
4714 remote_target::add_current_inferior_and_thread (const char *wait_status)
4716 bool fake_pid_p = false;
4718 switch_to_no_thread ();
4720 /* Now, if we have thread information, update the current thread's
4721 ptid. */
4722 ptid_t curr_ptid = get_current_thread (wait_status);
4724 if (curr_ptid != null_ptid)
4726 if (!m_features.remote_multi_process_p ())
4727 fake_pid_p = true;
4729 else
4731 /* Without this, some commands which require an active target
4732 (such as kill) won't work. This variable serves (at least)
4733 double duty as both the pid of the target process (if it has
4734 such), and as a flag indicating that a target is active. */
4735 curr_ptid = magic_null_ptid;
4736 fake_pid_p = true;
4739 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4741 /* Add the main thread and switch to it. Don't try reading
4742 registers yet, since we haven't fetched the target description
4743 yet. */
4744 thread_info *tp = add_thread_silent (this, curr_ptid);
4745 switch_to_thread_no_regs (tp);
4747 return tp;
4750 /* Print info about a thread that was found already stopped on
4751 connection. */
4753 void
4754 remote_target::print_one_stopped_thread (thread_info *thread)
4756 target_waitstatus ws;
4758 /* If there is a pending waitstatus, use it. If there isn't it's because
4759 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4760 and process_initial_stop_replies decided it wasn't interesting to save
4761 and report to the core. */
4762 if (thread->has_pending_waitstatus ())
4764 ws = thread->pending_waitstatus ();
4765 thread->clear_pending_waitstatus ();
4767 else
4769 ws.set_stopped (GDB_SIGNAL_0);
4772 switch_to_thread (thread);
4773 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4774 set_current_sal_from_frame (get_current_frame ());
4776 /* For "info program". */
4777 set_last_target_status (this, thread->ptid, ws);
4779 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4781 enum gdb_signal sig = ws.sig ();
4783 if (signal_print_state (sig))
4784 notify_signal_received (sig);
4787 notify_normal_stop (nullptr, 1);
4790 /* Process all initial stop replies the remote side sent in response
4791 to the ? packet. These indicate threads that were already stopped
4792 on initial connection. We mark these threads as stopped and print
4793 their current frame before giving the user the prompt. */
4795 void
4796 remote_target::process_initial_stop_replies (int from_tty)
4798 int pending_stop_replies = stop_reply_queue_length ();
4799 struct thread_info *selected = NULL;
4800 struct thread_info *lowest_stopped = NULL;
4801 struct thread_info *first = NULL;
4803 /* This is only used when the target is non-stop. */
4804 gdb_assert (target_is_non_stop_p ());
4806 /* Consume the initial pending events. */
4807 while (pending_stop_replies-- > 0)
4809 ptid_t waiton_ptid = minus_one_ptid;
4810 ptid_t event_ptid;
4811 struct target_waitstatus ws;
4812 int ignore_event = 0;
4814 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4815 if (remote_debug)
4816 print_target_wait_results (waiton_ptid, event_ptid, ws);
4818 switch (ws.kind ())
4820 case TARGET_WAITKIND_IGNORE:
4821 case TARGET_WAITKIND_NO_RESUMED:
4822 case TARGET_WAITKIND_SIGNALLED:
4823 case TARGET_WAITKIND_EXITED:
4824 /* We shouldn't see these, but if we do, just ignore. */
4825 remote_debug_printf ("event ignored");
4826 ignore_event = 1;
4827 break;
4829 default:
4830 break;
4833 if (ignore_event)
4834 continue;
4836 thread_info *evthread = this->find_thread (event_ptid);
4838 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4840 enum gdb_signal sig = ws.sig ();
4842 /* Stubs traditionally report SIGTRAP as initial signal,
4843 instead of signal 0. Suppress it. */
4844 if (sig == GDB_SIGNAL_TRAP)
4845 sig = GDB_SIGNAL_0;
4846 evthread->set_stop_signal (sig);
4847 ws.set_stopped (sig);
4850 if (ws.kind () != TARGET_WAITKIND_STOPPED
4851 || ws.sig () != GDB_SIGNAL_0)
4852 evthread->set_pending_waitstatus (ws);
4854 set_executing (this, event_ptid, false);
4855 set_running (this, event_ptid, false);
4856 get_remote_thread_info (evthread)->set_not_resumed ();
4859 /* "Notice" the new inferiors before anything related to
4860 registers/memory. */
4861 for (inferior *inf : all_non_exited_inferiors (this))
4863 inf->needs_setup = true;
4865 if (non_stop)
4867 thread_info *thread = any_live_thread_of_inferior (inf);
4868 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4869 from_tty);
4873 /* If all-stop on top of non-stop, pause all threads. Note this
4874 records the threads' stop pc, so must be done after "noticing"
4875 the inferiors. */
4876 if (!non_stop)
4879 /* At this point, the remote target is not async. It needs to be for
4880 the poll in stop_all_threads to consider events from it, so enable
4881 it temporarily. */
4882 gdb_assert (!this->is_async_p ());
4883 SCOPE_EXIT { target_async (false); };
4884 target_async (true);
4885 stop_all_threads ("remote connect in all-stop");
4888 /* If all threads of an inferior were already stopped, we
4889 haven't setup the inferior yet. */
4890 for (inferior *inf : all_non_exited_inferiors (this))
4892 if (inf->needs_setup)
4894 thread_info *thread = any_live_thread_of_inferior (inf);
4895 switch_to_thread_no_regs (thread);
4896 setup_inferior (0);
4901 /* Now go over all threads that are stopped, and print their current
4902 frame. If all-stop, then if there's a signalled thread, pick
4903 that as current. */
4904 for (thread_info *thread : all_non_exited_threads (this))
4906 if (first == NULL)
4907 first = thread;
4909 if (!non_stop)
4910 thread->set_running (false);
4911 else if (thread->state != THREAD_STOPPED)
4912 continue;
4914 if (selected == nullptr && thread->has_pending_waitstatus ())
4915 selected = thread;
4917 if (lowest_stopped == NULL
4918 || thread->inf->num < lowest_stopped->inf->num
4919 || thread->per_inf_num < lowest_stopped->per_inf_num)
4920 lowest_stopped = thread;
4922 if (non_stop)
4923 print_one_stopped_thread (thread);
4926 /* In all-stop, we only print the status of one thread, and leave
4927 others with their status pending. */
4928 if (!non_stop)
4930 thread_info *thread = selected;
4931 if (thread == NULL)
4932 thread = lowest_stopped;
4933 if (thread == NULL)
4934 thread = first;
4936 print_one_stopped_thread (thread);
4940 /* Mark a remote_target as starting (by setting the starting_up flag within
4941 its remote_state) for the lifetime of this object. The reference count
4942 on the remote target is temporarily incremented, to prevent the target
4943 being deleted under our feet. */
4945 struct scoped_mark_target_starting
4947 /* Constructor, TARGET is the target to be marked as starting, its
4948 reference count will be incremented. */
4949 scoped_mark_target_starting (remote_target *target)
4950 : m_remote_target (remote_target_ref::new_reference (target)),
4951 m_restore_starting_up (set_starting_up_flag (target))
4952 { /* Nothing. */ }
4954 private:
4956 /* Helper function, set the starting_up flag on TARGET and return an
4957 object which, when it goes out of scope, will restore the previous
4958 value of the starting_up flag. */
4959 static scoped_restore_tmpl<bool>
4960 set_starting_up_flag (remote_target *target)
4962 remote_state *rs = target->get_remote_state ();
4963 gdb_assert (!rs->starting_up);
4964 return make_scoped_restore (&rs->starting_up, true);
4967 /* A gdb::ref_ptr pointer to a remote_target. */
4968 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4970 /* A reference to the target on which we are operating. */
4971 remote_target_ref m_remote_target;
4973 /* An object which restores the previous value of the starting_up flag
4974 when it goes out of scope. */
4975 scoped_restore_tmpl<bool> m_restore_starting_up;
4978 /* Helper for remote_target::start_remote, start the remote connection and
4979 sync state. Return true if everything goes OK, otherwise, return false.
4980 This function exists so that the scoped_restore created within it will
4981 expire before we return to remote_target::start_remote. */
4983 bool
4984 remote_target::start_remote_1 (int from_tty, int extended_p)
4986 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4988 struct remote_state *rs = get_remote_state ();
4990 /* Signal other parts that we're going through the initial setup,
4991 and so things may not be stable yet. E.g., we don't try to
4992 install tracepoints until we've relocated symbols. Also, a
4993 Ctrl-C before we're connected and synced up can't interrupt the
4994 target. Instead, it offers to drop the (potentially wedged)
4995 connection. */
4996 scoped_mark_target_starting target_is_starting (this);
4998 QUIT;
5000 if (interrupt_on_connect)
5001 send_interrupt_sequence ();
5003 /* Ack any packet which the remote side has already sent. */
5004 remote_serial_write ("+", 1);
5006 /* The first packet we send to the target is the optional "supported
5007 packets" request. If the target can answer this, it will tell us
5008 which later probes to skip. */
5009 remote_query_supported ();
5011 /* Check vCont support and set the remote state's vCont_action_support
5012 attribute. */
5013 remote_vcont_probe ();
5015 /* If the stub wants to get a QAllow, compose one and send it. */
5016 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5017 set_permissions ();
5019 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5020 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5021 as a reply to known packet. For packet "vFile:setfs:" it is an
5022 invalid reply and GDB would return error in
5023 remote_hostio_set_filesystem, making remote files access impossible.
5024 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5025 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5027 const char v_mustreplyempty[] = "vMustReplyEmpty";
5029 putpkt (v_mustreplyempty);
5030 getpkt (&rs->buf);
5031 if (strcmp (rs->buf.data (), "OK") == 0)
5033 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5034 = PACKET_DISABLE;
5036 else if (strcmp (rs->buf.data (), "") != 0)
5037 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5038 rs->buf.data ());
5041 /* Next, we possibly activate noack mode.
5043 If the QStartNoAckMode packet configuration is set to AUTO,
5044 enable noack mode if the stub reported a wish for it with
5045 qSupported.
5047 If set to TRUE, then enable noack mode even if the stub didn't
5048 report it in qSupported. If the stub doesn't reply OK, the
5049 session ends with an error.
5051 If FALSE, then don't activate noack mode, regardless of what the
5052 stub claimed should be the default with qSupported. */
5054 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5056 putpkt ("QStartNoAckMode");
5057 getpkt (&rs->buf);
5058 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5059 rs->noack_mode = 1;
5062 if (extended_p)
5064 /* Tell the remote that we are using the extended protocol. */
5065 putpkt ("!");
5066 getpkt (&rs->buf);
5069 /* Let the target know which signals it is allowed to pass down to
5070 the program. */
5071 update_signals_program_target ();
5073 /* Next, if the target can specify a description, read it. We do
5074 this before anything involving memory or registers. */
5075 target_find_description ();
5077 /* Next, now that we know something about the target, update the
5078 address spaces in the program spaces. */
5079 update_address_spaces ();
5081 /* On OSs where the list of libraries is global to all
5082 processes, we fetch them early. */
5083 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5084 solib_add (NULL, from_tty, auto_solib_add);
5086 if (target_is_non_stop_p ())
5088 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5089 error (_("Non-stop mode requested, but remote "
5090 "does not support non-stop"));
5092 putpkt ("QNonStop:1");
5093 getpkt (&rs->buf);
5095 if (strcmp (rs->buf.data (), "OK") != 0)
5096 error (_("Remote refused setting non-stop mode with: %s"),
5097 rs->buf.data ());
5099 /* Find about threads and processes the stub is already
5100 controlling. We default to adding them in the running state.
5101 The '?' query below will then tell us about which threads are
5102 stopped. */
5103 this->update_thread_list ();
5105 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5107 /* Don't assume that the stub can operate in all-stop mode.
5108 Request it explicitly. */
5109 putpkt ("QNonStop:0");
5110 getpkt (&rs->buf);
5112 if (strcmp (rs->buf.data (), "OK") != 0)
5113 error (_("Remote refused setting all-stop mode with: %s"),
5114 rs->buf.data ());
5117 /* Upload TSVs regardless of whether the target is running or not. The
5118 remote stub, such as GDBserver, may have some predefined or builtin
5119 TSVs, even if the target is not running. */
5120 if (get_trace_status (current_trace_status ()) != -1)
5122 struct uploaded_tsv *uploaded_tsvs = NULL;
5124 upload_trace_state_variables (&uploaded_tsvs);
5125 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5128 /* Check whether the target is running now. */
5129 putpkt ("?");
5130 getpkt (&rs->buf);
5132 if (!target_is_non_stop_p ())
5134 char *wait_status = NULL;
5136 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5138 if (!extended_p)
5139 error (_("The target is not running (try extended-remote?)"));
5140 return false;
5142 else
5144 /* Save the reply for later. */
5145 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5146 strcpy (wait_status, rs->buf.data ());
5149 /* Fetch thread list. */
5150 target_update_thread_list ();
5152 /* Let the stub know that we want it to return the thread. */
5153 set_continue_thread (minus_one_ptid);
5155 if (thread_count (this) == 0)
5157 /* Target has no concept of threads at all. GDB treats
5158 non-threaded target as single-threaded; add a main
5159 thread. */
5160 thread_info *tp = add_current_inferior_and_thread (wait_status);
5161 get_remote_thread_info (tp)->set_resumed ();
5163 else
5165 /* We have thread information; select the thread the target
5166 says should be current. If we're reconnecting to a
5167 multi-threaded program, this will ideally be the thread
5168 that last reported an event before GDB disconnected. */
5169 ptid_t curr_thread = get_current_thread (wait_status);
5170 if (curr_thread == null_ptid)
5172 /* Odd... The target was able to list threads, but not
5173 tell us which thread was current (no "thread"
5174 register in T stop reply?). Just pick the first
5175 thread in the thread list then. */
5177 remote_debug_printf ("warning: couldn't determine remote "
5178 "current thread; picking first in list.");
5180 for (thread_info *tp : all_non_exited_threads (this,
5181 minus_one_ptid))
5183 switch_to_thread (tp);
5184 break;
5187 else
5188 switch_to_thread (this->find_thread (curr_thread));
5190 get_remote_thread_info (inferior_thread ())->set_resumed ();
5193 /* init_wait_for_inferior should be called before get_offsets in order
5194 to manage `inserted' flag in bp loc in a correct state.
5195 breakpoint_init_inferior, called from init_wait_for_inferior, set
5196 `inserted' flag to 0, while before breakpoint_re_set, called from
5197 start_remote, set `inserted' flag to 1. In the initialization of
5198 inferior, breakpoint_init_inferior should be called first, and then
5199 breakpoint_re_set can be called. If this order is broken, state of
5200 `inserted' flag is wrong, and cause some problems on breakpoint
5201 manipulation. */
5202 init_wait_for_inferior ();
5204 get_offsets (); /* Get text, data & bss offsets. */
5206 /* If we could not find a description using qXfer, and we know
5207 how to do it some other way, try again. This is not
5208 supported for non-stop; it could be, but it is tricky if
5209 there are no stopped threads when we connect. */
5210 if (remote_read_description_p (this)
5211 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5213 target_clear_description ();
5214 target_find_description ();
5217 /* Use the previously fetched status. */
5218 gdb_assert (wait_status != NULL);
5219 struct notif_event *reply
5220 = remote_notif_parse (this, &notif_client_stop, wait_status);
5221 push_stop_reply ((struct stop_reply *) reply);
5223 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5225 else
5227 /* Clear WFI global state. Do this before finding about new
5228 threads and inferiors, and setting the current inferior.
5229 Otherwise we would clear the proceed status of the current
5230 inferior when we want its stop_soon state to be preserved
5231 (see notice_new_inferior). */
5232 init_wait_for_inferior ();
5234 /* In non-stop, we will either get an "OK", meaning that there
5235 are no stopped threads at this time; or, a regular stop
5236 reply. In the latter case, there may be more than one thread
5237 stopped --- we pull them all out using the vStopped
5238 mechanism. */
5239 if (strcmp (rs->buf.data (), "OK") != 0)
5241 const notif_client *notif = &notif_client_stop;
5243 /* remote_notif_get_pending_replies acks this one, and gets
5244 the rest out. */
5245 rs->notif_state->pending_event[notif_client_stop.id]
5246 = remote_notif_parse (this, notif, rs->buf.data ());
5247 remote_notif_get_pending_events (notif);
5250 if (thread_count (this) == 0)
5252 if (!extended_p)
5253 error (_("The target is not running (try extended-remote?)"));
5254 return false;
5257 /* Report all signals during attach/startup. */
5258 pass_signals ({});
5260 /* If there are already stopped threads, mark them stopped and
5261 report their stops before giving the prompt to the user. */
5262 process_initial_stop_replies (from_tty);
5264 if (target_can_async_p ())
5265 target_async (true);
5268 /* Give the target a chance to look up symbols. */
5269 for (inferior *inf : all_inferiors (this))
5271 /* The inferiors that exist at this point were created from what
5272 was found already running on the remote side, so we know they
5273 have execution. */
5274 gdb_assert (this->has_execution (inf));
5276 /* No use without a symbol-file. */
5277 if (inf->pspace->symfile_object_file == nullptr)
5278 continue;
5280 /* Need to switch to a specific thread, because remote_check_symbols
5281 uses INFERIOR_PTID to set the general thread. */
5282 scoped_restore_current_thread restore_thread;
5283 thread_info *thread = any_thread_of_inferior (inf);
5284 switch_to_thread (thread);
5285 this->remote_check_symbols ();
5288 /* Possibly the target has been engaged in a trace run started
5289 previously; find out where things are at. */
5290 if (get_trace_status (current_trace_status ()) != -1)
5292 struct uploaded_tp *uploaded_tps = NULL;
5294 if (current_trace_status ()->running)
5295 gdb_printf (_("Trace is already running on the target.\n"));
5297 upload_tracepoints (&uploaded_tps);
5299 merge_uploaded_tracepoints (&uploaded_tps);
5302 /* Possibly the target has been engaged in a btrace record started
5303 previously; find out where things are at. */
5304 remote_btrace_maybe_reopen ();
5306 return true;
5309 /* Start the remote connection and sync state. */
5311 void
5312 remote_target::start_remote (int from_tty, int extended_p)
5314 if (start_remote_1 (from_tty, extended_p)
5315 && breakpoints_should_be_inserted_now ())
5316 insert_breakpoints ();
5319 const char *
5320 remote_target::connection_string ()
5322 remote_state *rs = get_remote_state ();
5324 if (rs->remote_desc->name != NULL)
5325 return rs->remote_desc->name;
5326 else
5327 return NULL;
5330 /* Open a connection to a remote debugger.
5331 NAME is the filename used for communication. */
5333 void
5334 remote_target::open (const char *name, int from_tty)
5336 open_1 (name, from_tty, 0);
5339 /* Open a connection to a remote debugger using the extended
5340 remote gdb protocol. NAME is the filename used for communication. */
5342 void
5343 extended_remote_target::open (const char *name, int from_tty)
5345 open_1 (name, from_tty, 1 /*extended_p */);
5348 void
5349 remote_features::reset_all_packet_configs_support ()
5351 int i;
5353 for (i = 0; i < PACKET_MAX; i++)
5354 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5357 /* Initialize all packet configs. */
5359 static void
5360 init_all_packet_configs (void)
5362 int i;
5364 for (i = 0; i < PACKET_MAX; i++)
5366 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5367 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5371 /* Symbol look-up. */
5373 void
5374 remote_target::remote_check_symbols ()
5376 char *tmp;
5377 int end;
5379 /* It doesn't make sense to send a qSymbol packet for an inferior that
5380 doesn't have execution, because the remote side doesn't know about
5381 inferiors without execution. */
5382 gdb_assert (target_has_execution ());
5384 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5385 return;
5387 /* Make sure the remote is pointing at the right process. Note
5388 there's no way to select "no process". */
5389 set_general_process ();
5391 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5392 because we need both at the same time. */
5393 gdb::char_vector msg (get_remote_packet_size ());
5394 gdb::char_vector reply (get_remote_packet_size ());
5396 /* Invite target to request symbol lookups. */
5398 putpkt ("qSymbol::");
5399 getpkt (&reply);
5400 m_features.packet_ok (reply, PACKET_qSymbol);
5402 while (startswith (reply.data (), "qSymbol:"))
5404 struct bound_minimal_symbol sym;
5406 tmp = &reply[8];
5407 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5408 strlen (tmp) / 2);
5409 msg[end] = '\0';
5410 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5411 if (sym.minsym == NULL)
5412 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5413 &reply[8]);
5414 else
5416 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5417 CORE_ADDR sym_addr = sym.value_address ();
5419 /* If this is a function address, return the start of code
5420 instead of any data function descriptor. */
5421 sym_addr = gdbarch_convert_from_func_ptr_addr
5422 (current_inferior ()->arch (), sym_addr,
5423 current_inferior ()->top_target ());
5425 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5426 phex_nz (sym_addr, addr_size), &reply[8]);
5429 putpkt (msg.data ());
5430 getpkt (&reply);
5434 static struct serial *
5435 remote_serial_open (const char *name)
5437 static int udp_warning = 0;
5439 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5440 of in ser-tcp.c, because it is the remote protocol assuming that the
5441 serial connection is reliable and not the serial connection promising
5442 to be. */
5443 if (!udp_warning && startswith (name, "udp:"))
5445 warning (_("The remote protocol may be unreliable over UDP.\n"
5446 "Some events may be lost, rendering further debugging "
5447 "impossible."));
5448 udp_warning = 1;
5451 return serial_open (name);
5454 /* Inform the target of our permission settings. The permission flags
5455 work without this, but if the target knows the settings, it can do
5456 a couple things. First, it can add its own check, to catch cases
5457 that somehow manage to get by the permissions checks in target
5458 methods. Second, if the target is wired to disallow particular
5459 settings (for instance, a system in the field that is not set up to
5460 be able to stop at a breakpoint), it can object to any unavailable
5461 permissions. */
5463 void
5464 remote_target::set_permissions ()
5466 struct remote_state *rs = get_remote_state ();
5468 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5469 "WriteReg:%x;WriteMem:%x;"
5470 "InsertBreak:%x;InsertTrace:%x;"
5471 "InsertFastTrace:%x;Stop:%x",
5472 may_write_registers, may_write_memory,
5473 may_insert_breakpoints, may_insert_tracepoints,
5474 may_insert_fast_tracepoints, may_stop);
5475 putpkt (rs->buf);
5476 getpkt (&rs->buf);
5478 /* If the target didn't like the packet, warn the user. Do not try
5479 to undo the user's settings, that would just be maddening. */
5480 if (strcmp (rs->buf.data (), "OK") != 0)
5481 warning (_("Remote refused setting permissions with: %s"),
5482 rs->buf.data ());
5485 /* This type describes each known response to the qSupported
5486 packet. */
5487 struct protocol_feature
5489 /* The name of this protocol feature. */
5490 const char *name;
5492 /* The default for this protocol feature. */
5493 enum packet_support default_support;
5495 /* The function to call when this feature is reported, or after
5496 qSupported processing if the feature is not supported.
5497 The first argument points to this structure. The second
5498 argument indicates whether the packet requested support be
5499 enabled, disabled, or probed (or the default, if this function
5500 is being called at the end of processing and this feature was
5501 not reported). The third argument may be NULL; if not NULL, it
5502 is a NUL-terminated string taken from the packet following
5503 this feature's name and an equals sign. */
5504 void (*func) (remote_target *remote, const struct protocol_feature *,
5505 enum packet_support, const char *);
5507 /* The corresponding packet for this feature. Only used if
5508 FUNC is remote_supported_packet. */
5509 int packet;
5512 static void
5513 remote_supported_packet (remote_target *remote,
5514 const struct protocol_feature *feature,
5515 enum packet_support support,
5516 const char *argument)
5518 if (argument)
5520 warning (_("Remote qSupported response supplied an unexpected value for"
5521 " \"%s\"."), feature->name);
5522 return;
5525 remote->m_features.m_protocol_packets[feature->packet].support = support;
5528 void
5529 remote_target::remote_packet_size (const protocol_feature *feature,
5530 enum packet_support support,
5531 const char *value)
5533 struct remote_state *rs = get_remote_state ();
5535 int packet_size;
5536 char *value_end;
5538 if (support != PACKET_ENABLE)
5539 return;
5541 if (value == NULL || *value == '\0')
5543 warning (_("Remote target reported \"%s\" without a size."),
5544 feature->name);
5545 return;
5548 errno = 0;
5549 packet_size = strtol (value, &value_end, 16);
5550 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5552 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5553 feature->name, value);
5554 return;
5557 /* Record the new maximum packet size. */
5558 rs->explicit_packet_size = packet_size;
5561 static void
5562 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5563 enum packet_support support, const char *value)
5565 remote->remote_packet_size (feature, support, value);
5568 void
5569 remote_target::remote_supported_thread_options (const protocol_feature *feature,
5570 enum packet_support support,
5571 const char *value)
5573 struct remote_state *rs = get_remote_state ();
5575 m_features.m_protocol_packets[feature->packet].support = support;
5577 if (support != PACKET_ENABLE)
5578 return;
5580 if (value == nullptr || *value == '\0')
5582 warning (_("Remote target reported \"%s\" without supported options."),
5583 feature->name);
5584 return;
5587 ULONGEST options = 0;
5588 const char *p = unpack_varlen_hex (value, &options);
5590 if (*p != '\0')
5592 warning (_("Remote target reported \"%s\" with "
5593 "bad thread options: \"%s\"."),
5594 feature->name, value);
5595 return;
5598 /* Record the set of supported options. */
5599 rs->supported_thread_options = (gdb_thread_option) options;
5602 static void
5603 remote_supported_thread_options (remote_target *remote,
5604 const protocol_feature *feature,
5605 enum packet_support support,
5606 const char *value)
5608 remote->remote_supported_thread_options (feature, support, value);
5611 static const struct protocol_feature remote_protocol_features[] = {
5612 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5613 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5614 PACKET_qXfer_auxv },
5615 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5616 PACKET_qXfer_exec_file },
5617 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5618 PACKET_qXfer_features },
5619 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5620 PACKET_qXfer_libraries },
5621 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5622 PACKET_qXfer_libraries_svr4 },
5623 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5624 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5625 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5626 PACKET_qXfer_memory_map },
5627 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5628 PACKET_qXfer_osdata },
5629 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5630 PACKET_qXfer_threads },
5631 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5632 PACKET_qXfer_traceframe_info },
5633 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5634 PACKET_QPassSignals },
5635 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5636 PACKET_QCatchSyscalls },
5637 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5638 PACKET_QProgramSignals },
5639 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5640 PACKET_QSetWorkingDir },
5641 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5642 PACKET_QStartupWithShell },
5643 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5644 PACKET_QEnvironmentHexEncoded },
5645 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5646 PACKET_QEnvironmentReset },
5647 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5648 PACKET_QEnvironmentUnset },
5649 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5650 PACKET_QStartNoAckMode },
5651 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5652 PACKET_multiprocess_feature },
5653 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5654 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5655 PACKET_qXfer_siginfo_read },
5656 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5657 PACKET_qXfer_siginfo_write },
5658 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5659 PACKET_ConditionalTracepoints },
5660 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5661 PACKET_ConditionalBreakpoints },
5662 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5663 PACKET_BreakpointCommands },
5664 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5665 PACKET_FastTracepoints },
5666 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5667 PACKET_StaticTracepoints },
5668 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5669 PACKET_InstallInTrace},
5670 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5671 PACKET_DisconnectedTracing_feature },
5672 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5673 PACKET_bc },
5674 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5675 PACKET_bs },
5676 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5677 PACKET_TracepointSource },
5678 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5679 PACKET_QAllow },
5680 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5681 PACKET_EnableDisableTracepoints_feature },
5682 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5683 PACKET_qXfer_fdpic },
5684 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5685 PACKET_qXfer_uib },
5686 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5687 PACKET_QDisableRandomization },
5688 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5689 { "QTBuffer:size", PACKET_DISABLE,
5690 remote_supported_packet, PACKET_QTBuffer_size},
5691 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5692 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5693 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5694 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5695 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5696 PACKET_qXfer_btrace },
5697 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5698 PACKET_qXfer_btrace_conf },
5699 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5700 PACKET_Qbtrace_conf_bts_size },
5701 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5702 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5703 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5704 PACKET_fork_event_feature },
5705 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5706 PACKET_vfork_event_feature },
5707 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5708 PACKET_exec_event_feature },
5709 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5710 PACKET_Qbtrace_conf_pt_size },
5711 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5712 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5713 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5714 PACKET_QThreadOptions },
5715 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5716 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5717 PACKET_memory_tagging_feature },
5720 static char *remote_support_xml;
5722 /* Register string appended to "xmlRegisters=" in qSupported query. */
5724 void
5725 register_remote_support_xml (const char *xml)
5727 #if defined(HAVE_LIBEXPAT)
5728 if (remote_support_xml == NULL)
5729 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5730 else
5732 char *copy = xstrdup (remote_support_xml + 13);
5733 char *saveptr;
5734 char *p = strtok_r (copy, ",", &saveptr);
5738 if (strcmp (p, xml) == 0)
5740 /* already there */
5741 xfree (copy);
5742 return;
5745 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5746 xfree (copy);
5748 remote_support_xml = reconcat (remote_support_xml,
5749 remote_support_xml, ",", xml,
5750 (char *) NULL);
5752 #endif
5755 static void
5756 remote_query_supported_append (std::string *msg, const char *append)
5758 if (!msg->empty ())
5759 msg->append (";");
5760 msg->append (append);
5763 void
5764 remote_target::remote_query_supported ()
5766 struct remote_state *rs = get_remote_state ();
5767 char *next;
5768 int i;
5769 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5771 /* The packet support flags are handled differently for this packet
5772 than for most others. We treat an error, a disabled packet, and
5773 an empty response identically: any features which must be reported
5774 to be used will be automatically disabled. An empty buffer
5775 accomplishes this, since that is also the representation for a list
5776 containing no features. */
5778 rs->buf[0] = 0;
5779 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5781 std::string q;
5783 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5784 != AUTO_BOOLEAN_FALSE)
5785 remote_query_supported_append (&q, "multiprocess+");
5787 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5788 != AUTO_BOOLEAN_FALSE)
5789 remote_query_supported_append (&q, "swbreak+");
5791 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5792 != AUTO_BOOLEAN_FALSE)
5793 remote_query_supported_append (&q, "hwbreak+");
5795 remote_query_supported_append (&q, "qRelocInsn+");
5797 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5798 != AUTO_BOOLEAN_FALSE)
5799 remote_query_supported_append (&q, "fork-events+");
5801 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5802 != AUTO_BOOLEAN_FALSE)
5803 remote_query_supported_append (&q, "vfork-events+");
5805 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5806 != AUTO_BOOLEAN_FALSE)
5807 remote_query_supported_append (&q, "exec-events+");
5809 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5810 != AUTO_BOOLEAN_FALSE)
5811 remote_query_supported_append (&q, "vContSupported+");
5813 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5814 != AUTO_BOOLEAN_FALSE)
5815 remote_query_supported_append (&q, "QThreadEvents+");
5817 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5818 != AUTO_BOOLEAN_FALSE)
5819 remote_query_supported_append (&q, "QThreadOptions+");
5821 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5822 != AUTO_BOOLEAN_FALSE)
5823 remote_query_supported_append (&q, "no-resumed+");
5825 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5826 != AUTO_BOOLEAN_FALSE)
5827 remote_query_supported_append (&q, "memory-tagging+");
5829 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5830 the qSupported:xmlRegisters=i386 handling. */
5831 if (remote_support_xml != NULL
5832 && (m_features.packet_support (PACKET_qXfer_features)
5833 != PACKET_DISABLE))
5834 remote_query_supported_append (&q, remote_support_xml);
5836 q = "qSupported:" + q;
5837 putpkt (q.c_str ());
5839 getpkt (&rs->buf);
5841 /* If an error occurred, warn, but do not return - just reset the
5842 buffer to empty and go on to disable features. */
5843 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5845 warning (_("Remote failure reply: %s"), rs->buf.data ());
5846 rs->buf[0] = 0;
5850 memset (seen, 0, sizeof (seen));
5852 next = rs->buf.data ();
5853 while (*next)
5855 enum packet_support is_supported;
5856 char *p, *end, *name_end, *value;
5858 /* First separate out this item from the rest of the packet. If
5859 there's another item after this, we overwrite the separator
5860 (terminated strings are much easier to work with). */
5861 p = next;
5862 end = strchr (p, ';');
5863 if (end == NULL)
5865 end = p + strlen (p);
5866 next = end;
5868 else
5870 *end = '\0';
5871 next = end + 1;
5873 if (end == p)
5875 warning (_("empty item in \"qSupported\" response"));
5876 continue;
5880 name_end = strchr (p, '=');
5881 if (name_end)
5883 /* This is a name=value entry. */
5884 is_supported = PACKET_ENABLE;
5885 value = name_end + 1;
5886 *name_end = '\0';
5888 else
5890 value = NULL;
5891 switch (end[-1])
5893 case '+':
5894 is_supported = PACKET_ENABLE;
5895 break;
5897 case '-':
5898 is_supported = PACKET_DISABLE;
5899 break;
5901 case '?':
5902 is_supported = PACKET_SUPPORT_UNKNOWN;
5903 break;
5905 default:
5906 warning (_("unrecognized item \"%s\" "
5907 "in \"qSupported\" response"), p);
5908 continue;
5910 end[-1] = '\0';
5913 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5914 if (strcmp (remote_protocol_features[i].name, p) == 0)
5916 const struct protocol_feature *feature;
5918 seen[i] = 1;
5919 feature = &remote_protocol_features[i];
5920 feature->func (this, feature, is_supported, value);
5921 break;
5925 /* If we increased the packet size, make sure to increase the global
5926 buffer size also. We delay this until after parsing the entire
5927 qSupported packet, because this is the same buffer we were
5928 parsing. */
5929 if (rs->buf.size () < rs->explicit_packet_size)
5930 rs->buf.resize (rs->explicit_packet_size);
5932 /* Handle the defaults for unmentioned features. */
5933 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5934 if (!seen[i])
5936 const struct protocol_feature *feature;
5938 feature = &remote_protocol_features[i];
5939 feature->func (this, feature, feature->default_support, NULL);
5943 /* Serial QUIT handler for the remote serial descriptor.
5945 Defers handling a Ctrl-C until we're done with the current
5946 command/response packet sequence, unless:
5948 - We're setting up the connection. Don't send a remote interrupt
5949 request, as we're not fully synced yet. Quit immediately
5950 instead.
5952 - The target has been resumed in the foreground
5953 (target_terminal::is_ours is false) with a synchronous resume
5954 packet, and we're blocked waiting for the stop reply, thus a
5955 Ctrl-C should be immediately sent to the target.
5957 - We get a second Ctrl-C while still within the same serial read or
5958 write. In that case the serial is seemingly wedged --- offer to
5959 quit/disconnect.
5961 - We see a second Ctrl-C without target response, after having
5962 previously interrupted the target. In that case the target/stub
5963 is probably wedged --- offer to quit/disconnect.
5966 void
5967 remote_target::remote_serial_quit_handler ()
5969 struct remote_state *rs = get_remote_state ();
5971 if (check_quit_flag ())
5973 /* If we're starting up, we're not fully synced yet. Quit
5974 immediately. */
5975 if (rs->starting_up)
5976 quit ();
5977 else if (rs->got_ctrlc_during_io)
5979 if (query (_("The target is not responding to GDB commands.\n"
5980 "Stop debugging it? ")))
5981 remote_unpush_and_throw (this);
5983 /* If ^C has already been sent once, offer to disconnect. */
5984 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5985 interrupt_query ();
5986 /* All-stop protocol, and blocked waiting for stop reply. Send
5987 an interrupt request. */
5988 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5989 target_interrupt ();
5990 else
5991 rs->got_ctrlc_during_io = 1;
5995 /* The remote_target that is current while the quit handler is
5996 overridden with remote_serial_quit_handler. */
5997 static remote_target *curr_quit_handler_target;
5999 static void
6000 remote_serial_quit_handler ()
6002 curr_quit_handler_target->remote_serial_quit_handler ();
6005 /* Remove the remote target from the target stack of each inferior
6006 that is using it. Upper targets depend on it so remove them
6007 first. */
6009 static void
6010 remote_unpush_target (remote_target *target)
6012 /* We have to unpush the target from all inferiors, even those that
6013 aren't running. */
6014 scoped_restore_current_inferior restore_current_inferior;
6016 for (inferior *inf : all_inferiors (target))
6018 switch_to_inferior_no_thread (inf);
6019 inf->pop_all_targets_at_and_above (process_stratum);
6020 generic_mourn_inferior ();
6023 /* Don't rely on target_close doing this when the target is popped
6024 from the last remote inferior above, because something may be
6025 holding a reference to the target higher up on the stack, meaning
6026 target_close won't be called yet. We lost the connection to the
6027 target, so clear these now, otherwise we may later throw
6028 TARGET_CLOSE_ERROR while trying to tell the remote target to
6029 close the file. */
6030 fileio_handles_invalidate_target (target);
6033 static void
6034 remote_unpush_and_throw (remote_target *target)
6036 remote_unpush_target (target);
6037 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6040 void
6041 remote_target::open_1 (const char *name, int from_tty, int extended_p)
6043 remote_target *curr_remote = get_current_remote_target ();
6045 if (name == 0)
6046 error (_("To open a remote debug connection, you need to specify what\n"
6047 "serial device is attached to the remote system\n"
6048 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6050 /* If we're connected to a running target, target_preopen will kill it.
6051 Ask this question first, before target_preopen has a chance to kill
6052 anything. */
6053 if (curr_remote != NULL && !target_has_execution ())
6055 if (from_tty
6056 && !query (_("Already connected to a remote target. Disconnect? ")))
6057 error (_("Still connected."));
6060 /* Here the possibly existing remote target gets unpushed. */
6061 target_preopen (from_tty);
6063 remote_fileio_reset ();
6064 reopen_exec_file ();
6065 reread_symbols (from_tty);
6067 remote_target *remote
6068 = (extended_p ? new extended_remote_target () : new remote_target ());
6069 target_ops_up target_holder (remote);
6071 remote_state *rs = remote->get_remote_state ();
6073 /* See FIXME above. */
6074 if (!target_async_permitted)
6075 rs->wait_forever_enabled_p = true;
6077 rs->remote_desc = remote_serial_open (name);
6079 if (baud_rate != -1)
6083 serial_setbaudrate (rs->remote_desc, baud_rate);
6085 catch (const gdb_exception_error &)
6087 /* The requested speed could not be set. Error out to
6088 top level after closing remote_desc. Take care to
6089 set remote_desc to NULL to avoid closing remote_desc
6090 more than once. */
6091 serial_close (rs->remote_desc);
6092 rs->remote_desc = NULL;
6093 throw;
6097 serial_setparity (rs->remote_desc, serial_parity);
6098 serial_raw (rs->remote_desc);
6100 /* If there is something sitting in the buffer we might take it as a
6101 response to a command, which would be bad. */
6102 serial_flush_input (rs->remote_desc);
6104 if (from_tty)
6106 gdb_puts ("Remote debugging using ");
6107 gdb_puts (name);
6108 gdb_puts ("\n");
6111 /* Switch to using the remote target now. */
6112 current_inferior ()->push_target (std::move (target_holder));
6114 /* Register extra event sources in the event loop. */
6115 rs->create_async_event_handler ();
6117 rs->notif_state = remote_notif_state_allocate (remote);
6119 /* Reset the target state; these things will be queried either by
6120 remote_query_supported or as they are needed. */
6121 remote->m_features.reset_all_packet_configs_support ();
6122 rs->explicit_packet_size = 0;
6123 rs->noack_mode = 0;
6124 rs->extended = extended_p;
6125 rs->waiting_for_stop_reply = 0;
6126 rs->ctrlc_pending_p = 0;
6127 rs->got_ctrlc_during_io = 0;
6129 rs->general_thread = not_sent_ptid;
6130 rs->continue_thread = not_sent_ptid;
6131 rs->remote_traceframe_number = -1;
6133 rs->last_resume_exec_dir = EXEC_FORWARD;
6135 /* Probe for ability to use "ThreadInfo" query, as required. */
6136 rs->use_threadinfo_query = 1;
6137 rs->use_threadextra_query = 1;
6139 rs->readahead_cache.invalidate ();
6141 if (target_async_permitted)
6143 /* FIXME: cagney/1999-09-23: During the initial connection it is
6144 assumed that the target is already ready and able to respond to
6145 requests. Unfortunately remote_start_remote() eventually calls
6146 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6147 around this. Eventually a mechanism that allows
6148 wait_for_inferior() to expect/get timeouts will be
6149 implemented. */
6150 rs->wait_forever_enabled_p = false;
6153 /* First delete any symbols previously loaded from shared libraries. */
6154 no_shared_libraries (NULL, 0);
6156 /* Start the remote connection. If error() or QUIT, discard this
6157 target (we'd otherwise be in an inconsistent state) and then
6158 propogate the error on up the exception chain. This ensures that
6159 the caller doesn't stumble along blindly assuming that the
6160 function succeeded. The CLI doesn't have this problem but other
6161 UI's, such as MI do.
6163 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6164 this function should return an error indication letting the
6165 caller restore the previous state. Unfortunately the command
6166 ``target remote'' is directly wired to this function making that
6167 impossible. On a positive note, the CLI side of this problem has
6168 been fixed - the function set_cmd_context() makes it possible for
6169 all the ``target ....'' commands to share a common callback
6170 function. See cli-dump.c. */
6175 remote->start_remote (from_tty, extended_p);
6177 catch (const gdb_exception &ex)
6179 /* Pop the partially set up target - unless something else did
6180 already before throwing the exception. */
6181 if (ex.error != TARGET_CLOSE_ERROR)
6182 remote_unpush_target (remote);
6183 throw;
6187 remote_btrace_reset (rs);
6189 if (target_async_permitted)
6190 rs->wait_forever_enabled_p = true;
6193 /* Determine if WS represents a fork status. */
6195 static bool
6196 is_fork_status (target_waitkind kind)
6198 return (kind == TARGET_WAITKIND_FORKED
6199 || kind == TARGET_WAITKIND_VFORKED);
6202 /* Return a reference to the field where a pending child status, if
6203 there's one, is recorded. If there's no child event pending, the
6204 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6206 static const target_waitstatus &
6207 thread_pending_status (struct thread_info *thread)
6209 return (thread->has_pending_waitstatus ()
6210 ? thread->pending_waitstatus ()
6211 : thread->pending_follow);
6214 /* Return THREAD's pending status if it is a pending fork/vfork (but
6215 not clone) parent, else return nullptr. */
6217 static const target_waitstatus *
6218 thread_pending_fork_status (struct thread_info *thread)
6220 const target_waitstatus &ws = thread_pending_status (thread);
6222 if (!is_fork_status (ws.kind ()))
6223 return nullptr;
6225 return &ws;
6228 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6229 event, else return nullptr. */
6231 static const target_waitstatus *
6232 thread_pending_child_status (thread_info *thread)
6234 const target_waitstatus &ws = thread_pending_status (thread);
6236 if (!is_new_child_status (ws.kind ()))
6237 return nullptr;
6239 return &ws;
6242 /* Detach the specified process. */
6244 void
6245 remote_target::remote_detach_pid (int pid)
6247 struct remote_state *rs = get_remote_state ();
6249 /* This should not be necessary, but the handling for D;PID in
6250 GDBserver versions prior to 8.2 incorrectly assumes that the
6251 selected process points to the same process we're detaching,
6252 leading to misbehavior (and possibly GDBserver crashing) when it
6253 does not. Since it's easy and cheap, work around it by forcing
6254 GDBserver to select GDB's current process. */
6255 set_general_process ();
6257 if (m_features.remote_multi_process_p ())
6258 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6259 else
6260 strcpy (rs->buf.data (), "D");
6262 putpkt (rs->buf);
6263 getpkt (&rs->buf);
6265 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6267 else if (rs->buf[0] == '\0')
6268 error (_("Remote doesn't know how to detach"));
6269 else
6271 /* It is possible that we have an unprocessed exit event for this
6272 pid. If this is the case then we can ignore the failure to detach
6273 and just pretend that the detach worked, as far as the user is
6274 concerned, the process exited immediately after the detach. */
6275 bool process_has_already_exited = false;
6276 remote_notif_get_pending_events (&notif_client_stop);
6277 for (stop_reply_up &reply : rs->stop_reply_queue)
6279 if (reply->ptid.pid () != pid)
6280 continue;
6282 enum target_waitkind kind = reply->ws.kind ();
6283 if (kind == TARGET_WAITKIND_EXITED
6284 || kind == TARGET_WAITKIND_SIGNALLED)
6286 process_has_already_exited = true;
6287 remote_debug_printf
6288 ("detach failed, but process already exited");
6289 break;
6293 if (!process_has_already_exited)
6294 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6298 /* This detaches a program to which we previously attached, using
6299 inferior_ptid to identify the process. After this is done, GDB
6300 can be used to debug some other program. We better not have left
6301 any breakpoints in the target program or it'll die when it hits
6302 one. */
6304 void
6305 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6307 int pid = inferior_ptid.pid ();
6308 struct remote_state *rs = get_remote_state ();
6309 int is_fork_parent;
6311 if (!target_has_execution ())
6312 error (_("No process to detach from."));
6314 target_announce_detach (from_tty);
6316 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6318 /* If we're in breakpoints-always-inserted mode, or the inferior
6319 is running, we have to remove breakpoints before detaching.
6320 We don't do this in common code instead because not all
6321 targets support removing breakpoints while the target is
6322 running. The remote target / gdbserver does, though. */
6323 remove_breakpoints_inf (current_inferior ());
6326 /* Tell the remote target to detach. */
6327 remote_detach_pid (pid);
6329 /* Exit only if this is the only active inferior. */
6330 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6331 gdb_puts (_("Ending remote debugging.\n"));
6333 /* See if any thread of the inferior we are detaching has a pending fork
6334 status. In that case, we must detach from the child resulting from
6335 that fork. */
6336 for (thread_info *thread : inf->non_exited_threads ())
6338 const target_waitstatus *ws = thread_pending_fork_status (thread);
6340 if (ws == nullptr)
6341 continue;
6343 remote_detach_pid (ws->child_ptid ().pid ());
6346 /* Check also for any pending fork events in the stop reply queue. */
6347 remote_notif_get_pending_events (&notif_client_stop);
6348 for (stop_reply_up &reply : rs->stop_reply_queue)
6350 if (reply->ptid.pid () != pid)
6351 continue;
6353 if (!is_fork_status (reply->ws.kind ()))
6354 continue;
6356 remote_detach_pid (reply->ws.child_ptid ().pid ());
6359 thread_info *tp = this->find_thread (inferior_ptid);
6361 /* Check to see if we are detaching a fork parent. Note that if we
6362 are detaching a fork child, tp == NULL. */
6363 is_fork_parent = (tp != NULL
6364 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6366 /* If doing detach-on-fork, we don't mourn, because that will delete
6367 breakpoints that should be available for the followed inferior. */
6368 if (!is_fork_parent)
6370 /* Save the pid as a string before mourning, since that will
6371 unpush the remote target, and we need the string after. */
6372 std::string infpid = target_pid_to_str (ptid_t (pid));
6374 target_mourn_inferior (inferior_ptid);
6375 if (print_inferior_events)
6376 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6377 inf->num, infpid.c_str ());
6379 else
6381 switch_to_no_thread ();
6382 detach_inferior (current_inferior ());
6386 void
6387 remote_target::detach (inferior *inf, int from_tty)
6389 remote_detach_1 (inf, from_tty);
6392 void
6393 extended_remote_target::detach (inferior *inf, int from_tty)
6395 remote_detach_1 (inf, from_tty);
6398 /* Target follow-fork function for remote targets. On entry, and
6399 at return, the current inferior is the fork parent.
6401 Note that although this is currently only used for extended-remote,
6402 it is named remote_follow_fork in anticipation of using it for the
6403 remote target as well. */
6405 void
6406 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6407 target_waitkind fork_kind, bool follow_child,
6408 bool detach_fork)
6410 process_stratum_target::follow_fork (child_inf, child_ptid,
6411 fork_kind, follow_child, detach_fork);
6413 if ((fork_kind == TARGET_WAITKIND_FORKED
6414 && m_features.remote_fork_event_p ())
6415 || (fork_kind == TARGET_WAITKIND_VFORKED
6416 && m_features.remote_vfork_event_p ()))
6418 /* When following the parent and detaching the child, we detach
6419 the child here. For the case of following the child and
6420 detaching the parent, the detach is done in the target-
6421 independent follow fork code in infrun.c. We can't use
6422 target_detach when detaching an unfollowed child because
6423 the client side doesn't know anything about the child. */
6424 if (detach_fork && !follow_child)
6426 /* Detach the fork child. */
6427 remote_detach_pid (child_ptid.pid ());
6432 void
6433 remote_target::follow_clone (ptid_t child_ptid)
6435 remote_add_thread (child_ptid, false, false, false);
6438 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6439 in the program space of the new inferior. */
6441 void
6442 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6443 const char *execd_pathname)
6445 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6447 /* We know that this is a target file name, so if it has the "target:"
6448 prefix we strip it off before saving it in the program space. */
6449 if (is_target_filename (execd_pathname))
6450 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6452 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6455 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6457 void
6458 remote_target::disconnect (const char *args, int from_tty)
6460 if (args)
6461 error (_("Argument given to \"disconnect\" when remotely debugging."));
6463 /* Make sure we unpush even the extended remote targets. Calling
6464 target_mourn_inferior won't unpush, and
6465 remote_target::mourn_inferior won't unpush if there is more than
6466 one inferior left. */
6467 remote_unpush_target (this);
6469 if (from_tty)
6470 gdb_puts ("Ending remote debugging.\n");
6473 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6474 be chatty about it. */
6476 void
6477 extended_remote_target::attach (const char *args, int from_tty)
6479 struct remote_state *rs = get_remote_state ();
6480 int pid;
6481 char *wait_status = NULL;
6483 pid = parse_pid_to_attach (args);
6485 /* Remote PID can be freely equal to getpid, do not check it here the same
6486 way as in other targets. */
6488 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6489 error (_("This target does not support attaching to a process"));
6491 target_announce_attach (from_tty, pid);
6493 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6494 putpkt (rs->buf);
6495 getpkt (&rs->buf);
6497 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6499 case PACKET_OK:
6500 if (!target_is_non_stop_p ())
6502 /* Save the reply for later. */
6503 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6504 strcpy (wait_status, rs->buf.data ());
6506 else if (strcmp (rs->buf.data (), "OK") != 0)
6507 error (_("Attaching to %s failed with: %s"),
6508 target_pid_to_str (ptid_t (pid)).c_str (),
6509 rs->buf.data ());
6510 break;
6511 case PACKET_UNKNOWN:
6512 error (_("This target does not support attaching to a process"));
6513 default:
6514 error (_("Attaching to %s failed"),
6515 target_pid_to_str (ptid_t (pid)).c_str ());
6518 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6520 inferior_ptid = ptid_t (pid);
6522 if (target_is_non_stop_p ())
6524 /* Get list of threads. */
6525 update_thread_list ();
6527 thread_info *thread = first_thread_of_inferior (current_inferior ());
6528 if (thread != nullptr)
6529 switch_to_thread (thread);
6531 /* Invalidate our notion of the remote current thread. */
6532 record_currthread (rs, minus_one_ptid);
6534 else
6536 /* Now, if we have thread information, update the main thread's
6537 ptid. */
6538 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6540 /* Add the main thread to the thread list. We add the thread
6541 silently in this case (the final true parameter). */
6542 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6544 switch_to_thread (thr);
6547 /* Next, if the target can specify a description, read it. We do
6548 this before anything involving memory or registers. */
6549 target_find_description ();
6551 if (!target_is_non_stop_p ())
6553 /* Use the previously fetched status. */
6554 gdb_assert (wait_status != NULL);
6556 struct notif_event *reply
6557 = remote_notif_parse (this, &notif_client_stop, wait_status);
6559 push_stop_reply ((struct stop_reply *) reply);
6561 else
6563 gdb_assert (wait_status == NULL);
6565 gdb_assert (target_can_async_p ());
6569 /* Implementation of the to_post_attach method. */
6571 void
6572 extended_remote_target::post_attach (int pid)
6574 /* Get text, data & bss offsets. */
6575 get_offsets ();
6577 /* In certain cases GDB might not have had the chance to start
6578 symbol lookup up until now. This could happen if the debugged
6579 binary is not using shared libraries, the vsyscall page is not
6580 present (on Linux) and the binary itself hadn't changed since the
6581 debugging process was started. */
6582 if (current_program_space->symfile_object_file != NULL)
6583 remote_check_symbols();
6587 /* Check for the availability of vCont. This function should also check
6588 the response. */
6590 void
6591 remote_target::remote_vcont_probe ()
6593 remote_state *rs = get_remote_state ();
6594 char *buf;
6596 strcpy (rs->buf.data (), "vCont?");
6597 putpkt (rs->buf);
6598 getpkt (&rs->buf);
6599 buf = rs->buf.data ();
6601 /* Make sure that the features we assume are supported. */
6602 if (startswith (buf, "vCont"))
6604 char *p = &buf[5];
6605 int support_c, support_C;
6607 rs->supports_vCont.s = 0;
6608 rs->supports_vCont.S = 0;
6609 support_c = 0;
6610 support_C = 0;
6611 rs->supports_vCont.t = 0;
6612 rs->supports_vCont.r = 0;
6613 while (p && *p == ';')
6615 p++;
6616 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6617 rs->supports_vCont.s = 1;
6618 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6619 rs->supports_vCont.S = 1;
6620 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6621 support_c = 1;
6622 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6623 support_C = 1;
6624 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6625 rs->supports_vCont.t = 1;
6626 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6627 rs->supports_vCont.r = 1;
6629 p = strchr (p, ';');
6632 /* If c, and C are not all supported, we can't use vCont. Clearing
6633 BUF will make packet_ok disable the packet. */
6634 if (!support_c || !support_C)
6635 buf[0] = 0;
6638 m_features.packet_ok (rs->buf, PACKET_vCont);
6641 /* Helper function for building "vCont" resumptions. Write a
6642 resumption to P. ENDP points to one-passed-the-end of the buffer
6643 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6644 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6645 resumed thread should be single-stepped and/or signalled. If PTID
6646 equals minus_one_ptid, then all threads are resumed; if PTID
6647 represents a process, then all threads of the process are
6648 resumed. */
6650 char *
6651 remote_target::append_resumption (char *p, char *endp,
6652 ptid_t ptid, int step, gdb_signal siggnal)
6654 struct remote_state *rs = get_remote_state ();
6656 if (step && siggnal != GDB_SIGNAL_0)
6657 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6658 else if (step
6659 /* GDB is willing to range step. */
6660 && use_range_stepping
6661 /* Target supports range stepping. */
6662 && rs->supports_vCont.r
6663 /* We don't currently support range stepping multiple
6664 threads with a wildcard (though the protocol allows it,
6665 so stubs shouldn't make an active effort to forbid
6666 it). */
6667 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6669 struct thread_info *tp;
6671 if (ptid == minus_one_ptid)
6673 /* If we don't know about the target thread's tid, then
6674 we're resuming magic_null_ptid (see caller). */
6675 tp = this->find_thread (magic_null_ptid);
6677 else
6678 tp = this->find_thread (ptid);
6679 gdb_assert (tp != NULL);
6681 if (tp->control.may_range_step)
6683 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6685 p += xsnprintf (p, endp - p, ";r%s,%s",
6686 phex_nz (tp->control.step_range_start,
6687 addr_size),
6688 phex_nz (tp->control.step_range_end,
6689 addr_size));
6691 else
6692 p += xsnprintf (p, endp - p, ";s");
6694 else if (step)
6695 p += xsnprintf (p, endp - p, ";s");
6696 else if (siggnal != GDB_SIGNAL_0)
6697 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6698 else
6699 p += xsnprintf (p, endp - p, ";c");
6701 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6703 ptid_t nptid;
6705 /* All (-1) threads of process. */
6706 nptid = ptid_t (ptid.pid (), -1);
6708 p += xsnprintf (p, endp - p, ":");
6709 p = write_ptid (p, endp, nptid);
6711 else if (ptid != minus_one_ptid)
6713 p += xsnprintf (p, endp - p, ":");
6714 p = write_ptid (p, endp, ptid);
6717 return p;
6720 /* Clear the thread's private info on resume. */
6722 static void
6723 resume_clear_thread_private_info (struct thread_info *thread)
6725 if (thread->priv != NULL)
6727 remote_thread_info *priv = get_remote_thread_info (thread);
6729 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6730 priv->watch_data_address = 0;
6734 /* Append a vCont continue-with-signal action for threads that have a
6735 non-zero stop signal. */
6737 char *
6738 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6739 ptid_t ptid)
6741 for (thread_info *thread : all_non_exited_threads (this, ptid))
6742 if (inferior_ptid != thread->ptid
6743 && thread->stop_signal () != GDB_SIGNAL_0)
6745 p = append_resumption (p, endp, thread->ptid,
6746 0, thread->stop_signal ());
6747 thread->set_stop_signal (GDB_SIGNAL_0);
6748 resume_clear_thread_private_info (thread);
6751 return p;
6754 /* Set the target running, using the packets that use Hc
6755 (c/s/C/S). */
6757 void
6758 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6759 gdb_signal siggnal)
6761 struct remote_state *rs = get_remote_state ();
6762 char *buf;
6764 rs->last_sent_signal = siggnal;
6765 rs->last_sent_step = step;
6767 /* The c/s/C/S resume packets use Hc, so set the continue
6768 thread. */
6769 if (ptid == minus_one_ptid)
6770 set_continue_thread (any_thread_ptid);
6771 else
6772 set_continue_thread (ptid);
6774 for (thread_info *thread : all_non_exited_threads (this))
6775 resume_clear_thread_private_info (thread);
6777 buf = rs->buf.data ();
6778 if (::execution_direction == EXEC_REVERSE)
6780 /* We don't pass signals to the target in reverse exec mode. */
6781 if (info_verbose && siggnal != GDB_SIGNAL_0)
6782 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6783 siggnal);
6785 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6786 error (_("Remote reverse-step not supported."));
6787 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6788 error (_("Remote reverse-continue not supported."));
6790 strcpy (buf, step ? "bs" : "bc");
6792 else if (siggnal != GDB_SIGNAL_0)
6794 buf[0] = step ? 'S' : 'C';
6795 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6796 buf[2] = tohex (((int) siggnal) & 0xf);
6797 buf[3] = '\0';
6799 else
6800 strcpy (buf, step ? "s" : "c");
6802 putpkt (buf);
6805 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6806 STEP, and SIGGNAL have the same meaning as in target_resume. This
6807 function returns non-zero iff it resumes the inferior.
6809 This function issues a strict subset of all possible vCont commands
6810 at the moment. */
6813 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6814 enum gdb_signal siggnal)
6816 struct remote_state *rs = get_remote_state ();
6817 char *p;
6818 char *endp;
6820 /* No reverse execution actions defined for vCont. */
6821 if (::execution_direction == EXEC_REVERSE)
6822 return 0;
6824 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6825 return 0;
6827 p = rs->buf.data ();
6828 endp = p + get_remote_packet_size ();
6830 /* If we could generate a wider range of packets, we'd have to worry
6831 about overflowing BUF. Should there be a generic
6832 "multi-part-packet" packet? */
6834 p += xsnprintf (p, endp - p, "vCont");
6836 if (scope_ptid == magic_null_ptid)
6838 /* MAGIC_NULL_PTID means that we don't have any active threads,
6839 so we don't have any TID numbers the inferior will
6840 understand. Make sure to only send forms that do not specify
6841 a TID. */
6842 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6844 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6846 /* Resume all threads (of all processes, or of a single
6847 process), with preference for INFERIOR_PTID. This assumes
6848 inferior_ptid belongs to the set of all threads we are about
6849 to resume. */
6850 if (step || siggnal != GDB_SIGNAL_0)
6852 /* Step inferior_ptid, with or without signal. */
6853 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6856 /* Also pass down any pending signaled resumption for other
6857 threads not the current. */
6858 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6860 /* And continue others without a signal. */
6861 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6863 else
6865 /* Scheduler locking; resume only SCOPE_PTID. */
6866 append_resumption (p, endp, scope_ptid, step, siggnal);
6869 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6870 putpkt (rs->buf);
6872 if (target_is_non_stop_p ())
6874 /* In non-stop, the stub replies to vCont with "OK". The stop
6875 reply will be reported asynchronously by means of a `%Stop'
6876 notification. */
6877 getpkt (&rs->buf);
6878 if (strcmp (rs->buf.data (), "OK") != 0)
6879 error (_("Unexpected vCont reply in non-stop mode: %s"),
6880 rs->buf.data ());
6883 return 1;
6886 /* Tell the remote machine to resume. */
6888 void
6889 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6891 struct remote_state *rs = get_remote_state ();
6893 /* When connected in non-stop mode, the core resumes threads
6894 individually. Resuming remote threads directly in target_resume
6895 would thus result in sending one packet per thread. Instead, to
6896 minimize roundtrip latency, here we just store the resume
6897 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6898 resumption will be done in remote_target::commit_resume, where we'll be
6899 able to do vCont action coalescing. */
6900 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6902 remote_thread_info *remote_thr
6903 = get_remote_thread_info (inferior_thread ());
6905 /* We don't expect the core to ask to resume an already resumed (from
6906 its point of view) thread. */
6907 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6909 remote_thr->set_resumed_pending_vcont (step, siggnal);
6911 /* There's actually nothing that says that the core can't
6912 request a wildcard resume in non-stop mode, though. It's
6913 just that we know it doesn't currently, so we don't bother
6914 with it. */
6915 gdb_assert (scope_ptid == inferior_ptid);
6916 return;
6919 commit_requested_thread_options ();
6921 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6922 (explained in remote-notif.c:handle_notification) so
6923 remote_notif_process is not called. We need find a place where
6924 it is safe to start a 'vNotif' sequence. It is good to do it
6925 before resuming inferior, because inferior was stopped and no RSP
6926 traffic at that moment. */
6927 if (!target_is_non_stop_p ())
6928 remote_notif_process (rs->notif_state, &notif_client_stop);
6930 rs->last_resume_exec_dir = ::execution_direction;
6932 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6933 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6934 remote_resume_with_hc (scope_ptid, step, siggnal);
6936 /* Update resumed state tracked by the remote target. */
6937 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6938 get_remote_thread_info (tp)->set_resumed ();
6940 /* We've just told the target to resume. The remote server will
6941 wait for the inferior to stop, and then send a stop reply. In
6942 the mean time, we can't start another command/query ourselves
6943 because the stub wouldn't be ready to process it. This applies
6944 only to the base all-stop protocol, however. In non-stop (which
6945 only supports vCont), the stub replies with an "OK", and is
6946 immediate able to process further serial input. */
6947 if (!target_is_non_stop_p ())
6948 rs->waiting_for_stop_reply = 1;
6951 /* Private per-inferior info for target remote processes. */
6953 struct remote_inferior : public private_inferior
6955 /* Whether we can send a wildcard vCont for this process. */
6956 bool may_wildcard_vcont = true;
6959 /* Get the remote private inferior data associated to INF. */
6961 static remote_inferior *
6962 get_remote_inferior (inferior *inf)
6964 if (inf->priv == NULL)
6965 inf->priv.reset (new remote_inferior);
6967 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6970 /* Class used to track the construction of a vCont packet in the
6971 outgoing packet buffer. This is used to send multiple vCont
6972 packets if we have more actions than would fit a single packet. */
6974 class vcont_builder
6976 public:
6977 explicit vcont_builder (remote_target *remote)
6978 : m_remote (remote)
6980 restart ();
6983 void flush ();
6984 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6986 private:
6987 void restart ();
6989 /* The remote target. */
6990 remote_target *m_remote;
6992 /* Pointer to the first action. P points here if no action has been
6993 appended yet. */
6994 char *m_first_action;
6996 /* Where the next action will be appended. */
6997 char *m_p;
6999 /* The end of the buffer. Must never write past this. */
7000 char *m_endp;
7003 /* Prepare the outgoing buffer for a new vCont packet. */
7005 void
7006 vcont_builder::restart ()
7008 struct remote_state *rs = m_remote->get_remote_state ();
7010 m_p = rs->buf.data ();
7011 m_endp = m_p + m_remote->get_remote_packet_size ();
7012 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7013 m_first_action = m_p;
7016 /* If the vCont packet being built has any action, send it to the
7017 remote end. */
7019 void
7020 vcont_builder::flush ()
7022 struct remote_state *rs;
7024 if (m_p == m_first_action)
7025 return;
7027 rs = m_remote->get_remote_state ();
7028 m_remote->putpkt (rs->buf);
7029 m_remote->getpkt (&rs->buf);
7030 if (strcmp (rs->buf.data (), "OK") != 0)
7031 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7034 /* The largest action is range-stepping, with its two addresses. This
7035 is more than sufficient. If a new, bigger action is created, it'll
7036 quickly trigger a failed assertion in append_resumption (and we'll
7037 just bump this). */
7038 #define MAX_ACTION_SIZE 200
7040 /* Append a new vCont action in the outgoing packet being built. If
7041 the action doesn't fit the packet along with previous actions, push
7042 what we've got so far to the remote end and start over a new vCont
7043 packet (with the new action). */
7045 void
7046 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7048 char buf[MAX_ACTION_SIZE + 1];
7050 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7051 ptid, step, siggnal);
7053 /* Check whether this new action would fit in the vCont packet along
7054 with previous actions. If not, send what we've got so far and
7055 start a new vCont packet. */
7056 size_t rsize = endp - buf;
7057 if (rsize > m_endp - m_p)
7059 flush ();
7060 restart ();
7062 /* Should now fit. */
7063 gdb_assert (rsize <= m_endp - m_p);
7066 memcpy (m_p, buf, rsize);
7067 m_p += rsize;
7068 *m_p = '\0';
7071 /* to_commit_resume implementation. */
7073 void
7074 remote_target::commit_resumed ()
7076 /* If connected in all-stop mode, we'd send the remote resume
7077 request directly from remote_resume. Likewise if
7078 reverse-debugging, as there are no defined vCont actions for
7079 reverse execution. */
7080 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7081 return;
7083 commit_requested_thread_options ();
7085 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7086 instead of resuming all threads of each process individually.
7087 However, if any thread of a process must remain halted, we can't
7088 send wildcard resumes and must send one action per thread.
7090 Care must be taken to not resume threads/processes the server
7091 side already told us are stopped, but the core doesn't know about
7092 yet, because the events are still in the vStopped notification
7093 queue. For example:
7095 #1 => vCont s:p1.1;c
7096 #2 <= OK
7097 #3 <= %Stopped T05 p1.1
7098 #4 => vStopped
7099 #5 <= T05 p1.2
7100 #6 => vStopped
7101 #7 <= OK
7102 #8 (infrun handles the stop for p1.1 and continues stepping)
7103 #9 => vCont s:p1.1;c
7105 The last vCont above would resume thread p1.2 by mistake, because
7106 the server has no idea that the event for p1.2 had not been
7107 handled yet.
7109 The server side must similarly ignore resume actions for the
7110 thread that has a pending %Stopped notification (and any other
7111 threads with events pending), until GDB acks the notification
7112 with vStopped. Otherwise, e.g., the following case is
7113 mishandled:
7115 #1 => g (or any other packet)
7116 #2 <= [registers]
7117 #3 <= %Stopped T05 p1.2
7118 #4 => vCont s:p1.1;c
7119 #5 <= OK
7121 Above, the server must not resume thread p1.2. GDB can't know
7122 that p1.2 stopped until it acks the %Stopped notification, and
7123 since from GDB's perspective all threads should be running, it
7124 sends a "c" action.
7126 Finally, special care must also be given to handling fork/vfork
7127 events. A (v)fork event actually tells us that two processes
7128 stopped -- the parent and the child. Until we follow the fork,
7129 we must not resume the child. Therefore, if we have a pending
7130 fork follow, we must not send a global wildcard resume action
7131 (vCont;c). We can still send process-wide wildcards though. */
7133 /* Start by assuming a global wildcard (vCont;c) is possible. */
7134 bool may_global_wildcard_vcont = true;
7136 /* And assume every process is individually wildcard-able too. */
7137 for (inferior *inf : all_non_exited_inferiors (this))
7139 remote_inferior *priv = get_remote_inferior (inf);
7141 priv->may_wildcard_vcont = true;
7144 /* Check for any pending events (not reported or processed yet) and
7145 disable process and global wildcard resumes appropriately. */
7146 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7148 bool any_pending_vcont_resume = false;
7150 for (thread_info *tp : all_non_exited_threads (this))
7152 remote_thread_info *priv = get_remote_thread_info (tp);
7154 /* If a thread of a process is not meant to be resumed, then we
7155 can't wildcard that process. */
7156 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7158 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7160 /* And if we can't wildcard a process, we can't wildcard
7161 everything either. */
7162 may_global_wildcard_vcont = false;
7163 continue;
7166 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7167 any_pending_vcont_resume = true;
7169 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7170 then we can't do a global wildcard, as that would resume the
7171 pending child. */
7172 if (thread_pending_child_status (tp) != nullptr)
7173 may_global_wildcard_vcont = false;
7176 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7177 do. */
7178 if (!any_pending_vcont_resume)
7179 return;
7181 /* Now let's build the vCont packet(s). Actions must be appended
7182 from narrower to wider scopes (thread -> process -> global). If
7183 we end up with too many actions for a single packet vcont_builder
7184 flushes the current vCont packet to the remote side and starts a
7185 new one. */
7186 struct vcont_builder vcont_builder (this);
7188 /* Threads first. */
7189 for (thread_info *tp : all_non_exited_threads (this))
7191 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7193 /* If the thread was previously vCont-resumed, no need to send a specific
7194 action for it. If we didn't receive a resume request for it, don't
7195 send an action for it either. */
7196 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7197 continue;
7199 gdb_assert (!thread_is_in_step_over_chain (tp));
7201 /* We should never be commit-resuming a thread that has a stop reply.
7202 Otherwise, we would end up reporting a stop event for a thread while
7203 it is running on the remote target. */
7204 remote_state *rs = get_remote_state ();
7205 for (const auto &stop_reply : rs->stop_reply_queue)
7206 gdb_assert (stop_reply->ptid != tp->ptid);
7208 const resumed_pending_vcont_info &info
7209 = remote_thr->resumed_pending_vcont_info ();
7211 /* Check if we need to send a specific action for this thread. If not,
7212 it will be included in a wildcard resume instead. */
7213 if (info.step || info.sig != GDB_SIGNAL_0
7214 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7215 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7217 remote_thr->set_resumed ();
7220 /* Now check whether we can send any process-wide wildcard. This is
7221 to avoid sending a global wildcard in the case nothing is
7222 supposed to be resumed. */
7223 bool any_process_wildcard = false;
7225 for (inferior *inf : all_non_exited_inferiors (this))
7227 if (get_remote_inferior (inf)->may_wildcard_vcont)
7229 any_process_wildcard = true;
7230 break;
7234 if (any_process_wildcard)
7236 /* If all processes are wildcard-able, then send a single "c"
7237 action, otherwise, send an "all (-1) threads of process"
7238 continue action for each running process, if any. */
7239 if (may_global_wildcard_vcont)
7241 vcont_builder.push_action (minus_one_ptid,
7242 false, GDB_SIGNAL_0);
7244 else
7246 for (inferior *inf : all_non_exited_inferiors (this))
7248 if (get_remote_inferior (inf)->may_wildcard_vcont)
7250 vcont_builder.push_action (ptid_t (inf->pid),
7251 false, GDB_SIGNAL_0);
7257 vcont_builder.flush ();
7260 /* Implementation of target_has_pending_events. */
7262 bool
7263 remote_target::has_pending_events ()
7265 if (target_can_async_p ())
7267 remote_state *rs = get_remote_state ();
7269 if (rs->async_event_handler_marked ())
7270 return true;
7272 /* Note that BUFCNT can be negative, indicating sticky
7273 error. */
7274 if (rs->remote_desc->bufcnt != 0)
7275 return true;
7277 return false;
7282 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7283 thread, all threads of a remote process, or all threads of all
7284 processes. */
7286 void
7287 remote_target::remote_stop_ns (ptid_t ptid)
7289 struct remote_state *rs = get_remote_state ();
7290 char *p = rs->buf.data ();
7291 char *endp = p + get_remote_packet_size ();
7293 /* If any thread that needs to stop was resumed but pending a vCont
7294 resume, generate a phony stop_reply. However, first check
7295 whether the thread wasn't resumed with a signal. Generating a
7296 phony stop in that case would result in losing the signal. */
7297 bool needs_commit = false;
7298 for (thread_info *tp : all_non_exited_threads (this, ptid))
7300 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7302 if (remote_thr->get_resume_state ()
7303 == resume_state::RESUMED_PENDING_VCONT)
7305 const resumed_pending_vcont_info &info
7306 = remote_thr->resumed_pending_vcont_info ();
7307 if (info.sig != GDB_SIGNAL_0)
7309 /* This signal must be forwarded to the inferior. We
7310 could commit-resume just this thread, but its simpler
7311 to just commit-resume everything. */
7312 needs_commit = true;
7313 break;
7318 if (needs_commit)
7319 commit_resumed ();
7320 else
7321 for (thread_info *tp : all_non_exited_threads (this, ptid))
7323 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7325 if (remote_thr->get_resume_state ()
7326 == resume_state::RESUMED_PENDING_VCONT)
7328 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7329 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7330 tp->ptid.lwp (),
7331 pulongest (tp->ptid.tid ()));
7333 /* Check that the thread wasn't resumed with a signal.
7334 Generating a phony stop would result in losing the
7335 signal. */
7336 const resumed_pending_vcont_info &info
7337 = remote_thr->resumed_pending_vcont_info ();
7338 gdb_assert (info.sig == GDB_SIGNAL_0);
7340 stop_reply *sr = new stop_reply ();
7341 sr->ptid = tp->ptid;
7342 sr->rs = rs;
7343 sr->ws.set_stopped (GDB_SIGNAL_0);
7344 sr->arch = tp->inf->arch ();
7345 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7346 sr->watch_data_address = 0;
7347 sr->core = 0;
7348 this->push_stop_reply (sr);
7350 /* Pretend that this thread was actually resumed on the
7351 remote target, then stopped. If we leave it in the
7352 RESUMED_PENDING_VCONT state and the commit_resumed
7353 method is called while the stop reply is still in the
7354 queue, we'll end up reporting a stop event to the core
7355 for that thread while it is running on the remote
7356 target... that would be bad. */
7357 remote_thr->set_resumed ();
7361 if (!rs->supports_vCont.t)
7362 error (_("Remote server does not support stopping threads"));
7364 if (ptid == minus_one_ptid
7365 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7366 p += xsnprintf (p, endp - p, "vCont;t");
7367 else
7369 ptid_t nptid;
7371 p += xsnprintf (p, endp - p, "vCont;t:");
7373 if (ptid.is_pid ())
7374 /* All (-1) threads of process. */
7375 nptid = ptid_t (ptid.pid (), -1);
7376 else
7378 /* Small optimization: if we already have a stop reply for
7379 this thread, no use in telling the stub we want this
7380 stopped. */
7381 if (peek_stop_reply (ptid))
7382 return;
7384 nptid = ptid;
7387 write_ptid (p, endp, nptid);
7390 /* In non-stop, we get an immediate OK reply. The stop reply will
7391 come in asynchronously by notification. */
7392 putpkt (rs->buf);
7393 getpkt (&rs->buf);
7394 if (strcmp (rs->buf.data (), "OK") != 0)
7395 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7396 rs->buf.data ());
7399 /* All-stop version of target_interrupt. Sends a break or a ^C to
7400 interrupt the remote target. It is undefined which thread of which
7401 process reports the interrupt. */
7403 void
7404 remote_target::remote_interrupt_as ()
7406 struct remote_state *rs = get_remote_state ();
7408 rs->ctrlc_pending_p = 1;
7410 /* If the inferior is stopped already, but the core didn't know
7411 about it yet, just ignore the request. The pending stop events
7412 will be collected in remote_wait. */
7413 if (stop_reply_queue_length () > 0)
7414 return;
7416 /* Send interrupt_sequence to remote target. */
7417 send_interrupt_sequence ();
7420 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7421 the remote target. It is undefined which thread of which process
7422 reports the interrupt. Throws an error if the packet is not
7423 supported by the server. */
7425 void
7426 remote_target::remote_interrupt_ns ()
7428 struct remote_state *rs = get_remote_state ();
7429 char *p = rs->buf.data ();
7430 char *endp = p + get_remote_packet_size ();
7432 xsnprintf (p, endp - p, "vCtrlC");
7434 /* In non-stop, we get an immediate OK reply. The stop reply will
7435 come in asynchronously by notification. */
7436 putpkt (rs->buf);
7437 getpkt (&rs->buf);
7439 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7441 case PACKET_OK:
7442 break;
7443 case PACKET_UNKNOWN:
7444 error (_("No support for interrupting the remote target."));
7445 case PACKET_ERROR:
7446 error (_("Interrupting target failed: %s"), rs->buf.data ());
7450 /* Implement the to_stop function for the remote targets. */
7452 void
7453 remote_target::stop (ptid_t ptid)
7455 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7457 if (target_is_non_stop_p ())
7458 remote_stop_ns (ptid);
7459 else
7461 /* We don't currently have a way to transparently pause the
7462 remote target in all-stop mode. Interrupt it instead. */
7463 remote_interrupt_as ();
7467 /* Implement the to_interrupt function for the remote targets. */
7469 void
7470 remote_target::interrupt ()
7472 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7474 if (target_is_non_stop_p ())
7475 remote_interrupt_ns ();
7476 else
7477 remote_interrupt_as ();
7480 /* Implement the to_pass_ctrlc function for the remote targets. */
7482 void
7483 remote_target::pass_ctrlc ()
7485 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7487 struct remote_state *rs = get_remote_state ();
7489 /* If we're starting up, we're not fully synced yet. Quit
7490 immediately. */
7491 if (rs->starting_up)
7492 quit ();
7493 /* If ^C has already been sent once, offer to disconnect. */
7494 else if (rs->ctrlc_pending_p)
7495 interrupt_query ();
7496 else
7497 target_interrupt ();
7500 /* Ask the user what to do when an interrupt is received. */
7502 void
7503 remote_target::interrupt_query ()
7505 struct remote_state *rs = get_remote_state ();
7507 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7509 if (query (_("The target is not responding to interrupt requests.\n"
7510 "Stop debugging it? ")))
7512 remote_unpush_target (this);
7513 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7516 else
7518 if (query (_("Interrupted while waiting for the program.\n"
7519 "Give up waiting? ")))
7520 quit ();
7524 /* Enable/disable target terminal ownership. Most targets can use
7525 terminal groups to control terminal ownership. Remote targets are
7526 different in that explicit transfer of ownership to/from GDB/target
7527 is required. */
7529 void
7530 remote_target::terminal_inferior ()
7532 /* NOTE: At this point we could also register our selves as the
7533 recipient of all input. Any characters typed could then be
7534 passed on down to the target. */
7537 void
7538 remote_target::terminal_ours ()
7542 static void
7543 remote_console_output (const char *msg)
7545 const char *p;
7547 for (p = msg; p[0] && p[1]; p += 2)
7549 char tb[2];
7550 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7552 tb[0] = c;
7553 tb[1] = 0;
7554 gdb_stdtarg->puts (tb);
7556 gdb_stdtarg->flush ();
7559 /* Return the length of the stop reply queue. */
7562 remote_target::stop_reply_queue_length ()
7564 remote_state *rs = get_remote_state ();
7565 return rs->stop_reply_queue.size ();
7568 static void
7569 remote_notif_stop_parse (remote_target *remote,
7570 const notif_client *self, const char *buf,
7571 struct notif_event *event)
7573 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7576 static void
7577 remote_notif_stop_ack (remote_target *remote,
7578 const notif_client *self, const char *buf,
7579 struct notif_event *event)
7581 struct stop_reply *stop_reply = (struct stop_reply *) event;
7583 /* acknowledge */
7584 putpkt (remote, self->ack_command);
7586 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7587 the notification. It was left in the queue because we need to
7588 acknowledge it and pull the rest of the notifications out. */
7589 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7590 remote->push_stop_reply (stop_reply);
7593 static int
7594 remote_notif_stop_can_get_pending_events (remote_target *remote,
7595 const notif_client *self)
7597 /* We can't get pending events in remote_notif_process for
7598 notification stop, and we have to do this in remote_wait_ns
7599 instead. If we fetch all queued events from stub, remote stub
7600 may exit and we have no chance to process them back in
7601 remote_wait_ns. */
7602 remote_state *rs = remote->get_remote_state ();
7603 rs->mark_async_event_handler ();
7604 return 0;
7607 stop_reply::~stop_reply ()
7609 for (cached_reg_t &reg : regcache)
7610 xfree (reg.data);
7613 static notif_event_up
7614 remote_notif_stop_alloc_reply ()
7616 return notif_event_up (new struct stop_reply ());
7619 /* A client of notification Stop. */
7621 const notif_client notif_client_stop =
7623 "Stop",
7624 "vStopped",
7625 remote_notif_stop_parse,
7626 remote_notif_stop_ack,
7627 remote_notif_stop_can_get_pending_events,
7628 remote_notif_stop_alloc_reply,
7629 REMOTE_NOTIF_STOP,
7632 /* If CONTEXT contains any fork/vfork/clone child threads that have
7633 not been reported yet, remove them from the CONTEXT list. If such
7634 a thread exists it is because we are stopped at a fork/vfork/clone
7635 catchpoint and have not yet called follow_fork/follow_clone, which
7636 will set up the host-side data structures for the new child. */
7638 void
7639 remote_target::remove_new_children (threads_listing_context *context)
7641 const notif_client *notif = &notif_client_stop;
7643 /* For any threads stopped at a (v)fork/clone event, remove the
7644 corresponding child threads from the CONTEXT list. */
7645 for (thread_info *thread : all_non_exited_threads (this))
7647 const target_waitstatus *ws = thread_pending_child_status (thread);
7649 if (ws == nullptr)
7650 continue;
7652 context->remove_thread (ws->child_ptid ());
7655 /* Check for any pending (v)fork/clone events (not reported or
7656 processed yet) in process PID and remove those child threads from
7657 the CONTEXT list as well. */
7658 remote_notif_get_pending_events (notif);
7659 for (auto &event : get_remote_state ()->stop_reply_queue)
7660 if (is_new_child_status (event->ws.kind ()))
7661 context->remove_thread (event->ws.child_ptid ());
7662 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7663 context->remove_thread (event->ptid);
7666 /* Check whether any event pending in the vStopped queue would prevent a
7667 global or process wildcard vCont action. Set *may_global_wildcard to
7668 false if we can't do a global wildcard (vCont;c), and clear the event
7669 inferior's may_wildcard_vcont flag if we can't do a process-wide
7670 wildcard resume (vCont;c:pPID.-1). */
7672 void
7673 remote_target::check_pending_events_prevent_wildcard_vcont
7674 (bool *may_global_wildcard)
7676 const notif_client *notif = &notif_client_stop;
7678 remote_notif_get_pending_events (notif);
7679 for (auto &event : get_remote_state ()->stop_reply_queue)
7681 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7682 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7683 continue;
7685 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7686 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7687 *may_global_wildcard = false;
7689 /* This may be the first time we heard about this process.
7690 Regardless, we must not do a global wildcard resume, otherwise
7691 we'd resume this process too. */
7692 *may_global_wildcard = false;
7693 if (event->ptid != null_ptid)
7695 inferior *inf = find_inferior_ptid (this, event->ptid);
7696 if (inf != NULL)
7697 get_remote_inferior (inf)->may_wildcard_vcont = false;
7702 /* Discard all pending stop replies of inferior INF. */
7704 void
7705 remote_target::discard_pending_stop_replies (struct inferior *inf)
7707 struct stop_reply *reply;
7708 struct remote_state *rs = get_remote_state ();
7709 struct remote_notif_state *rns = rs->notif_state;
7711 /* This function can be notified when an inferior exists. When the
7712 target is not remote, the notification state is NULL. */
7713 if (rs->remote_desc == NULL)
7714 return;
7716 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7718 /* Discard the in-flight notification. */
7719 if (reply != NULL && reply->ptid.pid () == inf->pid)
7721 /* Leave the notification pending, since the server expects that
7722 we acknowledge it with vStopped. But clear its contents, so
7723 that later on when we acknowledge it, we also discard it. */
7724 remote_debug_printf
7725 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7726 reply->ptid.to_string().c_str(),
7727 reply->ws.to_string ().c_str ());
7728 reply->ws.set_ignore ();
7731 /* Discard the stop replies we have already pulled with
7732 vStopped. */
7733 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7734 rs->stop_reply_queue.end (),
7735 [=] (const stop_reply_up &event)
7737 return event->ptid.pid () == inf->pid;
7739 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7740 remote_debug_printf
7741 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7742 (*it)->ptid.to_string().c_str(),
7743 (*it)->ws.to_string ().c_str ());
7744 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7747 /* Discard the stop replies for RS in stop_reply_queue. */
7749 void
7750 remote_target::discard_pending_stop_replies_in_queue ()
7752 remote_state *rs = get_remote_state ();
7754 /* Discard the stop replies we have already pulled with
7755 vStopped. */
7756 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7757 rs->stop_reply_queue.end (),
7758 [=] (const stop_reply_up &event)
7760 return event->rs == rs;
7762 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7765 /* Remove the first reply in 'stop_reply_queue' which matches
7766 PTID. */
7768 struct stop_reply *
7769 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7771 remote_state *rs = get_remote_state ();
7773 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7774 rs->stop_reply_queue.end (),
7775 [=] (const stop_reply_up &event)
7777 return event->ptid.matches (ptid);
7779 struct stop_reply *result;
7780 if (iter == rs->stop_reply_queue.end ())
7781 result = nullptr;
7782 else
7784 result = iter->release ();
7785 rs->stop_reply_queue.erase (iter);
7788 if (notif_debug)
7789 gdb_printf (gdb_stdlog,
7790 "notif: discard queued event: 'Stop' in %s\n",
7791 ptid.to_string ().c_str ());
7793 return result;
7796 /* Look for a queued stop reply belonging to PTID. If one is found,
7797 remove it from the queue, and return it. Returns NULL if none is
7798 found. If there are still queued events left to process, tell the
7799 event loop to get back to target_wait soon. */
7801 struct stop_reply *
7802 remote_target::queued_stop_reply (ptid_t ptid)
7804 remote_state *rs = get_remote_state ();
7805 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7807 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7809 /* There's still at least an event left. */
7810 rs->mark_async_event_handler ();
7813 return r;
7816 /* Push a fully parsed stop reply in the stop reply queue. Since we
7817 know that we now have at least one queued event left to pass to the
7818 core side, tell the event loop to get back to target_wait soon. */
7820 void
7821 remote_target::push_stop_reply (struct stop_reply *new_event)
7823 remote_state *rs = get_remote_state ();
7824 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7826 if (notif_debug)
7827 gdb_printf (gdb_stdlog,
7828 "notif: push 'Stop' %s to queue %d\n",
7829 new_event->ptid.to_string ().c_str (),
7830 int (rs->stop_reply_queue.size ()));
7832 /* Mark the pending event queue only if async mode is currently enabled.
7833 If async mode is not currently enabled, then, if it later becomes
7834 enabled, and there are events in this queue, we will mark the event
7835 token at that point, see remote_target::async. */
7836 if (target_is_async_p ())
7837 rs->mark_async_event_handler ();
7840 /* Returns true if we have a stop reply for PTID. */
7843 remote_target::peek_stop_reply (ptid_t ptid)
7845 remote_state *rs = get_remote_state ();
7846 for (auto &event : rs->stop_reply_queue)
7847 if (ptid == event->ptid
7848 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7849 return 1;
7850 return 0;
7853 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7854 starting with P and ending with PEND matches PREFIX. */
7856 static int
7857 strprefix (const char *p, const char *pend, const char *prefix)
7859 for ( ; p < pend; p++, prefix++)
7860 if (*p != *prefix)
7861 return 0;
7862 return *prefix == '\0';
7865 /* Parse the stop reply in BUF. Either the function succeeds, and the
7866 result is stored in EVENT, or throws an error. */
7868 void
7869 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7871 remote_arch_state *rsa = NULL;
7872 ULONGEST addr;
7873 const char *p;
7874 int skipregs = 0;
7876 event->ptid = null_ptid;
7877 event->rs = get_remote_state ();
7878 event->ws.set_ignore ();
7879 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7880 event->regcache.clear ();
7881 event->core = -1;
7883 switch (buf[0])
7885 case 'T': /* Status with PC, SP, FP, ... */
7886 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7887 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7888 ss = signal number
7889 n... = register number
7890 r... = register contents
7893 p = &buf[3]; /* after Txx */
7894 while (*p)
7896 const char *p1;
7897 int fieldsize;
7899 p1 = strchr (p, ':');
7900 if (p1 == NULL)
7901 error (_("Malformed packet(a) (missing colon): %s\n\
7902 Packet: '%s'\n"),
7903 p, buf);
7904 if (p == p1)
7905 error (_("Malformed packet(a) (missing register number): %s\n\
7906 Packet: '%s'\n"),
7907 p, buf);
7909 /* Some "registers" are actually extended stop information.
7910 Note if you're adding a new entry here: GDB 7.9 and
7911 earlier assume that all register "numbers" that start
7912 with an hex digit are real register numbers. Make sure
7913 the server only sends such a packet if it knows the
7914 client understands it. */
7916 if (strprefix (p, p1, "thread"))
7917 event->ptid = read_ptid (++p1, &p);
7918 else if (strprefix (p, p1, "syscall_entry"))
7920 ULONGEST sysno;
7922 p = unpack_varlen_hex (++p1, &sysno);
7923 event->ws.set_syscall_entry ((int) sysno);
7925 else if (strprefix (p, p1, "syscall_return"))
7927 ULONGEST sysno;
7929 p = unpack_varlen_hex (++p1, &sysno);
7930 event->ws.set_syscall_return ((int) sysno);
7932 else if (strprefix (p, p1, "watch")
7933 || strprefix (p, p1, "rwatch")
7934 || strprefix (p, p1, "awatch"))
7936 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7937 p = unpack_varlen_hex (++p1, &addr);
7938 event->watch_data_address = (CORE_ADDR) addr;
7940 else if (strprefix (p, p1, "swbreak"))
7942 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7944 /* Make sure the stub doesn't forget to indicate support
7945 with qSupported. */
7946 if (m_features.packet_support (PACKET_swbreak_feature)
7947 != PACKET_ENABLE)
7948 error (_("Unexpected swbreak stop reason"));
7950 /* The value part is documented as "must be empty",
7951 though we ignore it, in case we ever decide to make
7952 use of it in a backward compatible way. */
7953 p = strchrnul (p1 + 1, ';');
7955 else if (strprefix (p, p1, "hwbreak"))
7957 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7959 /* Make sure the stub doesn't forget to indicate support
7960 with qSupported. */
7961 if (m_features.packet_support (PACKET_hwbreak_feature)
7962 != PACKET_ENABLE)
7963 error (_("Unexpected hwbreak stop reason"));
7965 /* See above. */
7966 p = strchrnul (p1 + 1, ';');
7968 else if (strprefix (p, p1, "library"))
7970 event->ws.set_loaded ();
7971 p = strchrnul (p1 + 1, ';');
7973 else if (strprefix (p, p1, "replaylog"))
7975 event->ws.set_no_history ();
7976 /* p1 will indicate "begin" or "end", but it makes
7977 no difference for now, so ignore it. */
7978 p = strchrnul (p1 + 1, ';');
7980 else if (strprefix (p, p1, "core"))
7982 ULONGEST c;
7984 p = unpack_varlen_hex (++p1, &c);
7985 event->core = c;
7987 else if (strprefix (p, p1, "fork"))
7988 event->ws.set_forked (read_ptid (++p1, &p));
7989 else if (strprefix (p, p1, "vfork"))
7990 event->ws.set_vforked (read_ptid (++p1, &p));
7991 else if (strprefix (p, p1, "clone"))
7992 event->ws.set_thread_cloned (read_ptid (++p1, &p));
7993 else if (strprefix (p, p1, "vforkdone"))
7995 event->ws.set_vfork_done ();
7996 p = strchrnul (p1 + 1, ';');
7998 else if (strprefix (p, p1, "exec"))
8000 ULONGEST ignored;
8001 int pathlen;
8003 /* Determine the length of the execd pathname. */
8004 p = unpack_varlen_hex (++p1, &ignored);
8005 pathlen = (p - p1) / 2;
8007 /* Save the pathname for event reporting and for
8008 the next run command. */
8009 gdb::unique_xmalloc_ptr<char> pathname
8010 ((char *) xmalloc (pathlen + 1));
8011 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8012 pathname.get ()[pathlen] = '\0';
8014 /* This is freed during event handling. */
8015 event->ws.set_execd (std::move (pathname));
8017 /* Skip the registers included in this packet, since
8018 they may be for an architecture different from the
8019 one used by the original program. */
8020 skipregs = 1;
8022 else if (strprefix (p, p1, "create"))
8024 event->ws.set_thread_created ();
8025 p = strchrnul (p1 + 1, ';');
8027 else
8029 ULONGEST pnum;
8030 const char *p_temp;
8032 if (skipregs)
8034 p = strchrnul (p1 + 1, ';');
8035 p++;
8036 continue;
8039 /* Maybe a real ``P'' register number. */
8040 p_temp = unpack_varlen_hex (p, &pnum);
8041 /* If the first invalid character is the colon, we got a
8042 register number. Otherwise, it's an unknown stop
8043 reason. */
8044 if (p_temp == p1)
8046 /* If we haven't parsed the event's thread yet, find
8047 it now, in order to find the architecture of the
8048 reported expedited registers. */
8049 if (event->ptid == null_ptid)
8051 /* If there is no thread-id information then leave
8052 the event->ptid as null_ptid. Later in
8053 process_stop_reply we will pick a suitable
8054 thread. */
8055 const char *thr = strstr (p1 + 1, ";thread:");
8056 if (thr != NULL)
8057 event->ptid = read_ptid (thr + strlen (";thread:"),
8058 NULL);
8061 if (rsa == NULL)
8063 inferior *inf
8064 = (event->ptid == null_ptid
8065 ? NULL
8066 : find_inferior_ptid (this, event->ptid));
8067 /* If this is the first time we learn anything
8068 about this process, skip the registers
8069 included in this packet, since we don't yet
8070 know which architecture to use to parse them.
8071 We'll determine the architecture later when
8072 we process the stop reply and retrieve the
8073 target description, via
8074 remote_notice_new_inferior ->
8075 post_create_inferior. */
8076 if (inf == NULL)
8078 p = strchrnul (p1 + 1, ';');
8079 p++;
8080 continue;
8083 event->arch = inf->arch ();
8084 rsa = event->rs->get_remote_arch_state (event->arch);
8087 packet_reg *reg
8088 = packet_reg_from_pnum (event->arch, rsa, pnum);
8089 cached_reg_t cached_reg;
8091 if (reg == NULL)
8092 error (_("Remote sent bad register number %s: %s\n\
8093 Packet: '%s'\n"),
8094 hex_string (pnum), p, buf);
8096 cached_reg.num = reg->regnum;
8097 cached_reg.data = (gdb_byte *)
8098 xmalloc (register_size (event->arch, reg->regnum));
8100 p = p1 + 1;
8101 fieldsize = hex2bin (p, cached_reg.data,
8102 register_size (event->arch, reg->regnum));
8103 p += 2 * fieldsize;
8104 if (fieldsize < register_size (event->arch, reg->regnum))
8105 warning (_("Remote reply is too short: %s"), buf);
8107 event->regcache.push_back (cached_reg);
8109 else
8111 /* Not a number. Silently skip unknown optional
8112 info. */
8113 p = strchrnul (p1 + 1, ';');
8117 if (*p != ';')
8118 error (_("Remote register badly formatted: %s\nhere: %s"),
8119 buf, p);
8120 ++p;
8123 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8124 break;
8126 [[fallthrough]];
8127 case 'S': /* Old style status, just signal only. */
8129 int sig;
8131 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8132 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8133 event->ws.set_stopped ((enum gdb_signal) sig);
8134 else
8135 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8137 break;
8138 case 'w': /* Thread exited. */
8140 ULONGEST value;
8142 p = unpack_varlen_hex (&buf[1], &value);
8143 event->ws.set_thread_exited (value);
8144 if (*p != ';')
8145 error (_("stop reply packet badly formatted: %s"), buf);
8146 event->ptid = read_ptid (++p, NULL);
8147 break;
8149 case 'W': /* Target exited. */
8150 case 'X':
8152 ULONGEST value;
8154 /* GDB used to accept only 2 hex chars here. Stubs should
8155 only send more if they detect GDB supports multi-process
8156 support. */
8157 p = unpack_varlen_hex (&buf[1], &value);
8159 if (buf[0] == 'W')
8161 /* The remote process exited. */
8162 event->ws.set_exited (value);
8164 else
8166 /* The remote process exited with a signal. */
8167 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8168 event->ws.set_signalled ((enum gdb_signal) value);
8169 else
8170 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8173 /* If no process is specified, return null_ptid, and let the
8174 caller figure out the right process to use. */
8175 int pid = 0;
8176 if (*p == '\0')
8178 else if (*p == ';')
8180 p++;
8182 if (*p == '\0')
8184 else if (startswith (p, "process:"))
8186 ULONGEST upid;
8188 p += sizeof ("process:") - 1;
8189 unpack_varlen_hex (p, &upid);
8190 pid = upid;
8192 else
8193 error (_("unknown stop reply packet: %s"), buf);
8195 else
8196 error (_("unknown stop reply packet: %s"), buf);
8197 event->ptid = ptid_t (pid);
8199 break;
8200 case 'N':
8201 event->ws.set_no_resumed ();
8202 event->ptid = minus_one_ptid;
8203 break;
8207 /* When the stub wants to tell GDB about a new notification reply, it
8208 sends a notification (%Stop, for example). Those can come it at
8209 any time, hence, we have to make sure that any pending
8210 putpkt/getpkt sequence we're making is finished, before querying
8211 the stub for more events with the corresponding ack command
8212 (vStopped, for example). E.g., if we started a vStopped sequence
8213 immediately upon receiving the notification, something like this
8214 could happen:
8216 1.1) --> Hg 1
8217 1.2) <-- OK
8218 1.3) --> g
8219 1.4) <-- %Stop
8220 1.5) --> vStopped
8221 1.6) <-- (registers reply to step #1.3)
8223 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8224 query.
8226 To solve this, whenever we parse a %Stop notification successfully,
8227 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8228 doing whatever we were doing:
8230 2.1) --> Hg 1
8231 2.2) <-- OK
8232 2.3) --> g
8233 2.4) <-- %Stop
8234 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8235 2.5) <-- (registers reply to step #2.3)
8237 Eventually after step #2.5, we return to the event loop, which
8238 notices there's an event on the
8239 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8240 associated callback --- the function below. At this point, we're
8241 always safe to start a vStopped sequence. :
8243 2.6) --> vStopped
8244 2.7) <-- T05 thread:2
8245 2.8) --> vStopped
8246 2.9) --> OK
8249 void
8250 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8252 struct remote_state *rs = get_remote_state ();
8254 if (rs->notif_state->pending_event[nc->id] != NULL)
8256 if (notif_debug)
8257 gdb_printf (gdb_stdlog,
8258 "notif: process: '%s' ack pending event\n",
8259 nc->name);
8261 /* acknowledge */
8262 nc->ack (this, nc, rs->buf.data (),
8263 rs->notif_state->pending_event[nc->id]);
8264 rs->notif_state->pending_event[nc->id] = NULL;
8266 while (1)
8268 getpkt (&rs->buf);
8269 if (strcmp (rs->buf.data (), "OK") == 0)
8270 break;
8271 else
8272 remote_notif_ack (this, nc, rs->buf.data ());
8275 else
8277 if (notif_debug)
8278 gdb_printf (gdb_stdlog,
8279 "notif: process: '%s' no pending reply\n",
8280 nc->name);
8284 /* Wrapper around remote_target::remote_notif_get_pending_events to
8285 avoid having to export the whole remote_target class. */
8287 void
8288 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8290 remote->remote_notif_get_pending_events (nc);
8293 /* Called from process_stop_reply when the stop packet we are responding
8294 to didn't include a process-id or thread-id. STATUS is the stop event
8295 we are responding to.
8297 It is the task of this function to select a suitable thread (or process)
8298 and return its ptid, this is the thread (or process) we will assume the
8299 stop event came from.
8301 In some cases there isn't really any choice about which thread (or
8302 process) is selected, a basic remote with a single process containing a
8303 single thread might choose not to send any process-id or thread-id in
8304 its stop packets, this function will select and return the one and only
8305 thread.
8307 However, if a target supports multiple threads (or processes) and still
8308 doesn't include a thread-id (or process-id) in its stop packet then
8309 first, this is a badly behaving target, and second, we're going to have
8310 to select a thread (or process) at random and use that. This function
8311 will print a warning to the user if it detects that there is the
8312 possibility that GDB is guessing which thread (or process) to
8313 report.
8315 Note that this is called before GDB fetches the updated thread list from the
8316 target. So it's possible for the stop reply to be ambiguous and for GDB to
8317 not realize it. For example, if there's initially one thread, the target
8318 spawns a second thread, and then sends a stop reply without an id that
8319 concerns the first thread. GDB will assume the stop reply is about the
8320 first thread - the only thread it knows about - without printing a warning.
8321 Anyway, if the remote meant for the stop reply to be about the second thread,
8322 then it would be really broken, because GDB doesn't know about that thread
8323 yet. */
8325 ptid_t
8326 remote_target::select_thread_for_ambiguous_stop_reply
8327 (const target_waitstatus &status)
8329 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8331 /* Some stop events apply to all threads in an inferior, while others
8332 only apply to a single thread. */
8333 bool process_wide_stop
8334 = (status.kind () == TARGET_WAITKIND_EXITED
8335 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8337 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8339 thread_info *first_resumed_thread = nullptr;
8340 bool ambiguous = false;
8342 /* Consider all non-exited threads of the target, find the first resumed
8343 one. */
8344 for (thread_info *thr : all_non_exited_threads (this))
8346 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8348 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8349 continue;
8351 if (first_resumed_thread == nullptr)
8352 first_resumed_thread = thr;
8353 else if (!process_wide_stop
8354 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8355 ambiguous = true;
8358 gdb_assert (first_resumed_thread != nullptr);
8360 remote_debug_printf ("first resumed thread is %s",
8361 pid_to_str (first_resumed_thread->ptid).c_str ());
8362 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8364 /* Warn if the remote target is sending ambiguous stop replies. */
8365 if (ambiguous)
8367 static bool warned = false;
8369 if (!warned)
8371 /* If you are seeing this warning then the remote target has
8372 stopped without specifying a thread-id, but the target
8373 does have multiple threads (or inferiors), and so GDB is
8374 having to guess which thread stopped.
8376 Examples of what might cause this are the target sending
8377 and 'S' stop packet, or a 'T' stop packet and not
8378 including a thread-id.
8380 Additionally, the target might send a 'W' or 'X packet
8381 without including a process-id, when the target has
8382 multiple running inferiors. */
8383 if (process_wide_stop)
8384 warning (_("multi-inferior target stopped without "
8385 "sending a process-id, using first "
8386 "non-exited inferior"));
8387 else
8388 warning (_("multi-threaded target stopped without "
8389 "sending a thread-id, using first "
8390 "non-exited thread"));
8391 warned = true;
8395 /* If this is a stop for all threads then don't use a particular threads
8396 ptid, instead create a new ptid where only the pid field is set. */
8397 if (process_wide_stop)
8398 return ptid_t (first_resumed_thread->ptid.pid ());
8399 else
8400 return first_resumed_thread->ptid;
8403 /* Called when it is decided that STOP_REPLY holds the info of the
8404 event that is to be returned to the core. This function always
8405 destroys STOP_REPLY. */
8407 ptid_t
8408 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8409 struct target_waitstatus *status)
8411 *status = stop_reply->ws;
8412 ptid_t ptid = stop_reply->ptid;
8414 /* If no thread/process was reported by the stub then select a suitable
8415 thread/process. */
8416 if (ptid == null_ptid)
8417 ptid = select_thread_for_ambiguous_stop_reply (*status);
8418 gdb_assert (ptid != null_ptid);
8420 if (status->kind () != TARGET_WAITKIND_EXITED
8421 && status->kind () != TARGET_WAITKIND_SIGNALLED
8422 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8424 remote_notice_new_inferior (ptid, false);
8426 /* Expedited registers. */
8427 if (!stop_reply->regcache.empty ())
8429 /* 'w' stop replies don't cary expedited registers (which
8430 wouldn't make any sense for a thread that is gone
8431 already). */
8432 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8434 regcache *regcache
8435 = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
8436 stop_reply->arch);
8438 for (cached_reg_t &reg : stop_reply->regcache)
8440 regcache->raw_supply (reg.num, reg.data);
8441 xfree (reg.data);
8444 stop_reply->regcache.clear ();
8447 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8448 remote_thr->core = stop_reply->core;
8449 remote_thr->stop_reason = stop_reply->stop_reason;
8450 remote_thr->watch_data_address = stop_reply->watch_data_address;
8452 if (target_is_non_stop_p ())
8454 /* If the target works in non-stop mode, a stop-reply indicates that
8455 only this thread stopped. */
8456 remote_thr->set_not_resumed ();
8458 else
8460 /* If the target works in all-stop mode, a stop-reply indicates that
8461 all the target's threads stopped. */
8462 for (thread_info *tp : all_non_exited_threads (this))
8463 get_remote_thread_info (tp)->set_not_resumed ();
8467 delete stop_reply;
8468 return ptid;
8471 /* The non-stop mode version of target_wait. */
8473 ptid_t
8474 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8475 target_wait_flags options)
8477 struct remote_state *rs = get_remote_state ();
8478 struct stop_reply *stop_reply;
8479 int ret;
8480 bool is_notif = false;
8482 /* If in non-stop mode, get out of getpkt even if a
8483 notification is received. */
8485 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8486 while (1)
8488 if (ret != -1 && !is_notif)
8489 switch (rs->buf[0])
8491 case 'E': /* Error of some sort. */
8492 /* We're out of sync with the target now. Did it continue
8493 or not? We can't tell which thread it was in non-stop,
8494 so just ignore this. */
8495 warning (_("Remote failure reply: %s"), rs->buf.data ());
8496 break;
8497 case 'O': /* Console output. */
8498 remote_console_output (&rs->buf[1]);
8499 break;
8500 default:
8501 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8502 break;
8505 /* Acknowledge a pending stop reply that may have arrived in the
8506 mean time. */
8507 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8508 remote_notif_get_pending_events (&notif_client_stop);
8510 /* If indeed we noticed a stop reply, we're done. */
8511 stop_reply = queued_stop_reply (ptid);
8512 if (stop_reply != NULL)
8513 return process_stop_reply (stop_reply, status);
8515 /* Still no event. If we're just polling for an event, then
8516 return to the event loop. */
8517 if (options & TARGET_WNOHANG)
8519 status->set_ignore ();
8520 return minus_one_ptid;
8523 /* Otherwise do a blocking wait. */
8524 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8528 /* Return the first resumed thread. */
8530 static ptid_t
8531 first_remote_resumed_thread (remote_target *target)
8533 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8534 if (tp->resumed ())
8535 return tp->ptid;
8536 return null_ptid;
8539 /* Wait until the remote machine stops, then return, storing status in
8540 STATUS just as `wait' would. */
8542 ptid_t
8543 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8544 target_wait_flags options)
8546 struct remote_state *rs = get_remote_state ();
8547 ptid_t event_ptid = null_ptid;
8548 char *buf;
8549 struct stop_reply *stop_reply;
8551 again:
8553 status->set_ignore ();
8555 stop_reply = queued_stop_reply (ptid);
8556 if (stop_reply != NULL)
8558 /* None of the paths that push a stop reply onto the queue should
8559 have set the waiting_for_stop_reply flag. */
8560 gdb_assert (!rs->waiting_for_stop_reply);
8561 event_ptid = process_stop_reply (stop_reply, status);
8563 else
8565 bool forever = ((options & TARGET_WNOHANG) == 0
8566 && rs->wait_forever_enabled_p);
8568 if (!rs->waiting_for_stop_reply)
8570 status->set_no_resumed ();
8571 return minus_one_ptid;
8574 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8575 _never_ wait for ever -> test on target_is_async_p().
8576 However, before we do that we need to ensure that the caller
8577 knows how to take the target into/out of async mode. */
8578 bool is_notif;
8579 int ret = getpkt (&rs->buf, forever, &is_notif);
8581 /* GDB gets a notification. Return to core as this event is
8582 not interesting. */
8583 if (ret != -1 && is_notif)
8584 return minus_one_ptid;
8586 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8587 return minus_one_ptid;
8589 buf = rs->buf.data ();
8591 /* Assume that the target has acknowledged Ctrl-C unless we receive
8592 an 'F' or 'O' packet. */
8593 if (buf[0] != 'F' && buf[0] != 'O')
8594 rs->ctrlc_pending_p = 0;
8596 switch (buf[0])
8598 case 'E': /* Error of some sort. */
8599 /* We're out of sync with the target now. Did it continue or
8600 not? Not is more likely, so report a stop. */
8601 rs->waiting_for_stop_reply = 0;
8603 warning (_("Remote failure reply: %s"), buf);
8604 status->set_stopped (GDB_SIGNAL_0);
8605 break;
8606 case 'F': /* File-I/O request. */
8607 /* GDB may access the inferior memory while handling the File-I/O
8608 request, but we don't want GDB accessing memory while waiting
8609 for a stop reply. See the comments in putpkt_binary. Set
8610 waiting_for_stop_reply to 0 temporarily. */
8611 rs->waiting_for_stop_reply = 0;
8612 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8613 rs->ctrlc_pending_p = 0;
8614 /* GDB handled the File-I/O request, and the target is running
8615 again. Keep waiting for events. */
8616 rs->waiting_for_stop_reply = 1;
8617 break;
8618 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8620 /* There is a stop reply to handle. */
8621 rs->waiting_for_stop_reply = 0;
8623 stop_reply
8624 = (struct stop_reply *) remote_notif_parse (this,
8625 &notif_client_stop,
8626 rs->buf.data ());
8628 event_ptid = process_stop_reply (stop_reply, status);
8629 break;
8631 case 'O': /* Console output. */
8632 remote_console_output (buf + 1);
8633 break;
8634 case '\0':
8635 if (rs->last_sent_signal != GDB_SIGNAL_0)
8637 /* Zero length reply means that we tried 'S' or 'C' and the
8638 remote system doesn't support it. */
8639 target_terminal::ours_for_output ();
8640 gdb_printf
8641 ("Can't send signals to this remote system. %s not sent.\n",
8642 gdb_signal_to_name (rs->last_sent_signal));
8643 rs->last_sent_signal = GDB_SIGNAL_0;
8644 target_terminal::inferior ();
8646 strcpy (buf, rs->last_sent_step ? "s" : "c");
8647 putpkt (buf);
8648 break;
8650 [[fallthrough]];
8651 default:
8652 warning (_("Invalid remote reply: %s"), buf);
8653 break;
8657 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8658 return minus_one_ptid;
8659 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8661 /* Nothing interesting happened. If we're doing a non-blocking
8662 poll, we're done. Otherwise, go back to waiting. */
8663 if (options & TARGET_WNOHANG)
8664 return minus_one_ptid;
8665 else
8666 goto again;
8668 else if (status->kind () != TARGET_WAITKIND_EXITED
8669 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8671 if (event_ptid != null_ptid)
8672 record_currthread (rs, event_ptid);
8673 else
8674 event_ptid = first_remote_resumed_thread (this);
8676 else
8678 /* A process exit. Invalidate our notion of current thread. */
8679 record_currthread (rs, minus_one_ptid);
8680 /* It's possible that the packet did not include a pid. */
8681 if (event_ptid == null_ptid)
8682 event_ptid = first_remote_resumed_thread (this);
8683 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8684 if (event_ptid == null_ptid)
8685 event_ptid = magic_null_ptid;
8688 return event_ptid;
8691 /* Wait until the remote machine stops, then return, storing status in
8692 STATUS just as `wait' would. */
8694 ptid_t
8695 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8696 target_wait_flags options)
8698 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8700 remote_state *rs = get_remote_state ();
8702 /* Start by clearing the flag that asks for our wait method to be called,
8703 we'll mark it again at the end if needed. If the target is not in
8704 async mode then the async token should not be marked. */
8705 if (target_is_async_p ())
8706 rs->clear_async_event_handler ();
8707 else
8708 gdb_assert (!rs->async_event_handler_marked ());
8710 ptid_t event_ptid;
8712 if (target_is_non_stop_p ())
8713 event_ptid = wait_ns (ptid, status, options);
8714 else
8715 event_ptid = wait_as (ptid, status, options);
8717 if (target_is_async_p ())
8719 /* If there are events left in the queue, or unacknowledged
8720 notifications, then tell the event loop to call us again. */
8721 if (!rs->stop_reply_queue.empty ()
8722 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8723 rs->mark_async_event_handler ();
8726 return event_ptid;
8729 /* Fetch a single register using a 'p' packet. */
8732 remote_target::fetch_register_using_p (struct regcache *regcache,
8733 packet_reg *reg)
8735 struct gdbarch *gdbarch = regcache->arch ();
8736 struct remote_state *rs = get_remote_state ();
8737 char *buf, *p;
8738 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8739 int i;
8741 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8742 return 0;
8744 if (reg->pnum == -1)
8745 return 0;
8747 p = rs->buf.data ();
8748 *p++ = 'p';
8749 p += hexnumstr (p, reg->pnum);
8750 *p++ = '\0';
8751 putpkt (rs->buf);
8752 getpkt (&rs->buf);
8754 buf = rs->buf.data ();
8756 switch (m_features.packet_ok (rs->buf, PACKET_p))
8758 case PACKET_OK:
8759 break;
8760 case PACKET_UNKNOWN:
8761 return 0;
8762 case PACKET_ERROR:
8763 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8764 gdbarch_register_name (regcache->arch (), reg->regnum),
8765 buf);
8768 /* If this register is unfetchable, tell the regcache. */
8769 if (buf[0] == 'x')
8771 regcache->raw_supply (reg->regnum, NULL);
8772 return 1;
8775 /* Otherwise, parse and supply the value. */
8776 p = buf;
8777 i = 0;
8778 while (p[0] != 0)
8780 if (p[1] == 0)
8781 error (_("fetch_register_using_p: early buf termination"));
8783 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8784 p += 2;
8786 regcache->raw_supply (reg->regnum, regp);
8787 return 1;
8790 /* Fetch the registers included in the target's 'g' packet. */
8793 remote_target::send_g_packet ()
8795 struct remote_state *rs = get_remote_state ();
8796 int buf_len;
8798 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8799 putpkt (rs->buf);
8800 getpkt (&rs->buf);
8801 if (packet_check_result (rs->buf) == PACKET_ERROR)
8802 error (_("Could not read registers; remote failure reply '%s'"),
8803 rs->buf.data ());
8805 /* We can get out of synch in various cases. If the first character
8806 in the buffer is not a hex character, assume that has happened
8807 and try to fetch another packet to read. */
8808 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8809 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8810 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8811 && rs->buf[0] != 'x') /* New: unavailable register value. */
8813 remote_debug_printf ("Bad register packet; fetching a new packet");
8814 getpkt (&rs->buf);
8817 buf_len = strlen (rs->buf.data ());
8819 /* Sanity check the received packet. */
8820 if (buf_len % 2 != 0)
8821 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8823 return buf_len / 2;
8826 void
8827 remote_target::process_g_packet (struct regcache *regcache)
8829 struct gdbarch *gdbarch = regcache->arch ();
8830 struct remote_state *rs = get_remote_state ();
8831 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8832 int i, buf_len;
8833 char *p;
8834 char *regs;
8836 buf_len = strlen (rs->buf.data ());
8838 /* Further sanity checks, with knowledge of the architecture. */
8839 if (buf_len > 2 * rsa->sizeof_g_packet)
8840 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8841 "bytes): %s"),
8842 rsa->sizeof_g_packet, buf_len / 2,
8843 rs->buf.data ());
8845 /* Save the size of the packet sent to us by the target. It is used
8846 as a heuristic when determining the max size of packets that the
8847 target can safely receive. */
8848 if (rsa->actual_register_packet_size == 0)
8849 rsa->actual_register_packet_size = buf_len;
8851 /* If this is smaller than we guessed the 'g' packet would be,
8852 update our records. A 'g' reply that doesn't include a register's
8853 value implies either that the register is not available, or that
8854 the 'p' packet must be used. */
8855 if (buf_len < 2 * rsa->sizeof_g_packet)
8857 long sizeof_g_packet = buf_len / 2;
8859 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8861 long offset = rsa->regs[i].offset;
8862 long reg_size = register_size (gdbarch, i);
8864 if (rsa->regs[i].pnum == -1)
8865 continue;
8867 if (offset >= sizeof_g_packet)
8868 rsa->regs[i].in_g_packet = 0;
8869 else if (offset + reg_size > sizeof_g_packet)
8870 error (_("Truncated register %d in remote 'g' packet"), i);
8871 else
8872 rsa->regs[i].in_g_packet = 1;
8875 /* Looks valid enough, we can assume this is the correct length
8876 for a 'g' packet. It's important not to adjust
8877 rsa->sizeof_g_packet if we have truncated registers otherwise
8878 this "if" won't be run the next time the method is called
8879 with a packet of the same size and one of the internal errors
8880 below will trigger instead. */
8881 rsa->sizeof_g_packet = sizeof_g_packet;
8884 regs = (char *) alloca (rsa->sizeof_g_packet);
8886 /* Unimplemented registers read as all bits zero. */
8887 memset (regs, 0, rsa->sizeof_g_packet);
8889 /* Reply describes registers byte by byte, each byte encoded as two
8890 hex characters. Suck them all up, then supply them to the
8891 register cacheing/storage mechanism. */
8893 p = rs->buf.data ();
8894 for (i = 0; i < rsa->sizeof_g_packet; i++)
8896 if (p[0] == 0 || p[1] == 0)
8897 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8898 internal_error (_("unexpected end of 'g' packet reply"));
8900 if (p[0] == 'x' && p[1] == 'x')
8901 regs[i] = 0; /* 'x' */
8902 else
8903 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8904 p += 2;
8907 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8909 struct packet_reg *r = &rsa->regs[i];
8910 long reg_size = register_size (gdbarch, i);
8912 if (r->in_g_packet)
8914 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8915 /* This shouldn't happen - we adjusted in_g_packet above. */
8916 internal_error (_("unexpected end of 'g' packet reply"));
8917 else if (rs->buf[r->offset * 2] == 'x')
8919 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8920 /* The register isn't available, mark it as such (at
8921 the same time setting the value to zero). */
8922 regcache->raw_supply (r->regnum, NULL);
8924 else
8925 regcache->raw_supply (r->regnum, regs + r->offset);
8930 void
8931 remote_target::fetch_registers_using_g (struct regcache *regcache)
8933 send_g_packet ();
8934 process_g_packet (regcache);
8937 /* Make the remote selected traceframe match GDB's selected
8938 traceframe. */
8940 void
8941 remote_target::set_remote_traceframe ()
8943 int newnum;
8944 struct remote_state *rs = get_remote_state ();
8946 if (rs->remote_traceframe_number == get_traceframe_number ())
8947 return;
8949 /* Avoid recursion, remote_trace_find calls us again. */
8950 rs->remote_traceframe_number = get_traceframe_number ();
8952 newnum = target_trace_find (tfind_number,
8953 get_traceframe_number (), 0, 0, NULL);
8955 /* Should not happen. If it does, all bets are off. */
8956 if (newnum != get_traceframe_number ())
8957 warning (_("could not set remote traceframe"));
8960 void
8961 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8963 struct gdbarch *gdbarch = regcache->arch ();
8964 struct remote_state *rs = get_remote_state ();
8965 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8966 int i;
8968 set_remote_traceframe ();
8969 set_general_thread (regcache->ptid ());
8971 if (regnum >= 0)
8973 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8975 gdb_assert (reg != NULL);
8977 /* If this register might be in the 'g' packet, try that first -
8978 we are likely to read more than one register. If this is the
8979 first 'g' packet, we might be overly optimistic about its
8980 contents, so fall back to 'p'. */
8981 if (reg->in_g_packet)
8983 fetch_registers_using_g (regcache);
8984 if (reg->in_g_packet)
8985 return;
8988 if (fetch_register_using_p (regcache, reg))
8989 return;
8991 /* This register is not available. */
8992 regcache->raw_supply (reg->regnum, NULL);
8994 return;
8997 fetch_registers_using_g (regcache);
8999 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9000 if (!rsa->regs[i].in_g_packet)
9001 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
9003 /* This register is not available. */
9004 regcache->raw_supply (i, NULL);
9008 /* Prepare to store registers. Since we may send them all (using a
9009 'G' request), we have to read out the ones we don't want to change
9010 first. */
9012 void
9013 remote_target::prepare_to_store (struct regcache *regcache)
9015 struct remote_state *rs = get_remote_state ();
9016 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9017 int i;
9019 /* Make sure the entire registers array is valid. */
9020 switch (m_features.packet_support (PACKET_P))
9022 case PACKET_DISABLE:
9023 case PACKET_SUPPORT_UNKNOWN:
9024 /* Make sure all the necessary registers are cached. */
9025 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9026 if (rsa->regs[i].in_g_packet)
9027 regcache->raw_update (rsa->regs[i].regnum);
9028 break;
9029 case PACKET_ENABLE:
9030 break;
9034 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9035 packet was not recognized. */
9038 remote_target::store_register_using_P (const struct regcache *regcache,
9039 packet_reg *reg)
9041 struct gdbarch *gdbarch = regcache->arch ();
9042 struct remote_state *rs = get_remote_state ();
9043 /* Try storing a single register. */
9044 char *buf = rs->buf.data ();
9045 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9046 char *p;
9048 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9049 return 0;
9051 if (reg->pnum == -1)
9052 return 0;
9054 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9055 p = buf + strlen (buf);
9056 regcache->raw_collect (reg->regnum, regp);
9057 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9058 putpkt (rs->buf);
9059 getpkt (&rs->buf);
9061 switch (m_features.packet_ok (rs->buf, PACKET_P))
9063 case PACKET_OK:
9064 return 1;
9065 case PACKET_ERROR:
9066 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9067 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
9068 case PACKET_UNKNOWN:
9069 return 0;
9070 default:
9071 internal_error (_("Bad result from packet_ok"));
9075 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9076 contents of the register cache buffer. FIXME: ignores errors. */
9078 void
9079 remote_target::store_registers_using_G (const struct regcache *regcache)
9081 struct remote_state *rs = get_remote_state ();
9082 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9083 gdb_byte *regs;
9084 char *p;
9086 /* Extract all the registers in the regcache copying them into a
9087 local buffer. */
9089 int i;
9091 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9092 memset (regs, 0, rsa->sizeof_g_packet);
9093 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9095 struct packet_reg *r = &rsa->regs[i];
9097 if (r->in_g_packet)
9098 regcache->raw_collect (r->regnum, regs + r->offset);
9102 /* Command describes registers byte by byte,
9103 each byte encoded as two hex characters. */
9104 p = rs->buf.data ();
9105 *p++ = 'G';
9106 bin2hex (regs, p, rsa->sizeof_g_packet);
9107 putpkt (rs->buf);
9108 getpkt (&rs->buf);
9109 if (packet_check_result (rs->buf) == PACKET_ERROR)
9110 error (_("Could not write registers; remote failure reply '%s'"),
9111 rs->buf.data ());
9114 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9115 of the register cache buffer. FIXME: ignores errors. */
9117 void
9118 remote_target::store_registers (struct regcache *regcache, int regnum)
9120 struct gdbarch *gdbarch = regcache->arch ();
9121 struct remote_state *rs = get_remote_state ();
9122 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9123 int i;
9125 set_remote_traceframe ();
9126 set_general_thread (regcache->ptid ());
9128 if (regnum >= 0)
9130 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9132 gdb_assert (reg != NULL);
9134 /* Always prefer to store registers using the 'P' packet if
9135 possible; we often change only a small number of registers.
9136 Sometimes we change a larger number; we'd need help from a
9137 higher layer to know to use 'G'. */
9138 if (store_register_using_P (regcache, reg))
9139 return;
9141 /* For now, don't complain if we have no way to write the
9142 register. GDB loses track of unavailable registers too
9143 easily. Some day, this may be an error. We don't have
9144 any way to read the register, either... */
9145 if (!reg->in_g_packet)
9146 return;
9148 store_registers_using_G (regcache);
9149 return;
9152 store_registers_using_G (regcache);
9154 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9155 if (!rsa->regs[i].in_g_packet)
9156 if (!store_register_using_P (regcache, &rsa->regs[i]))
9157 /* See above for why we do not issue an error here. */
9158 continue;
9162 /* Return the number of hex digits in num. */
9164 static int
9165 hexnumlen (ULONGEST num)
9167 int i;
9169 for (i = 0; num != 0; i++)
9170 num >>= 4;
9172 return std::max (i, 1);
9175 /* Set BUF to the minimum number of hex digits representing NUM. */
9177 static int
9178 hexnumstr (char *buf, ULONGEST num)
9180 int len = hexnumlen (num);
9182 return hexnumnstr (buf, num, len);
9186 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9188 static int
9189 hexnumnstr (char *buf, ULONGEST num, int width)
9191 int i;
9193 buf[width] = '\0';
9195 for (i = width - 1; i >= 0; i--)
9197 buf[i] = "0123456789abcdef"[(num & 0xf)];
9198 num >>= 4;
9201 return width;
9204 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9206 static CORE_ADDR
9207 remote_address_masked (CORE_ADDR addr)
9209 unsigned int address_size = remote_address_size;
9211 /* If "remoteaddresssize" was not set, default to target address size. */
9212 if (!address_size)
9213 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9215 if (address_size > 0
9216 && address_size < (sizeof (ULONGEST) * 8))
9218 /* Only create a mask when that mask can safely be constructed
9219 in a ULONGEST variable. */
9220 ULONGEST mask = 1;
9222 mask = (mask << address_size) - 1;
9223 addr &= mask;
9225 return addr;
9228 /* Determine whether the remote target supports binary downloading.
9229 This is accomplished by sending a no-op memory write of zero length
9230 to the target at the specified address. It does not suffice to send
9231 the whole packet, since many stubs strip the eighth bit and
9232 subsequently compute a wrong checksum, which causes real havoc with
9233 remote_write_bytes.
9235 NOTE: This can still lose if the serial line is not eight-bit
9236 clean. In cases like this, the user should clear "remote
9237 X-packet". */
9239 void
9240 remote_target::check_binary_download (CORE_ADDR addr)
9242 struct remote_state *rs = get_remote_state ();
9244 switch (m_features.packet_support (PACKET_X))
9246 case PACKET_DISABLE:
9247 break;
9248 case PACKET_ENABLE:
9249 break;
9250 case PACKET_SUPPORT_UNKNOWN:
9252 char *p;
9254 p = rs->buf.data ();
9255 *p++ = 'X';
9256 p += hexnumstr (p, (ULONGEST) addr);
9257 *p++ = ',';
9258 p += hexnumstr (p, (ULONGEST) 0);
9259 *p++ = ':';
9260 *p = '\0';
9262 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9263 getpkt (&rs->buf);
9265 if (rs->buf[0] == '\0')
9267 remote_debug_printf ("binary downloading NOT supported by target");
9268 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9270 else
9272 remote_debug_printf ("binary downloading supported by target");
9273 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9275 break;
9280 /* Helper function to resize the payload in order to try to get a good
9281 alignment. We try to write an amount of data such that the next write will
9282 start on an address aligned on REMOTE_ALIGN_WRITES. */
9284 static int
9285 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9287 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9290 /* Write memory data directly to the remote machine.
9291 This does not inform the data cache; the data cache uses this.
9292 HEADER is the starting part of the packet.
9293 MEMADDR is the address in the remote memory space.
9294 MYADDR is the address of the buffer in our space.
9295 LEN_UNITS is the number of addressable units to write.
9296 UNIT_SIZE is the length in bytes of an addressable unit.
9297 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9298 should send data as binary ('X'), or hex-encoded ('M').
9300 The function creates packet of the form
9301 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9303 where encoding of <DATA> is terminated by PACKET_FORMAT.
9305 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9306 are omitted.
9308 Return the transferred status, error or OK (an
9309 'enum target_xfer_status' value). Save the number of addressable units
9310 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9312 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9313 exchange between gdb and the stub could look like (?? in place of the
9314 checksum):
9316 -> $m1000,4#??
9317 <- aaaabbbbccccdddd
9319 -> $M1000,3:eeeeffffeeee#??
9320 <- OK
9322 -> $m1000,4#??
9323 <- eeeeffffeeeedddd */
9325 target_xfer_status
9326 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9327 const gdb_byte *myaddr,
9328 ULONGEST len_units,
9329 int unit_size,
9330 ULONGEST *xfered_len_units,
9331 char packet_format, int use_length)
9333 struct remote_state *rs = get_remote_state ();
9334 char *p;
9335 char *plen = NULL;
9336 int plenlen = 0;
9337 int todo_units;
9338 int units_written;
9339 int payload_capacity_bytes;
9340 int payload_length_bytes;
9342 if (packet_format != 'X' && packet_format != 'M')
9343 internal_error (_("remote_write_bytes_aux: bad packet format"));
9345 if (len_units == 0)
9346 return TARGET_XFER_EOF;
9348 payload_capacity_bytes = get_memory_write_packet_size ();
9350 /* The packet buffer will be large enough for the payload;
9351 get_memory_packet_size ensures this. */
9352 rs->buf[0] = '\0';
9354 /* Compute the size of the actual payload by subtracting out the
9355 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9357 payload_capacity_bytes -= strlen ("$,:#NN");
9358 if (!use_length)
9359 /* The comma won't be used. */
9360 payload_capacity_bytes += 1;
9361 payload_capacity_bytes -= strlen (header);
9362 payload_capacity_bytes -= hexnumlen (memaddr);
9364 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9366 strcat (rs->buf.data (), header);
9367 p = rs->buf.data () + strlen (header);
9369 /* Compute a best guess of the number of bytes actually transfered. */
9370 if (packet_format == 'X')
9372 /* Best guess at number of bytes that will fit. */
9373 todo_units = std::min (len_units,
9374 (ULONGEST) payload_capacity_bytes / unit_size);
9375 if (use_length)
9376 payload_capacity_bytes -= hexnumlen (todo_units);
9377 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9379 else
9381 /* Number of bytes that will fit. */
9382 todo_units
9383 = std::min (len_units,
9384 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9385 if (use_length)
9386 payload_capacity_bytes -= hexnumlen (todo_units);
9387 todo_units = std::min (todo_units,
9388 (payload_capacity_bytes / unit_size) / 2);
9391 if (todo_units <= 0)
9392 internal_error (_("minimum packet size too small to write data"));
9394 /* If we already need another packet, then try to align the end
9395 of this packet to a useful boundary. */
9396 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9397 todo_units = align_for_efficient_write (todo_units, memaddr);
9399 /* Append "<memaddr>". */
9400 memaddr = remote_address_masked (memaddr);
9401 p += hexnumstr (p, (ULONGEST) memaddr);
9403 if (use_length)
9405 /* Append ",". */
9406 *p++ = ',';
9408 /* Append the length and retain its location and size. It may need to be
9409 adjusted once the packet body has been created. */
9410 plen = p;
9411 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9412 p += plenlen;
9415 /* Append ":". */
9416 *p++ = ':';
9417 *p = '\0';
9419 /* Append the packet body. */
9420 if (packet_format == 'X')
9422 /* Binary mode. Send target system values byte by byte, in
9423 increasing byte addresses. Only escape certain critical
9424 characters. */
9425 payload_length_bytes =
9426 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9427 &units_written, payload_capacity_bytes);
9429 /* If not all TODO units fit, then we'll need another packet. Make
9430 a second try to keep the end of the packet aligned. Don't do
9431 this if the packet is tiny. */
9432 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9434 int new_todo_units;
9436 new_todo_units = align_for_efficient_write (units_written, memaddr);
9438 if (new_todo_units != units_written)
9439 payload_length_bytes =
9440 remote_escape_output (myaddr, new_todo_units, unit_size,
9441 (gdb_byte *) p, &units_written,
9442 payload_capacity_bytes);
9445 p += payload_length_bytes;
9446 if (use_length && units_written < todo_units)
9448 /* Escape chars have filled up the buffer prematurely,
9449 and we have actually sent fewer units than planned.
9450 Fix-up the length field of the packet. Use the same
9451 number of characters as before. */
9452 plen += hexnumnstr (plen, (ULONGEST) units_written,
9453 plenlen);
9454 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9457 else
9459 /* Normal mode: Send target system values byte by byte, in
9460 increasing byte addresses. Each byte is encoded as a two hex
9461 value. */
9462 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9463 units_written = todo_units;
9466 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9467 getpkt (&rs->buf);
9469 if (rs->buf[0] == 'E')
9470 return TARGET_XFER_E_IO;
9472 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9473 send fewer units than we'd planned. */
9474 *xfered_len_units = (ULONGEST) units_written;
9475 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9478 /* Write memory data directly to the remote machine.
9479 This does not inform the data cache; the data cache uses this.
9480 MEMADDR is the address in the remote memory space.
9481 MYADDR is the address of the buffer in our space.
9482 LEN is the number of bytes.
9484 Return the transferred status, error or OK (an
9485 'enum target_xfer_status' value). Save the number of bytes
9486 transferred in *XFERED_LEN. Only transfer a single packet. */
9488 target_xfer_status
9489 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9490 ULONGEST len, int unit_size,
9491 ULONGEST *xfered_len)
9493 const char *packet_format = NULL;
9495 /* Check whether the target supports binary download. */
9496 check_binary_download (memaddr);
9498 switch (m_features.packet_support (PACKET_X))
9500 case PACKET_ENABLE:
9501 packet_format = "X";
9502 break;
9503 case PACKET_DISABLE:
9504 packet_format = "M";
9505 break;
9506 case PACKET_SUPPORT_UNKNOWN:
9507 internal_error (_("remote_write_bytes: bad internal state"));
9508 default:
9509 internal_error (_("bad switch"));
9512 return remote_write_bytes_aux (packet_format,
9513 memaddr, myaddr, len, unit_size, xfered_len,
9514 packet_format[0], 1);
9517 /* Read memory data directly from the remote machine.
9518 This does not use the data cache; the data cache uses this.
9519 MEMADDR is the address in the remote memory space.
9520 MYADDR is the address of the buffer in our space.
9521 LEN_UNITS is the number of addressable memory units to read..
9522 UNIT_SIZE is the length in bytes of an addressable unit.
9524 Return the transferred status, error or OK (an
9525 'enum target_xfer_status' value). Save the number of bytes
9526 transferred in *XFERED_LEN_UNITS.
9528 See the comment of remote_write_bytes_aux for an example of
9529 memory read/write exchange between gdb and the stub. */
9531 target_xfer_status
9532 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9533 ULONGEST len_units,
9534 int unit_size, ULONGEST *xfered_len_units)
9536 struct remote_state *rs = get_remote_state ();
9537 int buf_size_bytes; /* Max size of packet output buffer. */
9538 char *p;
9539 int todo_units;
9540 int decoded_bytes;
9542 buf_size_bytes = get_memory_read_packet_size ();
9543 /* The packet buffer will be large enough for the payload;
9544 get_memory_packet_size ensures this. */
9546 /* Number of units that will fit. */
9547 todo_units = std::min (len_units,
9548 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9550 /* Construct "m"<memaddr>","<len>". */
9551 memaddr = remote_address_masked (memaddr);
9552 p = rs->buf.data ();
9553 *p++ = 'm';
9554 p += hexnumstr (p, (ULONGEST) memaddr);
9555 *p++ = ',';
9556 p += hexnumstr (p, (ULONGEST) todo_units);
9557 *p = '\0';
9558 putpkt (rs->buf);
9559 getpkt (&rs->buf);
9560 if (rs->buf[0] == 'E'
9561 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9562 && rs->buf[3] == '\0')
9563 return TARGET_XFER_E_IO;
9564 /* Reply describes memory byte by byte, each byte encoded as two hex
9565 characters. */
9566 p = rs->buf.data ();
9567 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9568 /* Return what we have. Let higher layers handle partial reads. */
9569 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9570 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9573 /* Using the set of read-only target sections of remote, read live
9574 read-only memory.
9576 For interface/parameters/return description see target.h,
9577 to_xfer_partial. */
9579 target_xfer_status
9580 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9581 ULONGEST memaddr,
9582 ULONGEST len,
9583 int unit_size,
9584 ULONGEST *xfered_len)
9586 const struct target_section *secp;
9588 secp = target_section_by_addr (this, memaddr);
9589 if (secp != NULL
9590 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9592 ULONGEST memend = memaddr + len;
9594 const std::vector<target_section> *table
9595 = target_get_section_table (this);
9596 for (const target_section &p : *table)
9598 if (memaddr >= p.addr)
9600 if (memend <= p.endaddr)
9602 /* Entire transfer is within this section. */
9603 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9604 xfered_len);
9606 else if (memaddr >= p.endaddr)
9608 /* This section ends before the transfer starts. */
9609 continue;
9611 else
9613 /* This section overlaps the transfer. Just do half. */
9614 len = p.endaddr - memaddr;
9615 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9616 xfered_len);
9622 return TARGET_XFER_EOF;
9625 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9626 first if the requested memory is unavailable in traceframe.
9627 Otherwise, fall back to remote_read_bytes_1. */
9629 target_xfer_status
9630 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9631 gdb_byte *myaddr, ULONGEST len, int unit_size,
9632 ULONGEST *xfered_len)
9634 if (len == 0)
9635 return TARGET_XFER_EOF;
9637 if (get_traceframe_number () != -1)
9639 std::vector<mem_range> available;
9641 /* If we fail to get the set of available memory, then the
9642 target does not support querying traceframe info, and so we
9643 attempt reading from the traceframe anyway (assuming the
9644 target implements the old QTro packet then). */
9645 if (traceframe_available_memory (&available, memaddr, len))
9647 if (available.empty () || available[0].start != memaddr)
9649 enum target_xfer_status res;
9651 /* Don't read into the traceframe's available
9652 memory. */
9653 if (!available.empty ())
9655 LONGEST oldlen = len;
9657 len = available[0].start - memaddr;
9658 gdb_assert (len <= oldlen);
9661 /* This goes through the topmost target again. */
9662 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9663 len, unit_size, xfered_len);
9664 if (res == TARGET_XFER_OK)
9665 return TARGET_XFER_OK;
9666 else
9668 /* No use trying further, we know some memory starting
9669 at MEMADDR isn't available. */
9670 *xfered_len = len;
9671 return (*xfered_len != 0) ?
9672 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9676 /* Don't try to read more than how much is available, in
9677 case the target implements the deprecated QTro packet to
9678 cater for older GDBs (the target's knowledge of read-only
9679 sections may be outdated by now). */
9680 len = available[0].length;
9684 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9689 /* Sends a packet with content determined by the printf format string
9690 FORMAT and the remaining arguments, then gets the reply. Returns
9691 whether the packet was a success, a failure, or unknown. */
9693 packet_result
9694 remote_target::remote_send_printf (const char *format, ...)
9696 struct remote_state *rs = get_remote_state ();
9697 int max_size = get_remote_packet_size ();
9698 va_list ap;
9700 va_start (ap, format);
9702 rs->buf[0] = '\0';
9703 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9705 va_end (ap);
9707 if (size >= max_size)
9708 internal_error (_("Too long remote packet."));
9710 if (putpkt (rs->buf) < 0)
9711 error (_("Communication problem with target."));
9713 rs->buf[0] = '\0';
9714 getpkt (&rs->buf);
9716 return packet_check_result (rs->buf);
9719 /* Flash writing can take quite some time. We'll set
9720 effectively infinite timeout for flash operations.
9721 In future, we'll need to decide on a better approach. */
9722 static const int remote_flash_timeout = 1000;
9724 void
9725 remote_target::flash_erase (ULONGEST address, LONGEST length)
9727 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9728 enum packet_result ret;
9729 scoped_restore restore_timeout
9730 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9732 ret = remote_send_printf ("vFlashErase:%s,%s",
9733 phex (address, addr_size),
9734 phex (length, 4));
9735 switch (ret)
9737 case PACKET_UNKNOWN:
9738 error (_("Remote target does not support flash erase"));
9739 case PACKET_ERROR:
9740 error (_("Error erasing flash with vFlashErase packet"));
9741 default:
9742 break;
9746 target_xfer_status
9747 remote_target::remote_flash_write (ULONGEST address,
9748 ULONGEST length, ULONGEST *xfered_len,
9749 const gdb_byte *data)
9751 scoped_restore restore_timeout
9752 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9753 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9754 xfered_len,'X', 0);
9757 void
9758 remote_target::flash_done ()
9760 int ret;
9762 scoped_restore restore_timeout
9763 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9765 ret = remote_send_printf ("vFlashDone");
9767 switch (ret)
9769 case PACKET_UNKNOWN:
9770 error (_("Remote target does not support vFlashDone"));
9771 case PACKET_ERROR:
9772 error (_("Error finishing flash operation"));
9773 default:
9774 break;
9779 /* Stuff for dealing with the packets which are part of this protocol.
9780 See comment at top of file for details. */
9782 /* Read a single character from the remote end. The current quit
9783 handler is overridden to avoid quitting in the middle of packet
9784 sequence, as that would break communication with the remote server.
9785 See remote_serial_quit_handler for more detail. */
9788 remote_target::readchar (int timeout)
9790 int ch;
9791 struct remote_state *rs = get_remote_state ();
9795 scoped_restore restore_quit_target
9796 = make_scoped_restore (&curr_quit_handler_target, this);
9797 scoped_restore restore_quit
9798 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9800 rs->got_ctrlc_during_io = 0;
9802 ch = serial_readchar (rs->remote_desc, timeout);
9804 if (rs->got_ctrlc_during_io)
9805 set_quit_flag ();
9807 catch (const gdb_exception_error &ex)
9809 remote_unpush_target (this);
9810 throw_error (TARGET_CLOSE_ERROR,
9811 _("Remote communication error. "
9812 "Target disconnected: %s"),
9813 ex.what ());
9816 if (ch >= 0)
9817 return ch;
9819 if (ch == SERIAL_EOF)
9821 remote_unpush_target (this);
9822 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9825 return ch;
9828 /* Wrapper for serial_write that closes the target and throws if
9829 writing fails. The current quit handler is overridden to avoid
9830 quitting in the middle of packet sequence, as that would break
9831 communication with the remote server. See
9832 remote_serial_quit_handler for more detail. */
9834 void
9835 remote_target::remote_serial_write (const char *str, int len)
9837 struct remote_state *rs = get_remote_state ();
9839 scoped_restore restore_quit_target
9840 = make_scoped_restore (&curr_quit_handler_target, this);
9841 scoped_restore restore_quit
9842 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9844 rs->got_ctrlc_during_io = 0;
9848 serial_write (rs->remote_desc, str, len);
9850 catch (const gdb_exception_error &ex)
9852 remote_unpush_target (this);
9853 throw_error (TARGET_CLOSE_ERROR,
9854 _("Remote communication error. "
9855 "Target disconnected: %s"),
9856 ex.what ());
9859 if (rs->got_ctrlc_during_io)
9860 set_quit_flag ();
9863 void
9864 remote_target::remote_serial_send_break ()
9866 struct remote_state *rs = get_remote_state ();
9870 serial_send_break (rs->remote_desc);
9872 catch (const gdb_exception_error &ex)
9874 remote_unpush_target (this);
9875 throw_error (TARGET_CLOSE_ERROR,
9876 _("Remote communication error. "
9877 "Target disconnected: %s"),
9878 ex.what ());
9882 /* Return a string representing an escaped version of BUF, of len N.
9883 E.g. \n is converted to \\n, \t to \\t, etc. */
9885 static std::string
9886 escape_buffer (const char *buf, int n)
9888 string_file stb;
9890 stb.putstrn (buf, n, '\\');
9891 return stb.release ();
9895 remote_target::putpkt (const char *buf)
9897 return putpkt_binary (buf, strlen (buf));
9900 /* Wrapper around remote_target::putpkt to avoid exporting
9901 remote_target. */
9904 putpkt (remote_target *remote, const char *buf)
9906 return remote->putpkt (buf);
9909 /* Send a packet to the remote machine, with error checking. The data
9910 of the packet is in BUF. The string in BUF can be at most
9911 get_remote_packet_size () - 5 to account for the $, # and checksum,
9912 and for a possible /0 if we are debugging (remote_debug) and want
9913 to print the sent packet as a string. */
9916 remote_target::putpkt_binary (const char *buf, int cnt)
9918 struct remote_state *rs = get_remote_state ();
9919 int i;
9920 unsigned char csum = 0;
9921 gdb::def_vector<char> data (cnt + 6);
9922 char *buf2 = data.data ();
9924 int ch;
9925 int tcount = 0;
9926 char *p;
9928 /* Catch cases like trying to read memory or listing threads while
9929 we're waiting for a stop reply. The remote server wouldn't be
9930 ready to handle this request, so we'd hang and timeout. We don't
9931 have to worry about this in synchronous mode, because in that
9932 case it's not possible to issue a command while the target is
9933 running. This is not a problem in non-stop mode, because in that
9934 case, the stub is always ready to process serial input. */
9935 if (!target_is_non_stop_p ()
9936 && target_is_async_p ()
9937 && rs->waiting_for_stop_reply)
9939 error (_("Cannot execute this command while the target is running.\n"
9940 "Use the \"interrupt\" command to stop the target\n"
9941 "and then try again."));
9944 /* Copy the packet into buffer BUF2, encapsulating it
9945 and giving it a checksum. */
9947 p = buf2;
9948 *p++ = '$';
9950 for (i = 0; i < cnt; i++)
9952 csum += buf[i];
9953 *p++ = buf[i];
9955 *p++ = '#';
9956 *p++ = tohex ((csum >> 4) & 0xf);
9957 *p++ = tohex (csum & 0xf);
9959 /* Send it over and over until we get a positive ack. */
9961 while (1)
9963 if (remote_debug)
9965 *p = '\0';
9967 int len = (int) (p - buf2);
9968 int max_chars;
9970 if (remote_packet_max_chars < 0)
9971 max_chars = len;
9972 else
9973 max_chars = remote_packet_max_chars;
9975 std::string str
9976 = escape_buffer (buf2, std::min (len, max_chars));
9978 if (len > max_chars)
9979 remote_debug_printf_nofunc
9980 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9981 len - max_chars);
9982 else
9983 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9985 remote_serial_write (buf2, p - buf2);
9987 /* If this is a no acks version of the remote protocol, send the
9988 packet and move on. */
9989 if (rs->noack_mode)
9990 break;
9992 /* Read until either a timeout occurs (-2) or '+' is read.
9993 Handle any notification that arrives in the mean time. */
9994 while (1)
9996 ch = readchar (remote_timeout);
9998 switch (ch)
10000 case '+':
10001 remote_debug_printf_nofunc ("Received Ack");
10002 return 1;
10003 case '-':
10004 remote_debug_printf_nofunc ("Received Nak");
10005 [[fallthrough]];
10006 case SERIAL_TIMEOUT:
10007 tcount++;
10008 if (tcount > 3)
10009 return 0;
10010 break; /* Retransmit buffer. */
10011 case '$':
10013 remote_debug_printf ("Packet instead of Ack, ignoring it");
10014 /* It's probably an old response sent because an ACK
10015 was lost. Gobble up the packet and ack it so it
10016 doesn't get retransmitted when we resend this
10017 packet. */
10018 skip_frame ();
10019 remote_serial_write ("+", 1);
10020 continue; /* Now, go look for +. */
10023 case '%':
10025 int val;
10027 /* If we got a notification, handle it, and go back to looking
10028 for an ack. */
10029 /* We've found the start of a notification. Now
10030 collect the data. */
10031 val = read_frame (&rs->buf);
10032 if (val >= 0)
10034 remote_debug_printf_nofunc
10035 (" Notification received: %s",
10036 escape_buffer (rs->buf.data (), val).c_str ());
10038 handle_notification (rs->notif_state, rs->buf.data ());
10039 /* We're in sync now, rewait for the ack. */
10040 tcount = 0;
10042 else
10043 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10044 rs->buf.data ());
10045 continue;
10047 default:
10048 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10049 rs->buf.data ());
10050 continue;
10052 break; /* Here to retransmit. */
10055 #if 0
10056 /* This is wrong. If doing a long backtrace, the user should be
10057 able to get out next time we call QUIT, without anything as
10058 violent as interrupt_query. If we want to provide a way out of
10059 here without getting to the next QUIT, it should be based on
10060 hitting ^C twice as in remote_wait. */
10061 if (quit_flag)
10063 quit_flag = 0;
10064 interrupt_query ();
10066 #endif
10069 return 0;
10072 /* Come here after finding the start of a frame when we expected an
10073 ack. Do our best to discard the rest of this packet. */
10075 void
10076 remote_target::skip_frame ()
10078 int c;
10080 while (1)
10082 c = readchar (remote_timeout);
10083 switch (c)
10085 case SERIAL_TIMEOUT:
10086 /* Nothing we can do. */
10087 return;
10088 case '#':
10089 /* Discard the two bytes of checksum and stop. */
10090 c = readchar (remote_timeout);
10091 if (c >= 0)
10092 c = readchar (remote_timeout);
10094 return;
10095 case '*': /* Run length encoding. */
10096 /* Discard the repeat count. */
10097 c = readchar (remote_timeout);
10098 if (c < 0)
10099 return;
10100 break;
10101 default:
10102 /* A regular character. */
10103 break;
10108 /* Come here after finding the start of the frame. Collect the rest
10109 into *BUF, verifying the checksum, length, and handling run-length
10110 compression. NUL terminate the buffer. If there is not enough room,
10111 expand *BUF.
10113 Returns -1 on error, number of characters in buffer (ignoring the
10114 trailing NULL) on success. (could be extended to return one of the
10115 SERIAL status indications). */
10117 long
10118 remote_target::read_frame (gdb::char_vector *buf_p)
10120 unsigned char csum;
10121 long bc;
10122 int c;
10123 char *buf = buf_p->data ();
10124 struct remote_state *rs = get_remote_state ();
10126 csum = 0;
10127 bc = 0;
10129 while (1)
10131 c = readchar (remote_timeout);
10132 switch (c)
10134 case SERIAL_TIMEOUT:
10135 remote_debug_printf ("Timeout in mid-packet, retrying");
10136 return -1;
10138 case '$':
10139 remote_debug_printf ("Saw new packet start in middle of old one");
10140 return -1; /* Start a new packet, count retries. */
10142 case '#':
10144 unsigned char pktcsum;
10145 int check_0 = 0;
10146 int check_1 = 0;
10148 buf[bc] = '\0';
10150 check_0 = readchar (remote_timeout);
10151 if (check_0 >= 0)
10152 check_1 = readchar (remote_timeout);
10154 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10156 remote_debug_printf ("Timeout in checksum, retrying");
10157 return -1;
10159 else if (check_0 < 0 || check_1 < 0)
10161 remote_debug_printf ("Communication error in checksum");
10162 return -1;
10165 /* Don't recompute the checksum; with no ack packets we
10166 don't have any way to indicate a packet retransmission
10167 is necessary. */
10168 if (rs->noack_mode)
10169 return bc;
10171 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10172 if (csum == pktcsum)
10173 return bc;
10175 remote_debug_printf
10176 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10177 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10179 /* Number of characters in buffer ignoring trailing
10180 NULL. */
10181 return -1;
10183 case '*': /* Run length encoding. */
10185 int repeat;
10187 csum += c;
10188 c = readchar (remote_timeout);
10189 csum += c;
10190 repeat = c - ' ' + 3; /* Compute repeat count. */
10192 /* The character before ``*'' is repeated. */
10194 if (repeat > 0 && repeat <= 255 && bc > 0)
10196 if (bc + repeat - 1 >= buf_p->size () - 1)
10198 /* Make some more room in the buffer. */
10199 buf_p->resize (buf_p->size () + repeat);
10200 buf = buf_p->data ();
10203 memset (&buf[bc], buf[bc - 1], repeat);
10204 bc += repeat;
10205 continue;
10208 buf[bc] = '\0';
10209 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10210 return -1;
10212 default:
10213 if (bc >= buf_p->size () - 1)
10215 /* Make some more room in the buffer. */
10216 buf_p->resize (buf_p->size () * 2);
10217 buf = buf_p->data ();
10220 buf[bc++] = c;
10221 csum += c;
10222 continue;
10227 /* Set this to the maximum number of seconds to wait instead of waiting forever
10228 in target_wait(). If this timer times out, then it generates an error and
10229 the command is aborted. This replaces most of the need for timeouts in the
10230 GDB test suite, and makes it possible to distinguish between a hung target
10231 and one with slow communications. */
10233 static int watchdog = 0;
10234 static void
10235 show_watchdog (struct ui_file *file, int from_tty,
10236 struct cmd_list_element *c, const char *value)
10238 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10241 /* Read a packet from the remote machine, with error checking, and
10242 store it in *BUF. Resize *BUF if necessary to hold the result. If
10243 FOREVER, wait forever rather than timing out; this is used (in
10244 synchronous mode) to wait for a target that is is executing user
10245 code to stop. If FOREVER == false, this function is allowed to time
10246 out gracefully and return an indication of this to the caller.
10247 Otherwise return the number of bytes read. If IS_NOTIF is not
10248 NULL, then consider receiving a notification enough reason to
10249 return to the caller. In this case, *IS_NOTIF is an output boolean
10250 that indicates whether *BUF holds a notification or not (a regular
10251 packet). */
10254 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10256 struct remote_state *rs = get_remote_state ();
10257 int c;
10258 int tries;
10259 int timeout;
10260 int val = -1;
10262 strcpy (buf->data (), "timeout");
10264 if (forever)
10265 timeout = watchdog > 0 ? watchdog : -1;
10266 else if (is_notif != nullptr)
10267 timeout = 0; /* There should already be a char in the buffer. If
10268 not, bail out. */
10269 else
10270 timeout = remote_timeout;
10272 #define MAX_TRIES 3
10274 /* Process any number of notifications, and then return when
10275 we get a packet. */
10276 for (;;)
10278 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10279 times. */
10280 for (tries = 1; tries <= MAX_TRIES; tries++)
10282 /* This can loop forever if the remote side sends us
10283 characters continuously, but if it pauses, we'll get
10284 SERIAL_TIMEOUT from readchar because of timeout. Then
10285 we'll count that as a retry.
10287 Note that even when forever is set, we will only wait
10288 forever prior to the start of a packet. After that, we
10289 expect characters to arrive at a brisk pace. They should
10290 show up within remote_timeout intervals. */
10292 c = readchar (timeout);
10293 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10295 if (c == SERIAL_TIMEOUT)
10297 if (is_notif != nullptr)
10298 return -1; /* Don't complain, it's normal to not get
10299 anything in this case. */
10301 if (forever) /* Watchdog went off? Kill the target. */
10303 remote_unpush_target (this);
10304 throw_error (TARGET_CLOSE_ERROR,
10305 _("Watchdog timeout has expired. "
10306 "Target detached."));
10309 remote_debug_printf ("Timed out.");
10311 else
10313 /* We've found the start of a packet or notification.
10314 Now collect the data. */
10315 val = read_frame (buf);
10316 if (val >= 0)
10317 break;
10320 remote_serial_write ("-", 1);
10323 if (tries > MAX_TRIES)
10325 /* We have tried hard enough, and just can't receive the
10326 packet/notification. Give up. */
10327 gdb_printf (_("Ignoring packet error, continuing...\n"));
10329 /* Skip the ack char if we're in no-ack mode. */
10330 if (!rs->noack_mode)
10331 remote_serial_write ("+", 1);
10332 return -1;
10335 /* If we got an ordinary packet, return that to our caller. */
10336 if (c == '$')
10338 if (remote_debug)
10340 int max_chars;
10342 if (remote_packet_max_chars < 0)
10343 max_chars = val;
10344 else
10345 max_chars = remote_packet_max_chars;
10347 std::string str
10348 = escape_buffer (buf->data (),
10349 std::min (val, max_chars));
10351 if (val > max_chars)
10352 remote_debug_printf_nofunc
10353 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10354 val - max_chars);
10355 else
10356 remote_debug_printf_nofunc ("Packet received: %s",
10357 str.c_str ());
10360 /* Skip the ack char if we're in no-ack mode. */
10361 if (!rs->noack_mode)
10362 remote_serial_write ("+", 1);
10363 if (is_notif != NULL)
10364 *is_notif = false;
10365 return val;
10368 /* If we got a notification, handle it, and go back to looking
10369 for a packet. */
10370 else
10372 gdb_assert (c == '%');
10374 remote_debug_printf_nofunc
10375 (" Notification received: %s",
10376 escape_buffer (buf->data (), val).c_str ());
10378 if (is_notif != NULL)
10379 *is_notif = true;
10381 handle_notification (rs->notif_state, buf->data ());
10383 /* Notifications require no acknowledgement. */
10385 if (is_notif != nullptr)
10386 return val;
10391 /* Kill any new fork children of inferior INF that haven't been
10392 processed by follow_fork. */
10394 void
10395 remote_target::kill_new_fork_children (inferior *inf)
10397 remote_state *rs = get_remote_state ();
10398 const notif_client *notif = &notif_client_stop;
10400 /* Kill the fork child threads of any threads in inferior INF that are stopped
10401 at a fork event. */
10402 for (thread_info *thread : inf->non_exited_threads ())
10404 const target_waitstatus *ws = thread_pending_fork_status (thread);
10406 if (ws == nullptr)
10407 continue;
10409 int child_pid = ws->child_ptid ().pid ();
10410 int res = remote_vkill (child_pid);
10412 if (res != 0)
10413 error (_("Can't kill fork child process %d"), child_pid);
10416 /* Check for any pending fork events (not reported or processed yet)
10417 in inferior INF and kill those fork child threads as well. */
10418 remote_notif_get_pending_events (notif);
10419 for (auto &event : rs->stop_reply_queue)
10421 if (event->ptid.pid () != inf->pid)
10422 continue;
10424 if (!is_fork_status (event->ws.kind ()))
10425 continue;
10427 int child_pid = event->ws.child_ptid ().pid ();
10428 int res = remote_vkill (child_pid);
10430 if (res != 0)
10431 error (_("Can't kill fork child process %d"), child_pid);
10436 /* Target hook to kill the current inferior. */
10438 void
10439 remote_target::kill ()
10441 int res = -1;
10442 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10444 gdb_assert (inf != nullptr);
10446 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10448 /* If we're stopped while forking and we haven't followed yet,
10449 kill the child task. We need to do this before killing the
10450 parent task because if this is a vfork then the parent will
10451 be sleeping. */
10452 kill_new_fork_children (inf);
10454 res = remote_vkill (inf->pid);
10455 if (res == 0)
10457 target_mourn_inferior (inferior_ptid);
10458 return;
10462 /* If we are in 'target remote' mode and we are killing the only
10463 inferior, then we will tell gdbserver to exit and unpush the
10464 target. */
10465 if (res == -1 && !m_features.remote_multi_process_p ()
10466 && number_of_live_inferiors (this) == 1)
10468 remote_kill_k ();
10470 /* We've killed the remote end, we get to mourn it. If we are
10471 not in extended mode, mourning the inferior also unpushes
10472 remote_ops from the target stack, which closes the remote
10473 connection. */
10474 target_mourn_inferior (inferior_ptid);
10476 return;
10479 error (_("Can't kill process"));
10482 /* Send a kill request to the target using the 'vKill' packet. */
10485 remote_target::remote_vkill (int pid)
10487 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10488 return -1;
10490 remote_state *rs = get_remote_state ();
10492 /* Tell the remote target to detach. */
10493 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10494 putpkt (rs->buf);
10495 getpkt (&rs->buf);
10497 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10499 case PACKET_OK:
10500 return 0;
10501 case PACKET_ERROR:
10502 return 1;
10503 case PACKET_UNKNOWN:
10504 return -1;
10505 default:
10506 internal_error (_("Bad result from packet_ok"));
10510 /* Send a kill request to the target using the 'k' packet. */
10512 void
10513 remote_target::remote_kill_k ()
10515 /* Catch errors so the user can quit from gdb even when we
10516 aren't on speaking terms with the remote system. */
10519 putpkt ("k");
10521 catch (const gdb_exception_error &ex)
10523 if (ex.error == TARGET_CLOSE_ERROR)
10525 /* If we got an (EOF) error that caused the target
10526 to go away, then we're done, that's what we wanted.
10527 "k" is susceptible to cause a premature EOF, given
10528 that the remote server isn't actually required to
10529 reply to "k", and it can happen that it doesn't
10530 even get to reply ACK to the "k". */
10531 return;
10534 /* Otherwise, something went wrong. We didn't actually kill
10535 the target. Just propagate the exception, and let the
10536 user or higher layers decide what to do. */
10537 throw;
10541 void
10542 remote_target::mourn_inferior ()
10544 struct remote_state *rs = get_remote_state ();
10546 /* We're no longer interested in notification events of an inferior
10547 that exited or was killed/detached. */
10548 discard_pending_stop_replies (current_inferior ());
10550 /* In 'target remote' mode with one inferior, we close the connection. */
10551 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10553 remote_unpush_target (this);
10554 return;
10557 /* In case we got here due to an error, but we're going to stay
10558 connected. */
10559 rs->waiting_for_stop_reply = 0;
10561 /* If the current general thread belonged to the process we just
10562 detached from or has exited, the remote side current general
10563 thread becomes undefined. Considering a case like this:
10565 - We just got here due to a detach.
10566 - The process that we're detaching from happens to immediately
10567 report a global breakpoint being hit in non-stop mode, in the
10568 same thread we had selected before.
10569 - GDB attaches to this process again.
10570 - This event happens to be the next event we handle.
10572 GDB would consider that the current general thread didn't need to
10573 be set on the stub side (with Hg), since for all it knew,
10574 GENERAL_THREAD hadn't changed.
10576 Notice that although in all-stop mode, the remote server always
10577 sets the current thread to the thread reporting the stop event,
10578 that doesn't happen in non-stop mode; in non-stop, the stub *must
10579 not* change the current thread when reporting a breakpoint hit,
10580 due to the decoupling of event reporting and event handling.
10582 To keep things simple, we always invalidate our notion of the
10583 current thread. */
10584 record_currthread (rs, minus_one_ptid);
10586 /* Call common code to mark the inferior as not running. */
10587 generic_mourn_inferior ();
10590 bool
10591 extended_remote_target::supports_disable_randomization ()
10593 return (m_features.packet_support (PACKET_QDisableRandomization)
10594 == PACKET_ENABLE);
10597 void
10598 remote_target::extended_remote_disable_randomization (int val)
10600 struct remote_state *rs = get_remote_state ();
10601 char *reply;
10603 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10604 "QDisableRandomization:%x", val);
10605 putpkt (rs->buf);
10606 reply = remote_get_noisy_reply ();
10607 if (*reply == '\0')
10608 error (_("Target does not support QDisableRandomization."));
10609 if (strcmp (reply, "OK") != 0)
10610 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10614 remote_target::extended_remote_run (const std::string &args)
10616 struct remote_state *rs = get_remote_state ();
10617 int len;
10618 const char *remote_exec_file = get_remote_exec_file ();
10620 /* If the user has disabled vRun support, or we have detected that
10621 support is not available, do not try it. */
10622 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10623 return -1;
10625 strcpy (rs->buf.data (), "vRun;");
10626 len = strlen (rs->buf.data ());
10628 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10629 error (_("Remote file name too long for run packet"));
10630 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10631 strlen (remote_exec_file));
10633 if (!args.empty ())
10635 int i;
10637 gdb_argv argv (args.c_str ());
10638 for (i = 0; argv[i] != NULL; i++)
10640 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10641 error (_("Argument list too long for run packet"));
10642 rs->buf[len++] = ';';
10643 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10644 strlen (argv[i]));
10648 rs->buf[len++] = '\0';
10650 putpkt (rs->buf);
10651 getpkt (&rs->buf);
10653 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10655 case PACKET_OK:
10656 /* We have a wait response. All is well. */
10657 return 0;
10658 case PACKET_UNKNOWN:
10659 return -1;
10660 case PACKET_ERROR:
10661 if (remote_exec_file[0] == '\0')
10662 error (_("Running the default executable on the remote target failed; "
10663 "try \"set remote exec-file\"?"));
10664 else
10665 error (_("Running \"%s\" on the remote target failed"),
10666 remote_exec_file);
10667 default:
10668 gdb_assert_not_reached ("bad switch");
10672 /* Helper function to send set/unset environment packets. ACTION is
10673 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10674 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10675 sent. */
10677 void
10678 remote_target::send_environment_packet (const char *action,
10679 const char *packet,
10680 const char *value)
10682 remote_state *rs = get_remote_state ();
10684 /* Convert the environment variable to an hex string, which
10685 is the best format to be transmitted over the wire. */
10686 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10687 strlen (value));
10689 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10690 "%s:%s", packet, encoded_value.c_str ());
10692 putpkt (rs->buf);
10693 getpkt (&rs->buf);
10694 if (strcmp (rs->buf.data (), "OK") != 0)
10695 warning (_("Unable to %s environment variable '%s' on remote."),
10696 action, value);
10699 /* Helper function to handle the QEnvironment* packets. */
10701 void
10702 remote_target::extended_remote_environment_support ()
10704 remote_state *rs = get_remote_state ();
10706 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10708 putpkt ("QEnvironmentReset");
10709 getpkt (&rs->buf);
10710 if (strcmp (rs->buf.data (), "OK") != 0)
10711 warning (_("Unable to reset environment on remote."));
10714 gdb_environ *e = &current_inferior ()->environment;
10716 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10717 != PACKET_DISABLE)
10719 for (const std::string &el : e->user_set_env ())
10720 send_environment_packet ("set", "QEnvironmentHexEncoded",
10721 el.c_str ());
10725 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10726 for (const std::string &el : e->user_unset_env ())
10727 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10730 /* Helper function to set the current working directory for the
10731 inferior in the remote target. */
10733 void
10734 remote_target::extended_remote_set_inferior_cwd ()
10736 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10738 const std::string &inferior_cwd = current_inferior ()->cwd ();
10739 remote_state *rs = get_remote_state ();
10741 if (!inferior_cwd.empty ())
10743 std::string hexpath
10744 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10745 inferior_cwd.size ());
10747 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10748 "QSetWorkingDir:%s", hexpath.c_str ());
10750 else
10752 /* An empty inferior_cwd means that the user wants us to
10753 reset the remote server's inferior's cwd. */
10754 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10755 "QSetWorkingDir:");
10758 putpkt (rs->buf);
10759 getpkt (&rs->buf);
10760 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10761 error (_("\
10762 Remote replied unexpectedly while setting the inferior's working\n\
10763 directory: %s"),
10764 rs->buf.data ());
10769 /* In the extended protocol we want to be able to do things like
10770 "run" and have them basically work as expected. So we need
10771 a special create_inferior function. We support changing the
10772 executable file and the command line arguments, but not the
10773 environment. */
10775 void
10776 extended_remote_target::create_inferior (const char *exec_file,
10777 const std::string &args,
10778 char **env, int from_tty)
10780 int run_worked;
10781 char *stop_reply;
10782 struct remote_state *rs = get_remote_state ();
10783 const char *remote_exec_file = get_remote_exec_file ();
10785 /* If running asynchronously, register the target file descriptor
10786 with the event loop. */
10787 if (target_can_async_p ())
10788 target_async (true);
10790 /* Disable address space randomization if requested (and supported). */
10791 if (supports_disable_randomization ())
10792 extended_remote_disable_randomization (disable_randomization);
10794 /* If startup-with-shell is on, we inform gdbserver to start the
10795 remote inferior using a shell. */
10796 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10798 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10799 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10800 putpkt (rs->buf);
10801 getpkt (&rs->buf);
10802 if (strcmp (rs->buf.data (), "OK") != 0)
10803 error (_("\
10804 Remote replied unexpectedly while setting startup-with-shell: %s"),
10805 rs->buf.data ());
10808 extended_remote_environment_support ();
10810 extended_remote_set_inferior_cwd ();
10812 /* Now restart the remote server. */
10813 run_worked = extended_remote_run (args) != -1;
10814 if (!run_worked)
10816 /* vRun was not supported. Fail if we need it to do what the
10817 user requested. */
10818 if (remote_exec_file[0])
10819 error (_("Remote target does not support \"set remote exec-file\""));
10820 if (!args.empty ())
10821 error (_("Remote target does not support \"set args\" or run ARGS"));
10823 /* Fall back to "R". */
10824 extended_remote_restart ();
10827 /* vRun's success return is a stop reply. */
10828 stop_reply = run_worked ? rs->buf.data () : NULL;
10829 add_current_inferior_and_thread (stop_reply);
10831 /* Get updated offsets, if the stub uses qOffsets. */
10832 get_offsets ();
10836 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10837 the list of conditions (in agent expression bytecode format), if any, the
10838 target needs to evaluate. The output is placed into the packet buffer
10839 started from BUF and ended at BUF_END. */
10841 static int
10842 remote_add_target_side_condition (struct gdbarch *gdbarch,
10843 struct bp_target_info *bp_tgt, char *buf,
10844 char *buf_end)
10846 if (bp_tgt->conditions.empty ())
10847 return 0;
10849 buf += strlen (buf);
10850 xsnprintf (buf, buf_end - buf, "%s", ";");
10851 buf++;
10853 /* Send conditions to the target. */
10854 for (agent_expr *aexpr : bp_tgt->conditions)
10856 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10857 buf += strlen (buf);
10858 for (int i = 0; i < aexpr->buf.size (); ++i)
10859 buf = pack_hex_byte (buf, aexpr->buf[i]);
10860 *buf = '\0';
10862 return 0;
10865 static void
10866 remote_add_target_side_commands (struct gdbarch *gdbarch,
10867 struct bp_target_info *bp_tgt, char *buf)
10869 if (bp_tgt->tcommands.empty ())
10870 return;
10872 buf += strlen (buf);
10874 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10875 buf += strlen (buf);
10877 /* Concatenate all the agent expressions that are commands into the
10878 cmds parameter. */
10879 for (agent_expr *aexpr : bp_tgt->tcommands)
10881 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10882 buf += strlen (buf);
10883 for (int i = 0; i < aexpr->buf.size (); ++i)
10884 buf = pack_hex_byte (buf, aexpr->buf[i]);
10885 *buf = '\0';
10889 /* Insert a breakpoint. On targets that have software breakpoint
10890 support, we ask the remote target to do the work; on targets
10891 which don't, we insert a traditional memory breakpoint. */
10894 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10895 struct bp_target_info *bp_tgt)
10897 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10898 If it succeeds, then set the support to PACKET_ENABLE. If it
10899 fails, and the user has explicitly requested the Z support then
10900 report an error, otherwise, mark it disabled and go on. */
10902 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10904 CORE_ADDR addr = bp_tgt->reqstd_address;
10905 struct remote_state *rs;
10906 char *p, *endbuf;
10908 /* Make sure the remote is pointing at the right process, if
10909 necessary. */
10910 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10911 set_general_process ();
10913 rs = get_remote_state ();
10914 p = rs->buf.data ();
10915 endbuf = p + get_remote_packet_size ();
10917 *(p++) = 'Z';
10918 *(p++) = '0';
10919 *(p++) = ',';
10920 addr = (ULONGEST) remote_address_masked (addr);
10921 p += hexnumstr (p, addr);
10922 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10924 if (supports_evaluation_of_breakpoint_conditions ())
10925 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10927 if (can_run_breakpoint_commands ())
10928 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10930 putpkt (rs->buf);
10931 getpkt (&rs->buf);
10933 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10935 case PACKET_ERROR:
10936 return -1;
10937 case PACKET_OK:
10938 return 0;
10939 case PACKET_UNKNOWN:
10940 break;
10944 /* If this breakpoint has target-side commands but this stub doesn't
10945 support Z0 packets, throw error. */
10946 if (!bp_tgt->tcommands.empty ())
10947 throw_error (NOT_SUPPORTED_ERROR, _("\
10948 Target doesn't support breakpoints that have target side commands."));
10950 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10954 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10955 struct bp_target_info *bp_tgt,
10956 enum remove_bp_reason reason)
10958 CORE_ADDR addr = bp_tgt->placed_address;
10959 struct remote_state *rs = get_remote_state ();
10961 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10963 char *p = rs->buf.data ();
10964 char *endbuf = p + get_remote_packet_size ();
10966 /* Make sure the remote is pointing at the right process, if
10967 necessary. */
10968 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10969 set_general_process ();
10971 *(p++) = 'z';
10972 *(p++) = '0';
10973 *(p++) = ',';
10975 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10976 p += hexnumstr (p, addr);
10977 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10979 putpkt (rs->buf);
10980 getpkt (&rs->buf);
10982 return (rs->buf[0] == 'E');
10985 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10988 static enum Z_packet_type
10989 watchpoint_to_Z_packet (int type)
10991 switch (type)
10993 case hw_write:
10994 return Z_PACKET_WRITE_WP;
10995 break;
10996 case hw_read:
10997 return Z_PACKET_READ_WP;
10998 break;
10999 case hw_access:
11000 return Z_PACKET_ACCESS_WP;
11001 break;
11002 default:
11003 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
11008 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
11009 enum target_hw_bp_type type, struct expression *cond)
11011 struct remote_state *rs = get_remote_state ();
11012 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11013 char *p;
11014 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11016 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11017 + to_underlying (packet))) == PACKET_DISABLE)
11018 return 1;
11020 /* Make sure the remote is pointing at the right process, if
11021 necessary. */
11022 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11023 set_general_process ();
11025 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11026 p = strchr (rs->buf.data (), '\0');
11027 addr = remote_address_masked (addr);
11028 p += hexnumstr (p, (ULONGEST) addr);
11029 xsnprintf (p, endbuf - p, ",%x", len);
11031 putpkt (rs->buf);
11032 getpkt (&rs->buf);
11034 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11035 + to_underlying (packet))))
11037 case PACKET_ERROR:
11038 return -1;
11039 case PACKET_UNKNOWN:
11040 return 1;
11041 case PACKET_OK:
11042 return 0;
11044 internal_error (_("remote_insert_watchpoint: reached end of function"));
11047 bool
11048 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11049 CORE_ADDR start, int length)
11051 CORE_ADDR diff = remote_address_masked (addr - start);
11053 return diff < length;
11058 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11059 enum target_hw_bp_type type, struct expression *cond)
11061 struct remote_state *rs = get_remote_state ();
11062 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11063 char *p;
11064 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11066 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11067 + to_underlying (packet))) == PACKET_DISABLE)
11068 return -1;
11070 /* Make sure the remote is pointing at the right process, if
11071 necessary. */
11072 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11073 set_general_process ();
11075 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11076 p = strchr (rs->buf.data (), '\0');
11077 addr = remote_address_masked (addr);
11078 p += hexnumstr (p, (ULONGEST) addr);
11079 xsnprintf (p, endbuf - p, ",%x", len);
11080 putpkt (rs->buf);
11081 getpkt (&rs->buf);
11083 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11084 + to_underlying (packet))))
11086 case PACKET_ERROR:
11087 case PACKET_UNKNOWN:
11088 return -1;
11089 case PACKET_OK:
11090 return 0;
11092 internal_error (_("remote_remove_watchpoint: reached end of function"));
11096 static int remote_hw_watchpoint_limit = -1;
11097 static int remote_hw_watchpoint_length_limit = -1;
11098 static int remote_hw_breakpoint_limit = -1;
11101 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11103 if (remote_hw_watchpoint_length_limit == 0)
11104 return 0;
11105 else if (remote_hw_watchpoint_length_limit < 0)
11106 return 1;
11107 else if (len <= remote_hw_watchpoint_length_limit)
11108 return 1;
11109 else
11110 return 0;
11114 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11116 if (type == bp_hardware_breakpoint)
11118 if (remote_hw_breakpoint_limit == 0)
11119 return 0;
11120 else if (remote_hw_breakpoint_limit < 0)
11121 return 1;
11122 else if (cnt <= remote_hw_breakpoint_limit)
11123 return 1;
11125 else
11127 if (remote_hw_watchpoint_limit == 0)
11128 return 0;
11129 else if (remote_hw_watchpoint_limit < 0)
11130 return 1;
11131 else if (ot)
11132 return -1;
11133 else if (cnt <= remote_hw_watchpoint_limit)
11134 return 1;
11136 return -1;
11139 /* The to_stopped_by_sw_breakpoint method of target remote. */
11141 bool
11142 remote_target::stopped_by_sw_breakpoint ()
11144 struct thread_info *thread = inferior_thread ();
11146 return (thread->priv != NULL
11147 && (get_remote_thread_info (thread)->stop_reason
11148 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11151 /* The to_supports_stopped_by_sw_breakpoint method of target
11152 remote. */
11154 bool
11155 remote_target::supports_stopped_by_sw_breakpoint ()
11157 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11160 /* The to_stopped_by_hw_breakpoint method of target remote. */
11162 bool
11163 remote_target::stopped_by_hw_breakpoint ()
11165 struct thread_info *thread = inferior_thread ();
11167 return (thread->priv != NULL
11168 && (get_remote_thread_info (thread)->stop_reason
11169 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11172 /* The to_supports_stopped_by_hw_breakpoint method of target
11173 remote. */
11175 bool
11176 remote_target::supports_stopped_by_hw_breakpoint ()
11178 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11181 bool
11182 remote_target::stopped_by_watchpoint ()
11184 struct thread_info *thread = inferior_thread ();
11186 return (thread->priv != NULL
11187 && (get_remote_thread_info (thread)->stop_reason
11188 == TARGET_STOPPED_BY_WATCHPOINT));
11191 bool
11192 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11194 struct thread_info *thread = inferior_thread ();
11196 if (thread->priv != NULL
11197 && (get_remote_thread_info (thread)->stop_reason
11198 == TARGET_STOPPED_BY_WATCHPOINT))
11200 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11201 return true;
11204 return false;
11209 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11210 struct bp_target_info *bp_tgt)
11212 CORE_ADDR addr = bp_tgt->reqstd_address;
11213 struct remote_state *rs;
11214 char *p, *endbuf;
11215 char *message;
11217 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11218 return -1;
11220 /* Make sure the remote is pointing at the right process, if
11221 necessary. */
11222 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11223 set_general_process ();
11225 rs = get_remote_state ();
11226 p = rs->buf.data ();
11227 endbuf = p + get_remote_packet_size ();
11229 *(p++) = 'Z';
11230 *(p++) = '1';
11231 *(p++) = ',';
11233 addr = remote_address_masked (addr);
11234 p += hexnumstr (p, (ULONGEST) addr);
11235 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11237 if (supports_evaluation_of_breakpoint_conditions ())
11238 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11240 if (can_run_breakpoint_commands ())
11241 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11243 putpkt (rs->buf);
11244 getpkt (&rs->buf);
11246 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11248 case PACKET_ERROR:
11249 if (rs->buf[1] == '.')
11251 message = strchr (&rs->buf[2], '.');
11252 if (message)
11253 error (_("Remote failure reply: %s"), message + 1);
11255 return -1;
11256 case PACKET_UNKNOWN:
11257 return -1;
11258 case PACKET_OK:
11259 return 0;
11261 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11266 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11267 struct bp_target_info *bp_tgt)
11269 CORE_ADDR addr;
11270 struct remote_state *rs = get_remote_state ();
11271 char *p = rs->buf.data ();
11272 char *endbuf = p + get_remote_packet_size ();
11274 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11275 return -1;
11277 /* Make sure the remote is pointing at the right process, if
11278 necessary. */
11279 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11280 set_general_process ();
11282 *(p++) = 'z';
11283 *(p++) = '1';
11284 *(p++) = ',';
11286 addr = remote_address_masked (bp_tgt->placed_address);
11287 p += hexnumstr (p, (ULONGEST) addr);
11288 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11290 putpkt (rs->buf);
11291 getpkt (&rs->buf);
11293 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11295 case PACKET_ERROR:
11296 case PACKET_UNKNOWN:
11297 return -1;
11298 case PACKET_OK:
11299 return 0;
11301 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11304 /* Verify memory using the "qCRC:" request. */
11307 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11309 struct remote_state *rs = get_remote_state ();
11310 unsigned long host_crc, target_crc;
11311 char *tmp;
11313 /* It doesn't make sense to use qCRC if the remote target is
11314 connected but not running. */
11315 if (target_has_execution ()
11316 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11318 enum packet_result result;
11320 /* Make sure the remote is pointing at the right process. */
11321 set_general_process ();
11323 /* FIXME: assumes lma can fit into long. */
11324 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11325 (long) lma, (long) size);
11326 putpkt (rs->buf);
11328 /* Be clever; compute the host_crc before waiting for target
11329 reply. */
11330 host_crc = xcrc32 (data, size, 0xffffffff);
11332 getpkt (&rs->buf);
11334 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11335 if (result == PACKET_ERROR)
11336 return -1;
11337 else if (result == PACKET_OK)
11339 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11340 target_crc = target_crc * 16 + fromhex (*tmp);
11342 return (host_crc == target_crc);
11346 return simple_verify_memory (this, data, lma, size);
11349 /* compare-sections command
11351 With no arguments, compares each loadable section in the exec bfd
11352 with the same memory range on the target, and reports mismatches.
11353 Useful for verifying the image on the target against the exec file. */
11355 static void
11356 compare_sections_command (const char *args, int from_tty)
11358 asection *s;
11359 const char *sectname;
11360 bfd_size_type size;
11361 bfd_vma lma;
11362 int matched = 0;
11363 int mismatched = 0;
11364 int res;
11365 int read_only = 0;
11367 if (!current_program_space->exec_bfd ())
11368 error (_("command cannot be used without an exec file"));
11370 if (args != NULL && strcmp (args, "-r") == 0)
11372 read_only = 1;
11373 args = NULL;
11376 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11378 if (!(s->flags & SEC_LOAD))
11379 continue; /* Skip non-loadable section. */
11381 if (read_only && (s->flags & SEC_READONLY) == 0)
11382 continue; /* Skip writeable sections */
11384 size = bfd_section_size (s);
11385 if (size == 0)
11386 continue; /* Skip zero-length section. */
11388 sectname = bfd_section_name (s);
11389 if (args && strcmp (args, sectname) != 0)
11390 continue; /* Not the section selected by user. */
11392 matched = 1; /* Do this section. */
11393 lma = s->lma;
11395 gdb::byte_vector sectdata (size);
11396 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11397 sectdata.data (), 0, size);
11399 res = target_verify_memory (sectdata.data (), lma, size);
11401 if (res == -1)
11402 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11403 paddress (current_inferior ()->arch (), lma),
11404 paddress (current_inferior ()->arch (), lma + size));
11406 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11407 paddress (current_inferior ()->arch (), lma),
11408 paddress (current_inferior ()->arch (), lma + size));
11409 if (res)
11410 gdb_printf ("matched.\n");
11411 else
11413 gdb_printf ("MIS-MATCHED!\n");
11414 mismatched++;
11417 if (mismatched > 0)
11418 warning (_("One or more sections of the target image does "
11419 "not match the loaded file"));
11420 if (args && !matched)
11421 gdb_printf (_("No loaded section named '%s'.\n"), args);
11424 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11425 into remote target. The number of bytes written to the remote
11426 target is returned, or -1 for error. */
11428 target_xfer_status
11429 remote_target::remote_write_qxfer (const char *object_name,
11430 const char *annex, const gdb_byte *writebuf,
11431 ULONGEST offset, LONGEST len,
11432 ULONGEST *xfered_len,
11433 const unsigned int which_packet)
11435 int i, buf_len;
11436 ULONGEST n;
11437 struct remote_state *rs = get_remote_state ();
11438 int max_size = get_memory_write_packet_size ();
11440 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11441 return TARGET_XFER_E_IO;
11443 /* Insert header. */
11444 i = snprintf (rs->buf.data (), max_size,
11445 "qXfer:%s:write:%s:%s:",
11446 object_name, annex ? annex : "",
11447 phex_nz (offset, sizeof offset));
11448 max_size -= (i + 1);
11450 /* Escape as much data as fits into rs->buf. */
11451 buf_len = remote_escape_output
11452 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11454 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11455 || getpkt (&rs->buf) < 0
11456 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11457 return TARGET_XFER_E_IO;
11459 unpack_varlen_hex (rs->buf.data (), &n);
11461 *xfered_len = n;
11462 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11465 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11466 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11467 number of bytes read is returned, or 0 for EOF, or -1 for error.
11468 The number of bytes read may be less than LEN without indicating an
11469 EOF. PACKET is checked and updated to indicate whether the remote
11470 target supports this object. */
11472 target_xfer_status
11473 remote_target::remote_read_qxfer (const char *object_name,
11474 const char *annex,
11475 gdb_byte *readbuf, ULONGEST offset,
11476 LONGEST len,
11477 ULONGEST *xfered_len,
11478 const unsigned int which_packet)
11480 struct remote_state *rs = get_remote_state ();
11481 LONGEST i, n, packet_len;
11483 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11484 return TARGET_XFER_E_IO;
11486 /* Check whether we've cached an end-of-object packet that matches
11487 this request. */
11488 if (rs->finished_object)
11490 if (strcmp (object_name, rs->finished_object) == 0
11491 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11492 && offset == rs->finished_offset)
11493 return TARGET_XFER_EOF;
11496 /* Otherwise, we're now reading something different. Discard
11497 the cache. */
11498 xfree (rs->finished_object);
11499 xfree (rs->finished_annex);
11500 rs->finished_object = NULL;
11501 rs->finished_annex = NULL;
11504 /* Request only enough to fit in a single packet. The actual data
11505 may not, since we don't know how much of it will need to be escaped;
11506 the target is free to respond with slightly less data. We subtract
11507 five to account for the response type and the protocol frame. */
11508 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11509 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11510 "qXfer:%s:read:%s:%s,%s",
11511 object_name, annex ? annex : "",
11512 phex_nz (offset, sizeof offset),
11513 phex_nz (n, sizeof n));
11514 i = putpkt (rs->buf);
11515 if (i < 0)
11516 return TARGET_XFER_E_IO;
11518 rs->buf[0] = '\0';
11519 packet_len = getpkt (&rs->buf);
11520 if (packet_len < 0
11521 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11522 return TARGET_XFER_E_IO;
11524 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11525 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11527 /* 'm' means there is (or at least might be) more data after this
11528 batch. That does not make sense unless there's at least one byte
11529 of data in this reply. */
11530 if (rs->buf[0] == 'm' && packet_len == 1)
11531 error (_("Remote qXfer reply contained no data."));
11533 /* Got some data. */
11534 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11535 packet_len - 1, readbuf, n);
11537 /* 'l' is an EOF marker, possibly including a final block of data,
11538 or possibly empty. If we have the final block of a non-empty
11539 object, record this fact to bypass a subsequent partial read. */
11540 if (rs->buf[0] == 'l' && offset + i > 0)
11542 rs->finished_object = xstrdup (object_name);
11543 rs->finished_annex = xstrdup (annex ? annex : "");
11544 rs->finished_offset = offset + i;
11547 if (i == 0)
11548 return TARGET_XFER_EOF;
11549 else
11551 *xfered_len = i;
11552 return TARGET_XFER_OK;
11556 enum target_xfer_status
11557 remote_target::xfer_partial (enum target_object object,
11558 const char *annex, gdb_byte *readbuf,
11559 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11560 ULONGEST *xfered_len)
11562 struct remote_state *rs;
11563 int i;
11564 char *p2;
11565 char query_type;
11566 int unit_size
11567 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11569 set_remote_traceframe ();
11570 set_general_thread (inferior_ptid);
11572 rs = get_remote_state ();
11574 /* Handle memory using the standard memory routines. */
11575 if (object == TARGET_OBJECT_MEMORY)
11577 /* If the remote target is connected but not running, we should
11578 pass this request down to a lower stratum (e.g. the executable
11579 file). */
11580 if (!target_has_execution ())
11581 return TARGET_XFER_EOF;
11583 if (writebuf != NULL)
11584 return remote_write_bytes (offset, writebuf, len, unit_size,
11585 xfered_len);
11586 else
11587 return remote_read_bytes (offset, readbuf, len, unit_size,
11588 xfered_len);
11591 /* Handle extra signal info using qxfer packets. */
11592 if (object == TARGET_OBJECT_SIGNAL_INFO)
11594 if (readbuf)
11595 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11596 xfered_len, PACKET_qXfer_siginfo_read);
11597 else
11598 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11599 xfered_len, PACKET_qXfer_siginfo_write);
11602 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11604 if (readbuf)
11605 return remote_read_qxfer ("statictrace", annex,
11606 readbuf, offset, len, xfered_len,
11607 PACKET_qXfer_statictrace_read);
11608 else
11609 return TARGET_XFER_E_IO;
11612 /* Only handle flash writes. */
11613 if (writebuf != NULL)
11615 switch (object)
11617 case TARGET_OBJECT_FLASH:
11618 return remote_flash_write (offset, len, xfered_len,
11619 writebuf);
11621 default:
11622 return TARGET_XFER_E_IO;
11626 /* Map pre-existing objects onto letters. DO NOT do this for new
11627 objects!!! Instead specify new query packets. */
11628 switch (object)
11630 case TARGET_OBJECT_AVR:
11631 query_type = 'R';
11632 break;
11634 case TARGET_OBJECT_AUXV:
11635 gdb_assert (annex == NULL);
11636 return remote_read_qxfer
11637 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11639 case TARGET_OBJECT_AVAILABLE_FEATURES:
11640 return remote_read_qxfer
11641 ("features", annex, readbuf, offset, len, xfered_len,
11642 PACKET_qXfer_features);
11644 case TARGET_OBJECT_LIBRARIES:
11645 return remote_read_qxfer
11646 ("libraries", annex, readbuf, offset, len, xfered_len,
11647 PACKET_qXfer_libraries);
11649 case TARGET_OBJECT_LIBRARIES_SVR4:
11650 return remote_read_qxfer
11651 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11652 PACKET_qXfer_libraries_svr4);
11654 case TARGET_OBJECT_MEMORY_MAP:
11655 gdb_assert (annex == NULL);
11656 return remote_read_qxfer
11657 ("memory-map", annex, readbuf, offset, len, xfered_len,
11658 PACKET_qXfer_memory_map);
11660 case TARGET_OBJECT_OSDATA:
11661 /* Should only get here if we're connected. */
11662 gdb_assert (rs->remote_desc);
11663 return remote_read_qxfer
11664 ("osdata", annex, readbuf, offset, len, xfered_len,
11665 PACKET_qXfer_osdata);
11667 case TARGET_OBJECT_THREADS:
11668 gdb_assert (annex == NULL);
11669 return remote_read_qxfer
11670 ("threads", annex, readbuf, offset, len, xfered_len,
11671 PACKET_qXfer_threads);
11673 case TARGET_OBJECT_TRACEFRAME_INFO:
11674 gdb_assert (annex == NULL);
11675 return remote_read_qxfer
11676 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11677 PACKET_qXfer_traceframe_info);
11679 case TARGET_OBJECT_FDPIC:
11680 return remote_read_qxfer
11681 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11683 case TARGET_OBJECT_OPENVMS_UIB:
11684 return remote_read_qxfer
11685 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11687 case TARGET_OBJECT_BTRACE:
11688 return remote_read_qxfer
11689 ("btrace", annex, readbuf, offset, len, xfered_len,
11690 PACKET_qXfer_btrace);
11692 case TARGET_OBJECT_BTRACE_CONF:
11693 return remote_read_qxfer
11694 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11695 PACKET_qXfer_btrace_conf);
11697 case TARGET_OBJECT_EXEC_FILE:
11698 return remote_read_qxfer
11699 ("exec-file", annex, readbuf, offset, len, xfered_len,
11700 PACKET_qXfer_exec_file);
11702 default:
11703 return TARGET_XFER_E_IO;
11706 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11707 large enough let the caller deal with it. */
11708 if (len < get_remote_packet_size ())
11709 return TARGET_XFER_E_IO;
11710 len = get_remote_packet_size ();
11712 /* Except for querying the minimum buffer size, target must be open. */
11713 if (!rs->remote_desc)
11714 error (_("remote query is only available after target open"));
11716 gdb_assert (annex != NULL);
11717 gdb_assert (readbuf != NULL);
11719 p2 = rs->buf.data ();
11720 *p2++ = 'q';
11721 *p2++ = query_type;
11723 /* We used one buffer char for the remote protocol q command and
11724 another for the query type. As the remote protocol encapsulation
11725 uses 4 chars plus one extra in case we are debugging
11726 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11727 string. */
11728 i = 0;
11729 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11731 /* Bad caller may have sent forbidden characters. */
11732 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11733 *p2++ = annex[i];
11734 i++;
11736 *p2 = '\0';
11737 gdb_assert (annex[i] == '\0');
11739 i = putpkt (rs->buf);
11740 if (i < 0)
11741 return TARGET_XFER_E_IO;
11743 getpkt (&rs->buf);
11744 strcpy ((char *) readbuf, rs->buf.data ());
11746 *xfered_len = strlen ((char *) readbuf);
11747 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11750 /* Implementation of to_get_memory_xfer_limit. */
11752 ULONGEST
11753 remote_target::get_memory_xfer_limit ()
11755 return get_memory_write_packet_size ();
11759 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11760 const gdb_byte *pattern, ULONGEST pattern_len,
11761 CORE_ADDR *found_addrp)
11763 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11764 struct remote_state *rs = get_remote_state ();
11765 int max_size = get_memory_write_packet_size ();
11767 /* Number of packet bytes used to encode the pattern;
11768 this could be more than PATTERN_LEN due to escape characters. */
11769 int escaped_pattern_len;
11770 /* Amount of pattern that was encodable in the packet. */
11771 int used_pattern_len;
11772 int i;
11773 int found;
11774 ULONGEST found_addr;
11776 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11778 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11779 == len);
11782 /* Don't go to the target if we don't have to. This is done before
11783 checking packet_support to avoid the possibility that a success for this
11784 edge case means the facility works in general. */
11785 if (pattern_len > search_space_len)
11786 return 0;
11787 if (pattern_len == 0)
11789 *found_addrp = start_addr;
11790 return 1;
11793 /* If we already know the packet isn't supported, fall back to the simple
11794 way of searching memory. */
11796 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11798 /* Target doesn't provided special support, fall back and use the
11799 standard support (copy memory and do the search here). */
11800 return simple_search_memory (read_memory, start_addr, search_space_len,
11801 pattern, pattern_len, found_addrp);
11804 /* Make sure the remote is pointing at the right process. */
11805 set_general_process ();
11807 /* Insert header. */
11808 i = snprintf (rs->buf.data (), max_size,
11809 "qSearch:memory:%s;%s;",
11810 phex_nz (start_addr, addr_size),
11811 phex_nz (search_space_len, sizeof (search_space_len)));
11812 max_size -= (i + 1);
11814 /* Escape as much data as fits into rs->buf. */
11815 escaped_pattern_len =
11816 remote_escape_output (pattern, pattern_len, 1,
11817 (gdb_byte *) rs->buf.data () + i,
11818 &used_pattern_len, max_size);
11820 /* Bail if the pattern is too large. */
11821 if (used_pattern_len != pattern_len)
11822 error (_("Pattern is too large to transmit to remote target."));
11824 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11825 || getpkt (&rs->buf) < 0
11826 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11828 /* The request may not have worked because the command is not
11829 supported. If so, fall back to the simple way. */
11830 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11832 return simple_search_memory (read_memory, start_addr, search_space_len,
11833 pattern, pattern_len, found_addrp);
11835 return -1;
11838 if (rs->buf[0] == '0')
11839 found = 0;
11840 else if (rs->buf[0] == '1')
11842 found = 1;
11843 if (rs->buf[1] != ',')
11844 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11845 unpack_varlen_hex (&rs->buf[2], &found_addr);
11846 *found_addrp = found_addr;
11848 else
11849 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11851 return found;
11854 void
11855 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11857 struct remote_state *rs = get_remote_state ();
11858 char *p = rs->buf.data ();
11860 if (!rs->remote_desc)
11861 error (_("remote rcmd is only available after target open"));
11863 /* Send a NULL command across as an empty command. */
11864 if (command == NULL)
11865 command = "";
11867 /* The query prefix. */
11868 strcpy (rs->buf.data (), "qRcmd,");
11869 p = strchr (rs->buf.data (), '\0');
11871 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11872 > get_remote_packet_size ())
11873 error (_("\"monitor\" command ``%s'' is too long."), command);
11875 /* Encode the actual command. */
11876 bin2hex ((const gdb_byte *) command, p, strlen (command));
11878 if (putpkt (rs->buf) < 0)
11879 error (_("Communication problem with target."));
11881 /* get/display the response */
11882 while (1)
11884 char *buf;
11886 /* XXX - see also remote_get_noisy_reply(). */
11887 QUIT; /* Allow user to bail out with ^C. */
11888 rs->buf[0] = '\0';
11889 if (getpkt (&rs->buf) == -1)
11891 /* Timeout. Continue to (try to) read responses.
11892 This is better than stopping with an error, assuming the stub
11893 is still executing the (long) monitor command.
11894 If needed, the user can interrupt gdb using C-c, obtaining
11895 an effect similar to stop on timeout. */
11896 continue;
11898 buf = rs->buf.data ();
11899 if (buf[0] == '\0')
11900 error (_("Target does not support this command."));
11901 if (buf[0] == 'O' && buf[1] != 'K')
11903 remote_console_output (buf + 1); /* 'O' message from stub. */
11904 continue;
11906 if (strcmp (buf, "OK") == 0)
11907 break;
11908 if (strlen (buf) == 3 && buf[0] == 'E'
11909 && isxdigit (buf[1]) && isxdigit (buf[2]))
11911 error (_("Protocol error with Rcmd"));
11913 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11915 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11917 gdb_putc (c, outbuf);
11919 break;
11923 std::vector<mem_region>
11924 remote_target::memory_map ()
11926 std::vector<mem_region> result;
11927 std::optional<gdb::char_vector> text
11928 = target_read_stralloc (current_inferior ()->top_target (),
11929 TARGET_OBJECT_MEMORY_MAP, NULL);
11931 if (text)
11932 result = parse_memory_map (text->data ());
11934 return result;
11937 /* Set of callbacks used to implement the 'maint packet' command. */
11939 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11941 /* Called before the packet is sent. BUF is the packet content before
11942 the protocol specific prefix, suffix, and escaping is added. */
11944 void sending (gdb::array_view<const char> &buf) override
11946 gdb_puts ("sending: ");
11947 print_packet (buf);
11948 gdb_puts ("\n");
11951 /* Called with BUF, the reply from the remote target. */
11953 void received (gdb::array_view<const char> &buf) override
11955 gdb_puts ("received: \"");
11956 print_packet (buf);
11957 gdb_puts ("\"\n");
11960 private:
11962 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11963 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11965 static void
11966 print_packet (gdb::array_view<const char> &buf)
11968 string_file stb;
11970 for (int i = 0; i < buf.size (); ++i)
11972 gdb_byte c = buf[i];
11973 if (isprint (c))
11974 gdb_putc (c, &stb);
11975 else
11976 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11979 gdb_puts (stb.string ().c_str ());
11983 /* See remote.h. */
11985 void
11986 send_remote_packet (gdb::array_view<const char> &buf,
11987 send_remote_packet_callbacks *callbacks)
11989 if (buf.size () == 0 || buf.data ()[0] == '\0')
11990 error (_("a remote packet must not be empty"));
11992 remote_target *remote = get_current_remote_target ();
11993 if (remote == nullptr)
11994 error (_("packets can only be sent to a remote target"));
11996 callbacks->sending (buf);
11998 remote->putpkt_binary (buf.data (), buf.size ());
11999 remote_state *rs = remote->get_remote_state ();
12000 int bytes = remote->getpkt (&rs->buf);
12002 if (bytes < 0)
12003 error (_("error while fetching packet from remote target"));
12005 gdb::array_view<const char> view (&rs->buf[0], bytes);
12006 callbacks->received (view);
12009 /* Entry point for the 'maint packet' command. */
12011 static void
12012 cli_packet_command (const char *args, int from_tty)
12014 cli_packet_command_callbacks cb;
12015 gdb::array_view<const char> view
12016 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
12017 send_remote_packet (view, &cb);
12020 #if 0
12021 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12023 static void display_thread_info (struct gdb_ext_thread_info *info);
12025 static void threadset_test_cmd (char *cmd, int tty);
12027 static void threadalive_test (char *cmd, int tty);
12029 static void threadlist_test_cmd (char *cmd, int tty);
12031 int get_and_display_threadinfo (threadref *ref);
12033 static void threadinfo_test_cmd (char *cmd, int tty);
12035 static int thread_display_step (threadref *ref, void *context);
12037 static void threadlist_update_test_cmd (char *cmd, int tty);
12039 static void init_remote_threadtests (void);
12041 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12043 static void
12044 threadset_test_cmd (const char *cmd, int tty)
12046 int sample_thread = SAMPLE_THREAD;
12048 gdb_printf (_("Remote threadset test\n"));
12049 set_general_thread (sample_thread);
12053 static void
12054 threadalive_test (const char *cmd, int tty)
12056 int sample_thread = SAMPLE_THREAD;
12057 int pid = inferior_ptid.pid ();
12058 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12060 if (remote_thread_alive (ptid))
12061 gdb_printf ("PASS: Thread alive test\n");
12062 else
12063 gdb_printf ("FAIL: Thread alive test\n");
12066 void output_threadid (char *title, threadref *ref);
12068 void
12069 output_threadid (char *title, threadref *ref)
12071 char hexid[20];
12073 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12074 hexid[16] = 0;
12075 gdb_printf ("%s %s\n", title, (&hexid[0]));
12078 static void
12079 threadlist_test_cmd (const char *cmd, int tty)
12081 int startflag = 1;
12082 threadref nextthread;
12083 int done, result_count;
12084 threadref threadlist[3];
12086 gdb_printf ("Remote Threadlist test\n");
12087 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12088 &result_count, &threadlist[0]))
12089 gdb_printf ("FAIL: threadlist test\n");
12090 else
12092 threadref *scan = threadlist;
12093 threadref *limit = scan + result_count;
12095 while (scan < limit)
12096 output_threadid (" thread ", scan++);
12100 void
12101 display_thread_info (struct gdb_ext_thread_info *info)
12103 output_threadid ("Threadid: ", &info->threadid);
12104 gdb_printf ("Name: %s\n ", info->shortname);
12105 gdb_printf ("State: %s\n", info->display);
12106 gdb_printf ("other: %s\n\n", info->more_display);
12110 get_and_display_threadinfo (threadref *ref)
12112 int result;
12113 int set;
12114 struct gdb_ext_thread_info threadinfo;
12116 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12117 | TAG_MOREDISPLAY | TAG_DISPLAY;
12118 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12119 display_thread_info (&threadinfo);
12120 return result;
12123 static void
12124 threadinfo_test_cmd (const char *cmd, int tty)
12126 int athread = SAMPLE_THREAD;
12127 threadref thread;
12128 int set;
12130 int_to_threadref (&thread, athread);
12131 gdb_printf ("Remote Threadinfo test\n");
12132 if (!get_and_display_threadinfo (&thread))
12133 gdb_printf ("FAIL cannot get thread info\n");
12136 static int
12137 thread_display_step (threadref *ref, void *context)
12139 /* output_threadid(" threadstep ",ref); *//* simple test */
12140 return get_and_display_threadinfo (ref);
12143 static void
12144 threadlist_update_test_cmd (const char *cmd, int tty)
12146 gdb_printf ("Remote Threadlist update test\n");
12147 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12150 static void
12151 init_remote_threadtests (void)
12153 add_com ("tlist", class_obscure, threadlist_test_cmd,
12154 _("Fetch and print the remote list of "
12155 "thread identifiers, one pkt only."));
12156 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12157 _("Fetch and display info about one thread."));
12158 add_com ("tset", class_obscure, threadset_test_cmd,
12159 _("Test setting to a different thread."));
12160 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12161 _("Iterate through updating all remote thread info."));
12162 add_com ("talive", class_obscure, threadalive_test,
12163 _("Remote thread alive test."));
12166 #endif /* 0 */
12168 /* Convert a thread ID to a string. */
12170 std::string
12171 remote_target::pid_to_str (ptid_t ptid)
12173 if (ptid == null_ptid)
12174 return normal_pid_to_str (ptid);
12175 else if (ptid.is_pid ())
12177 /* Printing an inferior target id. */
12179 /* When multi-process extensions are off, there's no way in the
12180 remote protocol to know the remote process id, if there's any
12181 at all. There's one exception --- when we're connected with
12182 target extended-remote, and we manually attached to a process
12183 with "attach PID". We don't record anywhere a flag that
12184 allows us to distinguish that case from the case of
12185 connecting with extended-remote and the stub already being
12186 attached to a process, and reporting yes to qAttached, hence
12187 no smart special casing here. */
12188 if (!m_features.remote_multi_process_p ())
12189 return "Remote target";
12191 return normal_pid_to_str (ptid);
12193 else
12195 if (magic_null_ptid == ptid)
12196 return "Thread <main>";
12197 else if (m_features.remote_multi_process_p ())
12198 if (ptid.lwp () == 0)
12199 return normal_pid_to_str (ptid);
12200 else
12201 return string_printf ("Thread %d.%ld",
12202 ptid.pid (), ptid.lwp ());
12203 else
12204 return string_printf ("Thread %ld", ptid.lwp ());
12208 /* Get the address of the thread local variable in OBJFILE which is
12209 stored at OFFSET within the thread local storage for thread PTID. */
12211 CORE_ADDR
12212 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12213 CORE_ADDR offset)
12215 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12217 struct remote_state *rs = get_remote_state ();
12218 char *p = rs->buf.data ();
12219 char *endp = p + get_remote_packet_size ();
12220 enum packet_result result;
12222 strcpy (p, "qGetTLSAddr:");
12223 p += strlen (p);
12224 p = write_ptid (p, endp, ptid);
12225 *p++ = ',';
12226 p += hexnumstr (p, offset);
12227 *p++ = ',';
12228 p += hexnumstr (p, lm);
12229 *p++ = '\0';
12231 putpkt (rs->buf);
12232 getpkt (&rs->buf);
12233 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12234 if (result == PACKET_OK)
12236 ULONGEST addr;
12238 unpack_varlen_hex (rs->buf.data (), &addr);
12239 return addr;
12241 else if (result == PACKET_UNKNOWN)
12242 throw_error (TLS_GENERIC_ERROR,
12243 _("Remote target doesn't support qGetTLSAddr packet"));
12244 else
12245 throw_error (TLS_GENERIC_ERROR,
12246 _("Remote target failed to process qGetTLSAddr request"));
12248 else
12249 throw_error (TLS_GENERIC_ERROR,
12250 _("TLS not supported or disabled on this target"));
12251 /* Not reached. */
12252 return 0;
12255 /* Provide thread local base, i.e. Thread Information Block address.
12256 Returns 1 if ptid is found and thread_local_base is non zero. */
12258 bool
12259 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12261 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12263 struct remote_state *rs = get_remote_state ();
12264 char *p = rs->buf.data ();
12265 char *endp = p + get_remote_packet_size ();
12266 enum packet_result result;
12268 strcpy (p, "qGetTIBAddr:");
12269 p += strlen (p);
12270 p = write_ptid (p, endp, ptid);
12271 *p++ = '\0';
12273 putpkt (rs->buf);
12274 getpkt (&rs->buf);
12275 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12276 if (result == PACKET_OK)
12278 ULONGEST val;
12279 unpack_varlen_hex (rs->buf.data (), &val);
12280 if (addr)
12281 *addr = (CORE_ADDR) val;
12282 return true;
12284 else if (result == PACKET_UNKNOWN)
12285 error (_("Remote target doesn't support qGetTIBAddr packet"));
12286 else
12287 error (_("Remote target failed to process qGetTIBAddr request"));
12289 else
12290 error (_("qGetTIBAddr not supported or disabled on this target"));
12291 /* Not reached. */
12292 return false;
12295 /* Support for inferring a target description based on the current
12296 architecture and the size of a 'g' packet. While the 'g' packet
12297 can have any size (since optional registers can be left off the
12298 end), some sizes are easily recognizable given knowledge of the
12299 approximate architecture. */
12301 struct remote_g_packet_guess
12303 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12304 : bytes (bytes_),
12305 tdesc (tdesc_)
12309 int bytes;
12310 const struct target_desc *tdesc;
12313 struct remote_g_packet_data
12315 std::vector<remote_g_packet_guess> guesses;
12318 static const registry<gdbarch>::key<struct remote_g_packet_data>
12319 remote_g_packet_data_handle;
12321 static struct remote_g_packet_data *
12322 get_g_packet_data (struct gdbarch *gdbarch)
12324 struct remote_g_packet_data *data
12325 = remote_g_packet_data_handle.get (gdbarch);
12326 if (data == nullptr)
12327 data = remote_g_packet_data_handle.emplace (gdbarch);
12328 return data;
12331 void
12332 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12333 const struct target_desc *tdesc)
12335 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12337 gdb_assert (tdesc != NULL);
12339 for (const remote_g_packet_guess &guess : data->guesses)
12340 if (guess.bytes == bytes)
12341 internal_error (_("Duplicate g packet description added for size %d"),
12342 bytes);
12344 data->guesses.emplace_back (bytes, tdesc);
12347 /* Return true if remote_read_description would do anything on this target
12348 and architecture, false otherwise. */
12350 static bool
12351 remote_read_description_p (struct target_ops *target)
12353 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12355 return !data->guesses.empty ();
12358 const struct target_desc *
12359 remote_target::read_description ()
12361 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12363 /* Do not try this during initial connection, when we do not know
12364 whether there is a running but stopped thread. */
12365 if (!target_has_execution () || inferior_ptid == null_ptid)
12366 return beneath ()->read_description ();
12368 if (!data->guesses.empty ())
12370 int bytes = send_g_packet ();
12372 for (const remote_g_packet_guess &guess : data->guesses)
12373 if (guess.bytes == bytes)
12374 return guess.tdesc;
12376 /* We discard the g packet. A minor optimization would be to
12377 hold on to it, and fill the register cache once we have selected
12378 an architecture, but it's too tricky to do safely. */
12381 return beneath ()->read_description ();
12384 /* Remote file transfer support. This is host-initiated I/O, not
12385 target-initiated; for target-initiated, see remote-fileio.c. */
12387 /* If *LEFT is at least the length of STRING, copy STRING to
12388 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12389 decrease *LEFT. Otherwise raise an error. */
12391 static void
12392 remote_buffer_add_string (char **buffer, int *left, const char *string)
12394 int len = strlen (string);
12396 if (len > *left)
12397 error (_("Packet too long for target."));
12399 memcpy (*buffer, string, len);
12400 *buffer += len;
12401 *left -= len;
12403 /* NUL-terminate the buffer as a convenience, if there is
12404 room. */
12405 if (*left)
12406 **buffer = '\0';
12409 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12410 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12411 decrease *LEFT. Otherwise raise an error. */
12413 static void
12414 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12415 int len)
12417 if (2 * len > *left)
12418 error (_("Packet too long for target."));
12420 bin2hex (bytes, *buffer, len);
12421 *buffer += 2 * len;
12422 *left -= 2 * len;
12424 /* NUL-terminate the buffer as a convenience, if there is
12425 room. */
12426 if (*left)
12427 **buffer = '\0';
12430 /* If *LEFT is large enough, convert VALUE to hex and add it to
12431 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12432 decrease *LEFT. Otherwise raise an error. */
12434 static void
12435 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12437 int len = hexnumlen (value);
12439 if (len > *left)
12440 error (_("Packet too long for target."));
12442 hexnumstr (*buffer, value);
12443 *buffer += len;
12444 *left -= len;
12446 /* NUL-terminate the buffer as a convenience, if there is
12447 room. */
12448 if (*left)
12449 **buffer = '\0';
12452 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12453 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12454 was included, and *ATTACHMENT to point to the start of the annex
12455 if any. The length of the packet isn't needed here; there may
12456 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12458 Return 0 if the packet could be parsed, -1 if it could not. If
12459 -1 is returned, the other variables may not be initialized. */
12461 static int
12462 remote_hostio_parse_result (const char *buffer, int *retcode,
12463 fileio_error *remote_errno, const char **attachment)
12465 char *p, *p2;
12467 *remote_errno = FILEIO_SUCCESS;
12468 *attachment = NULL;
12470 if (buffer[0] != 'F')
12471 return -1;
12473 errno = 0;
12474 *retcode = strtol (&buffer[1], &p, 16);
12475 if (errno != 0 || p == &buffer[1])
12476 return -1;
12478 /* Check for ",errno". */
12479 if (*p == ',')
12481 errno = 0;
12482 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12483 if (errno != 0 || p + 1 == p2)
12484 return -1;
12485 p = p2;
12488 /* Check for ";attachment". If there is no attachment, the
12489 packet should end here. */
12490 if (*p == ';')
12492 *attachment = p + 1;
12493 return 0;
12495 else if (*p == '\0')
12496 return 0;
12497 else
12498 return -1;
12501 /* Send a prepared I/O packet to the target and read its response.
12502 The prepared packet is in the global RS->BUF before this function
12503 is called, and the answer is there when we return.
12505 COMMAND_BYTES is the length of the request to send, which may include
12506 binary data. WHICH_PACKET is the packet configuration to check
12507 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12508 is set to the error number and -1 is returned. Otherwise the value
12509 returned by the function is returned.
12511 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12512 attachment is expected; an error will be reported if there's a
12513 mismatch. If one is found, *ATTACHMENT will be set to point into
12514 the packet buffer and *ATTACHMENT_LEN will be set to the
12515 attachment's length. */
12518 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12519 fileio_error *remote_errno, const char **attachment,
12520 int *attachment_len)
12522 struct remote_state *rs = get_remote_state ();
12523 int ret, bytes_read;
12524 const char *attachment_tmp;
12526 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12528 *remote_errno = FILEIO_ENOSYS;
12529 return -1;
12532 putpkt_binary (rs->buf.data (), command_bytes);
12533 bytes_read = getpkt (&rs->buf);
12535 /* If it timed out, something is wrong. Don't try to parse the
12536 buffer. */
12537 if (bytes_read < 0)
12539 *remote_errno = FILEIO_EINVAL;
12540 return -1;
12543 switch (m_features.packet_ok (rs->buf, which_packet))
12545 case PACKET_ERROR:
12546 *remote_errno = FILEIO_EINVAL;
12547 return -1;
12548 case PACKET_UNKNOWN:
12549 *remote_errno = FILEIO_ENOSYS;
12550 return -1;
12551 case PACKET_OK:
12552 break;
12555 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12556 &attachment_tmp))
12558 *remote_errno = FILEIO_EINVAL;
12559 return -1;
12562 /* Make sure we saw an attachment if and only if we expected one. */
12563 if ((attachment_tmp == NULL && attachment != NULL)
12564 || (attachment_tmp != NULL && attachment == NULL))
12566 *remote_errno = FILEIO_EINVAL;
12567 return -1;
12570 /* If an attachment was found, it must point into the packet buffer;
12571 work out how many bytes there were. */
12572 if (attachment_tmp != NULL)
12574 *attachment = attachment_tmp;
12575 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12578 return ret;
12581 /* See declaration.h. */
12583 void
12584 readahead_cache::invalidate ()
12586 this->fd = -1;
12589 /* See declaration.h. */
12591 void
12592 readahead_cache::invalidate_fd (int fd)
12594 if (this->fd == fd)
12595 this->fd = -1;
12598 /* Set the filesystem remote_hostio functions that take FILENAME
12599 arguments will use. Return 0 on success, or -1 if an error
12600 occurs (and set *REMOTE_ERRNO). */
12603 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12604 fileio_error *remote_errno)
12606 struct remote_state *rs = get_remote_state ();
12607 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12608 char *p = rs->buf.data ();
12609 int left = get_remote_packet_size () - 1;
12610 char arg[9];
12611 int ret;
12613 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12614 return 0;
12616 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12617 return 0;
12619 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12621 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12622 remote_buffer_add_string (&p, &left, arg);
12624 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12625 remote_errno, NULL, NULL);
12627 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12628 return 0;
12630 if (ret == 0)
12631 rs->fs_pid = required_pid;
12633 return ret;
12636 /* Implementation of to_fileio_open. */
12639 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12640 int flags, int mode, int warn_if_slow,
12641 fileio_error *remote_errno)
12643 struct remote_state *rs = get_remote_state ();
12644 char *p = rs->buf.data ();
12645 int left = get_remote_packet_size () - 1;
12647 if (warn_if_slow)
12649 static int warning_issued = 0;
12651 gdb_printf (_("Reading %s from remote target...\n"),
12652 filename);
12654 if (!warning_issued)
12656 warning (_("File transfers from remote targets can be slow."
12657 " Use \"set sysroot\" to access files locally"
12658 " instead."));
12659 warning_issued = 1;
12663 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12664 return -1;
12666 remote_buffer_add_string (&p, &left, "vFile:open:");
12668 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12669 strlen (filename));
12670 remote_buffer_add_string (&p, &left, ",");
12672 remote_buffer_add_int (&p, &left, flags);
12673 remote_buffer_add_string (&p, &left, ",");
12675 remote_buffer_add_int (&p, &left, mode);
12677 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12678 remote_errno, NULL, NULL);
12682 remote_target::fileio_open (struct inferior *inf, const char *filename,
12683 int flags, int mode, int warn_if_slow,
12684 fileio_error *remote_errno)
12686 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12687 remote_errno);
12690 /* Implementation of to_fileio_pwrite. */
12693 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12694 ULONGEST offset, fileio_error *remote_errno)
12696 struct remote_state *rs = get_remote_state ();
12697 char *p = rs->buf.data ();
12698 int left = get_remote_packet_size ();
12699 int out_len;
12701 rs->readahead_cache.invalidate_fd (fd);
12703 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12705 remote_buffer_add_int (&p, &left, fd);
12706 remote_buffer_add_string (&p, &left, ",");
12708 remote_buffer_add_int (&p, &left, offset);
12709 remote_buffer_add_string (&p, &left, ",");
12711 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12712 (get_remote_packet_size ()
12713 - (p - rs->buf.data ())));
12715 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12716 remote_errno, NULL, NULL);
12720 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12721 ULONGEST offset, fileio_error *remote_errno)
12723 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12726 /* Helper for the implementation of to_fileio_pread. Read the file
12727 from the remote side with vFile:pread. */
12730 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12731 ULONGEST offset, fileio_error *remote_errno)
12733 struct remote_state *rs = get_remote_state ();
12734 char *p = rs->buf.data ();
12735 const char *attachment;
12736 int left = get_remote_packet_size ();
12737 int ret, attachment_len;
12738 int read_len;
12740 remote_buffer_add_string (&p, &left, "vFile:pread:");
12742 remote_buffer_add_int (&p, &left, fd);
12743 remote_buffer_add_string (&p, &left, ",");
12745 remote_buffer_add_int (&p, &left, len);
12746 remote_buffer_add_string (&p, &left, ",");
12748 remote_buffer_add_int (&p, &left, offset);
12750 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12751 remote_errno, &attachment,
12752 &attachment_len);
12754 if (ret < 0)
12755 return ret;
12757 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12758 read_buf, len);
12759 if (read_len != ret)
12760 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12762 return ret;
12765 /* See declaration.h. */
12768 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12769 ULONGEST offset)
12771 if (this->fd == fd
12772 && this->offset <= offset
12773 && offset < this->offset + this->buf.size ())
12775 ULONGEST max = this->offset + this->buf.size ();
12777 if (offset + len > max)
12778 len = max - offset;
12780 memcpy (read_buf, &this->buf[offset - this->offset], len);
12781 return len;
12784 return 0;
12787 /* Implementation of to_fileio_pread. */
12790 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12791 ULONGEST offset, fileio_error *remote_errno)
12793 int ret;
12794 struct remote_state *rs = get_remote_state ();
12795 readahead_cache *cache = &rs->readahead_cache;
12797 ret = cache->pread (fd, read_buf, len, offset);
12798 if (ret > 0)
12800 cache->hit_count++;
12802 remote_debug_printf ("readahead cache hit %s",
12803 pulongest (cache->hit_count));
12804 return ret;
12807 cache->miss_count++;
12809 remote_debug_printf ("readahead cache miss %s",
12810 pulongest (cache->miss_count));
12812 cache->fd = fd;
12813 cache->offset = offset;
12814 cache->buf.resize (get_remote_packet_size ());
12816 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12817 cache->buf.size (),
12818 cache->offset, remote_errno);
12819 if (ret <= 0)
12821 cache->invalidate_fd (fd);
12822 return ret;
12825 cache->buf.resize (ret);
12826 return cache->pread (fd, read_buf, len, offset);
12830 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12831 ULONGEST offset, fileio_error *remote_errno)
12833 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12836 /* Implementation of to_fileio_close. */
12839 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12841 struct remote_state *rs = get_remote_state ();
12842 char *p = rs->buf.data ();
12843 int left = get_remote_packet_size () - 1;
12845 rs->readahead_cache.invalidate_fd (fd);
12847 remote_buffer_add_string (&p, &left, "vFile:close:");
12849 remote_buffer_add_int (&p, &left, fd);
12851 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12852 remote_errno, NULL, NULL);
12856 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12858 return remote_hostio_close (fd, remote_errno);
12861 /* Implementation of to_fileio_unlink. */
12864 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12865 fileio_error *remote_errno)
12867 struct remote_state *rs = get_remote_state ();
12868 char *p = rs->buf.data ();
12869 int left = get_remote_packet_size () - 1;
12871 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12872 return -1;
12874 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12876 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12877 strlen (filename));
12879 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12880 remote_errno, NULL, NULL);
12884 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12885 fileio_error *remote_errno)
12887 return remote_hostio_unlink (inf, filename, remote_errno);
12890 /* Implementation of to_fileio_readlink. */
12892 std::optional<std::string>
12893 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12894 fileio_error *remote_errno)
12896 struct remote_state *rs = get_remote_state ();
12897 char *p = rs->buf.data ();
12898 const char *attachment;
12899 int left = get_remote_packet_size ();
12900 int len, attachment_len;
12901 int read_len;
12903 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12904 return {};
12906 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12908 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12909 strlen (filename));
12911 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12912 remote_errno, &attachment,
12913 &attachment_len);
12915 if (len < 0)
12916 return {};
12918 std::string ret (len, '\0');
12920 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12921 (gdb_byte *) &ret[0], len);
12922 if (read_len != len)
12923 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12925 return ret;
12928 /* Implementation of to_fileio_fstat. */
12931 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12933 struct remote_state *rs = get_remote_state ();
12934 char *p = rs->buf.data ();
12935 int left = get_remote_packet_size ();
12936 int attachment_len, ret;
12937 const char *attachment;
12938 struct fio_stat fst;
12939 int read_len;
12941 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12943 remote_buffer_add_int (&p, &left, fd);
12945 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12946 remote_errno, &attachment,
12947 &attachment_len);
12948 if (ret < 0)
12950 if (*remote_errno != FILEIO_ENOSYS)
12951 return ret;
12953 /* Strictly we should return -1, ENOSYS here, but when
12954 "set sysroot remote:" was implemented in August 2008
12955 BFD's need for a stat function was sidestepped with
12956 this hack. This was not remedied until March 2015
12957 so we retain the previous behavior to avoid breaking
12958 compatibility.
12960 Note that the memset is a March 2015 addition; older
12961 GDBs set st_size *and nothing else* so the structure
12962 would have garbage in all other fields. This might
12963 break something but retaining the previous behavior
12964 here would be just too wrong. */
12966 memset (st, 0, sizeof (struct stat));
12967 st->st_size = INT_MAX;
12968 return 0;
12971 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12972 (gdb_byte *) &fst, sizeof (fst));
12974 if (read_len != ret)
12975 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12977 if (read_len != sizeof (fst))
12978 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12979 read_len, (int) sizeof (fst));
12981 remote_fileio_to_host_stat (&fst, st);
12983 return 0;
12986 /* Implementation of to_filesystem_is_local. */
12988 bool
12989 remote_target::filesystem_is_local ()
12991 /* Valgrind GDB presents itself as a remote target but works
12992 on the local filesystem: it does not implement remote get
12993 and users are not expected to set a sysroot. To handle
12994 this case we treat the remote filesystem as local if the
12995 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12996 does not support vFile:open. */
12997 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12999 packet_support ps = m_features.packet_support (PACKET_vFile_open);
13001 if (ps == PACKET_SUPPORT_UNKNOWN)
13003 int fd;
13004 fileio_error remote_errno;
13006 /* Try opening a file to probe support. The supplied
13007 filename is irrelevant, we only care about whether
13008 the stub recognizes the packet or not. */
13009 fd = remote_hostio_open (NULL, "just probing",
13010 FILEIO_O_RDONLY, 0700, 0,
13011 &remote_errno);
13013 if (fd >= 0)
13014 remote_hostio_close (fd, &remote_errno);
13016 ps = m_features.packet_support (PACKET_vFile_open);
13019 if (ps == PACKET_DISABLE)
13021 static int warning_issued = 0;
13023 if (!warning_issued)
13025 warning (_("remote target does not support file"
13026 " transfer, attempting to access files"
13027 " from local filesystem."));
13028 warning_issued = 1;
13031 return true;
13035 return false;
13038 static char *
13039 remote_hostio_error (fileio_error errnum)
13041 int host_error = fileio_error_to_host (errnum);
13043 if (host_error == -1)
13044 error (_("Unknown remote I/O error %d"), errnum);
13045 else
13046 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13049 /* A RAII wrapper around a remote file descriptor. */
13051 class scoped_remote_fd
13053 public:
13054 scoped_remote_fd (remote_target *remote, int fd)
13055 : m_remote (remote), m_fd (fd)
13059 ~scoped_remote_fd ()
13061 if (m_fd != -1)
13065 fileio_error remote_errno;
13066 m_remote->remote_hostio_close (m_fd, &remote_errno);
13068 catch (...)
13070 /* Swallow exception before it escapes the dtor. If
13071 something goes wrong, likely the connection is gone,
13072 and there's nothing else that can be done. */
13077 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13079 /* Release ownership of the file descriptor, and return it. */
13080 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13082 int fd = m_fd;
13083 m_fd = -1;
13084 return fd;
13087 /* Return the owned file descriptor. */
13088 int get () const noexcept
13090 return m_fd;
13093 private:
13094 /* The remote target. */
13095 remote_target *m_remote;
13097 /* The owned remote I/O file descriptor. */
13098 int m_fd;
13101 void
13102 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13104 remote_target *remote = get_current_remote_target ();
13106 if (remote == nullptr)
13107 error (_("command can only be used with remote target"));
13109 remote->remote_file_put (local_file, remote_file, from_tty);
13112 void
13113 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13114 int from_tty)
13116 int retcode, bytes, io_size;
13117 fileio_error remote_errno;
13118 int bytes_in_buffer;
13119 int saw_eof;
13120 ULONGEST offset;
13122 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13123 if (file == NULL)
13124 perror_with_name (local_file);
13126 scoped_remote_fd fd
13127 (this, remote_hostio_open (NULL,
13128 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13129 | FILEIO_O_TRUNC),
13130 0700, 0, &remote_errno));
13131 if (fd.get () == -1)
13132 remote_hostio_error (remote_errno);
13134 /* Send up to this many bytes at once. They won't all fit in the
13135 remote packet limit, so we'll transfer slightly fewer. */
13136 io_size = get_remote_packet_size ();
13137 gdb::byte_vector buffer (io_size);
13139 bytes_in_buffer = 0;
13140 saw_eof = 0;
13141 offset = 0;
13142 while (bytes_in_buffer || !saw_eof)
13144 if (!saw_eof)
13146 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13147 io_size - bytes_in_buffer,
13148 file.get ());
13149 if (bytes == 0)
13151 if (ferror (file.get ()))
13152 error (_("Error reading %s."), local_file);
13153 else
13155 /* EOF. Unless there is something still in the
13156 buffer from the last iteration, we are done. */
13157 saw_eof = 1;
13158 if (bytes_in_buffer == 0)
13159 break;
13163 else
13164 bytes = 0;
13166 bytes += bytes_in_buffer;
13167 bytes_in_buffer = 0;
13169 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13170 offset, &remote_errno);
13172 if (retcode < 0)
13173 remote_hostio_error (remote_errno);
13174 else if (retcode == 0)
13175 error (_("Remote write of %d bytes returned 0!"), bytes);
13176 else if (retcode < bytes)
13178 /* Short write. Save the rest of the read data for the next
13179 write. */
13180 bytes_in_buffer = bytes - retcode;
13181 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13184 offset += retcode;
13187 if (remote_hostio_close (fd.release (), &remote_errno))
13188 remote_hostio_error (remote_errno);
13190 if (from_tty)
13191 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13194 void
13195 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13197 remote_target *remote = get_current_remote_target ();
13199 if (remote == nullptr)
13200 error (_("command can only be used with remote target"));
13202 remote->remote_file_get (remote_file, local_file, from_tty);
13205 void
13206 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13207 int from_tty)
13209 fileio_error remote_errno;
13210 int bytes, io_size;
13211 ULONGEST offset;
13213 scoped_remote_fd fd
13214 (this, remote_hostio_open (NULL,
13215 remote_file, FILEIO_O_RDONLY, 0, 0,
13216 &remote_errno));
13217 if (fd.get () == -1)
13218 remote_hostio_error (remote_errno);
13220 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13221 if (file == NULL)
13222 perror_with_name (local_file);
13224 /* Send up to this many bytes at once. They won't all fit in the
13225 remote packet limit, so we'll transfer slightly fewer. */
13226 io_size = get_remote_packet_size ();
13227 gdb::byte_vector buffer (io_size);
13229 offset = 0;
13230 while (1)
13232 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13233 &remote_errno);
13234 if (bytes == 0)
13235 /* Success, but no bytes, means end-of-file. */
13236 break;
13237 if (bytes == -1)
13238 remote_hostio_error (remote_errno);
13240 offset += bytes;
13242 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13243 if (bytes == 0)
13244 perror_with_name (local_file);
13247 if (remote_hostio_close (fd.release (), &remote_errno))
13248 remote_hostio_error (remote_errno);
13250 if (from_tty)
13251 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13254 void
13255 remote_file_delete (const char *remote_file, int from_tty)
13257 remote_target *remote = get_current_remote_target ();
13259 if (remote == nullptr)
13260 error (_("command can only be used with remote target"));
13262 remote->remote_file_delete (remote_file, from_tty);
13265 void
13266 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13268 int retcode;
13269 fileio_error remote_errno;
13271 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13272 if (retcode == -1)
13273 remote_hostio_error (remote_errno);
13275 if (from_tty)
13276 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13279 static void
13280 remote_put_command (const char *args, int from_tty)
13282 if (args == NULL)
13283 error_no_arg (_("file to put"));
13285 gdb_argv argv (args);
13286 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13287 error (_("Invalid parameters to remote put"));
13289 remote_file_put (argv[0], argv[1], from_tty);
13292 static void
13293 remote_get_command (const char *args, int from_tty)
13295 if (args == NULL)
13296 error_no_arg (_("file to get"));
13298 gdb_argv argv (args);
13299 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13300 error (_("Invalid parameters to remote get"));
13302 remote_file_get (argv[0], argv[1], from_tty);
13305 static void
13306 remote_delete_command (const char *args, int from_tty)
13308 if (args == NULL)
13309 error_no_arg (_("file to delete"));
13311 gdb_argv argv (args);
13312 if (argv[0] == NULL || argv[1] != NULL)
13313 error (_("Invalid parameters to remote delete"));
13315 remote_file_delete (argv[0], from_tty);
13318 bool
13319 remote_target::can_execute_reverse ()
13321 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13322 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13323 return true;
13324 else
13325 return false;
13328 bool
13329 remote_target::supports_non_stop ()
13331 return true;
13334 bool
13335 remote_target::supports_disable_randomization ()
13337 /* Only supported in extended mode. */
13338 return false;
13341 bool
13342 remote_target::supports_multi_process ()
13344 return m_features.remote_multi_process_p ();
13348 remote_target::remote_supports_cond_tracepoints ()
13350 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13351 == PACKET_ENABLE);
13354 bool
13355 remote_target::supports_evaluation_of_breakpoint_conditions ()
13357 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13358 == PACKET_ENABLE);
13362 remote_target::remote_supports_fast_tracepoints ()
13364 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13368 remote_target::remote_supports_static_tracepoints ()
13370 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13374 remote_target::remote_supports_install_in_trace ()
13376 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13379 bool
13380 remote_target::supports_enable_disable_tracepoint ()
13382 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13383 == PACKET_ENABLE);
13386 bool
13387 remote_target::supports_string_tracing ()
13389 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13392 bool
13393 remote_target::can_run_breakpoint_commands ()
13395 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13398 void
13399 remote_target::trace_init ()
13401 struct remote_state *rs = get_remote_state ();
13403 putpkt ("QTinit");
13404 remote_get_noisy_reply ();
13405 if (strcmp (rs->buf.data (), "OK") != 0)
13406 error (_("Target does not support this command."));
13409 /* Recursive routine to walk through command list including loops, and
13410 download packets for each command. */
13412 void
13413 remote_target::remote_download_command_source (int num, ULONGEST addr,
13414 struct command_line *cmds)
13416 struct remote_state *rs = get_remote_state ();
13417 struct command_line *cmd;
13419 for (cmd = cmds; cmd; cmd = cmd->next)
13421 QUIT; /* Allow user to bail out with ^C. */
13422 strcpy (rs->buf.data (), "QTDPsrc:");
13423 encode_source_string (num, addr, "cmd", cmd->line,
13424 rs->buf.data () + strlen (rs->buf.data ()),
13425 rs->buf.size () - strlen (rs->buf.data ()));
13426 putpkt (rs->buf);
13427 remote_get_noisy_reply ();
13428 if (strcmp (rs->buf.data (), "OK"))
13429 warning (_("Target does not support source download."));
13431 if (cmd->control_type == while_control
13432 || cmd->control_type == while_stepping_control)
13434 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13436 QUIT; /* Allow user to bail out with ^C. */
13437 strcpy (rs->buf.data (), "QTDPsrc:");
13438 encode_source_string (num, addr, "cmd", "end",
13439 rs->buf.data () + strlen (rs->buf.data ()),
13440 rs->buf.size () - strlen (rs->buf.data ()));
13441 putpkt (rs->buf);
13442 remote_get_noisy_reply ();
13443 if (strcmp (rs->buf.data (), "OK"))
13444 warning (_("Target does not support source download."));
13449 void
13450 remote_target::download_tracepoint (struct bp_location *loc)
13452 CORE_ADDR tpaddr;
13453 char addrbuf[40];
13454 std::vector<std::string> tdp_actions;
13455 std::vector<std::string> stepping_actions;
13456 char *pkt;
13457 struct breakpoint *b = loc->owner;
13458 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13459 struct remote_state *rs = get_remote_state ();
13460 int ret;
13461 const char *err_msg = _("Tracepoint packet too large for target.");
13462 size_t size_left;
13464 /* We use a buffer other than rs->buf because we'll build strings
13465 across multiple statements, and other statements in between could
13466 modify rs->buf. */
13467 gdb::char_vector buf (get_remote_packet_size ());
13469 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13471 tpaddr = loc->address;
13472 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13473 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13474 b->number, addrbuf, /* address */
13475 (b->enable_state == bp_enabled ? 'E' : 'D'),
13476 t->step_count, t->pass_count);
13478 if (ret < 0 || ret >= buf.size ())
13479 error ("%s", err_msg);
13481 /* Fast tracepoints are mostly handled by the target, but we can
13482 tell the target how big of an instruction block should be moved
13483 around. */
13484 if (b->type == bp_fast_tracepoint)
13486 /* Only test for support at download time; we may not know
13487 target capabilities at definition time. */
13488 if (remote_supports_fast_tracepoints ())
13490 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13491 NULL))
13493 size_left = buf.size () - strlen (buf.data ());
13494 ret = snprintf (buf.data () + strlen (buf.data ()),
13495 size_left, ":F%x",
13496 gdb_insn_length (loc->gdbarch, tpaddr));
13498 if (ret < 0 || ret >= size_left)
13499 error ("%s", err_msg);
13501 else
13502 /* If it passed validation at definition but fails now,
13503 something is very wrong. */
13504 internal_error (_("Fast tracepoint not valid during download"));
13506 else
13507 /* Fast tracepoints are functionally identical to regular
13508 tracepoints, so don't take lack of support as a reason to
13509 give up on the trace run. */
13510 warning (_("Target does not support fast tracepoints, "
13511 "downloading %d as regular tracepoint"), b->number);
13513 else if (b->type == bp_static_tracepoint
13514 || b->type == bp_static_marker_tracepoint)
13516 /* Only test for support at download time; we may not know
13517 target capabilities at definition time. */
13518 if (remote_supports_static_tracepoints ())
13520 struct static_tracepoint_marker marker;
13522 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13524 size_left = buf.size () - strlen (buf.data ());
13525 ret = snprintf (buf.data () + strlen (buf.data ()),
13526 size_left, ":S");
13528 if (ret < 0 || ret >= size_left)
13529 error ("%s", err_msg);
13531 else
13532 error (_("Static tracepoint not valid during download"));
13534 else
13535 /* Fast tracepoints are functionally identical to regular
13536 tracepoints, so don't take lack of support as a reason
13537 to give up on the trace run. */
13538 error (_("Target does not support static tracepoints"));
13540 /* If the tracepoint has a conditional, make it into an agent
13541 expression and append to the definition. */
13542 if (loc->cond)
13544 /* Only test support at download time, we may not know target
13545 capabilities at definition time. */
13546 if (remote_supports_cond_tracepoints ())
13548 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13549 loc->cond.get ());
13551 size_left = buf.size () - strlen (buf.data ());
13553 ret = snprintf (buf.data () + strlen (buf.data ()),
13554 size_left, ":X%x,", (int) aexpr->buf.size ());
13556 if (ret < 0 || ret >= size_left)
13557 error ("%s", err_msg);
13559 size_left = buf.size () - strlen (buf.data ());
13561 /* Two bytes to encode each aexpr byte, plus the terminating
13562 null byte. */
13563 if (aexpr->buf.size () * 2 + 1 > size_left)
13564 error ("%s", err_msg);
13566 pkt = buf.data () + strlen (buf.data ());
13568 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13569 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13570 *pkt = '\0';
13572 else
13573 warning (_("Target does not support conditional tracepoints, "
13574 "ignoring tp %d cond"), b->number);
13577 if (b->commands || !default_collect.empty ())
13579 size_left = buf.size () - strlen (buf.data ());
13581 ret = snprintf (buf.data () + strlen (buf.data ()),
13582 size_left, "-");
13584 if (ret < 0 || ret >= size_left)
13585 error ("%s", err_msg);
13588 putpkt (buf.data ());
13589 remote_get_noisy_reply ();
13590 if (strcmp (rs->buf.data (), "OK"))
13591 error (_("Target does not support tracepoints."));
13593 /* do_single_steps (t); */
13594 for (auto action_it = tdp_actions.begin ();
13595 action_it != tdp_actions.end (); action_it++)
13597 QUIT; /* Allow user to bail out with ^C. */
13599 bool has_more = ((action_it + 1) != tdp_actions.end ()
13600 || !stepping_actions.empty ());
13602 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13603 b->number, addrbuf, /* address */
13604 action_it->c_str (),
13605 has_more ? '-' : 0);
13607 if (ret < 0 || ret >= buf.size ())
13608 error ("%s", err_msg);
13610 putpkt (buf.data ());
13611 remote_get_noisy_reply ();
13612 if (strcmp (rs->buf.data (), "OK"))
13613 error (_("Error on target while setting tracepoints."));
13616 for (auto action_it = stepping_actions.begin ();
13617 action_it != stepping_actions.end (); action_it++)
13619 QUIT; /* Allow user to bail out with ^C. */
13621 bool is_first = action_it == stepping_actions.begin ();
13622 bool has_more = (action_it + 1) != stepping_actions.end ();
13624 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13625 b->number, addrbuf, /* address */
13626 is_first ? "S" : "",
13627 action_it->c_str (),
13628 has_more ? "-" : "");
13630 if (ret < 0 || ret >= buf.size ())
13631 error ("%s", err_msg);
13633 putpkt (buf.data ());
13634 remote_get_noisy_reply ();
13635 if (strcmp (rs->buf.data (), "OK"))
13636 error (_("Error on target while setting tracepoints."));
13639 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13641 if (b->locspec != nullptr)
13643 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13645 if (ret < 0 || ret >= buf.size ())
13646 error ("%s", err_msg);
13648 const char *str = b->locspec->to_string ();
13649 encode_source_string (b->number, loc->address, "at", str,
13650 buf.data () + strlen (buf.data ()),
13651 buf.size () - strlen (buf.data ()));
13652 putpkt (buf.data ());
13653 remote_get_noisy_reply ();
13654 if (strcmp (rs->buf.data (), "OK"))
13655 warning (_("Target does not support source download."));
13657 if (b->cond_string)
13659 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13661 if (ret < 0 || ret >= buf.size ())
13662 error ("%s", err_msg);
13664 encode_source_string (b->number, loc->address,
13665 "cond", b->cond_string.get (),
13666 buf.data () + strlen (buf.data ()),
13667 buf.size () - strlen (buf.data ()));
13668 putpkt (buf.data ());
13669 remote_get_noisy_reply ();
13670 if (strcmp (rs->buf.data (), "OK"))
13671 warning (_("Target does not support source download."));
13673 remote_download_command_source (b->number, loc->address,
13674 breakpoint_commands (b));
13678 bool
13679 remote_target::can_download_tracepoint ()
13681 struct remote_state *rs = get_remote_state ();
13682 struct trace_status *ts;
13683 int status;
13685 /* Don't try to install tracepoints until we've relocated our
13686 symbols, and fetched and merged the target's tracepoint list with
13687 ours. */
13688 if (rs->starting_up)
13689 return false;
13691 ts = current_trace_status ();
13692 status = get_trace_status (ts);
13694 if (status == -1 || !ts->running_known || !ts->running)
13695 return false;
13697 /* If we are in a tracing experiment, but remote stub doesn't support
13698 installing tracepoint in trace, we have to return. */
13699 if (!remote_supports_install_in_trace ())
13700 return false;
13702 return true;
13706 void
13707 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13709 struct remote_state *rs = get_remote_state ();
13710 char *p;
13712 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13713 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13714 tsv.builtin);
13715 p = rs->buf.data () + strlen (rs->buf.data ());
13716 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13717 >= get_remote_packet_size ())
13718 error (_("Trace state variable name too long for tsv definition packet"));
13719 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13720 *p++ = '\0';
13721 putpkt (rs->buf);
13722 remote_get_noisy_reply ();
13723 if (rs->buf[0] == '\0')
13724 error (_("Target does not support this command."));
13725 if (strcmp (rs->buf.data (), "OK") != 0)
13726 error (_("Error on target while downloading trace state variable."));
13729 void
13730 remote_target::enable_tracepoint (struct bp_location *location)
13732 struct remote_state *rs = get_remote_state ();
13734 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13735 location->owner->number,
13736 phex (location->address, sizeof (CORE_ADDR)));
13737 putpkt (rs->buf);
13738 remote_get_noisy_reply ();
13739 if (rs->buf[0] == '\0')
13740 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13741 if (strcmp (rs->buf.data (), "OK") != 0)
13742 error (_("Error on target while enabling tracepoint."));
13745 void
13746 remote_target::disable_tracepoint (struct bp_location *location)
13748 struct remote_state *rs = get_remote_state ();
13750 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13751 location->owner->number,
13752 phex (location->address, sizeof (CORE_ADDR)));
13753 putpkt (rs->buf);
13754 remote_get_noisy_reply ();
13755 if (rs->buf[0] == '\0')
13756 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13757 if (strcmp (rs->buf.data (), "OK") != 0)
13758 error (_("Error on target while disabling tracepoint."));
13761 void
13762 remote_target::trace_set_readonly_regions ()
13764 asection *s;
13765 bfd_size_type size;
13766 bfd_vma vma;
13767 int anysecs = 0;
13768 int offset = 0;
13769 bfd *abfd = current_program_space->exec_bfd ();
13771 if (!abfd)
13772 return; /* No information to give. */
13774 struct remote_state *rs = get_remote_state ();
13776 strcpy (rs->buf.data (), "QTro");
13777 offset = strlen (rs->buf.data ());
13778 for (s = abfd->sections; s; s = s->next)
13780 char tmp1[40], tmp2[40];
13781 int sec_length;
13783 if ((s->flags & SEC_LOAD) == 0
13784 /* || (s->flags & SEC_CODE) == 0 */
13785 || (s->flags & SEC_READONLY) == 0)
13786 continue;
13788 anysecs = 1;
13789 vma = bfd_section_vma (s);
13790 size = bfd_section_size (s);
13791 bfd_sprintf_vma (abfd, tmp1, vma);
13792 bfd_sprintf_vma (abfd, tmp2, vma + size);
13793 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13794 if (offset + sec_length + 1 > rs->buf.size ())
13796 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13797 != PACKET_ENABLE)
13798 warning (_("\
13799 Too many sections for read-only sections definition packet."));
13800 break;
13802 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13803 tmp1, tmp2);
13804 offset += sec_length;
13806 if (anysecs)
13808 putpkt (rs->buf);
13809 getpkt (&rs->buf);
13813 void
13814 remote_target::trace_start ()
13816 struct remote_state *rs = get_remote_state ();
13818 putpkt ("QTStart");
13819 remote_get_noisy_reply ();
13820 if (rs->buf[0] == '\0')
13821 error (_("Target does not support this command."));
13822 if (strcmp (rs->buf.data (), "OK") != 0)
13823 error (_("Bogus reply from target: %s"), rs->buf.data ());
13827 remote_target::get_trace_status (struct trace_status *ts)
13829 /* Initialize it just to avoid a GCC false warning. */
13830 char *p = NULL;
13831 enum packet_result result;
13832 struct remote_state *rs = get_remote_state ();
13834 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13835 return -1;
13837 /* FIXME we need to get register block size some other way. */
13838 trace_regblock_size
13839 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13841 putpkt ("qTStatus");
13845 p = remote_get_noisy_reply ();
13847 catch (const gdb_exception_error &ex)
13849 if (ex.error != TARGET_CLOSE_ERROR)
13851 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13852 return -1;
13854 throw;
13857 result = m_features.packet_ok (p, PACKET_qTStatus);
13859 /* If the remote target doesn't do tracing, flag it. */
13860 if (result == PACKET_UNKNOWN)
13861 return -1;
13863 /* We're working with a live target. */
13864 ts->filename = NULL;
13866 if (*p++ != 'T')
13867 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13869 /* Function 'parse_trace_status' sets default value of each field of
13870 'ts' at first, so we don't have to do it here. */
13871 parse_trace_status (p, ts);
13873 return ts->running;
13876 void
13877 remote_target::get_tracepoint_status (tracepoint *tp,
13878 struct uploaded_tp *utp)
13880 struct remote_state *rs = get_remote_state ();
13881 char *reply;
13882 size_t size = get_remote_packet_size ();
13884 if (tp)
13886 tp->hit_count = 0;
13887 tp->traceframe_usage = 0;
13888 for (bp_location &loc : tp->locations ())
13890 /* If the tracepoint was never downloaded, don't go asking for
13891 any status. */
13892 if (tp->number_on_target == 0)
13893 continue;
13894 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13895 phex_nz (loc.address, 0));
13896 putpkt (rs->buf);
13897 reply = remote_get_noisy_reply ();
13898 if (reply && *reply)
13900 if (*reply == 'V')
13901 parse_tracepoint_status (reply + 1, tp, utp);
13905 else if (utp)
13907 utp->hit_count = 0;
13908 utp->traceframe_usage = 0;
13909 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13910 phex_nz (utp->addr, 0));
13911 putpkt (rs->buf);
13912 reply = remote_get_noisy_reply ();
13913 if (reply && *reply)
13915 if (*reply == 'V')
13916 parse_tracepoint_status (reply + 1, tp, utp);
13921 void
13922 remote_target::trace_stop ()
13924 struct remote_state *rs = get_remote_state ();
13926 putpkt ("QTStop");
13927 remote_get_noisy_reply ();
13928 if (rs->buf[0] == '\0')
13929 error (_("Target does not support this command."));
13930 if (strcmp (rs->buf.data (), "OK") != 0)
13931 error (_("Bogus reply from target: %s"), rs->buf.data ());
13935 remote_target::trace_find (enum trace_find_type type, int num,
13936 CORE_ADDR addr1, CORE_ADDR addr2,
13937 int *tpp)
13939 struct remote_state *rs = get_remote_state ();
13940 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13941 char *p, *reply;
13942 int target_frameno = -1, target_tracept = -1;
13944 /* Lookups other than by absolute frame number depend on the current
13945 trace selected, so make sure it is correct on the remote end
13946 first. */
13947 if (type != tfind_number)
13948 set_remote_traceframe ();
13950 p = rs->buf.data ();
13951 strcpy (p, "QTFrame:");
13952 p = strchr (p, '\0');
13953 switch (type)
13955 case tfind_number:
13956 xsnprintf (p, endbuf - p, "%x", num);
13957 break;
13958 case tfind_pc:
13959 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13960 break;
13961 case tfind_tp:
13962 xsnprintf (p, endbuf - p, "tdp:%x", num);
13963 break;
13964 case tfind_range:
13965 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13966 phex_nz (addr2, 0));
13967 break;
13968 case tfind_outside:
13969 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13970 phex_nz (addr2, 0));
13971 break;
13972 default:
13973 error (_("Unknown trace find type %d"), type);
13976 putpkt (rs->buf);
13977 reply = remote_get_noisy_reply ();
13978 if (*reply == '\0')
13979 error (_("Target does not support this command."));
13981 while (reply && *reply)
13982 switch (*reply)
13984 case 'F':
13985 p = ++reply;
13986 target_frameno = (int) strtol (p, &reply, 16);
13987 if (reply == p)
13988 error (_("Unable to parse trace frame number"));
13989 /* Don't update our remote traceframe number cache on failure
13990 to select a remote traceframe. */
13991 if (target_frameno == -1)
13992 return -1;
13993 break;
13994 case 'T':
13995 p = ++reply;
13996 target_tracept = (int) strtol (p, &reply, 16);
13997 if (reply == p)
13998 error (_("Unable to parse tracepoint number"));
13999 break;
14000 case 'O': /* "OK"? */
14001 if (reply[1] == 'K' && reply[2] == '\0')
14002 reply += 2;
14003 else
14004 error (_("Bogus reply from target: %s"), reply);
14005 break;
14006 default:
14007 error (_("Bogus reply from target: %s"), reply);
14009 if (tpp)
14010 *tpp = target_tracept;
14012 rs->remote_traceframe_number = target_frameno;
14013 return target_frameno;
14016 bool
14017 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
14019 struct remote_state *rs = get_remote_state ();
14020 char *reply;
14021 ULONGEST uval;
14023 set_remote_traceframe ();
14025 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
14026 putpkt (rs->buf);
14027 reply = remote_get_noisy_reply ();
14028 if (reply && *reply)
14030 if (*reply == 'V')
14032 unpack_varlen_hex (reply + 1, &uval);
14033 *val = (LONGEST) uval;
14034 return true;
14037 return false;
14041 remote_target::save_trace_data (const char *filename)
14043 struct remote_state *rs = get_remote_state ();
14044 char *p, *reply;
14046 p = rs->buf.data ();
14047 strcpy (p, "QTSave:");
14048 p += strlen (p);
14049 if ((p - rs->buf.data ()) + strlen (filename) * 2
14050 >= get_remote_packet_size ())
14051 error (_("Remote file name too long for trace save packet"));
14052 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14053 *p++ = '\0';
14054 putpkt (rs->buf);
14055 reply = remote_get_noisy_reply ();
14056 if (*reply == '\0')
14057 error (_("Target does not support this command."));
14058 if (strcmp (reply, "OK") != 0)
14059 error (_("Bogus reply from target: %s"), reply);
14060 return 0;
14063 /* This is basically a memory transfer, but needs to be its own packet
14064 because we don't know how the target actually organizes its trace
14065 memory, plus we want to be able to ask for as much as possible, but
14066 not be unhappy if we don't get as much as we ask for. */
14068 LONGEST
14069 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14071 struct remote_state *rs = get_remote_state ();
14072 char *reply;
14073 char *p;
14074 int rslt;
14076 p = rs->buf.data ();
14077 strcpy (p, "qTBuffer:");
14078 p += strlen (p);
14079 p += hexnumstr (p, offset);
14080 *p++ = ',';
14081 p += hexnumstr (p, len);
14082 *p++ = '\0';
14084 putpkt (rs->buf);
14085 reply = remote_get_noisy_reply ();
14086 if (reply && *reply)
14088 /* 'l' by itself means we're at the end of the buffer and
14089 there is nothing more to get. */
14090 if (*reply == 'l')
14091 return 0;
14093 /* Convert the reply into binary. Limit the number of bytes to
14094 convert according to our passed-in buffer size, rather than
14095 what was returned in the packet; if the target is
14096 unexpectedly generous and gives us a bigger reply than we
14097 asked for, we don't want to crash. */
14098 rslt = hex2bin (reply, buf, len);
14099 return rslt;
14102 /* Something went wrong, flag as an error. */
14103 return -1;
14106 void
14107 remote_target::set_disconnected_tracing (int val)
14109 struct remote_state *rs = get_remote_state ();
14111 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14112 == PACKET_ENABLE)
14114 char *reply;
14116 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14117 "QTDisconnected:%x", val);
14118 putpkt (rs->buf);
14119 reply = remote_get_noisy_reply ();
14120 if (*reply == '\0')
14121 error (_("Target does not support this command."));
14122 if (strcmp (reply, "OK") != 0)
14123 error (_("Bogus reply from target: %s"), reply);
14125 else if (val)
14126 warning (_("Target does not support disconnected tracing."));
14130 remote_target::core_of_thread (ptid_t ptid)
14132 thread_info *info = this->find_thread (ptid);
14134 if (info != NULL && info->priv != NULL)
14135 return get_remote_thread_info (info)->core;
14137 return -1;
14140 void
14141 remote_target::set_circular_trace_buffer (int val)
14143 struct remote_state *rs = get_remote_state ();
14144 char *reply;
14146 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14147 "QTBuffer:circular:%x", val);
14148 putpkt (rs->buf);
14149 reply = remote_get_noisy_reply ();
14150 if (*reply == '\0')
14151 error (_("Target does not support this command."));
14152 if (strcmp (reply, "OK") != 0)
14153 error (_("Bogus reply from target: %s"), reply);
14156 traceframe_info_up
14157 remote_target::traceframe_info ()
14159 std::optional<gdb::char_vector> text
14160 = target_read_stralloc (current_inferior ()->top_target (),
14161 TARGET_OBJECT_TRACEFRAME_INFO,
14162 NULL);
14163 if (text)
14164 return parse_traceframe_info (text->data ());
14166 return NULL;
14169 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14170 instruction on which a fast tracepoint may be placed. Returns -1
14171 if the packet is not supported, and 0 if the minimum instruction
14172 length is unknown. */
14175 remote_target::get_min_fast_tracepoint_insn_len ()
14177 struct remote_state *rs = get_remote_state ();
14178 char *reply;
14180 /* If we're not debugging a process yet, the IPA can't be
14181 loaded. */
14182 if (!target_has_execution ())
14183 return 0;
14185 /* Make sure the remote is pointing at the right process. */
14186 set_general_process ();
14188 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14189 putpkt (rs->buf);
14190 reply = remote_get_noisy_reply ();
14191 if (*reply == '\0')
14192 return -1;
14193 else
14195 ULONGEST min_insn_len;
14197 unpack_varlen_hex (reply, &min_insn_len);
14199 return (int) min_insn_len;
14203 void
14204 remote_target::set_trace_buffer_size (LONGEST val)
14206 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14208 struct remote_state *rs = get_remote_state ();
14209 char *buf = rs->buf.data ();
14210 char *endbuf = buf + get_remote_packet_size ();
14211 enum packet_result result;
14213 gdb_assert (val >= 0 || val == -1);
14214 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14215 /* Send -1 as literal "-1" to avoid host size dependency. */
14216 if (val < 0)
14218 *buf++ = '-';
14219 buf += hexnumstr (buf, (ULONGEST) -val);
14221 else
14222 buf += hexnumstr (buf, (ULONGEST) val);
14224 putpkt (rs->buf);
14225 remote_get_noisy_reply ();
14226 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14228 if (result != PACKET_OK)
14229 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14233 bool
14234 remote_target::set_trace_notes (const char *user, const char *notes,
14235 const char *stop_notes)
14237 struct remote_state *rs = get_remote_state ();
14238 char *reply;
14239 char *buf = rs->buf.data ();
14240 char *endbuf = buf + get_remote_packet_size ();
14241 int nbytes;
14243 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14244 if (user)
14246 buf += xsnprintf (buf, endbuf - buf, "user:");
14247 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14248 buf += 2 * nbytes;
14249 *buf++ = ';';
14251 if (notes)
14253 buf += xsnprintf (buf, endbuf - buf, "notes:");
14254 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14255 buf += 2 * nbytes;
14256 *buf++ = ';';
14258 if (stop_notes)
14260 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14261 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14262 buf += 2 * nbytes;
14263 *buf++ = ';';
14265 /* Ensure the buffer is terminated. */
14266 *buf = '\0';
14268 putpkt (rs->buf);
14269 reply = remote_get_noisy_reply ();
14270 if (*reply == '\0')
14271 return false;
14273 if (strcmp (reply, "OK") != 0)
14274 error (_("Bogus reply from target: %s"), reply);
14276 return true;
14279 bool
14280 remote_target::use_agent (bool use)
14282 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14284 struct remote_state *rs = get_remote_state ();
14286 /* If the stub supports QAgent. */
14287 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14288 putpkt (rs->buf);
14289 getpkt (&rs->buf);
14291 if (strcmp (rs->buf.data (), "OK") == 0)
14293 ::use_agent = use;
14294 return true;
14298 return false;
14301 bool
14302 remote_target::can_use_agent ()
14304 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14307 #if defined (HAVE_LIBEXPAT)
14309 /* Check the btrace document version. */
14311 static void
14312 check_xml_btrace_version (struct gdb_xml_parser *parser,
14313 const struct gdb_xml_element *element,
14314 void *user_data,
14315 std::vector<gdb_xml_value> &attributes)
14317 const char *version
14318 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14320 if (strcmp (version, "1.0") != 0)
14321 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14324 /* Parse a btrace "block" xml record. */
14326 static void
14327 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14328 const struct gdb_xml_element *element,
14329 void *user_data,
14330 std::vector<gdb_xml_value> &attributes)
14332 struct btrace_data *btrace;
14333 ULONGEST *begin, *end;
14335 btrace = (struct btrace_data *) user_data;
14337 switch (btrace->format)
14339 case BTRACE_FORMAT_BTS:
14340 break;
14342 case BTRACE_FORMAT_NONE:
14343 btrace->format = BTRACE_FORMAT_BTS;
14344 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14345 break;
14347 default:
14348 gdb_xml_error (parser, _("Btrace format error."));
14351 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14352 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14353 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14356 /* Parse a "raw" xml record. */
14358 static void
14359 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14360 gdb_byte **pdata, size_t *psize)
14362 gdb_byte *bin;
14363 size_t len, size;
14365 len = strlen (body_text);
14366 if (len % 2 != 0)
14367 gdb_xml_error (parser, _("Bad raw data size."));
14369 size = len / 2;
14371 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14372 bin = data.get ();
14374 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14375 while (len > 0)
14377 char hi, lo;
14379 hi = *body_text++;
14380 lo = *body_text++;
14382 if (hi == 0 || lo == 0)
14383 gdb_xml_error (parser, _("Bad hex encoding."));
14385 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14386 len -= 2;
14389 *pdata = data.release ();
14390 *psize = size;
14393 /* Parse a btrace pt-config "cpu" xml record. */
14395 static void
14396 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14397 const struct gdb_xml_element *element,
14398 void *user_data,
14399 std::vector<gdb_xml_value> &attributes)
14401 struct btrace_data *btrace;
14402 const char *vendor;
14403 ULONGEST *family, *model, *stepping;
14405 vendor
14406 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14407 family
14408 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14409 model
14410 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14411 stepping
14412 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14414 btrace = (struct btrace_data *) user_data;
14416 if (strcmp (vendor, "GenuineIntel") == 0)
14417 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14419 btrace->variant.pt.config.cpu.family = *family;
14420 btrace->variant.pt.config.cpu.model = *model;
14421 btrace->variant.pt.config.cpu.stepping = *stepping;
14424 /* Parse a btrace pt "raw" xml record. */
14426 static void
14427 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14428 const struct gdb_xml_element *element,
14429 void *user_data, const char *body_text)
14431 struct btrace_data *btrace;
14433 btrace = (struct btrace_data *) user_data;
14434 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14435 &btrace->variant.pt.size);
14438 /* Parse a btrace "pt" xml record. */
14440 static void
14441 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14442 const struct gdb_xml_element *element,
14443 void *user_data,
14444 std::vector<gdb_xml_value> &attributes)
14446 struct btrace_data *btrace;
14448 btrace = (struct btrace_data *) user_data;
14449 btrace->format = BTRACE_FORMAT_PT;
14450 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14451 btrace->variant.pt.data = NULL;
14452 btrace->variant.pt.size = 0;
14455 static const struct gdb_xml_attribute block_attributes[] = {
14456 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14457 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14458 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14461 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14462 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14463 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14464 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14465 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14466 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14469 static const struct gdb_xml_element btrace_pt_config_children[] = {
14470 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14471 parse_xml_btrace_pt_config_cpu, NULL },
14472 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14475 static const struct gdb_xml_element btrace_pt_children[] = {
14476 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14477 NULL },
14478 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14479 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14482 static const struct gdb_xml_attribute btrace_attributes[] = {
14483 { "version", GDB_XML_AF_NONE, NULL, NULL },
14484 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14487 static const struct gdb_xml_element btrace_children[] = {
14488 { "block", block_attributes, NULL,
14489 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14490 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14491 NULL },
14492 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14495 static const struct gdb_xml_element btrace_elements[] = {
14496 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14497 check_xml_btrace_version, NULL },
14498 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14501 #endif /* defined (HAVE_LIBEXPAT) */
14503 /* Parse a branch trace xml document XML into DATA. */
14505 static void
14506 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14508 #if defined (HAVE_LIBEXPAT)
14510 int errcode;
14511 btrace_data result;
14512 result.format = BTRACE_FORMAT_NONE;
14514 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14515 buffer, &result);
14516 if (errcode != 0)
14517 error (_("Error parsing branch trace."));
14519 /* Keep parse results. */
14520 *btrace = std::move (result);
14522 #else /* !defined (HAVE_LIBEXPAT) */
14524 error (_("Cannot process branch trace. XML support was disabled at "
14525 "compile time."));
14527 #endif /* !defined (HAVE_LIBEXPAT) */
14530 #if defined (HAVE_LIBEXPAT)
14532 /* Parse a btrace-conf "bts" xml record. */
14534 static void
14535 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14536 const struct gdb_xml_element *element,
14537 void *user_data,
14538 std::vector<gdb_xml_value> &attributes)
14540 struct btrace_config *conf;
14541 struct gdb_xml_value *size;
14543 conf = (struct btrace_config *) user_data;
14544 conf->format = BTRACE_FORMAT_BTS;
14545 conf->bts.size = 0;
14547 size = xml_find_attribute (attributes, "size");
14548 if (size != NULL)
14549 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14552 /* Parse a btrace-conf "pt" xml record. */
14554 static void
14555 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14556 const struct gdb_xml_element *element,
14557 void *user_data,
14558 std::vector<gdb_xml_value> &attributes)
14560 struct btrace_config *conf;
14561 struct gdb_xml_value *size;
14563 conf = (struct btrace_config *) user_data;
14564 conf->format = BTRACE_FORMAT_PT;
14565 conf->pt.size = 0;
14567 size = xml_find_attribute (attributes, "size");
14568 if (size != NULL)
14569 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14572 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14573 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14574 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14577 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14578 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14579 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14582 static const struct gdb_xml_element btrace_conf_children[] = {
14583 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14584 parse_xml_btrace_conf_bts, NULL },
14585 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14586 parse_xml_btrace_conf_pt, NULL },
14587 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14590 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14591 { "version", GDB_XML_AF_NONE, NULL, NULL },
14592 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14595 static const struct gdb_xml_element btrace_conf_elements[] = {
14596 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14597 GDB_XML_EF_NONE, NULL, NULL },
14598 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14601 #endif /* defined (HAVE_LIBEXPAT) */
14603 /* Parse a branch trace configuration xml document XML into CONF. */
14605 static void
14606 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14608 #if defined (HAVE_LIBEXPAT)
14610 int errcode;
14611 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14612 btrace_conf_elements, xml, conf);
14613 if (errcode != 0)
14614 error (_("Error parsing branch trace configuration."));
14616 #else /* !defined (HAVE_LIBEXPAT) */
14618 error (_("Cannot process the branch trace configuration. XML support "
14619 "was disabled at compile time."));
14621 #endif /* !defined (HAVE_LIBEXPAT) */
14624 /* Reset our idea of our target's btrace configuration. */
14626 static void
14627 remote_btrace_reset (remote_state *rs)
14629 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14632 /* Synchronize the configuration with the target. */
14634 void
14635 remote_target::btrace_sync_conf (const btrace_config *conf)
14637 struct remote_state *rs;
14638 char *buf, *pos, *endbuf;
14640 rs = get_remote_state ();
14641 buf = rs->buf.data ();
14642 endbuf = buf + get_remote_packet_size ();
14644 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14645 && conf->bts.size != rs->btrace_config.bts.size)
14647 pos = buf;
14648 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14649 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14650 conf->bts.size);
14652 putpkt (buf);
14653 getpkt (&rs->buf);
14655 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14656 == PACKET_ERROR)
14658 if (buf[0] == 'E' && buf[1] == '.')
14659 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14660 else
14661 error (_("Failed to configure the BTS buffer size."));
14664 rs->btrace_config.bts.size = conf->bts.size;
14667 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14668 && conf->pt.size != rs->btrace_config.pt.size)
14670 pos = buf;
14671 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14672 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14673 conf->pt.size);
14675 putpkt (buf);
14676 getpkt (&rs->buf);
14678 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14679 == PACKET_ERROR)
14681 if (buf[0] == 'E' && buf[1] == '.')
14682 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14683 else
14684 error (_("Failed to configure the trace buffer size."));
14687 rs->btrace_config.pt.size = conf->pt.size;
14691 /* Read TP's btrace configuration from the target and store it into CONF. */
14693 static void
14694 btrace_read_config (thread_info *tp, btrace_config *conf)
14696 /* target_read_stralloc relies on INFERIOR_PTID. */
14697 scoped_restore_current_thread restore_thread;
14698 switch_to_thread (tp);
14700 std::optional<gdb::char_vector> xml
14701 = target_read_stralloc (current_inferior ()->top_target (),
14702 TARGET_OBJECT_BTRACE_CONF, "");
14703 if (xml)
14704 parse_xml_btrace_conf (conf, xml->data ());
14707 /* Maybe reopen target btrace. */
14709 void
14710 remote_target::remote_btrace_maybe_reopen ()
14712 struct remote_state *rs = get_remote_state ();
14713 int btrace_target_pushed = 0;
14714 #if !defined (HAVE_LIBIPT)
14715 int warned = 0;
14716 #endif
14718 /* Don't bother walking the entirety of the remote thread list when
14719 we know the feature isn't supported by the remote. */
14720 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14721 return;
14723 for (thread_info *tp : all_non_exited_threads (this))
14725 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14726 btrace_read_config (tp, &rs->btrace_config);
14728 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14729 continue;
14731 #if !defined (HAVE_LIBIPT)
14732 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14734 if (!warned)
14736 warned = 1;
14737 warning (_("Target is recording using Intel Processor Trace "
14738 "but support was disabled at compile time."));
14741 continue;
14743 #endif /* !defined (HAVE_LIBIPT) */
14745 /* Push target, once, but before anything else happens. This way our
14746 changes to the threads will be cleaned up by unpushing the target
14747 in case btrace_read_config () throws. */
14748 if (!btrace_target_pushed)
14750 btrace_target_pushed = 1;
14751 record_btrace_push_target ();
14752 gdb_printf (_("Target is recording using %s.\n"),
14753 btrace_format_string (rs->btrace_config.format));
14756 tp->btrace.target
14757 = new btrace_target_info { tp->ptid, rs->btrace_config };
14761 /* Enable branch tracing. */
14763 struct btrace_target_info *
14764 remote_target::enable_btrace (thread_info *tp,
14765 const struct btrace_config *conf)
14767 struct packet_config *packet = NULL;
14768 struct remote_state *rs = get_remote_state ();
14769 char *buf = rs->buf.data ();
14770 char *endbuf = buf + get_remote_packet_size ();
14772 unsigned int which_packet;
14773 switch (conf->format)
14775 case BTRACE_FORMAT_BTS:
14776 which_packet = PACKET_Qbtrace_bts;
14777 break;
14778 case BTRACE_FORMAT_PT:
14779 which_packet = PACKET_Qbtrace_pt;
14780 break;
14781 default:
14782 internal_error (_("Bad branch btrace format: %u."),
14783 (unsigned int) conf->format);
14786 packet = &m_features.m_protocol_packets[which_packet];
14787 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14788 error (_("Target does not support branch tracing."));
14790 btrace_sync_conf (conf);
14792 ptid_t ptid = tp->ptid;
14793 set_general_thread (ptid);
14795 buf += xsnprintf (buf, endbuf - buf, "%s",
14796 packets_descriptions[which_packet].name);
14797 putpkt (rs->buf);
14798 getpkt (&rs->buf);
14800 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14802 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14803 error (_("Could not enable branch tracing for %s: %s"),
14804 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14805 else
14806 error (_("Could not enable branch tracing for %s."),
14807 target_pid_to_str (ptid).c_str ());
14810 btrace_target_info *tinfo = new btrace_target_info { ptid };
14812 /* If we fail to read the configuration, we lose some information, but the
14813 tracing itself is not impacted. */
14816 btrace_read_config (tp, &tinfo->conf);
14818 catch (const gdb_exception_error &err)
14820 if (err.message != NULL)
14821 warning ("%s", err.what ());
14824 return tinfo;
14827 /* Disable branch tracing. */
14829 void
14830 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14832 struct remote_state *rs = get_remote_state ();
14833 char *buf = rs->buf.data ();
14834 char *endbuf = buf + get_remote_packet_size ();
14836 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14837 error (_("Target does not support branch tracing."));
14839 set_general_thread (tinfo->ptid);
14841 buf += xsnprintf (buf, endbuf - buf, "%s",
14842 packets_descriptions[PACKET_Qbtrace_off].name);
14843 putpkt (rs->buf);
14844 getpkt (&rs->buf);
14846 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14848 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14849 error (_("Could not disable branch tracing for %s: %s"),
14850 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14851 else
14852 error (_("Could not disable branch tracing for %s."),
14853 target_pid_to_str (tinfo->ptid).c_str ());
14856 delete tinfo;
14859 /* Teardown branch tracing. */
14861 void
14862 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14864 /* We must not talk to the target during teardown. */
14865 delete tinfo;
14868 /* Read the branch trace. */
14870 enum btrace_error
14871 remote_target::read_btrace (struct btrace_data *btrace,
14872 struct btrace_target_info *tinfo,
14873 enum btrace_read_type type)
14875 const char *annex;
14877 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14878 error (_("Target does not support branch tracing."));
14880 #if !defined(HAVE_LIBEXPAT)
14881 error (_("Cannot process branch tracing result. XML parsing not supported."));
14882 #endif
14884 switch (type)
14886 case BTRACE_READ_ALL:
14887 annex = "all";
14888 break;
14889 case BTRACE_READ_NEW:
14890 annex = "new";
14891 break;
14892 case BTRACE_READ_DELTA:
14893 annex = "delta";
14894 break;
14895 default:
14896 internal_error (_("Bad branch tracing read type: %u."),
14897 (unsigned int) type);
14900 std::optional<gdb::char_vector> xml
14901 = target_read_stralloc (current_inferior ()->top_target (),
14902 TARGET_OBJECT_BTRACE, annex);
14903 if (!xml)
14904 return BTRACE_ERR_UNKNOWN;
14906 parse_xml_btrace (btrace, xml->data ());
14908 return BTRACE_ERR_NONE;
14911 const struct btrace_config *
14912 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14914 return &tinfo->conf;
14917 bool
14918 remote_target::augmented_libraries_svr4_read ()
14920 return
14921 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14922 == PACKET_ENABLE);
14925 /* Implementation of to_load. */
14927 void
14928 remote_target::load (const char *name, int from_tty)
14930 generic_load (name, from_tty);
14933 /* Accepts an integer PID; returns a string representing a file that
14934 can be opened on the remote side to get the symbols for the child
14935 process. Returns NULL if the operation is not supported. */
14937 const char *
14938 remote_target::pid_to_exec_file (int pid)
14940 static std::optional<gdb::char_vector> filename;
14941 char *annex = NULL;
14943 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14944 return NULL;
14946 inferior *inf = find_inferior_pid (this, pid);
14947 if (inf == NULL)
14948 internal_error (_("not currently attached to process %d"), pid);
14950 if (!inf->fake_pid_p)
14952 const int annex_size = 9;
14954 annex = (char *) alloca (annex_size);
14955 xsnprintf (annex, annex_size, "%x", pid);
14958 filename = target_read_stralloc (current_inferior ()->top_target (),
14959 TARGET_OBJECT_EXEC_FILE, annex);
14961 return filename ? filename->data () : nullptr;
14964 /* Implement the to_can_do_single_step target_ops method. */
14967 remote_target::can_do_single_step ()
14969 /* We can only tell whether target supports single step or not by
14970 supported s and S vCont actions if the stub supports vContSupported
14971 feature. If the stub doesn't support vContSupported feature,
14972 we have conservatively to think target doesn't supports single
14973 step. */
14974 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14976 struct remote_state *rs = get_remote_state ();
14978 return rs->supports_vCont.s && rs->supports_vCont.S;
14980 else
14981 return 0;
14984 /* Implementation of the to_execution_direction method for the remote
14985 target. */
14987 enum exec_direction_kind
14988 remote_target::execution_direction ()
14990 struct remote_state *rs = get_remote_state ();
14992 return rs->last_resume_exec_dir;
14995 /* Return pointer to the thread_info struct which corresponds to
14996 THREAD_HANDLE (having length HANDLE_LEN). */
14998 thread_info *
14999 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
15000 int handle_len,
15001 inferior *inf)
15003 for (thread_info *tp : all_non_exited_threads (this))
15005 remote_thread_info *priv = get_remote_thread_info (tp);
15007 if (tp->inf == inf && priv != NULL)
15009 if (handle_len != priv->thread_handle.size ())
15010 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15011 handle_len, priv->thread_handle.size ());
15012 if (memcmp (thread_handle, priv->thread_handle.data (),
15013 handle_len) == 0)
15014 return tp;
15018 return NULL;
15021 gdb::array_view<const gdb_byte>
15022 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15024 remote_thread_info *priv = get_remote_thread_info (tp);
15025 return priv->thread_handle;
15028 bool
15029 remote_target::can_async_p ()
15031 /* This flag should be checked in the common target.c code. */
15032 gdb_assert (target_async_permitted);
15034 /* We're async whenever the serial device can. */
15035 return get_remote_state ()->can_async_p ();
15038 bool
15039 remote_target::is_async_p ()
15041 /* We're async whenever the serial device is. */
15042 return get_remote_state ()->is_async_p ();
15045 /* Pass the SERIAL event on and up to the client. One day this code
15046 will be able to delay notifying the client of an event until the
15047 point where an entire packet has been received. */
15049 static serial_event_ftype remote_async_serial_handler;
15051 static void
15052 remote_async_serial_handler (struct serial *scb, void *context)
15054 /* Don't propogate error information up to the client. Instead let
15055 the client find out about the error by querying the target. */
15056 inferior_event_handler (INF_REG_EVENT);
15060 remote_target::async_wait_fd ()
15062 struct remote_state *rs = get_remote_state ();
15063 return rs->remote_desc->fd;
15066 void
15067 remote_target::async (bool enable)
15069 struct remote_state *rs = get_remote_state ();
15071 if (enable)
15073 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15075 /* If there are pending events in the stop reply queue tell the
15076 event loop to process them. */
15077 if (!rs->stop_reply_queue.empty ())
15078 rs->mark_async_event_handler ();
15080 /* For simplicity, below we clear the pending events token
15081 without remembering whether it is marked, so here we always
15082 mark it. If there's actually no pending notification to
15083 process, this ends up being a no-op (other than a spurious
15084 event-loop wakeup). */
15085 if (target_is_non_stop_p ())
15086 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15088 else
15090 serial_async (rs->remote_desc, NULL, NULL);
15091 /* If the core is disabling async, it doesn't want to be
15092 disturbed with target events. Clear all async event sources
15093 too. */
15094 rs->clear_async_event_handler ();
15096 if (target_is_non_stop_p ())
15097 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15101 /* Implementation of the to_thread_events method. */
15103 void
15104 remote_target::thread_events (int enable)
15106 struct remote_state *rs = get_remote_state ();
15107 size_t size = get_remote_packet_size ();
15109 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15110 return;
15112 if (rs->last_thread_events == enable)
15113 return;
15115 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15116 putpkt (rs->buf);
15117 getpkt (&rs->buf);
15119 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
15121 case PACKET_OK:
15122 if (strcmp (rs->buf.data (), "OK") != 0)
15123 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15124 rs->last_thread_events = enable;
15125 break;
15126 case PACKET_ERROR:
15127 warning (_("Remote failure reply: %s"), rs->buf.data ());
15128 break;
15129 case PACKET_UNKNOWN:
15130 break;
15134 /* Implementation of the supports_set_thread_options target
15135 method. */
15137 bool
15138 remote_target::supports_set_thread_options (gdb_thread_options options)
15140 remote_state *rs = get_remote_state ();
15141 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15142 && (rs->supported_thread_options & options) == options);
15145 /* For coalescing reasons, actually sending the options to the target
15146 happens at resume time, via this function. See target_resume for
15147 all-stop, and target_commit_resumed for non-stop. */
15149 void
15150 remote_target::commit_requested_thread_options ()
15152 struct remote_state *rs = get_remote_state ();
15154 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15155 return;
15157 char *p = rs->buf.data ();
15158 char *endp = p + get_remote_packet_size ();
15160 /* Clear options for all threads by default. Note that unlike
15161 vCont, the rightmost options that match a thread apply, so we
15162 don't have to worry about whether we can use wildcard ptids. */
15163 strcpy (p, "QThreadOptions;0");
15164 p += strlen (p);
15166 /* Send the QThreadOptions packet stored in P. */
15167 auto flush = [&] ()
15169 *p++ = '\0';
15171 putpkt (rs->buf);
15172 getpkt (&rs->buf, 0);
15174 switch (m_features.packet_ok (rs->buf, PACKET_QThreadOptions))
15176 case PACKET_OK:
15177 if (strcmp (rs->buf.data (), "OK") != 0)
15178 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15179 break;
15180 case PACKET_ERROR:
15181 error (_("Remote failure reply: %s"), rs->buf.data ());
15182 case PACKET_UNKNOWN:
15183 gdb_assert_not_reached ("PACKET_UNKNOWN");
15184 break;
15188 /* Prepare P for another QThreadOptions packet. */
15189 auto restart = [&] ()
15191 p = rs->buf.data ();
15192 strcpy (p, "QThreadOptions");
15193 p += strlen (p);
15196 /* Now set non-zero options for threads that need them. We don't
15197 bother with the case of all threads of a process wanting the same
15198 non-zero options as that's not an expected scenario. */
15199 for (thread_info *tp : all_non_exited_threads (this))
15201 gdb_thread_options options = tp->thread_options ();
15203 if (options == 0)
15204 continue;
15206 /* It might be possible to we have more threads with options
15207 than can fit a single QThreadOptions packet. So build each
15208 options/thread pair in this separate buffer to make sure it
15209 fits. */
15210 constexpr size_t max_options_size = 100;
15211 char obuf[max_options_size];
15212 char *obuf_p = obuf;
15213 char *obuf_endp = obuf + max_options_size;
15215 *obuf_p++ = ';';
15216 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15217 phex_nz (options, sizeof (options)));
15218 if (tp->ptid != magic_null_ptid)
15220 *obuf_p++ = ':';
15221 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15224 size_t osize = obuf_p - obuf;
15225 if (osize > endp - p)
15227 /* This new options/thread pair doesn't fit the packet
15228 buffer. Send what we have already. */
15229 flush ();
15230 restart ();
15232 /* Should now fit. */
15233 gdb_assert (osize <= endp - p);
15236 memcpy (p, obuf, osize);
15237 p += osize;
15240 flush ();
15243 static void
15244 show_remote_cmd (const char *args, int from_tty)
15246 /* We can't just use cmd_show_list here, because we want to skip
15247 the redundant "show remote Z-packet" and the legacy aliases. */
15248 struct cmd_list_element *list = remote_show_cmdlist;
15249 struct ui_out *uiout = current_uiout;
15251 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15252 for (; list != NULL; list = list->next)
15253 if (strcmp (list->name, "Z-packet") == 0)
15254 continue;
15255 else if (list->type == not_set_cmd)
15256 /* Alias commands are exactly like the original, except they
15257 don't have the normal type. */
15258 continue;
15259 else
15261 ui_out_emit_tuple option_emitter (uiout, "option");
15263 uiout->field_string ("name", list->name);
15264 uiout->text (": ");
15265 if (list->type == show_cmd)
15266 do_show_command (NULL, from_tty, list);
15267 else
15268 cmd_func (list, NULL, from_tty);
15272 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15273 offer all inferiors using that program space a change to look up symbols. */
15275 static void
15276 remote_objfile_changed_check_symbols (program_space *pspace)
15278 /* The affected program space is possibly shared by multiple inferiors.
15279 Consider sending a qSymbol packet for each of the inferiors using that
15280 program space. */
15281 for (inferior *inf : all_inferiors ())
15283 if (inf->pspace != pspace)
15284 continue;
15286 /* Check whether the inferior's process target is a remote target. */
15287 remote_target *remote = as_remote_target (inf->process_target ());
15288 if (remote == nullptr)
15289 continue;
15291 /* When we are attaching or handling a fork child and the shared library
15292 subsystem reads the list of loaded libraries, we receive new objfile
15293 events in between each found library. The libraries are read in an
15294 undefined order, so if we gave the remote side a chance to look up
15295 symbols between each objfile, we might give it an inconsistent picture
15296 of the inferior. It could appear that a library A appears loaded but
15297 a library B does not, even though library A requires library B. That
15298 would present a state that couldn't normally exist in the inferior.
15300 So, skip these events, we'll give the remote a chance to look up
15301 symbols once all the loaded libraries and their symbols are known to
15302 GDB. */
15303 if (inf->in_initial_library_scan)
15304 continue;
15306 if (!remote->has_execution (inf))
15307 continue;
15309 /* Need to switch to a specific thread, because remote_check_symbols will
15310 set the general thread using INFERIOR_PTID.
15312 It's possible to have inferiors with no thread here, because we are
15313 called very early in the connection process, while the inferior is
15314 being set up, before threads are added. Just skip it, start_remote_1
15315 also calls remote_check_symbols when it's done setting things up. */
15316 thread_info *thread = any_thread_of_inferior (inf);
15317 if (thread != nullptr)
15319 scoped_restore_current_thread restore_thread;
15320 switch_to_thread (thread);
15321 remote->remote_check_symbols ();
15326 /* Function to be called whenever a new objfile (shlib) is detected. */
15328 static void
15329 remote_new_objfile (struct objfile *objfile)
15331 remote_objfile_changed_check_symbols (objfile->pspace);
15334 /* Pull all the tracepoints defined on the target and create local
15335 data structures representing them. We don't want to create real
15336 tracepoints yet, we don't want to mess up the user's existing
15337 collection. */
15340 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15342 struct remote_state *rs = get_remote_state ();
15343 char *p;
15345 /* Ask for a first packet of tracepoint definition. */
15346 putpkt ("qTfP");
15347 getpkt (&rs->buf);
15348 p = rs->buf.data ();
15349 while (*p && *p != 'l')
15351 parse_tracepoint_definition (p, utpp);
15352 /* Ask for another packet of tracepoint definition. */
15353 putpkt ("qTsP");
15354 getpkt (&rs->buf);
15355 p = rs->buf.data ();
15357 return 0;
15361 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15363 struct remote_state *rs = get_remote_state ();
15364 char *p;
15366 /* Ask for a first packet of variable definition. */
15367 putpkt ("qTfV");
15368 getpkt (&rs->buf);
15369 p = rs->buf.data ();
15370 while (*p && *p != 'l')
15372 parse_tsv_definition (p, utsvp);
15373 /* Ask for another packet of variable definition. */
15374 putpkt ("qTsV");
15375 getpkt (&rs->buf);
15376 p = rs->buf.data ();
15378 return 0;
15381 /* The "set/show range-stepping" show hook. */
15383 static void
15384 show_range_stepping (struct ui_file *file, int from_tty,
15385 struct cmd_list_element *c,
15386 const char *value)
15388 gdb_printf (file,
15389 _("Debugger's willingness to use range stepping "
15390 "is %s.\n"), value);
15393 /* Return true if the vCont;r action is supported by the remote
15394 stub. */
15396 bool
15397 remote_target::vcont_r_supported ()
15399 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15400 && get_remote_state ()->supports_vCont.r);
15403 /* The "set/show range-stepping" set hook. */
15405 static void
15406 set_range_stepping (const char *ignore_args, int from_tty,
15407 struct cmd_list_element *c)
15409 /* When enabling, check whether range stepping is actually supported
15410 by the target, and warn if not. */
15411 if (use_range_stepping)
15413 remote_target *remote = get_current_remote_target ();
15414 if (remote == NULL
15415 || !remote->vcont_r_supported ())
15416 warning (_("Range stepping is not supported by the current target"));
15420 static void
15421 show_remote_debug (struct ui_file *file, int from_tty,
15422 struct cmd_list_element *c, const char *value)
15424 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15425 value);
15428 static void
15429 show_remote_timeout (struct ui_file *file, int from_tty,
15430 struct cmd_list_element *c, const char *value)
15432 gdb_printf (file,
15433 _("Timeout limit to wait for target to respond is %s.\n"),
15434 value);
15437 /* Implement the "supports_memory_tagging" target_ops method. */
15439 bool
15440 remote_target::supports_memory_tagging ()
15442 return m_features.remote_memory_tagging_p ();
15445 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15447 static void
15448 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15449 size_t len, int type)
15451 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15453 std::string request = string_printf ("qMemTags:%s,%s:%s",
15454 phex_nz (address, addr_size),
15455 phex_nz (len, sizeof (len)),
15456 phex_nz (type, sizeof (type)));
15458 strcpy (packet.data (), request.c_str ());
15461 /* Parse the qMemTags packet reply into TAGS.
15463 Return true if successful, false otherwise. */
15465 static bool
15466 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15467 gdb::byte_vector &tags)
15469 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15470 return false;
15472 /* Copy the tag data. */
15473 tags = hex2bin (reply.data () + 1);
15475 return true;
15478 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15480 static void
15481 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15482 size_t len, int type,
15483 const gdb::byte_vector &tags)
15485 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15487 /* Put together the main packet, address and length. */
15488 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15489 phex_nz (address, addr_size),
15490 phex_nz (len, sizeof (len)),
15491 phex_nz (type, sizeof (type)));
15492 request += bin2hex (tags.data (), tags.size ());
15494 /* Check if we have exceeded the maximum packet size. */
15495 if (packet.size () < request.length ())
15496 error (_("Contents too big for packet QMemTags."));
15498 strcpy (packet.data (), request.c_str ());
15501 /* Implement the "fetch_memtags" target_ops method. */
15503 bool
15504 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15505 gdb::byte_vector &tags, int type)
15507 /* Make sure the qMemTags packet is supported. */
15508 if (!m_features.remote_memory_tagging_p ())
15509 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15511 struct remote_state *rs = get_remote_state ();
15513 create_fetch_memtags_request (rs->buf, address, len, type);
15515 putpkt (rs->buf);
15516 getpkt (&rs->buf);
15518 return parse_fetch_memtags_reply (rs->buf, tags);
15521 /* Implement the "store_memtags" target_ops method. */
15523 bool
15524 remote_target::store_memtags (CORE_ADDR address, size_t len,
15525 const gdb::byte_vector &tags, int type)
15527 /* Make sure the QMemTags packet is supported. */
15528 if (!m_features.remote_memory_tagging_p ())
15529 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15531 struct remote_state *rs = get_remote_state ();
15533 create_store_memtags_request (rs->buf, address, len, type, tags);
15535 putpkt (rs->buf);
15536 getpkt (&rs->buf);
15538 /* Verify if the request was successful. */
15539 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15542 /* Return true if remote target T is non-stop. */
15544 bool
15545 remote_target_is_non_stop_p (remote_target *t)
15547 scoped_restore_current_thread restore_thread;
15548 switch_to_target_no_thread (t);
15550 return target_is_non_stop_p ();
15553 #if GDB_SELF_TEST
15555 namespace selftests {
15557 static void
15558 test_memory_tagging_functions ()
15560 remote_target remote;
15562 struct packet_config *config
15563 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15565 scoped_restore restore_memtag_support_
15566 = make_scoped_restore (&config->support);
15568 /* Test memory tagging packet support. */
15569 config->support = PACKET_SUPPORT_UNKNOWN;
15570 SELF_CHECK (remote.supports_memory_tagging () == false);
15571 config->support = PACKET_DISABLE;
15572 SELF_CHECK (remote.supports_memory_tagging () == false);
15573 config->support = PACKET_ENABLE;
15574 SELF_CHECK (remote.supports_memory_tagging () == true);
15576 /* Setup testing. */
15577 gdb::char_vector packet;
15578 gdb::byte_vector tags, bv;
15579 std::string expected, reply;
15580 packet.resize (32000);
15582 /* Test creating a qMemTags request. */
15584 expected = "qMemTags:0,0:0";
15585 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15586 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15588 expected = "qMemTags:deadbeef,10:1";
15589 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15590 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15592 /* Test parsing a qMemTags reply. */
15594 /* Error reply, tags vector unmodified. */
15595 reply = "E00";
15596 strcpy (packet.data (), reply.c_str ());
15597 tags.resize (0);
15598 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15599 SELF_CHECK (tags.size () == 0);
15601 /* Valid reply, tags vector updated. */
15602 tags.resize (0);
15603 bv.resize (0);
15605 for (int i = 0; i < 5; i++)
15606 bv.push_back (i);
15608 reply = "m" + bin2hex (bv.data (), bv.size ());
15609 strcpy (packet.data (), reply.c_str ());
15611 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15612 SELF_CHECK (tags.size () == 5);
15614 for (int i = 0; i < 5; i++)
15615 SELF_CHECK (tags[i] == i);
15617 /* Test creating a QMemTags request. */
15619 /* Empty tag data. */
15620 tags.resize (0);
15621 expected = "QMemTags:0,0:0:";
15622 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15623 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15624 expected.length ()) == 0);
15626 /* Non-empty tag data. */
15627 tags.resize (0);
15628 for (int i = 0; i < 5; i++)
15629 tags.push_back (i);
15630 expected = "QMemTags:deadbeef,ff:1:0001020304";
15631 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15632 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15633 expected.length ()) == 0);
15636 } // namespace selftests
15637 #endif /* GDB_SELF_TEST */
15639 void _initialize_remote ();
15640 void
15641 _initialize_remote ()
15643 add_target (remote_target_info, remote_target::open);
15644 add_target (extended_remote_target_info, extended_remote_target::open);
15646 /* Hook into new objfile notification. */
15647 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15648 gdb::observers::all_objfiles_removed.attach
15649 (remote_objfile_changed_check_symbols, "remote");
15651 #if 0
15652 init_remote_threadtests ();
15653 #endif
15655 /* set/show remote ... */
15657 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15658 Remote protocol specific variables.\n\
15659 Configure various remote-protocol specific variables such as\n\
15660 the packets being used."),
15661 &remote_set_cmdlist,
15662 0 /* allow-unknown */, &setlist);
15663 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15664 Remote protocol specific variables.\n\
15665 Configure various remote-protocol specific variables such as\n\
15666 the packets being used."),
15667 &remote_show_cmdlist,
15668 0 /* allow-unknown */, &showlist);
15670 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15671 Compare section data on target to the exec file.\n\
15672 Argument is a single section name (default: all loaded sections).\n\
15673 To compare only read-only loaded sections, specify the -r option."),
15674 &cmdlist);
15676 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15677 Send an arbitrary packet to a remote target.\n\
15678 maintenance packet TEXT\n\
15679 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15680 this command sends the string TEXT to the inferior, and displays the\n\
15681 response packet. GDB supplies the initial `$' character, and the\n\
15682 terminating `#' character and checksum."),
15683 &maintenancelist);
15685 set_show_commands remotebreak_cmds
15686 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15687 Set whether to send break if interrupted."), _("\
15688 Show whether to send break if interrupted."), _("\
15689 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15690 set_remotebreak, show_remotebreak,
15691 &setlist, &showlist);
15692 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15693 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15695 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15696 interrupt_sequence_modes, &interrupt_sequence_mode,
15697 _("\
15698 Set interrupt sequence to remote target."), _("\
15699 Show interrupt sequence to remote target."), _("\
15700 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15701 NULL, show_interrupt_sequence,
15702 &remote_set_cmdlist,
15703 &remote_show_cmdlist);
15705 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15706 &interrupt_on_connect, _("\
15707 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15708 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15709 If set, interrupt sequence is sent to remote target."),
15710 NULL, NULL,
15711 &remote_set_cmdlist, &remote_show_cmdlist);
15713 /* Install commands for configuring memory read/write packets. */
15715 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15716 Set the maximum number of bytes per memory write packet (deprecated)."),
15717 &setlist);
15718 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15719 Show the maximum number of bytes per memory write packet (deprecated)."),
15720 &showlist);
15721 add_cmd ("memory-write-packet-size", no_class,
15722 set_memory_write_packet_size, _("\
15723 Set the maximum number of bytes per memory-write packet.\n\
15724 Specify the number of bytes in a packet or 0 (zero) for the\n\
15725 default packet size. The actual limit is further reduced\n\
15726 dependent on the target. Specify \"fixed\" to disable the\n\
15727 further restriction and \"limit\" to enable that restriction."),
15728 &remote_set_cmdlist);
15729 add_cmd ("memory-read-packet-size", no_class,
15730 set_memory_read_packet_size, _("\
15731 Set the maximum number of bytes per memory-read packet.\n\
15732 Specify the number of bytes in a packet or 0 (zero) for the\n\
15733 default packet size. The actual limit is further reduced\n\
15734 dependent on the target. Specify \"fixed\" to disable the\n\
15735 further restriction and \"limit\" to enable that restriction."),
15736 &remote_set_cmdlist);
15737 add_cmd ("memory-write-packet-size", no_class,
15738 show_memory_write_packet_size,
15739 _("Show the maximum number of bytes per memory-write packet."),
15740 &remote_show_cmdlist);
15741 add_cmd ("memory-read-packet-size", no_class,
15742 show_memory_read_packet_size,
15743 _("Show the maximum number of bytes per memory-read packet."),
15744 &remote_show_cmdlist);
15746 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15747 &remote_hw_watchpoint_limit, _("\
15748 Set the maximum number of target hardware watchpoints."), _("\
15749 Show the maximum number of target hardware watchpoints."), _("\
15750 Specify \"unlimited\" for unlimited hardware watchpoints."),
15751 NULL, show_hardware_watchpoint_limit,
15752 &remote_set_cmdlist,
15753 &remote_show_cmdlist);
15754 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15755 no_class,
15756 &remote_hw_watchpoint_length_limit, _("\
15757 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15758 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15759 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15760 NULL, show_hardware_watchpoint_length_limit,
15761 &remote_set_cmdlist, &remote_show_cmdlist);
15762 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15763 &remote_hw_breakpoint_limit, _("\
15764 Set the maximum number of target hardware breakpoints."), _("\
15765 Show the maximum number of target hardware breakpoints."), _("\
15766 Specify \"unlimited\" for unlimited hardware breakpoints."),
15767 NULL, show_hardware_breakpoint_limit,
15768 &remote_set_cmdlist, &remote_show_cmdlist);
15770 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15771 &remote_address_size, _("\
15772 Set the maximum size of the address (in bits) in a memory packet."), _("\
15773 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15774 NULL,
15775 NULL, /* FIXME: i18n: */
15776 &setlist, &showlist);
15778 init_all_packet_configs ();
15780 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15782 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15784 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15787 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15788 "catch-syscalls", 0);
15790 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15791 "program-signals", 0);
15793 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15794 "set-working-dir", 0);
15796 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15797 "startup-with-shell", 0);
15799 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15800 "environment-hex-encoded", 0);
15802 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15803 "environment-reset", 0);
15805 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15806 "environment-unset", 0);
15808 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15810 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15812 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15814 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15816 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15818 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15820 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15822 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15824 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15825 "read-aux-vector", 0);
15827 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15828 "pid-to-exec-file", 0);
15830 add_packet_config_cmd (PACKET_qXfer_features,
15831 "qXfer:features:read", "target-features", 0);
15833 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15834 "library-info", 0);
15836 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15837 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15839 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15840 "memory-map", 0);
15842 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15844 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15847 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15848 "read-siginfo-object", 0);
15850 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15851 "write-siginfo-object", 0);
15853 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15854 "qXfer:traceframe-info:read", "traceframe-info", 0);
15856 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15857 "unwind-info-block", 0);
15859 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15860 "get-thread-local-storage-address", 0);
15862 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15863 "get-thread-information-block-address", 0);
15865 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15867 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15869 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15872 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15873 "search-memory", 0);
15875 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15877 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15879 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15881 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15883 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15886 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15888 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15891 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15892 "hostio-readlink", 0);
15894 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15896 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15898 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15900 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15902 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15904 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15906 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15907 "ConditionalTracepoints", "conditional-tracepoints",
15910 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15911 "ConditionalBreakpoints", "conditional-breakpoints",
15914 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15915 "breakpoint-commands", 0);
15917 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15918 "fast-tracepoints", 0);
15920 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15921 "TracepointSource", 0);
15923 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15925 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15926 "static-tracepoints", 0);
15928 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15929 "install-in-trace", 0);
15931 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15932 "qXfer:statictrace:read", "read-sdata-object", 0);
15934 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15935 "read-fdpic-loadmap", 0);
15937 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15938 "disable-randomization", 0);
15940 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15942 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15943 "trace-buffer-size", 0);
15945 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15948 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15951 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15954 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15956 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15957 "read-btrace-conf", 0);
15959 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15960 "btrace-conf-bts-size", 0);
15962 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15963 "multiprocess-feature", 0);
15965 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15966 "swbreak-feature", 0);
15968 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15969 "hwbreak-feature", 0);
15971 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15972 "fork-event-feature", 0);
15974 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15975 "vfork-event-feature", 0);
15977 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15978 "btrace-conf-pt-size", 0);
15980 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15981 "verbose-resume-supported", 0);
15983 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15984 "exec-event-feature", 0);
15986 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15988 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15991 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
15992 "thread-options", 0);
15994 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15995 "no-resumed-stop-reply", 0);
15997 add_packet_config_cmd (PACKET_memory_tagging_feature,
15998 "memory-tagging-feature", "memory-tagging-feature", 0);
16000 /* Assert that we've registered "set remote foo-packet" commands
16001 for all packet configs. */
16003 int i;
16005 for (i = 0; i < PACKET_MAX; i++)
16007 /* Ideally all configs would have a command associated. Some
16008 still don't though. */
16009 int excepted;
16011 switch (i)
16013 case PACKET_QNonStop:
16014 case PACKET_EnableDisableTracepoints_feature:
16015 case PACKET_tracenz_feature:
16016 case PACKET_DisconnectedTracing_feature:
16017 case PACKET_augmented_libraries_svr4_read_feature:
16018 case PACKET_qCRC:
16019 /* Additions to this list need to be well justified:
16020 pre-existing packets are OK; new packets are not. */
16021 excepted = 1;
16022 break;
16023 default:
16024 excepted = 0;
16025 break;
16028 /* This catches both forgetting to add a config command, and
16029 forgetting to remove a packet from the exception list. */
16030 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16034 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16035 Z sub-packet has its own set and show commands, but users may
16036 have sets to this variable in their .gdbinit files (or in their
16037 documentation). */
16038 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16039 &remote_Z_packet_detect, _("\
16040 Set use of remote protocol `Z' packets."), _("\
16041 Show use of remote protocol `Z' packets."), _("\
16042 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16043 packets."),
16044 set_remote_protocol_Z_packet_cmd,
16045 show_remote_protocol_Z_packet_cmd,
16046 /* FIXME: i18n: Use of remote protocol
16047 `Z' packets is %s. */
16048 &remote_set_cmdlist, &remote_show_cmdlist);
16050 add_basic_prefix_cmd ("remote", class_files, _("\
16051 Manipulate files on the remote system.\n\
16052 Transfer files to and from the remote target system."),
16053 &remote_cmdlist,
16054 0 /* allow-unknown */, &cmdlist);
16056 add_cmd ("put", class_files, remote_put_command,
16057 _("Copy a local file to the remote system."),
16058 &remote_cmdlist);
16060 add_cmd ("get", class_files, remote_get_command,
16061 _("Copy a remote file to the local system."),
16062 &remote_cmdlist);
16064 add_cmd ("delete", class_files, remote_delete_command,
16065 _("Delete a remote file."),
16066 &remote_cmdlist);
16068 add_setshow_string_noescape_cmd ("exec-file", class_files,
16069 &remote_exec_file_var, _("\
16070 Set the remote pathname for \"run\"."), _("\
16071 Show the remote pathname for \"run\"."), NULL,
16072 set_remote_exec_file,
16073 show_remote_exec_file,
16074 &remote_set_cmdlist,
16075 &remote_show_cmdlist);
16077 add_setshow_boolean_cmd ("range-stepping", class_run,
16078 &use_range_stepping, _("\
16079 Enable or disable range stepping."), _("\
16080 Show whether target-assisted range stepping is enabled."), _("\
16081 If on, and the target supports it, when stepping a source line, GDB\n\
16082 tells the target to step the corresponding range of addresses itself instead\n\
16083 of issuing multiple single-steps. This speeds up source level\n\
16084 stepping. If off, GDB always issues single-steps, even if range\n\
16085 stepping is supported by the target. The default is on."),
16086 set_range_stepping,
16087 show_range_stepping,
16088 &setlist,
16089 &showlist);
16091 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16092 Set watchdog timer."), _("\
16093 Show watchdog timer."), _("\
16094 When non-zero, this timeout is used instead of waiting forever for a target\n\
16095 to finish a low-level step or continue operation. If the specified amount\n\
16096 of time passes without a response from the target, an error occurs."),
16097 NULL,
16098 show_watchdog,
16099 &setlist, &showlist);
16101 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16102 &remote_packet_max_chars, _("\
16103 Set the maximum number of characters to display for each remote packet."), _("\
16104 Show the maximum number of characters to display for each remote packet."), _("\
16105 Specify \"unlimited\" to display all the characters."),
16106 NULL, show_remote_packet_max_chars,
16107 &setdebuglist, &showdebuglist);
16109 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16110 _("Set debugging of remote protocol."),
16111 _("Show debugging of remote protocol."),
16112 _("\
16113 When enabled, each packet sent or received with the remote target\n\
16114 is displayed."),
16115 NULL,
16116 show_remote_debug,
16117 &setdebuglist, &showdebuglist);
16119 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16120 &remote_timeout, _("\
16121 Set timeout limit to wait for target to respond."), _("\
16122 Show timeout limit to wait for target to respond."), _("\
16123 This value is used to set the time limit for gdb to wait for a response\n\
16124 from the target."),
16125 NULL,
16126 show_remote_timeout,
16127 &setlist, &showlist);
16129 /* Eventually initialize fileio. See fileio.c */
16130 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16132 #if GDB_SELF_TEST
16133 selftests::register_test ("remote_memory_tagging",
16134 selftests::test_memory_tagging_functions);
16135 #endif