Updated Bulgarian translation for the binutils/ directory
[binutils-gdb.git] / gdb / remote.c
blob4948a54e322880019aec701f4079b52f8ca7b121
1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2024 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 <ctype.h>
23 #include <fcntl.h>
24 #include "exceptions.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 "cli/cli-cmds.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"
82 #include "cli/cli-style.h"
84 /* The remote target. */
86 static const char remote_doc[] = N_("\
87 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
88 Specify the serial device it is connected to\n\
89 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
91 /* See remote.h */
93 bool remote_debug = false;
95 #define OPAQUETHREADBYTES 8
97 /* a 64 bit opaque identifier */
98 typedef unsigned char threadref[OPAQUETHREADBYTES];
100 struct gdb_ext_thread_info;
101 struct threads_listing_context;
102 typedef int (*rmt_thread_action) (threadref *ref, void *context);
103 struct protocol_feature;
104 struct packet_reg;
106 struct stop_reply;
107 typedef std::unique_ptr<stop_reply> stop_reply_up;
109 /* Generic configuration support for packets the stub optionally
110 supports. Allows the user to specify the use of the packet as well
111 as allowing GDB to auto-detect support in the remote stub. */
113 enum packet_support
115 PACKET_SUPPORT_UNKNOWN = 0,
116 PACKET_ENABLE,
117 PACKET_DISABLE
120 /* Convert the packet support auto_boolean to a name used for gdb printing. */
122 static const char *
123 get_packet_support_name (auto_boolean support)
125 switch (support)
127 case AUTO_BOOLEAN_TRUE:
128 return "on";
129 case AUTO_BOOLEAN_FALSE:
130 return "off";
131 case AUTO_BOOLEAN_AUTO:
132 return "auto";
133 default:
134 gdb_assert_not_reached ("invalid var_auto_boolean");
138 /* Convert the target type (future remote target or currently connected target)
139 to a name used for gdb printing. */
141 static const char *
142 get_target_type_name (bool target_connected)
144 if (target_connected)
145 return _("on the current remote target");
146 else
147 return _("on future remote targets");
150 /* Analyze a packet's return value and update the packet config
151 accordingly. */
153 enum packet_status
155 PACKET_ERROR,
156 PACKET_OK,
157 PACKET_UNKNOWN
160 /* Keeps packet's return value. If packet's return value is PACKET_ERROR,
161 err_msg contains an error message string from E.string or the number
162 stored as a string from E.num. */
163 class packet_result
165 private:
166 /* Private ctors for internal use. Clients should use the public
167 factory static methods instead. */
169 /* Construct a PACKET_ERROR packet_result. */
170 packet_result (const char *err_msg, bool textual_err_msg)
171 : m_status (PACKET_ERROR),
172 m_err_msg (err_msg),
173 m_textual_err_msg (textual_err_msg)
176 /* Construct an PACKET_OK/PACKET_UNKNOWN packet_result. */
177 explicit packet_result (enum packet_status status)
178 : m_status (status)
180 gdb_assert (status != PACKET_ERROR);
183 public:
184 enum packet_status status () const
186 return this->m_status;
189 const char *err_msg () const
191 gdb_assert (this->m_status == PACKET_ERROR);
192 return this->m_err_msg.c_str ();
195 bool textual_err_msg () const
197 gdb_assert (this->m_status == PACKET_ERROR);
198 return this->m_textual_err_msg;
201 static packet_result make_numeric_error (const char *err_msg)
203 return packet_result (err_msg, false);
206 static packet_result make_textual_error (const char *err_msg)
208 return packet_result (err_msg, true);
211 static packet_result make_ok ()
213 return packet_result (PACKET_OK);
216 static packet_result make_unknown ()
218 return packet_result (PACKET_UNKNOWN);
221 private:
222 enum packet_status m_status;
223 std::string m_err_msg;
225 /* True if we have a textual error message, from an "E.MESSAGE"
226 response. */
227 bool m_textual_err_msg = false;
230 /* Enumeration of packets for a remote target. */
232 enum {
233 PACKET_vCont = 0,
234 PACKET_X,
235 PACKET_qSymbol,
236 PACKET_P,
237 PACKET_p,
238 PACKET_Z0,
239 PACKET_Z1,
240 PACKET_Z2,
241 PACKET_Z3,
242 PACKET_Z4,
243 PACKET_vFile_setfs,
244 PACKET_vFile_open,
245 PACKET_vFile_pread,
246 PACKET_vFile_pwrite,
247 PACKET_vFile_close,
248 PACKET_vFile_unlink,
249 PACKET_vFile_readlink,
250 PACKET_vFile_fstat,
251 PACKET_vFile_stat,
252 PACKET_qXfer_auxv,
253 PACKET_qXfer_features,
254 PACKET_qXfer_exec_file,
255 PACKET_qXfer_libraries,
256 PACKET_qXfer_libraries_svr4,
257 PACKET_qXfer_memory_map,
258 PACKET_qXfer_osdata,
259 PACKET_qXfer_threads,
260 PACKET_qXfer_statictrace_read,
261 PACKET_qXfer_traceframe_info,
262 PACKET_qXfer_uib,
263 PACKET_qGetTIBAddr,
264 PACKET_qGetTLSAddr,
265 PACKET_qSupported,
266 PACKET_qTStatus,
267 PACKET_QPassSignals,
268 PACKET_QCatchSyscalls,
269 PACKET_QProgramSignals,
270 PACKET_QSetWorkingDir,
271 PACKET_QStartupWithShell,
272 PACKET_QEnvironmentHexEncoded,
273 PACKET_QEnvironmentReset,
274 PACKET_QEnvironmentUnset,
275 PACKET_qCRC,
276 PACKET_qSearch_memory,
277 PACKET_vAttach,
278 PACKET_vRun,
279 PACKET_QStartNoAckMode,
280 PACKET_vKill,
281 PACKET_qXfer_siginfo_read,
282 PACKET_qXfer_siginfo_write,
283 PACKET_qAttached,
285 /* Support for conditional tracepoints. */
286 PACKET_ConditionalTracepoints,
288 /* Support for target-side breakpoint conditions. */
289 PACKET_ConditionalBreakpoints,
291 /* Support for target-side breakpoint commands. */
292 PACKET_BreakpointCommands,
294 /* Support for fast tracepoints. */
295 PACKET_FastTracepoints,
297 /* Support for static tracepoints. */
298 PACKET_StaticTracepoints,
300 /* Support for installing tracepoints while a trace experiment is
301 running. */
302 PACKET_InstallInTrace,
304 PACKET_bc,
305 PACKET_bs,
306 PACKET_TracepointSource,
307 PACKET_QAllow,
308 PACKET_qXfer_fdpic,
309 PACKET_QDisableRandomization,
310 PACKET_QAgent,
311 PACKET_QTBuffer_size,
312 PACKET_Qbtrace_off,
313 PACKET_Qbtrace_bts,
314 PACKET_Qbtrace_pt,
315 PACKET_qXfer_btrace,
317 /* Support for the QNonStop packet. */
318 PACKET_QNonStop,
320 /* Support for the QThreadEvents packet. */
321 PACKET_QThreadEvents,
323 /* Support for the QThreadOptions packet. */
324 PACKET_QThreadOptions,
326 /* Support for multi-process extensions. */
327 PACKET_multiprocess_feature,
329 /* Support for enabling and disabling tracepoints while a trace
330 experiment is running. */
331 PACKET_EnableDisableTracepoints_feature,
333 /* Support for collecting strings using the tracenz bytecode. */
334 PACKET_tracenz_feature,
336 /* Support for continuing to run a trace experiment while GDB is
337 disconnected. */
338 PACKET_DisconnectedTracing_feature,
340 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
341 PACKET_augmented_libraries_svr4_read_feature,
343 /* Support for the qXfer:btrace-conf:read packet. */
344 PACKET_qXfer_btrace_conf,
346 /* Support for the Qbtrace-conf:bts:size packet. */
347 PACKET_Qbtrace_conf_bts_size,
349 /* Support for swbreak+ feature. */
350 PACKET_swbreak_feature,
352 /* Support for hwbreak+ feature. */
353 PACKET_hwbreak_feature,
355 /* Support for fork events. */
356 PACKET_fork_event_feature,
358 /* Support for vfork events. */
359 PACKET_vfork_event_feature,
361 /* Support for the Qbtrace-conf:pt:size packet. */
362 PACKET_Qbtrace_conf_pt_size,
364 /* Support for exec events. */
365 PACKET_exec_event_feature,
367 /* Support for query supported vCont actions. */
368 PACKET_vContSupported,
370 /* Support remote CTRL-C. */
371 PACKET_vCtrlC,
373 /* Support TARGET_WAITKIND_NO_RESUMED. */
374 PACKET_no_resumed,
376 /* Support for memory tagging, allocation tag fetch/store
377 packets and the tag violation stop replies. */
378 PACKET_memory_tagging_feature,
380 /* Support for the qIsAddressTagged packet. */
381 PACKET_qIsAddressTagged,
383 /* Support for accepting error message in a E.errtext format.
384 This allows every remote packet to return E.errtext.
386 This feature only exists to fix a backwards compatibility issue
387 with the qRcmd and m packets. Historically, these two packets didn't
388 support E.errtext style errors, but when this feature is on
389 these two packets can receive E.errtext style errors.
391 All new packets should be written to always accept E.errtext style
392 errors, and so they should not need to check for this feature. */
393 PACKET_accept_error_message,
395 PACKET_MAX
398 struct threads_listing_context;
400 /* Stub vCont actions support.
402 Each field is a boolean flag indicating whether the stub reports
403 support for the corresponding action. */
405 struct vCont_action_support
407 /* vCont;t */
408 bool t = false;
410 /* vCont;r */
411 bool r = false;
413 /* vCont;s */
414 bool s = false;
416 /* vCont;S */
417 bool S = false;
420 /* About this many threadids fit in a packet. */
422 #define MAXTHREADLISTRESULTS 32
424 /* Data for the vFile:pread readahead cache. */
426 struct readahead_cache
428 /* Invalidate the readahead cache. */
429 void invalidate ();
431 /* Invalidate the readahead cache if it is holding data for FD. */
432 void invalidate_fd (int fd);
434 /* Serve pread from the readahead cache. Returns number of bytes
435 read, or 0 if the request can't be served from the cache. */
436 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
438 /* The file descriptor for the file that is being cached. -1 if the
439 cache is invalid. */
440 int fd = -1;
442 /* The offset into the file that the cache buffer corresponds
443 to. */
444 ULONGEST offset = 0;
446 /* The buffer holding the cache contents. */
447 gdb::byte_vector buf;
449 /* Cache hit and miss counters. */
450 ULONGEST hit_count = 0;
451 ULONGEST miss_count = 0;
454 /* Description of the remote protocol for a given architecture. */
456 struct packet_reg
458 long offset; /* Offset into G packet. */
459 long regnum; /* GDB's internal register number. */
460 LONGEST pnum; /* Remote protocol register number. */
461 int in_g_packet; /* Always part of G packet. */
462 /* long size in bytes; == register_size (arch, regnum);
463 at present. */
464 /* char *name; == gdbarch_register_name (arch, regnum);
465 at present. */
468 struct remote_arch_state
470 explicit remote_arch_state (struct gdbarch *gdbarch);
472 /* Description of the remote protocol registers. */
473 long sizeof_g_packet;
475 /* Description of the remote protocol registers indexed by REGNUM
476 (making an array gdbarch_num_regs in size). */
477 std::unique_ptr<packet_reg[]> regs;
479 /* This is the size (in chars) of the first response to the ``g''
480 packet. It is used as a heuristic when determining the maximum
481 size of memory-read and memory-write packets. A target will
482 typically only reserve a buffer large enough to hold the ``g''
483 packet. The size does not include packet overhead (headers and
484 trailers). */
485 long actual_register_packet_size;
487 /* This is the maximum size (in chars) of a non read/write packet.
488 It is also used as a cap on the size of read/write packets. */
489 long remote_packet_size;
492 /* Description of the remote protocol state for the currently
493 connected target. This is per-target state, and independent of the
494 selected architecture. */
496 class remote_state
498 public:
500 remote_state ();
501 ~remote_state ();
503 /* Get the remote arch state for GDBARCH. */
504 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
506 void create_async_event_handler ()
508 gdb_assert (m_async_event_handler_token == nullptr);
509 m_async_event_handler_token
510 = ::create_async_event_handler ([] (gdb_client_data data)
512 inferior_event_handler (INF_REG_EVENT);
514 nullptr, "remote");
517 void mark_async_event_handler ()
519 gdb_assert (this->is_async_p ());
520 ::mark_async_event_handler (m_async_event_handler_token);
523 void clear_async_event_handler ()
524 { ::clear_async_event_handler (m_async_event_handler_token); }
526 bool async_event_handler_marked () const
527 { return ::async_event_handler_marked (m_async_event_handler_token); }
529 void delete_async_event_handler ()
531 if (m_async_event_handler_token != nullptr)
532 ::delete_async_event_handler (&m_async_event_handler_token);
535 bool is_async_p () const
537 /* We're async whenever the serial device is. */
538 gdb_assert (this->remote_desc != nullptr);
539 return serial_is_async_p (this->remote_desc);
542 bool can_async_p () const
544 /* We can async whenever the serial device can. */
545 gdb_assert (this->remote_desc != nullptr);
546 return serial_can_async_p (this->remote_desc);
549 public: /* data */
551 /* A buffer to use for incoming packets, and its current size. The
552 buffer is grown dynamically for larger incoming packets.
553 Outgoing packets may also be constructed in this buffer.
554 The size of the buffer is always at least REMOTE_PACKET_SIZE;
555 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
556 packets. */
557 gdb::char_vector buf;
559 /* True if we're going through initial connection setup (finding out
560 about the remote side's threads, relocating symbols, etc.). */
561 bool starting_up = false;
563 /* If we negotiated packet size explicitly (and thus can bypass
564 heuristics for the largest packet size that will not overflow
565 a buffer in the stub), this will be set to that packet size.
566 Otherwise zero, meaning to use the guessed size. */
567 long explicit_packet_size = 0;
569 /* True, if in no ack mode. That is, neither GDB nor the stub will
570 expect acks from each other. The connection is assumed to be
571 reliable. */
572 bool noack_mode = false;
574 /* True if we're connected in extended remote mode. */
575 bool extended = false;
577 /* True if we resumed the target and we're waiting for the target to
578 stop. In the mean time, we can't start another command/query.
579 The remote server wouldn't be ready to process it, so we'd
580 timeout waiting for a reply that would never come and eventually
581 we'd close the connection. This can happen in asynchronous mode
582 because we allow GDB commands while the target is running. */
583 bool waiting_for_stop_reply = false;
585 /* The status of the stub support for the various vCont actions. */
586 vCont_action_support supports_vCont;
588 /* True if the user has pressed Ctrl-C, but the target hasn't
589 responded to that. */
590 bool ctrlc_pending_p = false;
592 /* True if we saw a Ctrl-C while reading or writing from/to the
593 remote descriptor. At that point it is not safe to send a remote
594 interrupt packet, so we instead remember we saw the Ctrl-C and
595 process it once we're done with sending/receiving the current
596 packet, which should be shortly. If however that takes too long,
597 and the user presses Ctrl-C again, we offer to disconnect. */
598 bool got_ctrlc_during_io = false;
600 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
601 remote_open knows that we don't have a file open when the program
602 starts. */
603 struct serial *remote_desc = nullptr;
605 /* These are the threads which we last sent to the remote system. The
606 TID member will be -1 for all or -2 for not sent yet. */
607 ptid_t general_thread = null_ptid;
608 ptid_t continue_thread = null_ptid;
610 /* This is the traceframe which we last selected on the remote system.
611 It will be -1 if no traceframe is selected. */
612 int remote_traceframe_number = -1;
614 char *last_pass_packet = nullptr;
616 /* The last QProgramSignals packet sent to the target. We bypass
617 sending a new program signals list down to the target if the new
618 packet is exactly the same as the last we sent. IOW, we only let
619 the target know about program signals list changes. */
620 char *last_program_signals_packet = nullptr;
622 /* Similarly, the last QThreadEvents state we sent to the
623 target. */
624 bool last_thread_events = false;
626 gdb_signal last_sent_signal = GDB_SIGNAL_0;
628 bool last_sent_step = false;
630 /* The execution direction of the last resume we got. */
631 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
633 char *finished_object = nullptr;
634 char *finished_annex = nullptr;
635 ULONGEST finished_offset = 0;
637 /* Should we try the 'ThreadInfo' query packet?
639 This variable (NOT available to the user: auto-detect only!)
640 determines whether GDB will use the new, simpler "ThreadInfo"
641 query or the older, more complex syntax for thread queries.
642 This is an auto-detect variable (set to true at each connect,
643 and set to false when the target fails to recognize it). */
644 bool use_threadinfo_query = false;
645 bool use_threadextra_query = false;
647 threadref echo_nextthread {};
648 threadref nextthread {};
649 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
651 /* The state of remote notification. */
652 struct remote_notif_state *notif_state = nullptr;
654 /* The branch trace configuration. */
655 struct btrace_config btrace_config {};
657 /* The argument to the last "vFile:setfs:" packet we sent, used
658 to avoid sending repeated unnecessary "vFile:setfs:" packets.
659 Initialized to -1 to indicate that no "vFile:setfs:" packet
660 has yet been sent. */
661 int fs_pid = -1;
663 /* A readahead cache for vFile:pread. Often, reading a binary
664 involves a sequence of small reads. E.g., when parsing an ELF
665 file. A readahead cache helps mostly the case of remote
666 debugging on a connection with higher latency, due to the
667 request/reply nature of the RSP. We only cache data for a single
668 file descriptor at a time. */
669 struct readahead_cache readahead_cache;
671 /* The list of already fetched and acknowledged stop events. This
672 queue is used for notification Stop, and other notifications
673 don't need queue for their events, because the notification
674 events of Stop can't be consumed immediately, so that events
675 should be queued first, and be consumed by remote_wait_{ns,as}
676 one per time. Other notifications can consume their events
677 immediately, so queue is not needed for them. */
678 std::vector<stop_reply_up> stop_reply_queue;
680 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
681 ``forever'' still use the normal timeout mechanism. This is
682 currently used by the ASYNC code to guarentee that target reads
683 during the initial connect always time-out. Once getpkt has been
684 modified to return a timeout indication and, in turn
685 remote_wait()/wait_for_inferior() have gained a timeout parameter
686 this can go away. */
687 bool wait_forever_enabled_p = true;
689 /* The set of thread options the target reported it supports, via
690 qSupported. */
691 gdb_thread_options supported_thread_options = 0;
693 private:
694 /* Asynchronous signal handle registered as event loop source for
695 when we have pending events ready to be passed to the core. */
696 async_event_handler *m_async_event_handler_token = nullptr;
698 /* Mapping of remote protocol data for each gdbarch. Usually there
699 is only one entry here, though we may see more with stubs that
700 support multi-process. */
701 std::unordered_map<struct gdbarch *, remote_arch_state>
702 m_arch_states;
705 static const target_info remote_target_info = {
706 "remote",
707 N_("Remote target using gdb-specific protocol"),
708 remote_doc
711 /* Description of a remote packet. */
713 struct packet_description
715 /* Name of the packet used for gdb output. */
716 const char *name;
718 /* Title of the packet, used by the set/show remote name-packet
719 commands to identify the individual packages and gdb output. */
720 const char *title;
723 /* Configuration of a remote packet. */
725 struct packet_config
727 /* If auto, GDB auto-detects support for this packet or feature,
728 either through qSupported, or by trying the packet and looking
729 at the response. If true, GDB assumes the target supports this
730 packet. If false, the packet is disabled. Configs that don't
731 have an associated command always have this set to auto. */
732 enum auto_boolean detect;
734 /* Does the target support this packet? */
735 enum packet_support support;
738 /* User configurable variables for the number of characters in a
739 memory read/write packet. MIN (rsa->remote_packet_size,
740 rsa->sizeof_g_packet) is the default. Some targets need smaller
741 values (fifo overruns, et.al.) and some users need larger values
742 (speed up transfers). The variables ``preferred_*'' (the user
743 request), ``current_*'' (what was actually set) and ``forced_*''
744 (Positive - a soft limit, negative - a hard limit). */
746 struct memory_packet_config
748 const char *name;
749 long size;
750 int fixed_p;
753 /* These global variables contain the default configuration for every new
754 remote_feature object. */
755 static memory_packet_config memory_read_packet_config =
757 "memory-read-packet-size",
759 static memory_packet_config memory_write_packet_config =
761 "memory-write-packet-size",
764 /* This global array contains packet descriptions (name and title). */
765 static packet_description packets_descriptions[PACKET_MAX];
766 /* This global array contains the default configuration for every new
767 per-remote target array. */
768 static packet_config remote_protocol_packets[PACKET_MAX];
770 /* Description of a remote target's features. It stores the configuration
771 and provides functions to determine supported features of the target. */
773 struct remote_features
775 remote_features ()
777 m_memory_read_packet_config = memory_read_packet_config;
778 m_memory_write_packet_config = memory_write_packet_config;
780 std::copy (std::begin (remote_protocol_packets),
781 std::end (remote_protocol_packets),
782 std::begin (m_protocol_packets));
784 ~remote_features () = default;
786 DISABLE_COPY_AND_ASSIGN (remote_features);
788 /* Returns whether a given packet defined by its enum value is supported. */
789 enum packet_support packet_support (int) const;
791 /* Returns the packet's corresponding "set remote foo-packet" command
792 state. See struct packet_config for more details. */
793 enum auto_boolean packet_set_cmd_state (int packet) const
794 { return m_protocol_packets[packet].detect; }
796 /* Returns true if the multi-process extensions are in effect. */
797 int remote_multi_process_p () const
798 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
800 /* Returns true if fork events are supported. */
801 int remote_fork_event_p () const
802 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
804 /* Returns true if vfork events are supported. */
805 int remote_vfork_event_p () const
806 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
808 /* Returns true if exec events are supported. */
809 int remote_exec_event_p () const
810 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
812 /* Returns true if memory tagging is supported, false otherwise. */
813 bool remote_memory_tagging_p () const
814 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
816 /* Reset all packets back to "unknown support". Called when opening a
817 new connection to a remote target. */
818 void reset_all_packet_configs_support ();
820 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
821 support configuration accordingly. */
822 packet_result packet_ok (const char *buf, const int which_packet);
823 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
825 /* Configuration of a remote target's memory read packet. */
826 memory_packet_config m_memory_read_packet_config;
827 /* Configuration of a remote target's memory write packet. */
828 memory_packet_config m_memory_write_packet_config;
830 /* The per-remote target array which stores a remote's packet
831 configurations. */
832 packet_config m_protocol_packets[PACKET_MAX];
835 class remote_target : public process_stratum_target
837 public:
838 remote_target () = default;
839 ~remote_target () override;
841 const target_info &info () const override
842 { return remote_target_info; }
844 const char *connection_string () override;
846 thread_control_capabilities get_thread_control_capabilities () override
847 { return tc_schedlock; }
849 /* Open a remote connection. */
850 static void open (const char *, int);
852 void close () override;
854 void detach (inferior *, int) override;
855 void disconnect (const char *, int) override;
857 void commit_requested_thread_options ();
859 void commit_resumed () override;
860 void resume (ptid_t, int, enum gdb_signal) override;
861 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
862 bool has_pending_events () override;
864 void fetch_registers (struct regcache *, int) override;
865 void store_registers (struct regcache *, int) override;
866 void prepare_to_store (struct regcache *) override;
868 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
870 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
871 enum remove_bp_reason) override;
874 bool stopped_by_sw_breakpoint () override;
875 bool supports_stopped_by_sw_breakpoint () override;
877 bool stopped_by_hw_breakpoint () override;
879 bool supports_stopped_by_hw_breakpoint () override;
881 bool stopped_by_watchpoint () override;
883 bool stopped_data_address (CORE_ADDR *) override;
885 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
887 int can_use_hw_breakpoint (enum bptype, int, int) override;
889 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
891 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
893 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
895 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
896 struct expression *) override;
898 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
899 struct expression *) override;
901 void kill () override;
903 void load (const char *, int) override;
905 void mourn_inferior () override;
907 void pass_signals (gdb::array_view<const unsigned char>) override;
909 int set_syscall_catchpoint (int, bool, int,
910 gdb::array_view<const int>) override;
912 void program_signals (gdb::array_view<const unsigned char>) override;
914 bool thread_alive (ptid_t ptid) override;
916 const char *thread_name (struct thread_info *) override;
918 void update_thread_list () override;
920 std::string pid_to_str (ptid_t) override;
922 const char *extra_thread_info (struct thread_info *) override;
924 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
926 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
927 int handle_len,
928 inferior *inf) override;
930 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
931 override;
933 void stop (ptid_t) override;
935 void interrupt () override;
937 void pass_ctrlc () override;
939 enum target_xfer_status xfer_partial (enum target_object object,
940 const char *annex,
941 gdb_byte *readbuf,
942 const gdb_byte *writebuf,
943 ULONGEST offset, ULONGEST len,
944 ULONGEST *xfered_len) override;
946 ULONGEST get_memory_xfer_limit () override;
948 void rcmd (const char *command, struct ui_file *output) override;
950 const char *pid_to_exec_file (int pid) override;
952 void log_command (const char *cmd) override
954 serial_log_command (this, cmd);
957 CORE_ADDR get_thread_local_address (ptid_t ptid,
958 CORE_ADDR load_module_addr,
959 CORE_ADDR offset) override;
961 bool can_execute_reverse () override;
963 std::vector<mem_region> memory_map () override;
965 void flash_erase (ULONGEST address, LONGEST length) override;
967 void flash_done () override;
969 const struct target_desc *read_description () override;
971 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
972 const gdb_byte *pattern, ULONGEST pattern_len,
973 CORE_ADDR *found_addrp) override;
975 bool can_async_p () override;
977 bool is_async_p () override;
979 void async (bool) override;
981 int async_wait_fd () override;
983 void thread_events (bool) override;
985 bool supports_set_thread_options (gdb_thread_options) override;
987 int can_do_single_step () override;
989 void terminal_inferior () override;
991 void terminal_ours () override;
993 bool supports_non_stop () override;
995 bool supports_multi_process () override;
997 bool supports_disable_randomization () override;
999 bool filesystem_is_local () override;
1002 int fileio_open (struct inferior *inf, const char *filename,
1003 int flags, int mode, int warn_if_slow,
1004 fileio_error *target_errno) override;
1006 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
1007 ULONGEST offset, fileio_error *target_errno) override;
1009 int fileio_pread (int fd, gdb_byte *read_buf, int len,
1010 ULONGEST offset, fileio_error *target_errno) override;
1012 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
1014 int fileio_stat (struct inferior *inf, const char *filename,
1015 struct stat *sb, fileio_error *target_errno) override;
1017 int fileio_close (int fd, fileio_error *target_errno) override;
1019 int fileio_unlink (struct inferior *inf,
1020 const char *filename,
1021 fileio_error *target_errno) override;
1023 std::optional<std::string>
1024 fileio_readlink (struct inferior *inf,
1025 const char *filename,
1026 fileio_error *target_errno) override;
1028 bool supports_enable_disable_tracepoint () override;
1030 bool supports_string_tracing () override;
1032 int remote_supports_cond_tracepoints ();
1034 bool supports_evaluation_of_breakpoint_conditions () override;
1036 int remote_supports_fast_tracepoints ();
1038 int remote_supports_static_tracepoints ();
1040 int remote_supports_install_in_trace ();
1042 bool can_run_breakpoint_commands () override;
1044 void trace_init () override;
1046 void download_tracepoint (struct bp_location *location) override;
1048 bool can_download_tracepoint () override;
1050 void download_trace_state_variable (const trace_state_variable &tsv) override;
1052 void enable_tracepoint (struct bp_location *location) override;
1054 void disable_tracepoint (struct bp_location *location) override;
1056 void trace_set_readonly_regions () override;
1058 void trace_start () override;
1060 int get_trace_status (struct trace_status *ts) override;
1062 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
1063 override;
1065 void trace_stop () override;
1067 int trace_find (enum trace_find_type type, int num,
1068 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
1070 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
1072 int save_trace_data (const char *filename) override;
1074 int upload_tracepoints (struct uploaded_tp **utpp) override;
1076 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
1078 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
1080 int get_min_fast_tracepoint_insn_len () override;
1082 void set_disconnected_tracing (int val) override;
1084 void set_circular_trace_buffer (int val) override;
1086 void set_trace_buffer_size (LONGEST val) override;
1088 bool set_trace_notes (const char *user, const char *notes,
1089 const char *stopnotes) override;
1091 int core_of_thread (ptid_t ptid) override;
1093 int verify_memory (const gdb_byte *data,
1094 CORE_ADDR memaddr, ULONGEST size) override;
1097 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
1099 void set_permissions () override;
1101 bool static_tracepoint_marker_at (CORE_ADDR,
1102 struct static_tracepoint_marker *marker)
1103 override;
1105 std::vector<static_tracepoint_marker>
1106 static_tracepoint_markers_by_strid (const char *id) override;
1108 traceframe_info_up traceframe_info () override;
1110 bool use_agent (bool use) override;
1111 bool can_use_agent () override;
1113 struct btrace_target_info *
1114 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1116 void disable_btrace (struct btrace_target_info *tinfo) override;
1118 void teardown_btrace (struct btrace_target_info *tinfo) override;
1120 enum btrace_error read_btrace (struct btrace_data *data,
1121 struct btrace_target_info *btinfo,
1122 enum btrace_read_type type) override;
1124 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1125 bool augmented_libraries_svr4_read () override;
1126 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1127 void follow_clone (ptid_t child_ptid) override;
1128 void follow_exec (inferior *, ptid_t, const char *) override;
1129 int insert_fork_catchpoint (int) override;
1130 int remove_fork_catchpoint (int) override;
1131 int insert_vfork_catchpoint (int) override;
1132 int remove_vfork_catchpoint (int) override;
1133 int insert_exec_catchpoint (int) override;
1134 int remove_exec_catchpoint (int) override;
1135 enum exec_direction_kind execution_direction () override;
1137 bool supports_memory_tagging () override;
1139 bool fetch_memtags (CORE_ADDR address, size_t len,
1140 gdb::byte_vector &tags, int type) override;
1142 bool store_memtags (CORE_ADDR address, size_t len,
1143 const gdb::byte_vector &tags, int type) override;
1145 bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
1147 public: /* Remote specific methods. */
1149 void remote_download_command_source (int num, ULONGEST addr,
1150 struct command_line *cmds);
1152 void remote_file_put (const char *local_file, const char *remote_file,
1153 int from_tty);
1154 void remote_file_get (const char *remote_file, const char *local_file,
1155 int from_tty);
1156 void remote_file_delete (const char *remote_file, int from_tty);
1158 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1159 ULONGEST offset, fileio_error *remote_errno);
1160 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1161 ULONGEST offset, fileio_error *remote_errno);
1162 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1163 ULONGEST offset, fileio_error *remote_errno);
1165 int remote_hostio_send_command (int command_bytes, int which_packet,
1166 fileio_error *remote_errno, const char **attachment,
1167 int *attachment_len);
1168 int remote_hostio_set_filesystem (struct inferior *inf,
1169 fileio_error *remote_errno);
1170 /* We should get rid of this and use fileio_open directly. */
1171 int remote_hostio_open (struct inferior *inf, const char *filename,
1172 int flags, int mode, int warn_if_slow,
1173 fileio_error *remote_errno);
1174 int remote_hostio_close (int fd, fileio_error *remote_errno);
1176 int remote_hostio_unlink (inferior *inf, const char *filename,
1177 fileio_error *remote_errno);
1179 struct remote_state *get_remote_state ();
1181 long get_remote_packet_size (void);
1182 long get_memory_packet_size (struct memory_packet_config *config);
1184 long get_memory_write_packet_size ();
1185 long get_memory_read_packet_size ();
1187 char *append_pending_thread_resumptions (char *p, char *endp,
1188 ptid_t ptid);
1189 static void open_1 (const char *name, int from_tty, int extended_p);
1190 void start_remote (int from_tty, int extended_p);
1191 void remote_detach_1 (struct inferior *inf, int from_tty);
1193 char *append_resumption (char *p, char *endp,
1194 ptid_t ptid, int step, gdb_signal siggnal);
1195 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1196 gdb_signal siggnal);
1198 thread_info *add_current_inferior_and_thread (const char *wait_status);
1200 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1201 target_wait_flags options);
1202 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1203 target_wait_flags options);
1205 ptid_t process_stop_reply (stop_reply_up stop_reply,
1206 target_waitstatus *status);
1208 ptid_t select_thread_for_ambiguous_stop_reply
1209 (const struct target_waitstatus &status);
1211 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1213 void print_one_stopped_thread (thread_info *thread);
1214 void process_initial_stop_replies (int from_tty);
1216 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1217 bool silent_p);
1219 void btrace_sync_conf (const btrace_config *conf);
1221 void remote_btrace_maybe_reopen ();
1223 void remove_new_children (threads_listing_context *context);
1224 void kill_new_fork_children (inferior *inf);
1225 void discard_pending_stop_replies (struct inferior *inf);
1226 int stop_reply_queue_length ();
1228 void check_pending_events_prevent_wildcard_vcont
1229 (bool *may_global_wildcard_vcont);
1231 void discard_pending_stop_replies_in_queue ();
1232 stop_reply_up remote_notif_remove_queued_reply (ptid_t ptid);
1233 stop_reply_up queued_stop_reply (ptid_t ptid);
1234 int peek_stop_reply (ptid_t ptid);
1235 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1237 void remote_stop_ns (ptid_t ptid);
1238 void remote_interrupt_as ();
1239 void remote_interrupt_ns ();
1241 char *remote_get_noisy_reply ();
1242 int remote_query_attached (int pid);
1243 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1244 int try_open_exec);
1246 ptid_t remote_current_thread (ptid_t oldpid);
1247 ptid_t get_current_thread (const char *wait_status);
1249 void set_thread (ptid_t ptid, int gen);
1250 void set_general_thread (ptid_t ptid);
1251 void set_continue_thread (ptid_t ptid);
1252 void set_general_process ();
1254 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1256 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1257 gdb_ext_thread_info *info);
1258 int remote_get_threadinfo (threadref *threadid, int fieldset,
1259 gdb_ext_thread_info *info);
1261 int parse_threadlist_response (const char *pkt, int result_limit,
1262 threadref *original_echo,
1263 threadref *resultlist,
1264 int *doneflag);
1265 int remote_get_threadlist (int startflag, threadref *nextthread,
1266 int result_limit, int *done, int *result_count,
1267 threadref *threadlist);
1269 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1270 void *context, int looplimit);
1272 int remote_get_threads_with_ql (threads_listing_context *context);
1273 int remote_get_threads_with_qxfer (threads_listing_context *context);
1274 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1276 void extended_remote_restart ();
1278 void get_offsets ();
1280 void remote_check_symbols ();
1282 void remote_supported_packet (const struct protocol_feature *feature,
1283 enum packet_support support,
1284 const char *argument);
1286 void remote_query_supported ();
1288 void remote_packet_size (const protocol_feature *feature,
1289 packet_support support, const char *value);
1290 void remote_supported_thread_options (const protocol_feature *feature,
1291 enum packet_support support,
1292 const char *value);
1294 void remote_serial_quit_handler ();
1296 void remote_detach_pid (int pid);
1298 void remote_vcont_probe ();
1300 void remote_resume_with_hc (ptid_t ptid, int step,
1301 gdb_signal siggnal);
1303 void send_interrupt_sequence ();
1304 void interrupt_query ();
1306 void remote_notif_get_pending_events (const notif_client *nc);
1308 int fetch_register_using_p (struct regcache *regcache,
1309 packet_reg *reg);
1310 int send_g_packet ();
1311 void process_g_packet (struct regcache *regcache);
1312 void fetch_registers_using_g (struct regcache *regcache);
1313 int store_register_using_P (const struct regcache *regcache,
1314 packet_reg *reg);
1315 void store_registers_using_G (const struct regcache *regcache);
1317 void set_remote_traceframe ();
1319 void check_binary_download (CORE_ADDR addr);
1321 target_xfer_status remote_write_bytes_aux (const char *header,
1322 CORE_ADDR memaddr,
1323 const gdb_byte *myaddr,
1324 ULONGEST len_units,
1325 int unit_size,
1326 ULONGEST *xfered_len_units,
1327 char packet_format,
1328 int use_length);
1330 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1331 const gdb_byte *myaddr, ULONGEST len,
1332 int unit_size, ULONGEST *xfered_len);
1334 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1335 ULONGEST len_units,
1336 int unit_size, ULONGEST *xfered_len_units);
1338 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1339 ULONGEST memaddr,
1340 ULONGEST len,
1341 int unit_size,
1342 ULONGEST *xfered_len);
1344 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1345 gdb_byte *myaddr, ULONGEST len,
1346 int unit_size,
1347 ULONGEST *xfered_len);
1349 packet_status remote_send_printf (const char *format, ...)
1350 ATTRIBUTE_PRINTF (2, 3);
1352 target_xfer_status remote_flash_write (ULONGEST address,
1353 ULONGEST length, ULONGEST *xfered_len,
1354 const gdb_byte *data);
1356 int readchar (int timeout);
1358 void remote_serial_write (const char *str, int len);
1359 void remote_serial_send_break ();
1361 int putpkt (const char *buf);
1362 int putpkt_binary (const char *buf, int cnt);
1364 int putpkt (const gdb::char_vector &buf)
1366 return putpkt (buf.data ());
1369 void skip_frame ();
1370 long read_frame (gdb::char_vector *buf_p);
1371 int getpkt (gdb::char_vector *buf, bool forever = false,
1372 bool *is_notif = nullptr);
1373 int remote_vkill (int pid);
1374 void remote_kill_k ();
1376 void extended_remote_disable_randomization (int val);
1377 int extended_remote_run (const std::string &args);
1379 void send_environment_packet (const char *action,
1380 const char *packet,
1381 const char *value);
1383 void extended_remote_environment_support ();
1384 void extended_remote_set_inferior_cwd ();
1386 target_xfer_status remote_write_qxfer (const char *object_name,
1387 const char *annex,
1388 const gdb_byte *writebuf,
1389 ULONGEST offset, LONGEST len,
1390 ULONGEST *xfered_len,
1391 const unsigned int which_packet);
1393 target_xfer_status remote_read_qxfer (const char *object_name,
1394 const char *annex,
1395 gdb_byte *readbuf, ULONGEST offset,
1396 LONGEST len,
1397 ULONGEST *xfered_len,
1398 const unsigned int which_packet);
1400 void push_stop_reply (stop_reply_up new_event);
1402 bool vcont_r_supported ();
1404 remote_features m_features;
1406 private:
1408 bool start_remote_1 (int from_tty, int extended_p);
1410 /* The remote state. Don't reference this directly. Use the
1411 get_remote_state method instead. */
1412 remote_state m_remote_state;
1415 static const target_info extended_remote_target_info = {
1416 "extended-remote",
1417 N_("Extended remote target using gdb-specific protocol"),
1418 remote_doc
1421 /* Set up the extended remote target by extending the standard remote
1422 target and adding to it. */
1424 class extended_remote_target final : public remote_target
1426 public:
1427 const target_info &info () const override
1428 { return extended_remote_target_info; }
1430 /* Open an extended-remote connection. */
1431 static void open (const char *, int);
1433 bool can_create_inferior () override { return true; }
1434 void create_inferior (const char *, const std::string &,
1435 char **, int) override;
1437 void detach (inferior *, int) override;
1439 bool can_attach () override { return true; }
1440 void attach (const char *, int) override;
1442 void post_attach (int) override;
1443 bool supports_disable_randomization () override;
1446 struct stop_reply : public notif_event
1448 /* The identifier of the thread about this event */
1449 ptid_t ptid;
1451 /* The remote state this event is associated with. When the remote
1452 connection, represented by a remote_state object, is closed,
1453 all the associated stop_reply events should be released. */
1454 struct remote_state *rs;
1456 struct target_waitstatus ws;
1458 /* The architecture associated with the expedited registers. */
1459 gdbarch *arch;
1461 /* Expedited registers. This makes remote debugging a bit more
1462 efficient for those targets that provide critical registers as
1463 part of their normal status mechanism (as another roundtrip to
1464 fetch them is avoided). */
1465 std::vector<cached_reg_t> regcache;
1467 enum target_stop_reason stop_reason;
1469 CORE_ADDR watch_data_address;
1471 int core;
1474 /* Return TARGET as a remote_target if it is one, else nullptr. */
1476 static remote_target *
1477 as_remote_target (process_stratum_target *target)
1479 return dynamic_cast<remote_target *> (target);
1482 /* See remote.h. */
1484 bool
1485 is_remote_target (process_stratum_target *target)
1487 return as_remote_target (target) != nullptr;
1490 /* Per-program-space data key. */
1491 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1492 remote_pspace_data;
1494 /* The variable registered as the control variable used by the
1495 remote exec-file commands. While the remote exec-file setting is
1496 per-program-space, the set/show machinery uses this as the
1497 location of the remote exec-file value. */
1498 static std::string remote_exec_file_var;
1500 /* The size to align memory write packets, when practical. The protocol
1501 does not guarantee any alignment, and gdb will generate short
1502 writes and unaligned writes, but even as a best-effort attempt this
1503 can improve bulk transfers. For instance, if a write is misaligned
1504 relative to the target's data bus, the stub may need to make an extra
1505 round trip fetching data from the target. This doesn't make a
1506 huge difference, but it's easy to do, so we try to be helpful.
1508 The alignment chosen is arbitrary; usually data bus width is
1509 important here, not the possibly larger cache line size. */
1510 enum { REMOTE_ALIGN_WRITES = 16 };
1512 /* Prototypes for local functions. */
1514 static int hexnumlen (ULONGEST num);
1516 static int stubhex (int ch);
1518 static int hexnumstr (char *, ULONGEST);
1520 static int hexnumnstr (char *, ULONGEST, int);
1522 static CORE_ADDR remote_address_masked (CORE_ADDR);
1524 static int stub_unpack_int (const char *buff, int fieldlength);
1526 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1527 cmd_list_element *c);
1529 static void show_packet_config_cmd (ui_file *file,
1530 const unsigned int which_packet,
1531 remote_target *remote);
1533 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1534 int from_tty,
1535 struct cmd_list_element *c,
1536 const char *value);
1538 static ptid_t read_ptid (const char *buf, const char **obuf);
1540 static bool remote_read_description_p (struct target_ops *target);
1542 static void remote_console_output (const char *msg, ui_file *stream);
1544 static void remote_btrace_reset (remote_state *rs);
1546 [[noreturn]] static void remote_unpush_and_throw (remote_target *target);
1548 /* For "remote". */
1550 static struct cmd_list_element *remote_cmdlist;
1552 /* For "set remote" and "show remote". */
1554 static struct cmd_list_element *remote_set_cmdlist;
1555 static struct cmd_list_element *remote_show_cmdlist;
1557 /* Controls whether GDB is willing to use range stepping. */
1559 static bool use_range_stepping = true;
1561 /* From the remote target's point of view, each thread is in one of these three
1562 states. */
1563 enum class resume_state
1565 /* Not resumed - we haven't been asked to resume this thread. */
1566 NOT_RESUMED,
1568 /* We have been asked to resume this thread, but haven't sent a vCont action
1569 for it yet. We'll need to consider it next time commit_resume is
1570 called. */
1571 RESUMED_PENDING_VCONT,
1573 /* We have been asked to resume this thread, and we have sent a vCont action
1574 for it. */
1575 RESUMED,
1578 /* Information about a thread's pending vCont-resume. Used when a thread is in
1579 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1580 stores this information which is then picked up by
1581 remote_target::commit_resume to know which is the proper action for this
1582 thread to include in the vCont packet. */
1583 struct resumed_pending_vcont_info
1585 /* True if the last resume call for this thread was a step request, false
1586 if a continue request. */
1587 bool step;
1589 /* The signal specified in the last resume call for this thread. */
1590 gdb_signal sig;
1593 /* Private data that we'll store in (struct thread_info)->priv. */
1594 struct remote_thread_info : public private_thread_info
1596 std::string extra;
1597 std::string name;
1598 int core = -1;
1600 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1601 sequence of bytes. */
1602 gdb::byte_vector thread_handle;
1604 /* Whether the target stopped for a breakpoint/watchpoint. */
1605 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1607 /* This is set to the data address of the access causing the target
1608 to stop for a watchpoint. */
1609 CORE_ADDR watch_data_address = 0;
1611 /* Get the thread's resume state. */
1612 enum resume_state get_resume_state () const
1614 return m_resume_state;
1617 /* Put the thread in the NOT_RESUMED state. */
1618 void set_not_resumed ()
1620 m_resume_state = resume_state::NOT_RESUMED;
1623 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1624 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1626 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1627 m_resumed_pending_vcont_info.step = step;
1628 m_resumed_pending_vcont_info.sig = sig;
1631 /* Get the information this thread's pending vCont-resumption.
1633 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1634 state. */
1635 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1637 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1639 return m_resumed_pending_vcont_info;
1642 /* Put the thread in the VCONT_RESUMED state. */
1643 void set_resumed ()
1645 m_resume_state = resume_state::RESUMED;
1648 private:
1649 /* Resume state for this thread. This is used to implement vCont action
1650 coalescing (only when the target operates in non-stop mode).
1652 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1653 which notes that this thread must be considered in the next commit_resume
1654 call.
1656 remote_target::commit_resume sends a vCont packet with actions for the
1657 threads in the RESUMED_PENDING_VCONT state and moves them to the
1658 VCONT_RESUMED state.
1660 When reporting a stop to the core for a thread, that thread is moved back
1661 to the NOT_RESUMED state. */
1662 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1664 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1665 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1668 remote_state::remote_state ()
1669 : buf (400)
1673 remote_state::~remote_state ()
1675 xfree (this->last_pass_packet);
1676 xfree (this->last_program_signals_packet);
1677 xfree (this->finished_object);
1678 xfree (this->finished_annex);
1681 /* Utility: generate error from an incoming stub packet. */
1682 static void
1683 trace_error (char *buf)
1685 if (*buf++ != 'E')
1686 return; /* not an error msg */
1687 switch (*buf)
1689 case '1': /* malformed packet error */
1690 if (*++buf == '0') /* general case: */
1691 error (_("remote.c: error in outgoing packet."));
1692 else
1693 error (_("remote.c: error in outgoing packet at field #%ld."),
1694 strtol (buf, NULL, 16));
1695 default:
1696 error (_("Target returns error code '%s'."), buf);
1700 /* Utility: wait for reply from stub, while accepting "O" packets. */
1702 char *
1703 remote_target::remote_get_noisy_reply ()
1705 struct remote_state *rs = get_remote_state ();
1707 do /* Loop on reply from remote stub. */
1709 char *buf;
1711 QUIT; /* Allow user to bail out with ^C. */
1712 getpkt (&rs->buf);
1713 buf = rs->buf.data ();
1714 if (buf[0] == 'E')
1715 trace_error (buf);
1716 else if (startswith (buf, "qRelocInsn:"))
1718 ULONGEST ul;
1719 CORE_ADDR from, to, org_to;
1720 const char *p, *pp;
1721 int adjusted_size = 0;
1722 int relocated = 0;
1724 p = buf + strlen ("qRelocInsn:");
1725 pp = unpack_varlen_hex (p, &ul);
1726 if (*pp != ';')
1727 error (_("invalid qRelocInsn packet: %s"), buf);
1728 from = ul;
1730 p = pp + 1;
1731 unpack_varlen_hex (p, &ul);
1732 to = ul;
1734 org_to = to;
1738 gdbarch_relocate_instruction (current_inferior ()->arch (),
1739 &to, from);
1740 relocated = 1;
1742 catch (const gdb_exception &ex)
1744 if (ex.error == MEMORY_ERROR)
1746 /* Propagate memory errors silently back to the
1747 target. The stub may have limited the range of
1748 addresses we can write to, for example. */
1750 else
1752 /* Something unexpectedly bad happened. Be verbose
1753 so we can tell what, and propagate the error back
1754 to the stub, so it doesn't get stuck waiting for
1755 a response. */
1756 exception_fprintf (gdb_stderr, ex,
1757 _("warning: relocating instruction: "));
1759 putpkt ("E01");
1762 if (relocated)
1764 adjusted_size = to - org_to;
1766 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1767 putpkt (buf);
1770 else if (buf[0] == 'O' && buf[1] != 'K')
1772 /* 'O' message from stub */
1773 remote_console_output (buf + 1, gdb_stdtarg);
1775 else
1776 return buf; /* Here's the actual reply. */
1778 while (1);
1781 struct remote_arch_state *
1782 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1784 remote_arch_state *rsa;
1786 auto it = this->m_arch_states.find (gdbarch);
1787 if (it == this->m_arch_states.end ())
1789 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1790 std::forward_as_tuple (gdbarch),
1791 std::forward_as_tuple (gdbarch));
1792 rsa = &p.first->second;
1794 /* Make sure that the packet buffer is plenty big enough for
1795 this architecture. */
1796 if (this->buf.size () < rsa->remote_packet_size)
1797 this->buf.resize (2 * rsa->remote_packet_size);
1799 else
1800 rsa = &it->second;
1802 return rsa;
1805 /* Fetch the global remote target state. */
1807 remote_state *
1808 remote_target::get_remote_state ()
1810 /* Make sure that the remote architecture state has been
1811 initialized, because doing so might reallocate rs->buf. Any
1812 function which calls getpkt also needs to be mindful of changes
1813 to rs->buf, but this call limits the number of places which run
1814 into trouble. */
1815 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1817 return &m_remote_state;
1820 /* Fetch the remote exec-file from the current program space. */
1822 static const char *
1823 get_remote_exec_file (void)
1825 char *remote_exec_file;
1827 remote_exec_file = remote_pspace_data.get (current_program_space);
1828 if (remote_exec_file == NULL)
1829 return "";
1831 return remote_exec_file;
1834 /* Set the remote exec file for PSPACE. */
1836 static void
1837 set_pspace_remote_exec_file (struct program_space *pspace,
1838 const char *remote_exec_file)
1840 char *old_file = remote_pspace_data.get (pspace);
1842 xfree (old_file);
1843 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1846 /* The "set/show remote exec-file" set command hook. */
1848 static void
1849 set_remote_exec_file (const char *ignored, int from_tty,
1850 struct cmd_list_element *c)
1852 set_pspace_remote_exec_file (current_program_space,
1853 remote_exec_file_var.c_str ());
1856 /* The "set/show remote exec-file" show command hook. */
1858 static void
1859 show_remote_exec_file (struct ui_file *file, int from_tty,
1860 struct cmd_list_element *cmd, const char *value)
1862 gdb_printf (file, "%s\n", get_remote_exec_file ());
1865 static int
1866 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1868 int regnum, num_remote_regs, offset;
1869 struct packet_reg **remote_regs;
1871 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1873 struct packet_reg *r = &regs[regnum];
1875 if (register_size (gdbarch, regnum) == 0)
1876 /* Do not try to fetch zero-sized (placeholder) registers. */
1877 r->pnum = -1;
1878 else
1879 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1881 r->regnum = regnum;
1884 /* Define the g/G packet format as the contents of each register
1885 with a remote protocol number, in order of ascending protocol
1886 number. */
1888 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1889 for (num_remote_regs = 0, regnum = 0;
1890 regnum < gdbarch_num_regs (gdbarch);
1891 regnum++)
1892 if (regs[regnum].pnum != -1)
1893 remote_regs[num_remote_regs++] = &regs[regnum];
1895 std::sort (remote_regs, remote_regs + num_remote_regs,
1896 [] (const packet_reg *a, const packet_reg *b)
1897 { return a->pnum < b->pnum; });
1899 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1901 remote_regs[regnum]->in_g_packet = 1;
1902 remote_regs[regnum]->offset = offset;
1903 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1906 return offset;
1909 /* Given the architecture described by GDBARCH, return the remote
1910 protocol register's number and the register's offset in the g/G
1911 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1912 If the target does not have a mapping for REGNUM, return false,
1913 otherwise, return true. */
1916 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1917 int *pnum, int *poffset)
1919 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1921 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1923 map_regcache_remote_table (gdbarch, regs.data ());
1925 *pnum = regs[regnum].pnum;
1926 *poffset = regs[regnum].offset;
1928 return *pnum != -1;
1931 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1933 /* Use the architecture to build a regnum<->pnum table, which will be
1934 1:1 unless a feature set specifies otherwise. */
1935 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1937 /* Record the maximum possible size of the g packet - it may turn out
1938 to be smaller. */
1939 this->sizeof_g_packet
1940 = map_regcache_remote_table (gdbarch, this->regs.get ());
1942 /* Default maximum number of characters in a packet body. Many
1943 remote stubs have a hardwired buffer size of 400 bytes
1944 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1945 as the maximum packet-size to ensure that the packet and an extra
1946 NUL character can always fit in the buffer. This stops GDB
1947 trashing stubs that try to squeeze an extra NUL into what is
1948 already a full buffer (As of 1999-12-04 that was most stubs). */
1949 this->remote_packet_size = 400 - 1;
1951 /* This one is filled in when a ``g'' packet is received. */
1952 this->actual_register_packet_size = 0;
1954 /* Should rsa->sizeof_g_packet needs more space than the
1955 default, adjust the size accordingly. Remember that each byte is
1956 encoded as two characters. 32 is the overhead for the packet
1957 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1958 (``$NN:G...#NN'') is a better guess, the below has been padded a
1959 little. */
1960 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1961 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1964 /* Get a pointer to the current remote target. If not connected to a
1965 remote target, return NULL. */
1967 static remote_target *
1968 get_current_remote_target ()
1970 target_ops *proc_target = current_inferior ()->process_target ();
1971 return dynamic_cast<remote_target *> (proc_target);
1974 /* Return the current allowed size of a remote packet. This is
1975 inferred from the current architecture, and should be used to
1976 limit the length of outgoing packets. */
1977 long
1978 remote_target::get_remote_packet_size ()
1980 struct remote_state *rs = get_remote_state ();
1981 remote_arch_state *rsa
1982 = rs->get_remote_arch_state (current_inferior ()->arch ());
1984 if (rs->explicit_packet_size)
1985 return rs->explicit_packet_size;
1987 return rsa->remote_packet_size;
1990 static struct packet_reg *
1991 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1992 long regnum)
1994 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1995 return NULL;
1996 else
1998 struct packet_reg *r = &rsa->regs[regnum];
2000 gdb_assert (r->regnum == regnum);
2001 return r;
2005 static struct packet_reg *
2006 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
2007 LONGEST pnum)
2009 int i;
2011 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
2013 struct packet_reg *r = &rsa->regs[i];
2015 if (r->pnum == pnum)
2016 return r;
2018 return NULL;
2021 /* Allow the user to specify what sequence to send to the remote
2022 when he requests a program interruption: Although ^C is usually
2023 what remote systems expect (this is the default, here), it is
2024 sometimes preferable to send a break. On other systems such
2025 as the Linux kernel, a break followed by g, which is Magic SysRq g
2026 is required in order to interrupt the execution. */
2027 const char interrupt_sequence_control_c[] = "Ctrl-C";
2028 const char interrupt_sequence_break[] = "BREAK";
2029 const char interrupt_sequence_break_g[] = "BREAK-g";
2030 static const char *const interrupt_sequence_modes[] =
2032 interrupt_sequence_control_c,
2033 interrupt_sequence_break,
2034 interrupt_sequence_break_g,
2035 NULL
2037 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
2039 static void
2040 show_interrupt_sequence (struct ui_file *file, int from_tty,
2041 struct cmd_list_element *c,
2042 const char *value)
2044 if (interrupt_sequence_mode == interrupt_sequence_control_c)
2045 gdb_printf (file,
2046 _("Send the ASCII ETX character (Ctrl-c) "
2047 "to the remote target to interrupt the "
2048 "execution of the program.\n"));
2049 else if (interrupt_sequence_mode == interrupt_sequence_break)
2050 gdb_printf (file,
2051 _("send a break signal to the remote target "
2052 "to interrupt the execution of the program.\n"));
2053 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
2054 gdb_printf (file,
2055 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
2056 "the remote target to interrupt the execution "
2057 "of Linux kernel.\n"));
2058 else
2059 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
2060 interrupt_sequence_mode);
2063 /* This boolean variable specifies whether interrupt_sequence is sent
2064 to the remote target when gdb connects to it.
2065 This is mostly needed when you debug the Linux kernel: The Linux kernel
2066 expects BREAK g which is Magic SysRq g for connecting gdb. */
2067 static bool interrupt_on_connect = false;
2069 /* This variable is used to implement the "set/show remotebreak" commands.
2070 Since these commands are now deprecated in favor of "set/show remote
2071 interrupt-sequence", it no longer has any effect on the code. */
2072 static bool remote_break;
2074 static void
2075 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
2077 if (remote_break)
2078 interrupt_sequence_mode = interrupt_sequence_break;
2079 else
2080 interrupt_sequence_mode = interrupt_sequence_control_c;
2083 static void
2084 show_remotebreak (struct ui_file *file, int from_tty,
2085 struct cmd_list_element *c,
2086 const char *value)
2090 /* This variable sets the number of bits in an address that are to be
2091 sent in a memory ("M" or "m") packet. Normally, after stripping
2092 leading zeros, the entire address would be sent. This variable
2093 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2094 initial implementation of remote.c restricted the address sent in
2095 memory packets to ``host::sizeof long'' bytes - (typically 32
2096 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2097 address was never sent. Since fixing this bug may cause a break in
2098 some remote targets this variable is principally provided to
2099 facilitate backward compatibility. */
2101 static unsigned int remote_address_size;
2104 /* The default max memory-write-packet-size, when the setting is
2105 "fixed". The 16k is historical. (It came from older GDB's using
2106 alloca for buffers and the knowledge (folklore?) that some hosts
2107 don't cope very well with large alloca calls.) */
2108 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2110 /* The minimum remote packet size for memory transfers. Ensures we
2111 can write at least one byte. */
2112 #define MIN_MEMORY_PACKET_SIZE 20
2114 /* Get the memory packet size, assuming it is fixed. */
2116 static long
2117 get_fixed_memory_packet_size (struct memory_packet_config *config)
2119 gdb_assert (config->fixed_p);
2121 if (config->size <= 0)
2122 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2123 else
2124 return config->size;
2127 /* Compute the current size of a read/write packet. Since this makes
2128 use of ``actual_register_packet_size'' the computation is dynamic. */
2130 long
2131 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2133 struct remote_state *rs = get_remote_state ();
2134 remote_arch_state *rsa
2135 = rs->get_remote_arch_state (current_inferior ()->arch ());
2137 long what_they_get;
2138 if (config->fixed_p)
2139 what_they_get = get_fixed_memory_packet_size (config);
2140 else
2142 what_they_get = get_remote_packet_size ();
2143 /* Limit the packet to the size specified by the user. */
2144 if (config->size > 0
2145 && what_they_get > config->size)
2146 what_they_get = config->size;
2148 /* Limit it to the size of the targets ``g'' response unless we have
2149 permission from the stub to use a larger packet size. */
2150 if (rs->explicit_packet_size == 0
2151 && rsa->actual_register_packet_size > 0
2152 && what_they_get > rsa->actual_register_packet_size)
2153 what_they_get = rsa->actual_register_packet_size;
2155 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2156 what_they_get = MIN_MEMORY_PACKET_SIZE;
2158 /* Make sure there is room in the global buffer for this packet
2159 (including its trailing NUL byte). */
2160 if (rs->buf.size () < what_they_get + 1)
2161 rs->buf.resize (2 * what_they_get);
2163 return what_they_get;
2166 /* Update the size of a read/write packet. If they user wants
2167 something really big then do a sanity check. */
2169 static void
2170 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2171 bool target_connected)
2173 int fixed_p = config->fixed_p;
2174 long size = config->size;
2176 if (args == NULL)
2177 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2178 else if (strcmp (args, "hard") == 0
2179 || strcmp (args, "fixed") == 0)
2180 fixed_p = 1;
2181 else if (strcmp (args, "soft") == 0
2182 || strcmp (args, "limit") == 0)
2183 fixed_p = 0;
2184 else
2186 char *end;
2188 size = strtoul (args, &end, 0);
2189 if (args == end)
2190 error (_("Invalid %s (bad syntax)."), config->name);
2192 /* Instead of explicitly capping the size of a packet to or
2193 disallowing it, the user is allowed to set the size to
2194 something arbitrarily large. */
2197 /* Extra checks? */
2198 if (fixed_p && !config->fixed_p)
2200 /* So that the query shows the correct value. */
2201 long query_size = (size <= 0
2202 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2203 : size);
2205 if (target_connected
2206 && !query (_("The target may not be able to correctly handle a %s\n"
2207 "of %ld bytes. Change the packet size? "),
2208 config->name, query_size))
2209 error (_("Packet size not changed."));
2210 else if (!target_connected
2211 && !query (_("Future remote targets may not be able to "
2212 "correctly handle a %s\nof %ld bytes. Change the "
2213 "packet size for future remote targets? "),
2214 config->name, query_size))
2215 error (_("Packet size not changed."));
2217 /* Update the config. */
2218 config->fixed_p = fixed_p;
2219 config->size = size;
2221 const char *target_type = get_target_type_name (target_connected);
2222 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2223 args);
2227 /* Show the memory-read or write-packet size configuration CONFIG of the
2228 target REMOTE. If REMOTE is nullptr, the default configuration for future
2229 remote targets should be passed in CONFIG. */
2231 static void
2232 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2234 const char *target_type = get_target_type_name (remote != nullptr);
2236 if (config->size == 0)
2237 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2238 else
2239 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2240 config->size);
2242 if (config->fixed_p)
2243 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2244 get_fixed_memory_packet_size (config));
2245 else
2247 if (remote != nullptr)
2248 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2249 remote->get_memory_packet_size (config));
2250 else
2251 gdb_puts ("The actual limit will be further reduced "
2252 "dependent on the target.\n");
2256 /* Configure the memory-write-packet size of the currently selected target. If
2257 no target is available, the default configuration for future remote targets
2258 is configured. */
2260 static void
2261 set_memory_write_packet_size (const char *args, int from_tty)
2263 remote_target *remote = get_current_remote_target ();
2264 if (remote != nullptr)
2266 set_memory_packet_size
2267 (args, &remote->m_features.m_memory_write_packet_config, true);
2269 else
2271 memory_packet_config* config = &memory_write_packet_config;
2272 set_memory_packet_size (args, config, false);
2276 /* Display the memory-write-packet size of the currently selected target. If
2277 no target is available, the default configuration for future remote targets
2278 is shown. */
2280 static void
2281 show_memory_write_packet_size (const char *args, int from_tty)
2283 remote_target *remote = get_current_remote_target ();
2284 if (remote != nullptr)
2285 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2286 remote);
2287 else
2288 show_memory_packet_size (&memory_write_packet_config, nullptr);
2291 /* Show the number of hardware watchpoints that can be used. */
2293 static void
2294 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2295 struct cmd_list_element *c,
2296 const char *value)
2298 gdb_printf (file, _("The maximum number of target hardware "
2299 "watchpoints is %s.\n"), value);
2302 /* Show the length limit (in bytes) for hardware watchpoints. */
2304 static void
2305 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2306 struct cmd_list_element *c,
2307 const char *value)
2309 gdb_printf (file, _("The maximum length (in bytes) of a target "
2310 "hardware watchpoint is %s.\n"), value);
2313 /* Show the number of hardware breakpoints that can be used. */
2315 static void
2316 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2317 struct cmd_list_element *c,
2318 const char *value)
2320 gdb_printf (file, _("The maximum number of target hardware "
2321 "breakpoints is %s.\n"), value);
2324 /* Controls the maximum number of characters to display in the debug output
2325 for each remote packet. The remaining characters are omitted. */
2327 static int remote_packet_max_chars = 512;
2329 /* Show the maximum number of characters to display for each remote packet
2330 when remote debugging is enabled. */
2332 static void
2333 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2334 struct cmd_list_element *c,
2335 const char *value)
2337 gdb_printf (file, _("Number of remote packet characters to "
2338 "display is %s.\n"), value);
2341 long
2342 remote_target::get_memory_write_packet_size ()
2344 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2347 /* Configure the memory-read-packet size of the currently selected target. If
2348 no target is available, the default configuration for future remote targets
2349 is adapted. */
2351 static void
2352 set_memory_read_packet_size (const char *args, int from_tty)
2354 remote_target *remote = get_current_remote_target ();
2355 if (remote != nullptr)
2356 set_memory_packet_size
2357 (args, &remote->m_features.m_memory_read_packet_config, true);
2358 else
2360 memory_packet_config* config = &memory_read_packet_config;
2361 set_memory_packet_size (args, config, false);
2366 /* Display the memory-read-packet size of the currently selected target. If
2367 no target is available, the default configuration for future remote targets
2368 is shown. */
2370 static void
2371 show_memory_read_packet_size (const char *args, int from_tty)
2373 remote_target *remote = get_current_remote_target ();
2374 if (remote != nullptr)
2375 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2376 remote);
2377 else
2378 show_memory_packet_size (&memory_read_packet_config, nullptr);
2381 long
2382 remote_target::get_memory_read_packet_size ()
2384 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2386 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2387 extra buffer size argument before the memory read size can be
2388 increased beyond this. */
2389 if (size > get_remote_packet_size ())
2390 size = get_remote_packet_size ();
2391 return size;
2394 static enum packet_support packet_config_support (const packet_config *config);
2397 static void
2398 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2399 cmd_list_element *c)
2401 remote_target *remote = get_current_remote_target ();
2402 gdb_assert (c->var.has_value ());
2404 auto *default_config = static_cast<packet_config *> (c->context ());
2405 const int packet_idx = std::distance (remote_protocol_packets,
2406 default_config);
2408 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2410 const char *name = packets_descriptions[packet_idx].name;
2411 const auto_boolean value = c->var->get<auto_boolean> ();
2412 const char *support = get_packet_support_name (value);
2413 const char *target_type = get_target_type_name (remote != nullptr);
2415 if (remote != nullptr)
2416 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2417 else
2418 remote_protocol_packets[packet_idx].detect = value;
2420 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2421 target_type, support);
2422 return;
2425 internal_error (_("Could not find config for %s"), c->name);
2428 static void
2429 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2430 remote_target *remote)
2432 const char *support = "internal-error";
2433 const char *target_type = get_target_type_name (remote != nullptr);
2435 packet_config *config;
2436 if (remote != nullptr)
2437 config = &remote->m_features.m_protocol_packets[which_packet];
2438 else
2439 config = &remote_protocol_packets[which_packet];
2441 switch (packet_config_support (config))
2443 case PACKET_ENABLE:
2444 support = "enabled";
2445 break;
2446 case PACKET_DISABLE:
2447 support = "disabled";
2448 break;
2449 case PACKET_SUPPORT_UNKNOWN:
2450 support = "unknown";
2451 break;
2453 switch (config->detect)
2455 case AUTO_BOOLEAN_AUTO:
2456 gdb_printf (file,
2457 _("Support for the '%s' packet %s is \"auto\", "
2458 "currently %s.\n"),
2459 packets_descriptions[which_packet].name, target_type,
2460 support);
2461 break;
2462 case AUTO_BOOLEAN_TRUE:
2463 case AUTO_BOOLEAN_FALSE:
2464 gdb_printf (file,
2465 _("Support for the '%s' packet %s is \"%s\".\n"),
2466 packets_descriptions[which_packet].name, target_type,
2467 get_packet_support_name (config->detect));
2468 break;
2472 static void
2473 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2474 const char *title, int legacy)
2476 packets_descriptions[which_packet].name = name;
2477 packets_descriptions[which_packet].title = title;
2479 packet_config *config = &remote_protocol_packets[which_packet];
2481 gdb::unique_xmalloc_ptr<char> set_doc
2482 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2483 name, title);
2484 gdb::unique_xmalloc_ptr<char> show_doc
2485 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2486 name, title);
2487 /* set/show TITLE-packet {auto,on,off} */
2488 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2489 set_show_commands cmds
2490 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2491 &config->detect, set_doc.get (),
2492 show_doc.get (), NULL, /* help_doc */
2493 set_remote_protocol_packet_cmd,
2494 show_remote_protocol_packet_cmd,
2495 &remote_set_cmdlist, &remote_show_cmdlist);
2496 cmds.show->set_context (config);
2497 cmds.set->set_context (config);
2499 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2500 if (legacy)
2502 /* It's not clear who should take ownership of the LEGACY_NAME string
2503 created below, so, for now, place the string into a static vector
2504 which ensures the strings is released when GDB exits. */
2505 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2506 gdb::unique_xmalloc_ptr<char> legacy_name
2507 = xstrprintf ("%s-packet", name);
2508 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2509 &remote_set_cmdlist);
2510 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2511 &remote_show_cmdlist);
2512 legacy_names.emplace_back (std::move (legacy_name));
2516 /* Check GDBserver's reply packet. Return packet_result structure
2517 which contains the packet_status enum and an error message for the
2518 PACKET_ERROR case.
2520 An error packet can always take the form Exx (where xx is a hex
2521 code). */
2522 static packet_result
2523 packet_check_result (const char *buf)
2525 if (buf[0] != '\0')
2527 /* The stub recognized the packet request. Check that the
2528 operation succeeded. */
2529 if (buf[0] == 'E'
2530 && isxdigit (buf[1]) && isxdigit (buf[2])
2531 && buf[3] == '\0')
2532 /* "Enn" - definitely an error. */
2533 return packet_result::make_numeric_error (buf + 1);
2535 /* Always treat "E." as an error. This will be used for
2536 more verbose error messages, such as E.memtypes. */
2537 if (buf[0] == 'E' && buf[1] == '.')
2539 if (buf[2] != '\0')
2540 return packet_result::make_textual_error (buf + 2);
2541 else
2542 return packet_result::make_textual_error ("no error provided");
2545 /* The packet may or may not be OK. Just assume it is. */
2546 return packet_result::make_ok ();
2548 else
2550 /* The stub does not support the packet. */
2551 return packet_result::make_unknown ();
2555 static packet_result
2556 packet_check_result (const gdb::char_vector &buf)
2558 return packet_check_result (buf.data ());
2561 packet_result
2562 remote_features::packet_ok (const char *buf, const int which_packet)
2564 packet_config *config = &m_protocol_packets[which_packet];
2565 packet_description *descr = &packets_descriptions[which_packet];
2567 if (config->detect != AUTO_BOOLEAN_TRUE
2568 && config->support == PACKET_DISABLE)
2569 internal_error (_("packet_ok: attempt to use a disabled packet"));
2571 packet_result result = packet_check_result (buf);
2572 switch (result.status ())
2574 case PACKET_OK:
2575 case PACKET_ERROR:
2576 /* The stub recognized the packet request. */
2577 if (config->support == PACKET_SUPPORT_UNKNOWN)
2579 remote_debug_printf ("Packet %s (%s) is supported",
2580 descr->name, descr->title);
2581 config->support = PACKET_ENABLE;
2583 break;
2584 case PACKET_UNKNOWN:
2585 /* The stub does not support the packet. */
2586 if (config->detect == AUTO_BOOLEAN_AUTO
2587 && config->support == PACKET_ENABLE)
2589 /* If the stub previously indicated that the packet was
2590 supported then there is a protocol error. */
2591 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2592 descr->name, descr->title);
2594 else if (config->detect == AUTO_BOOLEAN_TRUE)
2596 /* The user set it wrong. */
2597 error (_("Enabled packet %s (%s) not recognized by stub"),
2598 descr->name, descr->title);
2601 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2602 descr->title);
2603 config->support = PACKET_DISABLE;
2604 break;
2607 return result;
2610 packet_result
2611 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2613 return packet_ok (buf.data (), which_packet);
2616 /* Returns whether a given packet or feature is supported. This takes
2617 into account the state of the corresponding "set remote foo-packet"
2618 command, which may be used to bypass auto-detection. */
2620 static enum packet_support
2621 packet_config_support (const packet_config *config)
2623 switch (config->detect)
2625 case AUTO_BOOLEAN_TRUE:
2626 return PACKET_ENABLE;
2627 case AUTO_BOOLEAN_FALSE:
2628 return PACKET_DISABLE;
2629 case AUTO_BOOLEAN_AUTO:
2630 return config->support;
2631 default:
2632 gdb_assert_not_reached ("bad switch");
2636 packet_support
2637 remote_features::packet_support (int packet) const
2639 const packet_config *config = &m_protocol_packets[packet];
2640 return packet_config_support (config);
2643 static void
2644 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2645 struct cmd_list_element *c,
2646 const char *value)
2648 remote_target *remote = get_current_remote_target ();
2649 gdb_assert (c->var.has_value ());
2651 auto *default_config = static_cast<packet_config *> (c->context ());
2652 const int packet_idx = std::distance (remote_protocol_packets,
2653 default_config);
2655 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2657 show_packet_config_cmd (file, packet_idx, remote);
2658 return;
2660 internal_error (_("Could not find config for %s"), c->name);
2663 /* Should we try one of the 'Z' requests? */
2665 enum Z_packet_type
2667 Z_PACKET_SOFTWARE_BP,
2668 Z_PACKET_HARDWARE_BP,
2669 Z_PACKET_WRITE_WP,
2670 Z_PACKET_READ_WP,
2671 Z_PACKET_ACCESS_WP,
2672 NR_Z_PACKET_TYPES
2675 /* For compatibility with older distributions. Provide a ``set remote
2676 Z-packet ...'' command that updates all the Z packet types. */
2678 static enum auto_boolean remote_Z_packet_detect;
2680 static void
2681 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2682 struct cmd_list_element *c)
2684 remote_target *remote = get_current_remote_target ();
2685 int i;
2687 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2689 if (remote != nullptr)
2690 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2691 = remote_Z_packet_detect;
2692 else
2693 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2696 const char *support = get_packet_support_name (remote_Z_packet_detect);
2697 const char *target_type = get_target_type_name (remote != nullptr);
2698 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2699 support);
2703 static void
2704 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2705 struct cmd_list_element *c,
2706 const char *value)
2708 remote_target *remote = get_current_remote_target ();
2709 int i;
2711 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2712 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2715 /* Insert fork catchpoint target routine. If fork events are enabled
2716 then return success, nothing more to do. */
2719 remote_target::insert_fork_catchpoint (int pid)
2721 return !m_features.remote_fork_event_p ();
2724 /* Remove fork catchpoint target routine. Nothing to do, just
2725 return success. */
2728 remote_target::remove_fork_catchpoint (int pid)
2730 return 0;
2733 /* Insert vfork catchpoint target routine. If vfork events are enabled
2734 then return success, nothing more to do. */
2737 remote_target::insert_vfork_catchpoint (int pid)
2739 return !m_features.remote_vfork_event_p ();
2742 /* Remove vfork catchpoint target routine. Nothing to do, just
2743 return success. */
2746 remote_target::remove_vfork_catchpoint (int pid)
2748 return 0;
2751 /* Insert exec catchpoint target routine. If exec events are
2752 enabled, just return success. */
2755 remote_target::insert_exec_catchpoint (int pid)
2757 return !m_features.remote_exec_event_p ();
2760 /* Remove exec catchpoint target routine. Nothing to do, just
2761 return success. */
2764 remote_target::remove_exec_catchpoint (int pid)
2766 return 0;
2771 /* Take advantage of the fact that the TID field is not used, to tag
2772 special ptids with it set to != 0. */
2773 static const ptid_t magic_null_ptid (42000, -1, 1);
2774 static const ptid_t not_sent_ptid (42000, -2, 1);
2775 static const ptid_t any_thread_ptid (42000, 0, 1);
2777 /* Find out if the stub attached to PID (and hence GDB should offer to
2778 detach instead of killing it when bailing out). */
2781 remote_target::remote_query_attached (int pid)
2783 struct remote_state *rs = get_remote_state ();
2784 size_t size = get_remote_packet_size ();
2786 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2787 return 0;
2789 if (m_features.remote_multi_process_p ())
2790 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2791 else
2792 xsnprintf (rs->buf.data (), size, "qAttached");
2794 putpkt (rs->buf);
2795 getpkt (&rs->buf);
2797 packet_result result = m_features.packet_ok (rs->buf, PACKET_qAttached);
2798 switch (result.status ())
2800 case PACKET_OK:
2801 if (strcmp (rs->buf.data (), "1") == 0)
2802 return 1;
2803 break;
2804 case PACKET_ERROR:
2805 warning (_("Remote failure reply: %s"), result.err_msg ());
2806 break;
2807 case PACKET_UNKNOWN:
2808 break;
2811 return 0;
2814 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2815 has been invented by GDB, instead of reported by the target. Since
2816 we can be connected to a remote system before before knowing about
2817 any inferior, mark the target with execution when we find the first
2818 inferior. If ATTACHED is 1, then we had just attached to this
2819 inferior. If it is 0, then we just created this inferior. If it
2820 is -1, then try querying the remote stub to find out if it had
2821 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2822 attempt to open this inferior's executable as the main executable
2823 if no main executable is open already. */
2825 inferior *
2826 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2827 int try_open_exec)
2829 struct inferior *inf;
2831 /* Check whether this process we're learning about is to be
2832 considered attached, or if is to be considered to have been
2833 spawned by the stub. */
2834 if (attached == -1)
2835 attached = remote_query_attached (pid);
2837 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2839 /* If the target shares code across all inferiors, then every
2840 attach adds a new inferior. */
2841 inf = add_inferior (pid);
2843 /* ... and every inferior is bound to the same program space.
2844 However, each inferior may still have its own address
2845 space. */
2846 inf->aspace = maybe_new_address_space ();
2847 inf->pspace = current_program_space;
2849 else
2851 /* In the traditional debugging scenario, there's a 1-1 match
2852 between program/address spaces. We simply bind the inferior
2853 to the program space's address space. */
2854 inf = current_inferior ();
2856 /* However, if the current inferior is already bound to a
2857 process, find some other empty inferior. */
2858 if (inf->pid != 0)
2860 inf = nullptr;
2861 for (inferior *it : all_inferiors ())
2862 if (it->pid == 0)
2864 inf = it;
2865 break;
2868 if (inf == nullptr)
2870 /* Since all inferiors were already bound to a process, add
2871 a new inferior. */
2872 inf = add_inferior_with_spaces ();
2874 switch_to_inferior_no_thread (inf);
2875 inf->push_target (this);
2876 inferior_appeared (inf, pid);
2879 inf->attach_flag = attached;
2880 inf->fake_pid_p = fake_pid_p;
2882 /* If no main executable is currently open then attempt to
2883 open the file that was executed to create this inferior. */
2884 if (try_open_exec && current_program_space->exec_filename () == nullptr)
2885 exec_file_locate_attach (pid, 0, 1);
2887 /* Check for exec file mismatch, and let the user solve it. */
2888 validate_exec_file (1);
2890 return inf;
2893 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2894 static remote_thread_info *get_remote_thread_info (remote_target *target,
2895 ptid_t ptid);
2897 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2898 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2899 remote_state::starting_up flag) is true then the new thread is added
2900 silently, otherwise the new thread will be announced to the user. */
2902 thread_info *
2903 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2904 bool silent_p)
2906 struct remote_state *rs = get_remote_state ();
2907 struct thread_info *thread;
2909 /* GDB historically didn't pull threads in the initial connection
2910 setup. If the remote target doesn't even have a concept of
2911 threads (e.g., a bare-metal target), even if internally we
2912 consider that a single-threaded target, mentioning a new thread
2913 might be confusing to the user. Be silent then, preserving the
2914 age old behavior. */
2915 if (rs->starting_up || silent_p)
2916 thread = add_thread_silent (this, ptid);
2917 else
2918 thread = add_thread (this, ptid);
2920 if (executing)
2921 get_remote_thread_info (thread)->set_resumed ();
2922 set_executing (this, ptid, executing);
2923 set_running (this, ptid, running);
2925 return thread;
2928 /* Come here when we learn about a thread id from the remote target.
2929 It may be the first time we hear about such thread, so take the
2930 opportunity to add it to GDB's thread list. In case this is the
2931 first time we're noticing its corresponding inferior, add it to
2932 GDB's inferior list as well. EXECUTING indicates whether the
2933 thread is (internally) executing or stopped. */
2935 void
2936 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2938 /* In non-stop mode, we assume new found threads are (externally)
2939 running until proven otherwise with a stop reply. In all-stop,
2940 we can only get here if all threads are stopped. */
2941 bool running = target_is_non_stop_p ();
2943 /* If this is a new thread, add it to GDB's thread list.
2944 If we leave it up to WFI to do this, bad things will happen. */
2946 thread_info *tp = this->find_thread (currthread);
2947 if (tp != NULL && tp->state == THREAD_EXITED)
2949 /* We're seeing an event on a thread id we knew had exited.
2950 This has to be a new thread reusing the old id. Add it. */
2951 remote_add_thread (currthread, running, executing, false);
2952 return;
2955 if (!in_thread_list (this, currthread))
2957 struct inferior *inf = NULL;
2958 int pid = currthread.pid ();
2960 if (inferior_ptid.is_pid ()
2961 && pid == inferior_ptid.pid ())
2963 /* inferior_ptid has no thread member yet. This can happen
2964 with the vAttach -> remote_wait,"TAAthread:" path if the
2965 stub doesn't support qC. This is the first stop reported
2966 after an attach, so this is the main thread. Update the
2967 ptid in the thread list. */
2968 if (in_thread_list (this, ptid_t (pid)))
2969 thread_change_ptid (this, inferior_ptid, currthread);
2970 else
2972 thread_info *thr
2973 = remote_add_thread (currthread, running, executing, false);
2974 switch_to_thread (thr);
2976 return;
2979 if (magic_null_ptid == inferior_ptid)
2981 /* inferior_ptid is not set yet. This can happen with the
2982 vRun -> remote_wait,"TAAthread:" path if the stub
2983 doesn't support qC. This is the first stop reported
2984 after an attach, so this is the main thread. Update the
2985 ptid in the thread list. */
2986 thread_change_ptid (this, inferior_ptid, currthread);
2987 return;
2990 /* When connecting to a target remote, or to a target
2991 extended-remote which already was debugging an inferior, we
2992 may not know about it yet. Add it before adding its child
2993 thread, so notifications are emitted in a sensible order. */
2994 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2996 bool fake_pid_p = !m_features.remote_multi_process_p ();
2998 inf = remote_add_inferior (fake_pid_p,
2999 currthread.pid (), -1, 1);
3002 /* This is really a new thread. Add it. */
3003 thread_info *new_thr
3004 = remote_add_thread (currthread, running, executing, false);
3006 /* If we found a new inferior, let the common code do whatever
3007 it needs to with it (e.g., read shared libraries, insert
3008 breakpoints), unless we're just setting up an all-stop
3009 connection. */
3010 if (inf != NULL)
3012 struct remote_state *rs = get_remote_state ();
3014 if (!rs->starting_up)
3015 notice_new_inferior (new_thr, executing, 0);
3020 /* Return THREAD's private thread data, creating it if necessary. */
3022 static remote_thread_info *
3023 get_remote_thread_info (thread_info *thread)
3025 gdb_assert (thread != NULL);
3027 if (thread->priv == NULL)
3028 thread->priv.reset (new remote_thread_info);
3030 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
3033 /* Return PTID's private thread data, creating it if necessary. */
3035 static remote_thread_info *
3036 get_remote_thread_info (remote_target *target, ptid_t ptid)
3038 thread_info *thr = target->find_thread (ptid);
3039 return get_remote_thread_info (thr);
3042 /* Call this function as a result of
3043 1) A halt indication (T packet) containing a thread id
3044 2) A direct query of currthread
3045 3) Successful execution of set thread */
3047 static void
3048 record_currthread (struct remote_state *rs, ptid_t currthread)
3050 rs->general_thread = currthread;
3053 /* If 'QPassSignals' is supported, tell the remote stub what signals
3054 it can simply pass through to the inferior without reporting. */
3056 void
3057 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
3059 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
3061 char *pass_packet, *p;
3062 int count = 0;
3063 struct remote_state *rs = get_remote_state ();
3065 gdb_assert (pass_signals.size () < 256);
3066 for (size_t i = 0; i < pass_signals.size (); i++)
3068 if (pass_signals[i])
3069 count++;
3071 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
3072 strcpy (pass_packet, "QPassSignals:");
3073 p = pass_packet + strlen (pass_packet);
3074 for (size_t i = 0; i < pass_signals.size (); i++)
3076 if (pass_signals[i])
3078 if (i >= 16)
3079 *p++ = tohex (i >> 4);
3080 *p++ = tohex (i & 15);
3081 if (count)
3082 *p++ = ';';
3083 else
3084 break;
3085 count--;
3088 *p = 0;
3089 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
3091 putpkt (pass_packet);
3092 getpkt (&rs->buf);
3093 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
3094 xfree (rs->last_pass_packet);
3095 rs->last_pass_packet = pass_packet;
3097 else
3098 xfree (pass_packet);
3102 /* If 'QCatchSyscalls' is supported, tell the remote stub
3103 to report syscalls to GDB. */
3106 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3107 gdb::array_view<const int> syscall_counts)
3109 const char *catch_packet;
3110 int n_sysno = 0;
3112 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3114 /* Not supported. */
3115 return 1;
3118 if (needed && any_count == 0)
3120 /* Count how many syscalls are to be caught. */
3121 for (size_t i = 0; i < syscall_counts.size (); i++)
3123 if (syscall_counts[i] != 0)
3124 n_sysno++;
3128 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3129 pid, needed, any_count, n_sysno);
3131 std::string built_packet;
3132 if (needed)
3134 /* Prepare a packet with the sysno list, assuming max 8+1
3135 characters for a sysno. If the resulting packet size is too
3136 big, fallback on the non-selective packet. */
3137 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3138 built_packet.reserve (maxpktsz);
3139 built_packet = "QCatchSyscalls:1";
3140 if (any_count == 0)
3142 /* Add in each syscall to be caught. */
3143 for (size_t i = 0; i < syscall_counts.size (); i++)
3145 if (syscall_counts[i] != 0)
3146 string_appendf (built_packet, ";%zx", i);
3149 if (built_packet.size () > get_remote_packet_size ())
3151 /* catch_packet too big. Fallback to less efficient
3152 non selective mode, with GDB doing the filtering. */
3153 catch_packet = "QCatchSyscalls:1";
3155 else
3156 catch_packet = built_packet.c_str ();
3158 else
3159 catch_packet = "QCatchSyscalls:0";
3161 struct remote_state *rs = get_remote_state ();
3163 putpkt (catch_packet);
3164 getpkt (&rs->buf);
3165 packet_result result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3166 if (result.status () == PACKET_OK)
3167 return 0;
3168 else
3169 return -1;
3172 /* If 'QProgramSignals' is supported, tell the remote stub what
3173 signals it should pass through to the inferior when detaching. */
3175 void
3176 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3178 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3180 char *packet, *p;
3181 int count = 0;
3182 struct remote_state *rs = get_remote_state ();
3184 gdb_assert (signals.size () < 256);
3185 for (size_t i = 0; i < signals.size (); i++)
3187 if (signals[i])
3188 count++;
3190 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3191 strcpy (packet, "QProgramSignals:");
3192 p = packet + strlen (packet);
3193 for (size_t i = 0; i < signals.size (); i++)
3195 if (signal_pass_state (i))
3197 if (i >= 16)
3198 *p++ = tohex (i >> 4);
3199 *p++ = tohex (i & 15);
3200 if (count)
3201 *p++ = ';';
3202 else
3203 break;
3204 count--;
3207 *p = 0;
3208 if (!rs->last_program_signals_packet
3209 || strcmp (rs->last_program_signals_packet, packet) != 0)
3211 putpkt (packet);
3212 getpkt (&rs->buf);
3213 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3214 xfree (rs->last_program_signals_packet);
3215 rs->last_program_signals_packet = packet;
3217 else
3218 xfree (packet);
3222 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3223 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3224 thread. If GEN is set, set the general thread, if not, then set
3225 the step/continue thread. */
3226 void
3227 remote_target::set_thread (ptid_t ptid, int gen)
3229 struct remote_state *rs = get_remote_state ();
3230 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3231 char *buf = rs->buf.data ();
3232 char *endbuf = buf + get_remote_packet_size ();
3234 if (state == ptid)
3235 return;
3237 *buf++ = 'H';
3238 *buf++ = gen ? 'g' : 'c';
3239 if (ptid == magic_null_ptid)
3240 xsnprintf (buf, endbuf - buf, "0");
3241 else if (ptid == any_thread_ptid)
3242 xsnprintf (buf, endbuf - buf, "0");
3243 else if (ptid == minus_one_ptid)
3244 xsnprintf (buf, endbuf - buf, "-1");
3245 else
3246 write_ptid (buf, endbuf, ptid);
3247 putpkt (rs->buf);
3248 getpkt (&rs->buf);
3249 if (gen)
3250 rs->general_thread = ptid;
3251 else
3252 rs->continue_thread = ptid;
3255 void
3256 remote_target::set_general_thread (ptid_t ptid)
3258 set_thread (ptid, 1);
3261 void
3262 remote_target::set_continue_thread (ptid_t ptid)
3264 set_thread (ptid, 0);
3267 /* Change the remote current process. Which thread within the process
3268 ends up selected isn't important, as long as it is the same process
3269 as what INFERIOR_PTID points to.
3271 This comes from that fact that there is no explicit notion of
3272 "selected process" in the protocol. The selected process for
3273 general operations is the process the selected general thread
3274 belongs to. */
3276 void
3277 remote_target::set_general_process ()
3279 /* If the remote can't handle multiple processes, don't bother. */
3280 if (!m_features.remote_multi_process_p ())
3281 return;
3283 remote_state *rs = get_remote_state ();
3285 /* We only need to change the remote current thread if it's pointing
3286 at some other process. */
3287 if (rs->general_thread.pid () != inferior_ptid.pid ())
3288 set_general_thread (inferior_ptid);
3292 /* Return nonzero if this is the main thread that we made up ourselves
3293 to model non-threaded targets as single-threaded. */
3295 static int
3296 remote_thread_always_alive (ptid_t ptid)
3298 if (ptid == magic_null_ptid)
3299 /* The main thread is always alive. */
3300 return 1;
3302 if (ptid.pid () != 0 && ptid.lwp () == 0)
3303 /* The main thread is always alive. This can happen after a
3304 vAttach, if the remote side doesn't support
3305 multi-threading. */
3306 return 1;
3308 return 0;
3311 /* Return nonzero if the thread PTID is still alive on the remote
3312 system. */
3314 bool
3315 remote_target::thread_alive (ptid_t ptid)
3317 struct remote_state *rs = get_remote_state ();
3318 char *p, *endp;
3320 /* Check if this is a thread that we made up ourselves to model
3321 non-threaded targets as single-threaded. */
3322 if (remote_thread_always_alive (ptid))
3323 return 1;
3325 p = rs->buf.data ();
3326 endp = p + get_remote_packet_size ();
3328 *p++ = 'T';
3329 write_ptid (p, endp, ptid);
3331 putpkt (rs->buf);
3332 getpkt (&rs->buf);
3333 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3336 /* Return a pointer to a thread name if we know it and NULL otherwise.
3337 The thread_info object owns the memory for the name. */
3339 const char *
3340 remote_target::thread_name (struct thread_info *info)
3342 if (info->priv != NULL)
3344 const std::string &name = get_remote_thread_info (info)->name;
3345 return !name.empty () ? name.c_str () : NULL;
3348 return NULL;
3351 /* About these extended threadlist and threadinfo packets. They are
3352 variable length packets but, the fields within them are often fixed
3353 length. They are redundant enough to send over UDP as is the
3354 remote protocol in general. There is a matching unit test module
3355 in libstub. */
3357 /* WARNING: This threadref data structure comes from the remote O.S.,
3358 libstub protocol encoding, and remote.c. It is not particularly
3359 changeable. */
3361 /* Right now, the internal structure is int. We want it to be bigger.
3362 Plan to fix this. */
3364 typedef int gdb_threadref; /* Internal GDB thread reference. */
3366 /* gdb_ext_thread_info is an internal GDB data structure which is
3367 equivalent to the reply of the remote threadinfo packet. */
3369 struct gdb_ext_thread_info
3371 threadref threadid; /* External form of thread reference. */
3372 int active; /* Has state interesting to GDB?
3373 regs, stack. */
3374 char display[256]; /* Brief state display, name,
3375 blocked/suspended. */
3376 char shortname[32]; /* To be used to name threads. */
3377 char more_display[256]; /* Long info, statistics, queue depth,
3378 whatever. */
3381 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3383 static const char *unpack_nibble (const char *buf, int *val);
3385 static const char *unpack_byte (const char *buf, int *value);
3387 static char *pack_int (char *buf, int value);
3389 static const char *unpack_int (const char *buf, int *value);
3391 static const char *unpack_string (const char *src, char *dest, int length);
3393 static char *pack_threadid (char *pkt, threadref *id);
3395 static const char *unpack_threadid (const char *inbuf, threadref *id);
3397 void int_to_threadref (threadref *id, int value);
3399 static int threadref_to_int (threadref *ref);
3401 static void copy_threadref (threadref *dest, threadref *src);
3403 static int threadmatch (threadref *dest, threadref *src);
3405 static char *pack_threadinfo_request (char *pkt, int mode,
3406 threadref *id);
3408 static char *pack_threadlist_request (char *pkt, int startflag,
3409 int threadcount,
3410 threadref *nextthread);
3412 static int remote_newthread_step (threadref *ref, void *context);
3415 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3416 buffer we're allowed to write to. Returns
3417 BUF+CHARACTERS_WRITTEN. */
3419 char *
3420 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3422 int pid, tid;
3424 if (m_features.remote_multi_process_p ())
3426 pid = ptid.pid ();
3427 if (pid < 0)
3428 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3429 else
3430 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3432 tid = ptid.lwp ();
3433 if (tid < 0)
3434 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3435 else
3436 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3438 return buf;
3441 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3442 last parsed char. Returns null_ptid if no thread id is found, and
3443 throws an error if the thread id has an invalid format. */
3445 static ptid_t
3446 read_ptid (const char *buf, const char **obuf)
3448 const char *p = buf;
3449 const char *pp;
3450 ULONGEST pid = 0, tid = 0;
3452 if (*p == 'p')
3454 /* Multi-process ptid. */
3455 pp = unpack_varlen_hex (p + 1, &pid);
3456 if (*pp != '.')
3457 error (_("invalid remote ptid: %s"), p);
3459 p = pp;
3460 pp = unpack_varlen_hex (p + 1, &tid);
3461 if (obuf)
3462 *obuf = pp;
3463 return ptid_t (pid, tid);
3466 /* No multi-process. Just a tid. */
3467 pp = unpack_varlen_hex (p, &tid);
3469 /* Return null_ptid when no thread id is found. */
3470 if (p == pp)
3472 if (obuf)
3473 *obuf = pp;
3474 return null_ptid;
3477 /* Since the stub is not sending a process id, default to what's
3478 current_inferior, unless it doesn't have a PID yet. If so,
3479 then since there's no way to know the pid of the reported
3480 threads, use the magic number. */
3481 inferior *inf = current_inferior ();
3482 if (inf->pid == 0)
3483 pid = magic_null_ptid.pid ();
3484 else
3485 pid = inf->pid;
3487 if (obuf)
3488 *obuf = pp;
3489 return ptid_t (pid, tid);
3492 static int
3493 stubhex (int ch)
3495 if (ch >= 'a' && ch <= 'f')
3496 return ch - 'a' + 10;
3497 if (ch >= '0' && ch <= '9')
3498 return ch - '0';
3499 if (ch >= 'A' && ch <= 'F')
3500 return ch - 'A' + 10;
3501 return -1;
3504 static int
3505 stub_unpack_int (const char *buff, int fieldlength)
3507 int nibble;
3508 int retval = 0;
3510 while (fieldlength)
3512 nibble = stubhex (*buff++);
3513 retval |= nibble;
3514 fieldlength--;
3515 if (fieldlength)
3516 retval = retval << 4;
3518 return retval;
3521 static const char *
3522 unpack_nibble (const char *buf, int *val)
3524 *val = fromhex (*buf++);
3525 return buf;
3528 static const char *
3529 unpack_byte (const char *buf, int *value)
3531 *value = stub_unpack_int (buf, 2);
3532 return buf + 2;
3535 static char *
3536 pack_int (char *buf, int value)
3538 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3539 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3540 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3541 buf = pack_hex_byte (buf, (value & 0xff));
3542 return buf;
3545 static const char *
3546 unpack_int (const char *buf, int *value)
3548 *value = stub_unpack_int (buf, 8);
3549 return buf + 8;
3552 #if 0 /* Currently unused, uncomment when needed. */
3553 static char *pack_string (char *pkt, char *string);
3555 static char *
3556 pack_string (char *pkt, char *string)
3558 char ch;
3559 int len;
3561 len = strlen (string);
3562 if (len > 200)
3563 len = 200; /* Bigger than most GDB packets, junk??? */
3564 pkt = pack_hex_byte (pkt, len);
3565 while (len-- > 0)
3567 ch = *string++;
3568 if ((ch == '\0') || (ch == '#'))
3569 ch = '*'; /* Protect encapsulation. */
3570 *pkt++ = ch;
3572 return pkt;
3574 #endif /* 0 (unused) */
3576 static const char *
3577 unpack_string (const char *src, char *dest, int length)
3579 while (length--)
3580 *dest++ = *src++;
3581 *dest = '\0';
3582 return src;
3585 static char *
3586 pack_threadid (char *pkt, threadref *id)
3588 char *limit;
3589 unsigned char *altid;
3591 altid = (unsigned char *) id;
3592 limit = pkt + BUF_THREAD_ID_SIZE;
3593 while (pkt < limit)
3594 pkt = pack_hex_byte (pkt, *altid++);
3595 return pkt;
3599 static const char *
3600 unpack_threadid (const char *inbuf, threadref *id)
3602 char *altref;
3603 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3604 int x, y;
3606 altref = (char *) id;
3608 while (inbuf < limit)
3610 x = stubhex (*inbuf++);
3611 y = stubhex (*inbuf++);
3612 *altref++ = (x << 4) | y;
3614 return inbuf;
3617 /* Externally, threadrefs are 64 bits but internally, they are still
3618 ints. This is due to a mismatch of specifications. We would like
3619 to use 64bit thread references internally. This is an adapter
3620 function. */
3622 void
3623 int_to_threadref (threadref *id, int value)
3625 unsigned char *scan;
3627 scan = (unsigned char *) id;
3629 int i = 4;
3630 while (i--)
3631 *scan++ = 0;
3633 *scan++ = (value >> 24) & 0xff;
3634 *scan++ = (value >> 16) & 0xff;
3635 *scan++ = (value >> 8) & 0xff;
3636 *scan++ = (value & 0xff);
3639 static int
3640 threadref_to_int (threadref *ref)
3642 int i, value = 0;
3643 unsigned char *scan;
3645 scan = *ref;
3646 scan += 4;
3647 i = 4;
3648 while (i-- > 0)
3649 value = (value << 8) | ((*scan++) & 0xff);
3650 return value;
3653 static void
3654 copy_threadref (threadref *dest, threadref *src)
3656 int i;
3657 unsigned char *csrc, *cdest;
3659 csrc = (unsigned char *) src;
3660 cdest = (unsigned char *) dest;
3661 i = 8;
3662 while (i--)
3663 *cdest++ = *csrc++;
3666 static int
3667 threadmatch (threadref *dest, threadref *src)
3669 /* Things are broken right now, so just assume we got a match. */
3670 #if 0
3671 unsigned char *srcp, *destp;
3672 int i, result;
3673 srcp = (char *) src;
3674 destp = (char *) dest;
3676 result = 1;
3677 while (i-- > 0)
3678 result &= (*srcp++ == *destp++) ? 1 : 0;
3679 return result;
3680 #endif
3681 return 1;
3685 threadid:1, # always request threadid
3686 context_exists:2,
3687 display:4,
3688 unique_name:8,
3689 more_display:16
3692 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3694 static char *
3695 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3697 *pkt++ = 'q'; /* Info Query */
3698 *pkt++ = 'P'; /* process or thread info */
3699 pkt = pack_int (pkt, mode); /* mode */
3700 pkt = pack_threadid (pkt, id); /* threadid */
3701 *pkt = '\0'; /* terminate */
3702 return pkt;
3705 /* These values tag the fields in a thread info response packet. */
3706 /* Tagging the fields allows us to request specific fields and to
3707 add more fields as time goes by. */
3709 #define TAG_THREADID 1 /* Echo the thread identifier. */
3710 #define TAG_EXISTS 2 /* Is this process defined enough to
3711 fetch registers and its stack? */
3712 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3713 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3714 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3715 the process. */
3718 remote_target::remote_unpack_thread_info_response (const char *pkt,
3719 threadref *expectedref,
3720 gdb_ext_thread_info *info)
3722 struct remote_state *rs = get_remote_state ();
3723 int mask, length;
3724 int tag;
3725 threadref ref;
3726 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3727 int retval = 1;
3729 /* info->threadid = 0; FIXME: implement zero_threadref. */
3730 info->active = 0;
3731 info->display[0] = '\0';
3732 info->shortname[0] = '\0';
3733 info->more_display[0] = '\0';
3735 /* Assume the characters indicating the packet type have been
3736 stripped. */
3737 pkt = unpack_int (pkt, &mask); /* arg mask */
3738 pkt = unpack_threadid (pkt, &ref);
3740 if (mask == 0)
3741 warning (_("Incomplete response to threadinfo request."));
3742 if (!threadmatch (&ref, expectedref))
3743 { /* This is an answer to a different request. */
3744 warning (_("ERROR RMT Thread info mismatch."));
3745 return 0;
3747 copy_threadref (&info->threadid, &ref);
3749 /* Loop on tagged fields , try to bail if something goes wrong. */
3751 /* Packets are terminated with nulls. */
3752 while ((pkt < limit) && mask && *pkt)
3754 pkt = unpack_int (pkt, &tag); /* tag */
3755 pkt = unpack_byte (pkt, &length); /* length */
3756 if (!(tag & mask)) /* Tags out of synch with mask. */
3758 warning (_("ERROR RMT: threadinfo tag mismatch."));
3759 retval = 0;
3760 break;
3762 if (tag == TAG_THREADID)
3764 if (length != 16)
3766 warning (_("ERROR RMT: length of threadid is not 16."));
3767 retval = 0;
3768 break;
3770 pkt = unpack_threadid (pkt, &ref);
3771 mask = mask & ~TAG_THREADID;
3772 continue;
3774 if (tag == TAG_EXISTS)
3776 info->active = stub_unpack_int (pkt, length);
3777 pkt += length;
3778 mask = mask & ~(TAG_EXISTS);
3779 if (length > 8)
3781 warning (_("ERROR RMT: 'exists' length too long."));
3782 retval = 0;
3783 break;
3785 continue;
3787 if (tag == TAG_THREADNAME)
3789 pkt = unpack_string (pkt, &info->shortname[0], length);
3790 mask = mask & ~TAG_THREADNAME;
3791 continue;
3793 if (tag == TAG_DISPLAY)
3795 pkt = unpack_string (pkt, &info->display[0], length);
3796 mask = mask & ~TAG_DISPLAY;
3797 continue;
3799 if (tag == TAG_MOREDISPLAY)
3801 pkt = unpack_string (pkt, &info->more_display[0], length);
3802 mask = mask & ~TAG_MOREDISPLAY;
3803 continue;
3805 warning (_("ERROR RMT: unknown thread info tag."));
3806 break; /* Not a tag we know about. */
3808 return retval;
3812 remote_target::remote_get_threadinfo (threadref *threadid,
3813 int fieldset,
3814 gdb_ext_thread_info *info)
3816 struct remote_state *rs = get_remote_state ();
3817 int result;
3819 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3820 putpkt (rs->buf);
3821 getpkt (&rs->buf);
3823 if (rs->buf[0] == '\0')
3824 return 0;
3826 result = remote_unpack_thread_info_response (&rs->buf[2],
3827 threadid, info);
3828 return result;
3831 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3833 static char *
3834 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3835 threadref *nextthread)
3837 *pkt++ = 'q'; /* info query packet */
3838 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3839 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3840 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3841 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3842 *pkt = '\0';
3843 return pkt;
3846 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3849 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3850 threadref *original_echo,
3851 threadref *resultlist,
3852 int *doneflag)
3854 struct remote_state *rs = get_remote_state ();
3855 int count, resultcount, done;
3857 resultcount = 0;
3858 /* Assume the 'q' and 'M chars have been stripped. */
3859 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3860 /* done parse past here */
3861 pkt = unpack_byte (pkt, &count); /* count field */
3862 pkt = unpack_nibble (pkt, &done);
3863 /* The first threadid is the argument threadid. */
3864 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3865 while ((count-- > 0) && (pkt < limit))
3867 pkt = unpack_threadid (pkt, resultlist++);
3868 if (resultcount++ >= result_limit)
3869 break;
3871 if (doneflag)
3872 *doneflag = done;
3873 return resultcount;
3876 /* Fetch the next batch of threads from the remote. Returns -1 if the
3877 qL packet is not supported, 0 on error and 1 on success. */
3880 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3881 int result_limit, int *done, int *result_count,
3882 threadref *threadlist)
3884 struct remote_state *rs = get_remote_state ();
3885 int result = 1;
3887 /* Truncate result limit to be smaller than the packet size. */
3888 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3889 >= get_remote_packet_size ())
3890 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3892 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3893 nextthread);
3894 putpkt (rs->buf);
3895 getpkt (&rs->buf);
3896 if (rs->buf[0] == '\0')
3898 /* Packet not supported. */
3899 return -1;
3902 *result_count =
3903 parse_threadlist_response (&rs->buf[2], result_limit,
3904 &rs->echo_nextthread, threadlist, done);
3906 if (!threadmatch (&rs->echo_nextthread, nextthread))
3908 /* FIXME: This is a good reason to drop the packet. */
3909 /* Possibly, there is a duplicate response. */
3910 /* Possibilities :
3911 retransmit immediatly - race conditions
3912 retransmit after timeout - yes
3913 exit
3914 wait for packet, then exit
3916 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3917 return 0; /* I choose simply exiting. */
3919 if (*result_count <= 0)
3921 if (*done != 1)
3923 warning (_("RMT ERROR : failed to get remote thread list."));
3924 result = 0;
3926 return result; /* break; */
3928 if (*result_count > result_limit)
3930 *result_count = 0;
3931 warning (_("RMT ERROR: threadlist response longer than requested."));
3932 return 0;
3934 return result;
3937 /* Fetch the list of remote threads, with the qL packet, and call
3938 STEPFUNCTION for each thread found. Stops iterating and returns 1
3939 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3940 STEPFUNCTION returns false. If the packet is not supported,
3941 returns -1. */
3944 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3945 void *context, int looplimit)
3947 struct remote_state *rs = get_remote_state ();
3948 int done, i, result_count;
3949 int startflag = 1;
3950 int result = 1;
3951 int loopcount = 0;
3953 done = 0;
3954 while (!done)
3956 if (loopcount++ > looplimit)
3958 result = 0;
3959 warning (_("Remote fetch threadlist -infinite loop-."));
3960 break;
3962 result = remote_get_threadlist (startflag, &rs->nextthread,
3963 MAXTHREADLISTRESULTS,
3964 &done, &result_count,
3965 rs->resultthreadlist);
3966 if (result <= 0)
3967 break;
3968 /* Clear for later iterations. */
3969 startflag = 0;
3970 /* Setup to resume next batch of thread references, set nextthread. */
3971 if (result_count >= 1)
3972 copy_threadref (&rs->nextthread,
3973 &rs->resultthreadlist[result_count - 1]);
3974 i = 0;
3975 while (result_count--)
3977 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3979 result = 0;
3980 break;
3984 return result;
3987 /* A thread found on the remote target. */
3989 struct thread_item
3991 explicit thread_item (ptid_t ptid_)
3992 : ptid (ptid_)
3995 thread_item (thread_item &&other) = default;
3996 thread_item &operator= (thread_item &&other) = default;
3998 DISABLE_COPY_AND_ASSIGN (thread_item);
4000 /* The thread's PTID. */
4001 ptid_t ptid;
4003 /* The thread's extra info. */
4004 std::string extra;
4006 /* The thread's name. */
4007 std::string name;
4009 /* The core the thread was running on. -1 if not known. */
4010 int core = -1;
4012 /* The thread handle associated with the thread. */
4013 gdb::byte_vector thread_handle;
4016 /* Context passed around to the various methods listing remote
4017 threads. As new threads are found, they're added to the ITEMS
4018 vector. */
4020 struct threads_listing_context
4022 /* Return true if this object contains an entry for a thread with ptid
4023 PTID. */
4025 bool contains_thread (ptid_t ptid) const
4027 auto match_ptid = [&] (const thread_item &item)
4029 return item.ptid == ptid;
4032 auto it = std::find_if (this->items.begin (),
4033 this->items.end (),
4034 match_ptid);
4036 return it != this->items.end ();
4039 /* Remove the thread with ptid PTID. */
4041 void remove_thread (ptid_t ptid)
4043 auto match_ptid = [&] (const thread_item &item)
4045 return item.ptid == ptid;
4048 auto it = std::remove_if (this->items.begin (),
4049 this->items.end (),
4050 match_ptid);
4052 if (it != this->items.end ())
4053 this->items.erase (it);
4056 /* The threads found on the remote target. */
4057 std::vector<thread_item> items;
4060 static int
4061 remote_newthread_step (threadref *ref, void *data)
4063 struct threads_listing_context *context
4064 = (struct threads_listing_context *) data;
4065 int pid = inferior_ptid.pid ();
4066 int lwp = threadref_to_int (ref);
4067 ptid_t ptid (pid, lwp);
4069 context->items.emplace_back (ptid);
4071 return 1; /* continue iterator */
4074 #define CRAZY_MAX_THREADS 1000
4076 ptid_t
4077 remote_target::remote_current_thread (ptid_t oldpid)
4079 struct remote_state *rs = get_remote_state ();
4081 putpkt ("qC");
4082 getpkt (&rs->buf);
4083 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
4085 const char *obuf;
4086 ptid_t result;
4088 result = read_ptid (&rs->buf[2], &obuf);
4089 if (*obuf != '\0')
4090 remote_debug_printf ("warning: garbage in qC reply");
4092 return result;
4094 else
4095 return oldpid;
4098 /* List remote threads using the deprecated qL packet. */
4101 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4103 if (remote_threadlist_iterator (remote_newthread_step, context,
4104 CRAZY_MAX_THREADS) >= 0)
4105 return 1;
4107 return 0;
4110 #if defined(HAVE_LIBEXPAT)
4112 static void
4113 start_thread (struct gdb_xml_parser *parser,
4114 const struct gdb_xml_element *element,
4115 void *user_data,
4116 std::vector<gdb_xml_value> &attributes)
4118 struct threads_listing_context *data
4119 = (struct threads_listing_context *) user_data;
4120 struct gdb_xml_value *attr;
4122 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4123 ptid_t ptid = read_ptid (id, NULL);
4125 thread_item &item = data->items.emplace_back (ptid);
4127 attr = xml_find_attribute (attributes, "core");
4128 if (attr != NULL)
4129 item.core = *(ULONGEST *) attr->value.get ();
4131 attr = xml_find_attribute (attributes, "name");
4132 if (attr != NULL)
4133 item.name = (const char *) attr->value.get ();
4135 attr = xml_find_attribute (attributes, "handle");
4136 if (attr != NULL)
4137 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4140 static void
4141 end_thread (struct gdb_xml_parser *parser,
4142 const struct gdb_xml_element *element,
4143 void *user_data, const char *body_text)
4145 struct threads_listing_context *data
4146 = (struct threads_listing_context *) user_data;
4148 if (body_text != NULL && *body_text != '\0')
4149 data->items.back ().extra = body_text;
4152 const struct gdb_xml_attribute thread_attributes[] = {
4153 { "id", GDB_XML_AF_NONE, NULL, NULL },
4154 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4155 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4156 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4157 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4160 const struct gdb_xml_element thread_children[] = {
4161 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4164 const struct gdb_xml_element threads_children[] = {
4165 { "thread", thread_attributes, thread_children,
4166 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4167 start_thread, end_thread },
4168 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4171 const struct gdb_xml_element threads_elements[] = {
4172 { "threads", NULL, threads_children,
4173 GDB_XML_EF_NONE, NULL, NULL },
4174 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4177 #endif
4179 /* List remote threads using qXfer:threads:read. */
4182 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4184 #if defined(HAVE_LIBEXPAT)
4185 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4187 std::optional<gdb::char_vector> xml
4188 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4190 if (xml && (*xml)[0] != '\0')
4192 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4193 threads_elements, xml->data (), context);
4196 return 1;
4198 #endif
4200 return 0;
4203 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4206 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4208 struct remote_state *rs = get_remote_state ();
4210 if (rs->use_threadinfo_query)
4212 const char *bufp;
4214 putpkt ("qfThreadInfo");
4215 getpkt (&rs->buf);
4216 bufp = rs->buf.data ();
4217 if (bufp[0] != '\0') /* q packet recognized */
4219 while (*bufp++ == 'm') /* reply contains one or more TID */
4223 ptid_t ptid = read_ptid (bufp, &bufp);
4224 context->items.emplace_back (ptid);
4226 while (*bufp++ == ','); /* comma-separated list */
4227 putpkt ("qsThreadInfo");
4228 getpkt (&rs->buf);
4229 bufp = rs->buf.data ();
4231 return 1;
4233 else
4235 /* Packet not recognized. */
4236 rs->use_threadinfo_query = 0;
4240 return 0;
4243 /* Return true if INF only has one non-exited thread. */
4245 static bool
4246 has_single_non_exited_thread (inferior *inf)
4248 int count = 0;
4249 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4250 if (++count > 1)
4251 break;
4252 return count == 1;
4255 /* Implement the to_update_thread_list function for the remote
4256 targets. */
4258 void
4259 remote_target::update_thread_list ()
4261 struct threads_listing_context context;
4262 int got_list = 0;
4264 /* We have a few different mechanisms to fetch the thread list. Try
4265 them all, starting with the most preferred one first, falling
4266 back to older methods. */
4267 if (remote_get_threads_with_qxfer (&context)
4268 || remote_get_threads_with_qthreadinfo (&context)
4269 || remote_get_threads_with_ql (&context))
4271 got_list = 1;
4273 if (context.items.empty ()
4274 && remote_thread_always_alive (inferior_ptid))
4276 /* Some targets don't really support threads, but still
4277 reply an (empty) thread list in response to the thread
4278 listing packets, instead of replying "packet not
4279 supported". Exit early so we don't delete the main
4280 thread. */
4281 return;
4284 /* CONTEXT now holds the current thread list on the remote
4285 target end. Delete GDB-side threads no longer found on the
4286 target. */
4287 for (thread_info *tp : all_threads_safe ())
4289 if (tp->inf->process_target () != this)
4290 continue;
4292 if (!context.contains_thread (tp->ptid))
4294 /* Do not remove the thread if it is the last thread in
4295 the inferior. This situation happens when we have a
4296 pending exit process status to process. Otherwise we
4297 may end up with a seemingly live inferior (i.e. pid
4298 != 0) that has no threads. */
4299 if (has_single_non_exited_thread (tp->inf))
4300 continue;
4302 /* Do not remove the thread if we've requested to be
4303 notified of its exit. For example, the thread may be
4304 displaced stepping, infrun will need to handle the
4305 exit event, and displaced stepping info is recorded
4306 in the thread object. If we deleted the thread now,
4307 we'd lose that info. */
4308 if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
4309 continue;
4311 /* Not found. */
4312 delete_thread (tp);
4316 /* Remove any unreported fork/vfork/clone child threads from
4317 CONTEXT so that we don't interfere with follow
4318 fork/vfork/clone, which is where creation of such threads is
4319 handled. */
4320 remove_new_children (&context);
4322 /* And now add threads we don't know about yet to our list. */
4323 for (thread_item &item : context.items)
4325 if (item.ptid != null_ptid)
4327 /* In non-stop mode, we assume new found threads are
4328 executing until proven otherwise with a stop reply.
4329 In all-stop, we can only get here if all threads are
4330 stopped. */
4331 bool executing = target_is_non_stop_p ();
4333 remote_notice_new_inferior (item.ptid, executing);
4335 thread_info *tp = this->find_thread (item.ptid);
4336 remote_thread_info *info = get_remote_thread_info (tp);
4337 info->core = item.core;
4338 info->extra = std::move (item.extra);
4339 info->name = std::move (item.name);
4340 info->thread_handle = std::move (item.thread_handle);
4345 if (!got_list)
4347 /* If no thread listing method is supported, then query whether
4348 each known thread is alive, one by one, with the T packet.
4349 If the target doesn't support threads at all, then this is a
4350 no-op. See remote_thread_alive. */
4351 prune_threads ();
4356 * Collect a descriptive string about the given thread.
4357 * The target may say anything it wants to about the thread
4358 * (typically info about its blocked / runnable state, name, etc.).
4359 * This string will appear in the info threads display.
4361 * Optional: targets are not required to implement this function.
4364 const char *
4365 remote_target::extra_thread_info (thread_info *tp)
4367 struct remote_state *rs = get_remote_state ();
4368 int set;
4369 threadref id;
4370 struct gdb_ext_thread_info threadinfo;
4372 if (rs->remote_desc == 0) /* paranoia */
4373 internal_error (_("remote_threads_extra_info"));
4375 if (tp->ptid == magic_null_ptid
4376 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4377 /* This is the main thread which was added by GDB. The remote
4378 server doesn't know about it. */
4379 return NULL;
4381 std::string &extra = get_remote_thread_info (tp)->extra;
4383 /* If already have cached info, use it. */
4384 if (!extra.empty ())
4385 return extra.c_str ();
4387 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4389 /* If we're using qXfer:threads:read, then the extra info is
4390 included in the XML. So if we didn't have anything cached,
4391 it's because there's really no extra info. */
4392 return NULL;
4395 if (rs->use_threadextra_query)
4397 char *b = rs->buf.data ();
4398 char *endb = b + get_remote_packet_size ();
4400 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4401 b += strlen (b);
4402 write_ptid (b, endb, tp->ptid);
4404 putpkt (rs->buf);
4405 getpkt (&rs->buf);
4406 if (rs->buf[0] != 0)
4408 extra.resize (strlen (rs->buf.data ()) / 2);
4409 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4410 return extra.c_str ();
4414 /* If the above query fails, fall back to the old method. */
4415 rs->use_threadextra_query = 0;
4416 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4417 | TAG_MOREDISPLAY | TAG_DISPLAY;
4418 int_to_threadref (&id, tp->ptid.lwp ());
4419 if (remote_get_threadinfo (&id, set, &threadinfo))
4420 if (threadinfo.active)
4422 if (*threadinfo.shortname)
4423 string_appendf (extra, " Name: %s", threadinfo.shortname);
4424 if (*threadinfo.display)
4426 if (!extra.empty ())
4427 extra += ',';
4428 string_appendf (extra, " State: %s", threadinfo.display);
4430 if (*threadinfo.more_display)
4432 if (!extra.empty ())
4433 extra += ',';
4434 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4436 return extra.c_str ();
4438 return NULL;
4442 bool
4443 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4444 struct static_tracepoint_marker *marker)
4446 struct remote_state *rs = get_remote_state ();
4447 char *p = rs->buf.data ();
4449 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4450 p += strlen (p);
4451 p += hexnumstr (p, addr);
4452 putpkt (rs->buf);
4453 getpkt (&rs->buf);
4454 p = rs->buf.data ();
4456 if (*p == 'E')
4457 error (_("Remote failure reply: %s"), p);
4459 if (*p++ == 'm')
4461 parse_static_tracepoint_marker_definition (p, NULL, marker);
4462 return true;
4465 return false;
4468 std::vector<static_tracepoint_marker>
4469 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4471 struct remote_state *rs = get_remote_state ();
4472 std::vector<static_tracepoint_marker> markers;
4473 const char *p;
4474 static_tracepoint_marker marker;
4476 /* Ask for a first packet of static tracepoint marker
4477 definition. */
4478 putpkt ("qTfSTM");
4479 getpkt (&rs->buf);
4480 p = rs->buf.data ();
4481 if (*p == 'E')
4482 error (_("Remote failure reply: %s"), p);
4484 while (*p++ == 'm')
4488 parse_static_tracepoint_marker_definition (p, &p, &marker);
4490 if (strid == NULL || marker.str_id == strid)
4491 markers.push_back (std::move (marker));
4493 while (*p++ == ','); /* comma-separated list */
4494 /* Ask for another packet of static tracepoint definition. */
4495 putpkt ("qTsSTM");
4496 getpkt (&rs->buf);
4497 p = rs->buf.data ();
4500 return markers;
4504 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4506 ptid_t
4507 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4509 return ptid_t (inferior_ptid.pid (), lwp);
4513 /* Restart the remote side; this is an extended protocol operation. */
4515 void
4516 remote_target::extended_remote_restart ()
4518 struct remote_state *rs = get_remote_state ();
4520 /* Send the restart command; for reasons I don't understand the
4521 remote side really expects a number after the "R". */
4522 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4523 putpkt (rs->buf);
4525 remote_fileio_reset ();
4528 /* Clean up connection to a remote debugger. */
4530 void
4531 remote_target::close ()
4533 /* Make sure we leave stdin registered in the event loop. */
4534 terminal_ours ();
4536 trace_reset_local_state ();
4538 delete this;
4541 remote_target::~remote_target ()
4543 struct remote_state *rs = get_remote_state ();
4545 /* Check for NULL because we may get here with a partially
4546 constructed target/connection. */
4547 if (rs->remote_desc == nullptr)
4548 return;
4550 serial_close (rs->remote_desc);
4552 /* We are destroying the remote target, so we should discard
4553 everything of this target. */
4554 discard_pending_stop_replies_in_queue ();
4556 rs->delete_async_event_handler ();
4558 delete rs->notif_state;
4561 /* Query the remote side for the text, data and bss offsets. */
4563 void
4564 remote_target::get_offsets ()
4566 struct remote_state *rs = get_remote_state ();
4567 char *buf;
4568 char *ptr;
4569 int lose, num_segments = 0, do_sections, do_segments;
4570 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4572 if (current_program_space->symfile_object_file == NULL)
4573 return;
4575 putpkt ("qOffsets");
4576 getpkt (&rs->buf);
4577 buf = rs->buf.data ();
4579 if (buf[0] == '\000')
4580 return; /* Return silently. Stub doesn't support
4581 this command. */
4582 if (buf[0] == 'E')
4584 warning (_("Remote failure reply: %s"), buf);
4585 return;
4588 /* Pick up each field in turn. This used to be done with scanf, but
4589 scanf will make trouble if CORE_ADDR size doesn't match
4590 conversion directives correctly. The following code will work
4591 with any size of CORE_ADDR. */
4592 text_addr = data_addr = bss_addr = 0;
4593 ptr = buf;
4594 lose = 0;
4596 if (startswith (ptr, "Text="))
4598 ptr += 5;
4599 /* Don't use strtol, could lose on big values. */
4600 while (*ptr && *ptr != ';')
4601 text_addr = (text_addr << 4) + fromhex (*ptr++);
4603 if (startswith (ptr, ";Data="))
4605 ptr += 6;
4606 while (*ptr && *ptr != ';')
4607 data_addr = (data_addr << 4) + fromhex (*ptr++);
4609 else
4610 lose = 1;
4612 if (!lose && startswith (ptr, ";Bss="))
4614 ptr += 5;
4615 while (*ptr && *ptr != ';')
4616 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4618 if (bss_addr != data_addr)
4619 warning (_("Target reported unsupported offsets: %s"), buf);
4621 else
4622 lose = 1;
4624 else if (startswith (ptr, "TextSeg="))
4626 ptr += 8;
4627 /* Don't use strtol, could lose on big values. */
4628 while (*ptr && *ptr != ';')
4629 text_addr = (text_addr << 4) + fromhex (*ptr++);
4630 num_segments = 1;
4632 if (startswith (ptr, ";DataSeg="))
4634 ptr += 9;
4635 while (*ptr && *ptr != ';')
4636 data_addr = (data_addr << 4) + fromhex (*ptr++);
4637 num_segments++;
4640 else
4641 lose = 1;
4643 if (lose)
4644 error (_("Malformed response to offset query, %s"), buf);
4645 else if (*ptr != '\0')
4646 warning (_("Target reported unsupported offsets: %s"), buf);
4648 objfile *objf = current_program_space->symfile_object_file;
4649 section_offsets offs = objf->section_offsets;
4651 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4652 do_segments = (data != NULL);
4653 do_sections = num_segments == 0;
4655 if (num_segments > 0)
4657 segments[0] = text_addr;
4658 segments[1] = data_addr;
4660 /* If we have two segments, we can still try to relocate everything
4661 by assuming that the .text and .data offsets apply to the whole
4662 text and data segments. Convert the offsets given in the packet
4663 to base addresses for symfile_map_offsets_to_segments. */
4664 else if (data != nullptr && data->segments.size () == 2)
4666 segments[0] = data->segments[0].base + text_addr;
4667 segments[1] = data->segments[1].base + data_addr;
4668 num_segments = 2;
4670 /* If the object file has only one segment, assume that it is text
4671 rather than data; main programs with no writable data are rare,
4672 but programs with no code are useless. Of course the code might
4673 have ended up in the data segment... to detect that we would need
4674 the permissions here. */
4675 else if (data && data->segments.size () == 1)
4677 segments[0] = data->segments[0].base + text_addr;
4678 num_segments = 1;
4680 /* There's no way to relocate by segment. */
4681 else
4682 do_segments = 0;
4684 if (do_segments)
4686 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4687 data.get (), offs,
4688 num_segments, segments);
4690 if (ret == 0 && !do_sections)
4691 error (_("Can not handle qOffsets TextSeg "
4692 "response with this symbol file"));
4694 if (ret > 0)
4695 do_sections = 0;
4698 if (do_sections)
4700 offs[SECT_OFF_TEXT (objf)] = text_addr;
4702 /* This is a temporary kludge to force data and bss to use the
4703 same offsets because that's what nlmconv does now. The real
4704 solution requires changes to the stub and remote.c that I
4705 don't have time to do right now. */
4707 offs[SECT_OFF_DATA (objf)] = data_addr;
4708 offs[SECT_OFF_BSS (objf)] = data_addr;
4711 objfile_relocate (objf, offs);
4714 /* Send interrupt_sequence to remote target. */
4716 void
4717 remote_target::send_interrupt_sequence ()
4719 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4720 remote_serial_write ("\x03", 1);
4721 else if (interrupt_sequence_mode == interrupt_sequence_break)
4722 remote_serial_send_break ();
4723 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4725 remote_serial_send_break ();
4726 remote_serial_write ("g", 1);
4728 else
4729 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4730 interrupt_sequence_mode);
4733 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4734 and extract the PTID. Returns NULL_PTID if not found. */
4736 static ptid_t
4737 stop_reply_extract_thread (const char *stop_reply)
4739 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4741 const char *p;
4743 /* Txx r:val ; r:val (...) */
4744 p = &stop_reply[3];
4746 /* Look for "register" named "thread". */
4747 while (*p != '\0')
4749 const char *p1;
4751 p1 = strchr (p, ':');
4752 if (p1 == NULL)
4753 return null_ptid;
4755 if (strncmp (p, "thread", p1 - p) == 0)
4756 return read_ptid (++p1, &p);
4758 p1 = strchr (p, ';');
4759 if (p1 == NULL)
4760 return null_ptid;
4761 p1++;
4763 p = p1;
4767 return null_ptid;
4770 /* Determine the remote side's current thread. If we have a stop
4771 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4772 "thread" register we can extract the current thread from. If not,
4773 ask the remote which is the current thread with qC. The former
4774 method avoids a roundtrip. */
4776 ptid_t
4777 remote_target::get_current_thread (const char *wait_status)
4779 ptid_t ptid = null_ptid;
4781 /* Note we don't use remote_parse_stop_reply as that makes use of
4782 the target architecture, which we haven't yet fully determined at
4783 this point. */
4784 if (wait_status != NULL)
4785 ptid = stop_reply_extract_thread (wait_status);
4786 if (ptid == null_ptid)
4787 ptid = remote_current_thread (inferior_ptid);
4789 return ptid;
4792 /* Query the remote target for which is the current thread/process,
4793 add it to our tables, and update INFERIOR_PTID. The caller is
4794 responsible for setting the state such that the remote end is ready
4795 to return the current thread.
4797 This function is called after handling the '?' or 'vRun' packets,
4798 whose response is a stop reply from which we can also try
4799 extracting the thread. If the target doesn't support the explicit
4800 qC query, we infer the current thread from that stop reply, passed
4801 in in WAIT_STATUS, which may be NULL.
4803 The function returns pointer to the main thread of the inferior. */
4805 thread_info *
4806 remote_target::add_current_inferior_and_thread (const char *wait_status)
4808 bool fake_pid_p = false;
4810 switch_to_no_thread ();
4812 /* Now, if we have thread information, update the current thread's
4813 ptid. */
4814 ptid_t curr_ptid = get_current_thread (wait_status);
4816 if (curr_ptid != null_ptid)
4818 if (!m_features.remote_multi_process_p ())
4819 fake_pid_p = true;
4821 else
4823 /* Without this, some commands which require an active target
4824 (such as kill) won't work. This variable serves (at least)
4825 double duty as both the pid of the target process (if it has
4826 such), and as a flag indicating that a target is active. */
4827 curr_ptid = magic_null_ptid;
4828 fake_pid_p = true;
4831 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4833 /* Add the main thread and switch to it. Don't try reading
4834 registers yet, since we haven't fetched the target description
4835 yet. */
4836 thread_info *tp = add_thread_silent (this, curr_ptid);
4837 switch_to_thread_no_regs (tp);
4839 return tp;
4842 /* Print info about a thread that was found already stopped on
4843 connection. */
4845 void
4846 remote_target::print_one_stopped_thread (thread_info *thread)
4848 target_waitstatus ws;
4850 /* If there is a pending waitstatus, use it. If there isn't it's because
4851 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4852 and process_initial_stop_replies decided it wasn't interesting to save
4853 and report to the core. */
4854 if (thread->has_pending_waitstatus ())
4856 ws = thread->pending_waitstatus ();
4857 thread->clear_pending_waitstatus ();
4859 else
4861 ws.set_stopped (GDB_SIGNAL_0);
4864 switch_to_thread (thread);
4865 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4866 set_current_sal_from_frame (get_current_frame ());
4868 /* For "info program". */
4869 set_last_target_status (this, thread->ptid, ws);
4871 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4873 enum gdb_signal sig = ws.sig ();
4875 if (signal_print_state (sig))
4876 notify_signal_received (sig);
4879 notify_normal_stop (nullptr, 1);
4882 /* Process all initial stop replies the remote side sent in response
4883 to the ? packet. These indicate threads that were already stopped
4884 on initial connection. We mark these threads as stopped and print
4885 their current frame before giving the user the prompt. */
4887 void
4888 remote_target::process_initial_stop_replies (int from_tty)
4890 int pending_stop_replies = stop_reply_queue_length ();
4891 struct thread_info *selected = NULL;
4892 struct thread_info *lowest_stopped = NULL;
4893 struct thread_info *first = NULL;
4895 /* This is only used when the target is non-stop. */
4896 gdb_assert (target_is_non_stop_p ());
4898 /* Consume the initial pending events. */
4899 while (pending_stop_replies-- > 0)
4901 ptid_t waiton_ptid = minus_one_ptid;
4902 ptid_t event_ptid;
4903 struct target_waitstatus ws;
4904 int ignore_event = 0;
4906 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4907 if (remote_debug)
4908 print_target_wait_results (waiton_ptid, event_ptid, ws);
4910 switch (ws.kind ())
4912 case TARGET_WAITKIND_IGNORE:
4913 case TARGET_WAITKIND_NO_RESUMED:
4914 case TARGET_WAITKIND_SIGNALLED:
4915 case TARGET_WAITKIND_EXITED:
4916 /* We shouldn't see these, but if we do, just ignore. */
4917 remote_debug_printf ("event ignored");
4918 ignore_event = 1;
4919 break;
4921 default:
4922 break;
4925 if (ignore_event)
4926 continue;
4928 thread_info *evthread = this->find_thread (event_ptid);
4930 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4932 enum gdb_signal sig = ws.sig ();
4934 /* Stubs traditionally report SIGTRAP as initial signal,
4935 instead of signal 0. Suppress it. */
4936 if (sig == GDB_SIGNAL_TRAP)
4937 sig = GDB_SIGNAL_0;
4938 evthread->set_stop_signal (sig);
4939 ws.set_stopped (sig);
4942 if (ws.kind () != TARGET_WAITKIND_STOPPED
4943 || ws.sig () != GDB_SIGNAL_0)
4944 evthread->set_pending_waitstatus (ws);
4946 set_executing (this, event_ptid, false);
4947 set_running (this, event_ptid, false);
4948 get_remote_thread_info (evthread)->set_not_resumed ();
4951 /* "Notice" the new inferiors before anything related to
4952 registers/memory. */
4953 for (inferior *inf : all_non_exited_inferiors (this))
4955 inf->needs_setup = true;
4957 if (non_stop)
4959 thread_info *thread = any_live_thread_of_inferior (inf);
4960 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4961 from_tty);
4965 /* If all-stop on top of non-stop, pause all threads. Note this
4966 records the threads' stop pc, so must be done after "noticing"
4967 the inferiors. */
4968 if (!non_stop)
4971 /* At this point, the remote target is not async. It needs to be for
4972 the poll in stop_all_threads to consider events from it, so enable
4973 it temporarily. */
4974 gdb_assert (!this->is_async_p ());
4975 SCOPE_EXIT { target_async (false); };
4976 target_async (true);
4977 stop_all_threads ("remote connect in all-stop");
4980 /* If all threads of an inferior were already stopped, we
4981 haven't setup the inferior yet. */
4982 for (inferior *inf : all_non_exited_inferiors (this))
4984 if (inf->needs_setup)
4986 thread_info *thread = any_live_thread_of_inferior (inf);
4987 switch_to_thread_no_regs (thread);
4988 setup_inferior (0);
4993 /* Now go over all threads that are stopped, and print their current
4994 frame. If all-stop, then if there's a signalled thread, pick
4995 that as current. */
4996 for (thread_info *thread : all_non_exited_threads (this))
4998 if (first == NULL)
4999 first = thread;
5001 if (!non_stop)
5002 thread->set_running (false);
5003 else if (thread->state != THREAD_STOPPED)
5004 continue;
5006 if (selected == nullptr && thread->has_pending_waitstatus ())
5007 selected = thread;
5009 if (lowest_stopped == NULL
5010 || thread->inf->num < lowest_stopped->inf->num
5011 || thread->per_inf_num < lowest_stopped->per_inf_num)
5012 lowest_stopped = thread;
5014 if (non_stop)
5015 print_one_stopped_thread (thread);
5018 /* In all-stop, we only print the status of one thread, and leave
5019 others with their status pending. */
5020 if (!non_stop)
5022 thread_info *thread = selected;
5023 if (thread == NULL)
5024 thread = lowest_stopped;
5025 if (thread == NULL)
5026 thread = first;
5028 print_one_stopped_thread (thread);
5032 /* Mark a remote_target as starting (by setting the starting_up flag within
5033 its remote_state) for the lifetime of this object. The reference count
5034 on the remote target is temporarily incremented, to prevent the target
5035 being deleted under our feet. */
5037 struct scoped_mark_target_starting
5039 /* Constructor, TARGET is the target to be marked as starting, its
5040 reference count will be incremented. */
5041 scoped_mark_target_starting (remote_target *target)
5042 : m_remote_target (remote_target_ref::new_reference (target)),
5043 m_restore_starting_up (set_starting_up_flag (target))
5044 { /* Nothing. */ }
5046 private:
5048 /* Helper function, set the starting_up flag on TARGET and return an
5049 object which, when it goes out of scope, will restore the previous
5050 value of the starting_up flag. */
5051 static scoped_restore_tmpl<bool>
5052 set_starting_up_flag (remote_target *target)
5054 remote_state *rs = target->get_remote_state ();
5055 gdb_assert (!rs->starting_up);
5056 return make_scoped_restore (&rs->starting_up, true);
5059 /* A gdb::ref_ptr pointer to a remote_target. */
5060 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
5062 /* A reference to the target on which we are operating. */
5063 remote_target_ref m_remote_target;
5065 /* An object which restores the previous value of the starting_up flag
5066 when it goes out of scope. */
5067 scoped_restore_tmpl<bool> m_restore_starting_up;
5070 /* Transfer ownership of the stop_reply owned by EVENT to a
5071 stop_reply_up object. */
5073 static stop_reply_up
5074 as_stop_reply_up (notif_event_up event)
5076 auto *stop_reply = static_cast<struct stop_reply *> (event.release ());
5077 return stop_reply_up (stop_reply);
5080 /* Helper for remote_target::start_remote, start the remote connection and
5081 sync state. Return true if everything goes OK, otherwise, return false.
5082 This function exists so that the scoped_restore created within it will
5083 expire before we return to remote_target::start_remote. */
5085 bool
5086 remote_target::start_remote_1 (int from_tty, int extended_p)
5088 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
5090 struct remote_state *rs = get_remote_state ();
5092 /* Signal other parts that we're going through the initial setup,
5093 and so things may not be stable yet. E.g., we don't try to
5094 install tracepoints until we've relocated symbols. Also, a
5095 Ctrl-C before we're connected and synced up can't interrupt the
5096 target. Instead, it offers to drop the (potentially wedged)
5097 connection. */
5098 scoped_mark_target_starting target_is_starting (this);
5100 QUIT;
5102 if (interrupt_on_connect)
5103 send_interrupt_sequence ();
5105 /* Ack any packet which the remote side has already sent. */
5106 remote_serial_write ("+", 1);
5108 /* The first packet we send to the target is the optional "supported
5109 packets" request. If the target can answer this, it will tell us
5110 which later probes to skip. */
5111 remote_query_supported ();
5113 /* Check vCont support and set the remote state's vCont_action_support
5114 attribute. */
5115 remote_vcont_probe ();
5117 /* If the stub wants to get a QAllow, compose one and send it. */
5118 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5119 set_permissions ();
5121 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5122 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5123 as a reply to known packet. For packet "vFile:setfs:" it is an
5124 invalid reply and GDB would return error in
5125 remote_hostio_set_filesystem, making remote files access impossible.
5126 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5127 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5129 const char v_mustreplyempty[] = "vMustReplyEmpty";
5131 putpkt (v_mustreplyempty);
5132 getpkt (&rs->buf);
5133 if (strcmp (rs->buf.data (), "OK") == 0)
5135 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5136 = PACKET_DISABLE;
5138 else if (strcmp (rs->buf.data (), "") != 0)
5139 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5140 rs->buf.data ());
5143 /* Next, we possibly activate noack mode.
5145 If the QStartNoAckMode packet configuration is set to AUTO,
5146 enable noack mode if the stub reported a wish for it with
5147 qSupported.
5149 If set to TRUE, then enable noack mode even if the stub didn't
5150 report it in qSupported. If the stub doesn't reply OK, the
5151 session ends with an error.
5153 If FALSE, then don't activate noack mode, regardless of what the
5154 stub claimed should be the default with qSupported. */
5156 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5158 putpkt ("QStartNoAckMode");
5159 getpkt (&rs->buf);
5160 if ((m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode)).status ()
5161 == PACKET_OK)
5162 rs->noack_mode = 1;
5165 if (extended_p)
5167 /* Tell the remote that we are using the extended protocol. */
5168 putpkt ("!");
5169 getpkt (&rs->buf);
5172 /* Let the target know which signals it is allowed to pass down to
5173 the program. */
5174 update_signals_program_target ();
5176 /* Next, if the target can specify a description, read it. We do
5177 this before anything involving memory or registers. */
5178 target_find_description ();
5180 /* Next, now that we know something about the target, update the
5181 address spaces in the program spaces. */
5182 update_address_spaces ();
5184 /* On OSs where the list of libraries is global to all
5185 processes, we fetch them early. */
5186 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5187 solib_add (NULL, from_tty, auto_solib_add);
5189 if (target_is_non_stop_p ())
5191 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5192 error (_("Non-stop mode requested, but remote "
5193 "does not support non-stop"));
5195 putpkt ("QNonStop:1");
5196 getpkt (&rs->buf);
5198 if (strcmp (rs->buf.data (), "OK") != 0)
5199 error (_("Remote refused setting non-stop mode with: %s"),
5200 rs->buf.data ());
5202 /* Find about threads and processes the stub is already
5203 controlling. We default to adding them in the running state.
5204 The '?' query below will then tell us about which threads are
5205 stopped. */
5206 this->update_thread_list ();
5208 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5210 /* Don't assume that the stub can operate in all-stop mode.
5211 Request it explicitly. */
5212 putpkt ("QNonStop:0");
5213 getpkt (&rs->buf);
5215 if (strcmp (rs->buf.data (), "OK") != 0)
5216 error (_("Remote refused setting all-stop mode with: %s"),
5217 rs->buf.data ());
5220 /* Upload TSVs regardless of whether the target is running or not. The
5221 remote stub, such as GDBserver, may have some predefined or builtin
5222 TSVs, even if the target is not running. */
5223 if (get_trace_status (current_trace_status ()) != -1)
5225 struct uploaded_tsv *uploaded_tsvs = NULL;
5227 upload_trace_state_variables (&uploaded_tsvs);
5228 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5231 /* Check whether the target is running now. */
5232 putpkt ("?");
5233 getpkt (&rs->buf);
5235 if (!target_is_non_stop_p ())
5237 char *wait_status = NULL;
5239 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5241 if (!extended_p)
5242 error (_("The target is not running (try extended-remote?)"));
5243 return false;
5245 else
5247 /* Save the reply for later. */
5248 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5249 strcpy (wait_status, rs->buf.data ());
5252 /* Fetch thread list. */
5253 target_update_thread_list ();
5255 /* Let the stub know that we want it to return the thread. */
5256 set_continue_thread (minus_one_ptid);
5258 if (thread_count (this) == 0)
5260 /* Target has no concept of threads at all. GDB treats
5261 non-threaded target as single-threaded; add a main
5262 thread. */
5263 thread_info *tp = add_current_inferior_and_thread (wait_status);
5264 get_remote_thread_info (tp)->set_resumed ();
5266 else
5268 /* We have thread information; select the thread the target
5269 says should be current. If we're reconnecting to a
5270 multi-threaded program, this will ideally be the thread
5271 that last reported an event before GDB disconnected. */
5272 ptid_t curr_thread = get_current_thread (wait_status);
5273 if (curr_thread == null_ptid)
5275 /* Odd... The target was able to list threads, but not
5276 tell us which thread was current (no "thread"
5277 register in T stop reply?). Just pick the first
5278 thread in the thread list then. */
5280 remote_debug_printf ("warning: couldn't determine remote "
5281 "current thread; picking first in list.");
5283 for (thread_info *tp : all_non_exited_threads (this,
5284 minus_one_ptid))
5286 switch_to_thread (tp);
5287 break;
5290 else
5291 switch_to_thread (this->find_thread (curr_thread));
5293 get_remote_thread_info (inferior_thread ())->set_resumed ();
5296 /* init_wait_for_inferior should be called before get_offsets in order
5297 to manage `inserted' flag in bp loc in a correct state.
5298 breakpoint_init_inferior, called from init_wait_for_inferior, set
5299 `inserted' flag to 0, while before breakpoint_re_set, called from
5300 start_remote, set `inserted' flag to 1. In the initialization of
5301 inferior, breakpoint_init_inferior should be called first, and then
5302 breakpoint_re_set can be called. If this order is broken, state of
5303 `inserted' flag is wrong, and cause some problems on breakpoint
5304 manipulation. */
5305 init_wait_for_inferior ();
5307 get_offsets (); /* Get text, data & bss offsets. */
5309 /* If we could not find a description using qXfer, and we know
5310 how to do it some other way, try again. This is not
5311 supported for non-stop; it could be, but it is tricky if
5312 there are no stopped threads when we connect. */
5313 if (remote_read_description_p (this)
5314 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5316 target_clear_description ();
5317 target_find_description ();
5320 /* Use the previously fetched status. */
5321 gdb_assert (wait_status != NULL);
5322 notif_event_up reply
5323 = remote_notif_parse (this, &notif_client_stop, wait_status);
5324 push_stop_reply (as_stop_reply_up (std::move (reply)));
5326 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5328 else
5330 /* Clear WFI global state. Do this before finding about new
5331 threads and inferiors, and setting the current inferior.
5332 Otherwise we would clear the proceed status of the current
5333 inferior when we want its stop_soon state to be preserved
5334 (see notice_new_inferior). */
5335 init_wait_for_inferior ();
5337 /* In non-stop, we will either get an "OK", meaning that there
5338 are no stopped threads at this time; or, a regular stop
5339 reply. In the latter case, there may be more than one thread
5340 stopped --- we pull them all out using the vStopped
5341 mechanism. */
5342 if (strcmp (rs->buf.data (), "OK") != 0)
5344 const notif_client *notif = &notif_client_stop;
5346 /* remote_notif_get_pending_replies acks this one, and gets
5347 the rest out. */
5348 rs->notif_state->pending_event[notif_client_stop.id]
5349 = remote_notif_parse (this, notif, rs->buf.data ());
5350 remote_notif_get_pending_events (notif);
5353 if (thread_count (this) == 0)
5355 if (!extended_p)
5356 error (_("The target is not running (try extended-remote?)"));
5357 return false;
5360 /* Report all signals during attach/startup. */
5361 pass_signals ({});
5363 /* If there are already stopped threads, mark them stopped and
5364 report their stops before giving the prompt to the user. */
5365 process_initial_stop_replies (from_tty);
5367 if (target_can_async_p ())
5368 target_async (true);
5371 /* Give the target a chance to look up symbols. */
5372 for (inferior *inf : all_inferiors (this))
5374 /* The inferiors that exist at this point were created from what
5375 was found already running on the remote side, so we know they
5376 have execution. */
5377 gdb_assert (this->has_execution (inf));
5379 /* No use without a symbol-file. */
5380 if (inf->pspace->symfile_object_file == nullptr)
5381 continue;
5383 /* Need to switch to a specific thread, because remote_check_symbols
5384 uses INFERIOR_PTID to set the general thread. */
5385 scoped_restore_current_thread restore_thread;
5386 thread_info *thread = any_thread_of_inferior (inf);
5387 switch_to_thread (thread);
5388 this->remote_check_symbols ();
5391 /* Possibly the target has been engaged in a trace run started
5392 previously; find out where things are at. */
5393 if (get_trace_status (current_trace_status ()) != -1)
5395 struct uploaded_tp *uploaded_tps = NULL;
5397 if (current_trace_status ()->running)
5398 gdb_printf (_("Trace is already running on the target.\n"));
5400 upload_tracepoints (&uploaded_tps);
5402 merge_uploaded_tracepoints (&uploaded_tps);
5405 /* Possibly the target has been engaged in a btrace record started
5406 previously; find out where things are at. */
5407 remote_btrace_maybe_reopen ();
5409 return true;
5412 /* Start the remote connection and sync state. */
5414 void
5415 remote_target::start_remote (int from_tty, int extended_p)
5417 if (start_remote_1 (from_tty, extended_p)
5418 && breakpoints_should_be_inserted_now ())
5419 insert_breakpoints ();
5422 const char *
5423 remote_target::connection_string ()
5425 remote_state *rs = get_remote_state ();
5427 if (rs->remote_desc->name != NULL)
5428 return rs->remote_desc->name;
5429 else
5430 return NULL;
5433 /* Open a connection to a remote debugger.
5434 NAME is the filename used for communication. */
5436 void
5437 remote_target::open (const char *name, int from_tty)
5439 open_1 (name, from_tty, 0);
5442 /* Open a connection to a remote debugger using the extended
5443 remote gdb protocol. NAME is the filename used for communication. */
5445 void
5446 extended_remote_target::open (const char *name, int from_tty)
5448 open_1 (name, from_tty, 1 /*extended_p */);
5451 void
5452 remote_features::reset_all_packet_configs_support ()
5454 int i;
5456 for (i = 0; i < PACKET_MAX; i++)
5457 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5460 /* Initialize all packet configs. */
5462 static void
5463 init_all_packet_configs (void)
5465 int i;
5467 for (i = 0; i < PACKET_MAX; i++)
5469 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5470 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5474 /* Symbol look-up. */
5476 void
5477 remote_target::remote_check_symbols ()
5479 char *tmp;
5480 int end;
5482 /* It doesn't make sense to send a qSymbol packet for an inferior that
5483 doesn't have execution, because the remote side doesn't know about
5484 inferiors without execution. */
5485 gdb_assert (target_has_execution ());
5487 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5488 return;
5490 /* Make sure the remote is pointing at the right process. Note
5491 there's no way to select "no process". */
5492 set_general_process ();
5494 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5495 because we need both at the same time. */
5496 gdb::char_vector msg (get_remote_packet_size ());
5497 gdb::char_vector reply (get_remote_packet_size ());
5499 /* Invite target to request symbol lookups. */
5501 putpkt ("qSymbol::");
5502 getpkt (&reply);
5503 m_features.packet_ok (reply, PACKET_qSymbol);
5505 while (startswith (reply.data (), "qSymbol:"))
5507 struct bound_minimal_symbol sym;
5509 tmp = &reply[8];
5510 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5511 strlen (tmp) / 2);
5512 msg[end] = '\0';
5513 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5514 if (sym.minsym == NULL)
5515 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5516 &reply[8]);
5517 else
5519 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5520 CORE_ADDR sym_addr = sym.value_address ();
5522 /* If this is a function address, return the start of code
5523 instead of any data function descriptor. */
5524 sym_addr = gdbarch_convert_from_func_ptr_addr
5525 (current_inferior ()->arch (), sym_addr,
5526 current_inferior ()->top_target ());
5528 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5529 phex_nz (sym_addr, addr_size), &reply[8]);
5532 putpkt (msg.data ());
5533 getpkt (&reply);
5537 static struct serial *
5538 remote_serial_open (const char *name)
5540 static int udp_warning = 0;
5542 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5543 of in ser-tcp.c, because it is the remote protocol assuming that the
5544 serial connection is reliable and not the serial connection promising
5545 to be. */
5546 if (!udp_warning && startswith (name, "udp:"))
5548 warning (_("The remote protocol may be unreliable over UDP.\n"
5549 "Some events may be lost, rendering further debugging "
5550 "impossible."));
5551 udp_warning = 1;
5554 return serial_open (name);
5557 /* Inform the target of our permission settings. The permission flags
5558 work without this, but if the target knows the settings, it can do
5559 a couple things. First, it can add its own check, to catch cases
5560 that somehow manage to get by the permissions checks in target
5561 methods. Second, if the target is wired to disallow particular
5562 settings (for instance, a system in the field that is not set up to
5563 be able to stop at a breakpoint), it can object to any unavailable
5564 permissions. */
5566 void
5567 remote_target::set_permissions ()
5569 struct remote_state *rs = get_remote_state ();
5571 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5572 "WriteReg:%x;WriteMem:%x;"
5573 "InsertBreak:%x;InsertTrace:%x;"
5574 "InsertFastTrace:%x;Stop:%x",
5575 may_write_registers, may_write_memory,
5576 may_insert_breakpoints, may_insert_tracepoints,
5577 may_insert_fast_tracepoints, may_stop);
5578 putpkt (rs->buf);
5579 getpkt (&rs->buf);
5581 /* If the target didn't like the packet, warn the user. Do not try
5582 to undo the user's settings, that would just be maddening. */
5583 if (strcmp (rs->buf.data (), "OK") != 0)
5584 warning (_("Remote refused setting permissions with: %s"),
5585 rs->buf.data ());
5588 /* This type describes each known response to the qSupported
5589 packet. */
5590 struct protocol_feature
5592 /* The name of this protocol feature. */
5593 const char *name;
5595 /* The default for this protocol feature. */
5596 enum packet_support default_support;
5598 /* The function to call when this feature is reported, or after
5599 qSupported processing if the feature is not supported.
5600 The first argument points to this structure. The second
5601 argument indicates whether the packet requested support be
5602 enabled, disabled, or probed (or the default, if this function
5603 is being called at the end of processing and this feature was
5604 not reported). The third argument may be NULL; if not NULL, it
5605 is a NUL-terminated string taken from the packet following
5606 this feature's name and an equals sign. */
5607 void (*func) (remote_target *remote, const struct protocol_feature *,
5608 enum packet_support, const char *);
5610 /* The corresponding packet for this feature. Only used if
5611 FUNC is remote_supported_packet. */
5612 int packet;
5615 static void
5616 remote_supported_packet (remote_target *remote,
5617 const struct protocol_feature *feature,
5618 enum packet_support support,
5619 const char *argument)
5621 if (argument)
5623 warning (_("Remote qSupported response supplied an unexpected value for"
5624 " \"%s\"."), feature->name);
5625 return;
5628 remote->m_features.m_protocol_packets[feature->packet].support = support;
5631 void
5632 remote_target::remote_packet_size (const protocol_feature *feature,
5633 enum packet_support support,
5634 const char *value)
5636 struct remote_state *rs = get_remote_state ();
5638 int packet_size;
5639 char *value_end;
5641 if (support != PACKET_ENABLE)
5642 return;
5644 if (value == NULL || *value == '\0')
5646 warning (_("Remote target reported \"%s\" without a size."),
5647 feature->name);
5648 return;
5651 errno = 0;
5652 packet_size = strtol (value, &value_end, 16);
5653 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5655 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5656 feature->name, value);
5657 return;
5660 /* Record the new maximum packet size. */
5661 rs->explicit_packet_size = packet_size;
5664 static void
5665 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5666 enum packet_support support, const char *value)
5668 remote->remote_packet_size (feature, support, value);
5671 void
5672 remote_target::remote_supported_thread_options (const protocol_feature *feature,
5673 enum packet_support support,
5674 const char *value)
5676 struct remote_state *rs = get_remote_state ();
5678 m_features.m_protocol_packets[feature->packet].support = support;
5680 if (support != PACKET_ENABLE)
5681 return;
5683 if (value == nullptr || *value == '\0')
5685 warning (_("Remote target reported \"%s\" without supported options."),
5686 feature->name);
5687 return;
5690 ULONGEST options = 0;
5691 const char *p = unpack_varlen_hex (value, &options);
5693 if (*p != '\0')
5695 warning (_("Remote target reported \"%s\" with "
5696 "bad thread options: \"%s\"."),
5697 feature->name, value);
5698 return;
5701 /* Record the set of supported options. */
5702 rs->supported_thread_options = (gdb_thread_option) options;
5705 static void
5706 remote_supported_thread_options (remote_target *remote,
5707 const protocol_feature *feature,
5708 enum packet_support support,
5709 const char *value)
5711 remote->remote_supported_thread_options (feature, support, value);
5714 static const struct protocol_feature remote_protocol_features[] = {
5715 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5716 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5717 PACKET_qXfer_auxv },
5718 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5719 PACKET_qXfer_exec_file },
5720 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5721 PACKET_qXfer_features },
5722 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5723 PACKET_qXfer_libraries },
5724 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5725 PACKET_qXfer_libraries_svr4 },
5726 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5727 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5728 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5729 PACKET_qXfer_memory_map },
5730 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5731 PACKET_qXfer_osdata },
5732 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5733 PACKET_qXfer_threads },
5734 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5735 PACKET_qXfer_traceframe_info },
5736 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5737 PACKET_QPassSignals },
5738 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5739 PACKET_QCatchSyscalls },
5740 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5741 PACKET_QProgramSignals },
5742 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5743 PACKET_QSetWorkingDir },
5744 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5745 PACKET_QStartupWithShell },
5746 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5747 PACKET_QEnvironmentHexEncoded },
5748 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5749 PACKET_QEnvironmentReset },
5750 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5751 PACKET_QEnvironmentUnset },
5752 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5753 PACKET_QStartNoAckMode },
5754 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5755 PACKET_multiprocess_feature },
5756 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5757 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5758 PACKET_qXfer_siginfo_read },
5759 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5760 PACKET_qXfer_siginfo_write },
5761 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5762 PACKET_ConditionalTracepoints },
5763 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5764 PACKET_ConditionalBreakpoints },
5765 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5766 PACKET_BreakpointCommands },
5767 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5768 PACKET_FastTracepoints },
5769 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5770 PACKET_StaticTracepoints },
5771 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5772 PACKET_InstallInTrace},
5773 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5774 PACKET_DisconnectedTracing_feature },
5775 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5776 PACKET_bc },
5777 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5778 PACKET_bs },
5779 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5780 PACKET_TracepointSource },
5781 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5782 PACKET_QAllow },
5783 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5784 PACKET_EnableDisableTracepoints_feature },
5785 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5786 PACKET_qXfer_fdpic },
5787 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5788 PACKET_qXfer_uib },
5789 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5790 PACKET_QDisableRandomization },
5791 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5792 { "QTBuffer:size", PACKET_DISABLE,
5793 remote_supported_packet, PACKET_QTBuffer_size},
5794 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5795 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5796 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5797 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5798 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5799 PACKET_qXfer_btrace },
5800 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5801 PACKET_qXfer_btrace_conf },
5802 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5803 PACKET_Qbtrace_conf_bts_size },
5804 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5805 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5806 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5807 PACKET_fork_event_feature },
5808 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5809 PACKET_vfork_event_feature },
5810 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5811 PACKET_exec_event_feature },
5812 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5813 PACKET_Qbtrace_conf_pt_size },
5814 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5815 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5816 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5817 PACKET_QThreadOptions },
5818 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5819 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5820 PACKET_memory_tagging_feature },
5821 { "error-message", PACKET_ENABLE, remote_supported_packet,
5822 PACKET_accept_error_message },
5825 static char *remote_support_xml;
5827 /* Register string appended to "xmlRegisters=" in qSupported query. */
5829 void
5830 register_remote_support_xml (const char *xml)
5832 #if defined(HAVE_LIBEXPAT)
5833 if (remote_support_xml == NULL)
5834 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5835 else
5837 char *copy = xstrdup (remote_support_xml + 13);
5838 char *saveptr;
5839 char *p = strtok_r (copy, ",", &saveptr);
5843 if (strcmp (p, xml) == 0)
5845 /* already there */
5846 xfree (copy);
5847 return;
5850 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5851 xfree (copy);
5853 remote_support_xml = reconcat (remote_support_xml,
5854 remote_support_xml, ",", xml,
5855 (char *) NULL);
5857 #endif
5860 static void
5861 remote_query_supported_append (std::string *msg, const char *append)
5863 if (!msg->empty ())
5864 msg->append (";");
5865 msg->append (append);
5868 void
5869 remote_target::remote_query_supported ()
5871 struct remote_state *rs = get_remote_state ();
5872 char *next;
5873 int i;
5874 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5876 /* The packet support flags are handled differently for this packet
5877 than for most others. We treat an error, a disabled packet, and
5878 an empty response identically: any features which must be reported
5879 to be used will be automatically disabled. An empty buffer
5880 accomplishes this, since that is also the representation for a list
5881 containing no features. */
5883 rs->buf[0] = 0;
5884 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5886 std::string q;
5888 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5889 != AUTO_BOOLEAN_FALSE)
5890 remote_query_supported_append (&q, "multiprocess+");
5892 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5893 != AUTO_BOOLEAN_FALSE)
5894 remote_query_supported_append (&q, "swbreak+");
5896 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5897 != AUTO_BOOLEAN_FALSE)
5898 remote_query_supported_append (&q, "hwbreak+");
5900 remote_query_supported_append (&q, "qRelocInsn+");
5902 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5903 != AUTO_BOOLEAN_FALSE)
5904 remote_query_supported_append (&q, "fork-events+");
5906 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5907 != AUTO_BOOLEAN_FALSE)
5908 remote_query_supported_append (&q, "vfork-events+");
5910 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5911 != AUTO_BOOLEAN_FALSE)
5912 remote_query_supported_append (&q, "exec-events+");
5914 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5915 != AUTO_BOOLEAN_FALSE)
5916 remote_query_supported_append (&q, "vContSupported+");
5918 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5919 != AUTO_BOOLEAN_FALSE)
5920 remote_query_supported_append (&q, "QThreadEvents+");
5922 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5923 != AUTO_BOOLEAN_FALSE)
5924 remote_query_supported_append (&q, "QThreadOptions+");
5926 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5927 != AUTO_BOOLEAN_FALSE)
5928 remote_query_supported_append (&q, "no-resumed+");
5930 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5931 != AUTO_BOOLEAN_FALSE)
5932 remote_query_supported_append (&q, "memory-tagging+");
5934 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5935 the qSupported:xmlRegisters=i386 handling. */
5936 if (remote_support_xml != NULL
5937 && (m_features.packet_support (PACKET_qXfer_features)
5938 != PACKET_DISABLE))
5939 remote_query_supported_append (&q, remote_support_xml);
5941 if (m_features.packet_set_cmd_state (PACKET_accept_error_message)
5942 != AUTO_BOOLEAN_FALSE)
5943 remote_query_supported_append (&q, "error-message+");
5945 q = "qSupported:" + q;
5946 putpkt (q.c_str ());
5948 getpkt (&rs->buf);
5950 /* If an error occurred, warn, but do not return - just reset the
5951 buffer to empty and go on to disable features. */
5952 packet_result result = m_features.packet_ok (rs->buf, PACKET_qSupported);
5953 if (result.status () == PACKET_ERROR)
5955 warning (_("Remote failure reply: %s"), result.err_msg ());
5956 rs->buf[0] = 0;
5960 memset (seen, 0, sizeof (seen));
5962 next = rs->buf.data ();
5963 while (*next)
5965 enum packet_support is_supported;
5966 char *p, *end, *name_end, *value;
5968 /* First separate out this item from the rest of the packet. If
5969 there's another item after this, we overwrite the separator
5970 (terminated strings are much easier to work with). */
5971 p = next;
5972 end = strchr (p, ';');
5973 if (end == NULL)
5975 end = p + strlen (p);
5976 next = end;
5978 else
5980 *end = '\0';
5981 next = end + 1;
5983 if (end == p)
5985 warning (_("empty item in \"qSupported\" response"));
5986 continue;
5990 name_end = strchr (p, '=');
5991 if (name_end)
5993 /* This is a name=value entry. */
5994 is_supported = PACKET_ENABLE;
5995 value = name_end + 1;
5996 *name_end = '\0';
5998 else
6000 value = NULL;
6001 switch (end[-1])
6003 case '+':
6004 is_supported = PACKET_ENABLE;
6005 break;
6007 case '-':
6008 is_supported = PACKET_DISABLE;
6009 break;
6011 case '?':
6012 is_supported = PACKET_SUPPORT_UNKNOWN;
6013 break;
6015 default:
6016 warning (_("unrecognized item \"%s\" "
6017 "in \"qSupported\" response"), p);
6018 continue;
6020 end[-1] = '\0';
6023 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6024 if (strcmp (remote_protocol_features[i].name, p) == 0)
6026 const struct protocol_feature *feature;
6028 seen[i] = 1;
6029 feature = &remote_protocol_features[i];
6030 feature->func (this, feature, is_supported, value);
6031 break;
6035 /* If we increased the packet size, make sure to increase the global
6036 buffer size also. We delay this until after parsing the entire
6037 qSupported packet, because this is the same buffer we were
6038 parsing. */
6039 if (rs->buf.size () < rs->explicit_packet_size)
6040 rs->buf.resize (rs->explicit_packet_size);
6042 /* Handle the defaults for unmentioned features. */
6043 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6044 if (!seen[i])
6046 const struct protocol_feature *feature;
6048 feature = &remote_protocol_features[i];
6049 feature->func (this, feature, feature->default_support, NULL);
6053 /* Serial QUIT handler for the remote serial descriptor.
6055 Defers handling a Ctrl-C until we're done with the current
6056 command/response packet sequence, unless:
6058 - We're setting up the connection. Don't send a remote interrupt
6059 request, as we're not fully synced yet. Quit immediately
6060 instead.
6062 - The target has been resumed in the foreground
6063 (target_terminal::is_ours is false) with a synchronous resume
6064 packet, and we're blocked waiting for the stop reply, thus a
6065 Ctrl-C should be immediately sent to the target.
6067 - We get a second Ctrl-C while still within the same serial read or
6068 write. In that case the serial is seemingly wedged --- offer to
6069 quit/disconnect.
6071 - We see a second Ctrl-C without target response, after having
6072 previously interrupted the target. In that case the target/stub
6073 is probably wedged --- offer to quit/disconnect.
6076 void
6077 remote_target::remote_serial_quit_handler ()
6079 struct remote_state *rs = get_remote_state ();
6081 if (check_quit_flag ())
6083 /* If we're starting up, we're not fully synced yet. Quit
6084 immediately. */
6085 if (rs->starting_up)
6086 quit ();
6087 else if (rs->got_ctrlc_during_io)
6089 if (query (_("The target is not responding to GDB commands.\n"
6090 "Stop debugging it? ")))
6091 remote_unpush_and_throw (this);
6093 /* If ^C has already been sent once, offer to disconnect. */
6094 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
6095 interrupt_query ();
6096 /* All-stop protocol, and blocked waiting for stop reply. Send
6097 an interrupt request. */
6098 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
6099 target_interrupt ();
6100 else
6101 rs->got_ctrlc_during_io = 1;
6105 /* The remote_target that is current while the quit handler is
6106 overridden with remote_serial_quit_handler. */
6107 static remote_target *curr_quit_handler_target;
6109 static void
6110 remote_serial_quit_handler ()
6112 curr_quit_handler_target->remote_serial_quit_handler ();
6115 /* Remove the remote target from the target stack of each inferior
6116 that is using it. Upper targets depend on it so remove them
6117 first. */
6119 static void
6120 remote_unpush_target (remote_target *target)
6122 /* We have to unpush the target from all inferiors, even those that
6123 aren't running. */
6124 scoped_restore_current_inferior restore_current_inferior;
6126 for (inferior *inf : all_inferiors (target))
6128 switch_to_inferior_no_thread (inf);
6129 inf->pop_all_targets_at_and_above (process_stratum);
6130 generic_mourn_inferior ();
6133 /* Don't rely on target_close doing this when the target is popped
6134 from the last remote inferior above, because something may be
6135 holding a reference to the target higher up on the stack, meaning
6136 target_close won't be called yet. We lost the connection to the
6137 target, so clear these now, otherwise we may later throw
6138 TARGET_CLOSE_ERROR while trying to tell the remote target to
6139 close the file. */
6140 fileio_handles_invalidate_target (target);
6143 [[noreturn]] static void
6144 remote_unpush_and_throw (remote_target *target)
6146 remote_unpush_target (target);
6147 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6150 void
6151 remote_target::open_1 (const char *name, int from_tty, int extended_p)
6153 remote_target *curr_remote = get_current_remote_target ();
6155 if (name == 0)
6156 error (_("To open a remote debug connection, you need to specify what\n"
6157 "serial device is attached to the remote system\n"
6158 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6160 /* If we're connected to a running target, target_preopen will kill it.
6161 Ask this question first, before target_preopen has a chance to kill
6162 anything. */
6163 if (curr_remote != NULL && !target_has_execution ())
6165 if (from_tty
6166 && !query (_("Already connected to a remote target. Disconnect? ")))
6167 error (_("Still connected."));
6170 /* Here the possibly existing remote target gets unpushed. */
6171 target_preopen (from_tty);
6173 remote_fileio_reset ();
6174 reopen_exec_file ();
6175 reread_symbols (from_tty);
6177 remote_target *remote
6178 = (extended_p ? new extended_remote_target () : new remote_target ());
6179 target_ops_up target_holder (remote);
6181 remote_state *rs = remote->get_remote_state ();
6183 /* See FIXME above. */
6184 if (!target_async_permitted)
6185 rs->wait_forever_enabled_p = true;
6187 rs->remote_desc = remote_serial_open (name);
6189 if (baud_rate != -1)
6193 serial_setbaudrate (rs->remote_desc, baud_rate);
6195 catch (const gdb_exception_error &)
6197 /* The requested speed could not be set. Error out to
6198 top level after closing remote_desc. Take care to
6199 set remote_desc to NULL to avoid closing remote_desc
6200 more than once. */
6201 serial_close (rs->remote_desc);
6202 rs->remote_desc = NULL;
6203 throw;
6207 serial_setparity (rs->remote_desc, serial_parity);
6208 serial_raw (rs->remote_desc);
6210 /* If there is something sitting in the buffer we might take it as a
6211 response to a command, which would be bad. */
6212 serial_flush_input (rs->remote_desc);
6214 if (from_tty)
6216 gdb_puts ("Remote debugging using ");
6217 gdb_puts (name);
6218 gdb_puts ("\n");
6221 /* Switch to using the remote target now. */
6222 current_inferior ()->push_target (std::move (target_holder));
6224 /* Register extra event sources in the event loop. */
6225 rs->create_async_event_handler ();
6227 rs->notif_state = remote_notif_state_allocate (remote);
6229 /* Reset the target state; these things will be queried either by
6230 remote_query_supported or as they are needed. */
6231 remote->m_features.reset_all_packet_configs_support ();
6232 rs->explicit_packet_size = 0;
6233 rs->noack_mode = 0;
6234 rs->extended = extended_p;
6235 rs->waiting_for_stop_reply = 0;
6236 rs->ctrlc_pending_p = 0;
6237 rs->got_ctrlc_during_io = 0;
6239 rs->general_thread = not_sent_ptid;
6240 rs->continue_thread = not_sent_ptid;
6241 rs->remote_traceframe_number = -1;
6243 rs->last_resume_exec_dir = EXEC_FORWARD;
6245 /* Probe for ability to use "ThreadInfo" query, as required. */
6246 rs->use_threadinfo_query = 1;
6247 rs->use_threadextra_query = 1;
6249 rs->readahead_cache.invalidate ();
6251 if (target_async_permitted)
6253 /* FIXME: cagney/1999-09-23: During the initial connection it is
6254 assumed that the target is already ready and able to respond to
6255 requests. Unfortunately remote_start_remote() eventually calls
6256 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6257 around this. Eventually a mechanism that allows
6258 wait_for_inferior() to expect/get timeouts will be
6259 implemented. */
6260 rs->wait_forever_enabled_p = false;
6263 /* First delete any symbols previously loaded from shared libraries. */
6264 no_shared_libraries (current_program_space);
6266 /* Start the remote connection. If error() or QUIT, discard this
6267 target (we'd otherwise be in an inconsistent state) and then
6268 propogate the error on up the exception chain. This ensures that
6269 the caller doesn't stumble along blindly assuming that the
6270 function succeeded. The CLI doesn't have this problem but other
6271 UI's, such as MI do.
6273 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6274 this function should return an error indication letting the
6275 caller restore the previous state. Unfortunately the command
6276 ``target remote'' is directly wired to this function making that
6277 impossible. On a positive note, the CLI side of this problem has
6278 been fixed - the function set_cmd_context() makes it possible for
6279 all the ``target ....'' commands to share a common callback
6280 function. See cli-dump.c. */
6285 remote->start_remote (from_tty, extended_p);
6287 catch (const gdb_exception &ex)
6289 /* Pop the partially set up target - unless something else did
6290 already before throwing the exception. */
6291 if (ex.error != TARGET_CLOSE_ERROR)
6292 remote_unpush_target (remote);
6293 throw;
6297 remote_btrace_reset (rs);
6299 if (target_async_permitted)
6300 rs->wait_forever_enabled_p = true;
6303 /* Determine if WS represents a fork status. */
6305 static bool
6306 is_fork_status (target_waitkind kind)
6308 return (kind == TARGET_WAITKIND_FORKED
6309 || kind == TARGET_WAITKIND_VFORKED);
6312 /* Return a reference to the field where a pending child status, if
6313 there's one, is recorded. If there's no child event pending, the
6314 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6316 static const target_waitstatus &
6317 thread_pending_status (struct thread_info *thread)
6319 return (thread->has_pending_waitstatus ()
6320 ? thread->pending_waitstatus ()
6321 : thread->pending_follow);
6324 /* Return THREAD's pending status if it is a pending fork/vfork (but
6325 not clone) parent, else return nullptr. */
6327 static const target_waitstatus *
6328 thread_pending_fork_status (struct thread_info *thread)
6330 const target_waitstatus &ws = thread_pending_status (thread);
6332 if (!is_fork_status (ws.kind ()))
6333 return nullptr;
6335 return &ws;
6338 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6339 event, else return nullptr. */
6341 static const target_waitstatus *
6342 thread_pending_child_status (thread_info *thread)
6344 const target_waitstatus &ws = thread_pending_status (thread);
6346 if (!is_new_child_status (ws.kind ()))
6347 return nullptr;
6349 return &ws;
6352 /* Detach the specified process. */
6354 void
6355 remote_target::remote_detach_pid (int pid)
6357 struct remote_state *rs = get_remote_state ();
6359 /* This should not be necessary, but the handling for D;PID in
6360 GDBserver versions prior to 8.2 incorrectly assumes that the
6361 selected process points to the same process we're detaching,
6362 leading to misbehavior (and possibly GDBserver crashing) when it
6363 does not. Since it's easy and cheap, work around it by forcing
6364 GDBserver to select GDB's current process. */
6365 set_general_process ();
6367 if (m_features.remote_multi_process_p ())
6368 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6369 else
6370 strcpy (rs->buf.data (), "D");
6372 putpkt (rs->buf);
6373 getpkt (&rs->buf);
6375 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6377 else if (rs->buf[0] == '\0')
6378 error (_("Remote doesn't know how to detach"));
6379 else
6381 /* It is possible that we have an unprocessed exit event for this
6382 pid. If this is the case then we can ignore the failure to detach
6383 and just pretend that the detach worked, as far as the user is
6384 concerned, the process exited immediately after the detach. */
6385 bool process_has_already_exited = false;
6386 remote_notif_get_pending_events (&notif_client_stop);
6387 for (stop_reply_up &reply : rs->stop_reply_queue)
6389 if (reply->ptid.pid () != pid)
6390 continue;
6392 enum target_waitkind kind = reply->ws.kind ();
6393 if (kind == TARGET_WAITKIND_EXITED
6394 || kind == TARGET_WAITKIND_SIGNALLED)
6396 process_has_already_exited = true;
6397 remote_debug_printf
6398 ("detach failed, but process already exited");
6399 break;
6403 if (!process_has_already_exited)
6404 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6408 /* This detaches a program to which we previously attached, using
6409 inferior_ptid to identify the process. After this is done, GDB
6410 can be used to debug some other program. We better not have left
6411 any breakpoints in the target program or it'll die when it hits
6412 one. */
6414 void
6415 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6417 int pid = inferior_ptid.pid ();
6418 struct remote_state *rs = get_remote_state ();
6419 int is_fork_parent;
6421 if (!target_has_execution ())
6422 error (_("No process to detach from."));
6424 target_announce_detach (from_tty);
6426 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6428 /* If we're in breakpoints-always-inserted mode, or the inferior
6429 is running, we have to remove breakpoints before detaching.
6430 We don't do this in common code instead because not all
6431 targets support removing breakpoints while the target is
6432 running. The remote target / gdbserver does, though. */
6433 remove_breakpoints_inf (current_inferior ());
6436 /* Tell the remote target to detach. */
6437 remote_detach_pid (pid);
6439 /* Exit only if this is the only active inferior. */
6440 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6441 gdb_puts (_("Ending remote debugging.\n"));
6443 /* See if any thread of the inferior we are detaching has a pending fork
6444 status. In that case, we must detach from the child resulting from
6445 that fork. */
6446 for (thread_info *thread : inf->non_exited_threads ())
6448 const target_waitstatus *ws = thread_pending_fork_status (thread);
6450 if (ws == nullptr)
6451 continue;
6453 remote_detach_pid (ws->child_ptid ().pid ());
6456 /* Check also for any pending fork events in the stop reply queue. */
6457 remote_notif_get_pending_events (&notif_client_stop);
6458 for (stop_reply_up &reply : rs->stop_reply_queue)
6460 if (reply->ptid.pid () != pid)
6461 continue;
6463 if (!is_fork_status (reply->ws.kind ()))
6464 continue;
6466 remote_detach_pid (reply->ws.child_ptid ().pid ());
6469 thread_info *tp = this->find_thread (inferior_ptid);
6471 /* Check to see if we are detaching a fork parent. Note that if we
6472 are detaching a fork child, tp == NULL. */
6473 is_fork_parent = (tp != NULL
6474 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6476 /* If doing detach-on-fork, we don't mourn, because that will delete
6477 breakpoints that should be available for the followed inferior. */
6478 if (!is_fork_parent)
6480 /* Save the pid as a string before mourning, since that will
6481 unpush the remote target, and we need the string after. */
6482 std::string infpid = target_pid_to_str (ptid_t (pid));
6484 target_mourn_inferior (inferior_ptid);
6485 if (print_inferior_events)
6486 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6487 inf->num, infpid.c_str ());
6489 else
6491 switch_to_no_thread ();
6492 detach_inferior (current_inferior ());
6496 void
6497 remote_target::detach (inferior *inf, int from_tty)
6499 remote_detach_1 (inf, from_tty);
6502 void
6503 extended_remote_target::detach (inferior *inf, int from_tty)
6505 remote_detach_1 (inf, from_tty);
6508 /* Target follow-fork function for remote targets. On entry, and
6509 at return, the current inferior is the fork parent.
6511 Note that although this is currently only used for extended-remote,
6512 it is named remote_follow_fork in anticipation of using it for the
6513 remote target as well. */
6515 void
6516 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6517 target_waitkind fork_kind, bool follow_child,
6518 bool detach_fork)
6520 process_stratum_target::follow_fork (child_inf, child_ptid,
6521 fork_kind, follow_child, detach_fork);
6523 if ((fork_kind == TARGET_WAITKIND_FORKED
6524 && m_features.remote_fork_event_p ())
6525 || (fork_kind == TARGET_WAITKIND_VFORKED
6526 && m_features.remote_vfork_event_p ()))
6528 /* When following the parent and detaching the child, we detach
6529 the child here. For the case of following the child and
6530 detaching the parent, the detach is done in the target-
6531 independent follow fork code in infrun.c. We can't use
6532 target_detach when detaching an unfollowed child because
6533 the client side doesn't know anything about the child. */
6534 if (detach_fork && !follow_child)
6536 /* Detach the fork child. */
6537 remote_detach_pid (child_ptid.pid ());
6542 void
6543 remote_target::follow_clone (ptid_t child_ptid)
6545 remote_add_thread (child_ptid, false, false, false);
6548 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6549 in the program space of the new inferior. */
6551 void
6552 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6553 const char *execd_pathname)
6555 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6557 /* We know that this is a target file name, so if it has the "target:"
6558 prefix we strip it off before saving it in the program space. */
6559 if (is_target_filename (execd_pathname))
6560 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6562 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6565 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6567 void
6568 remote_target::disconnect (const char *args, int from_tty)
6570 if (args)
6571 error (_("Argument given to \"disconnect\" when remotely debugging."));
6573 /* Make sure we unpush even the extended remote targets. Calling
6574 target_mourn_inferior won't unpush, and
6575 remote_target::mourn_inferior won't unpush if there is more than
6576 one inferior left. */
6577 remote_unpush_target (this);
6579 if (from_tty)
6580 gdb_puts ("Ending remote debugging.\n");
6583 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6584 be chatty about it. */
6586 void
6587 extended_remote_target::attach (const char *args, int from_tty)
6589 struct remote_state *rs = get_remote_state ();
6590 int pid;
6591 char *wait_status = NULL;
6593 pid = parse_pid_to_attach (args);
6595 /* Remote PID can be freely equal to getpid, do not check it here the same
6596 way as in other targets. */
6598 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6599 error (_("This target does not support attaching to a process"));
6601 target_announce_attach (from_tty, pid);
6603 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6604 putpkt (rs->buf);
6605 getpkt (&rs->buf);
6607 packet_result result = m_features.packet_ok (rs->buf, PACKET_vAttach);
6608 switch (result.status ())
6610 case PACKET_OK:
6611 if (!target_is_non_stop_p ())
6613 /* Save the reply for later. */
6614 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6615 strcpy (wait_status, rs->buf.data ());
6617 else if (strcmp (rs->buf.data (), "OK") != 0)
6618 error (_("Attaching to %s failed with: %s"),
6619 target_pid_to_str (ptid_t (pid)).c_str (),
6620 rs->buf.data ());
6621 break;
6622 case PACKET_UNKNOWN:
6623 error (_("This target does not support attaching to a process"));
6624 case PACKET_ERROR:
6625 error (_("Attaching to %s failed: %s"),
6626 target_pid_to_str (ptid_t (pid)).c_str (), result.err_msg ());
6629 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6631 inferior_ptid = ptid_t (pid);
6633 if (target_is_non_stop_p ())
6635 /* Get list of threads. */
6636 update_thread_list ();
6638 thread_info *thread = first_thread_of_inferior (current_inferior ());
6639 if (thread != nullptr)
6640 switch_to_thread (thread);
6642 /* Invalidate our notion of the remote current thread. */
6643 record_currthread (rs, minus_one_ptid);
6645 else
6647 /* Now, if we have thread information, update the main thread's
6648 ptid. */
6649 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6651 /* Add the main thread to the thread list. We add the thread
6652 silently in this case (the final true parameter). */
6653 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6655 switch_to_thread (thr);
6658 /* Next, if the target can specify a description, read it. We do
6659 this before anything involving memory or registers. */
6660 target_find_description ();
6662 if (!target_is_non_stop_p ())
6664 /* Use the previously fetched status. */
6665 gdb_assert (wait_status != NULL);
6667 notif_event_up reply
6668 = remote_notif_parse (this, &notif_client_stop, wait_status);
6669 push_stop_reply (as_stop_reply_up (std::move (reply)));
6671 else
6673 gdb_assert (wait_status == NULL);
6675 gdb_assert (target_can_async_p ());
6679 /* Implementation of the to_post_attach method. */
6681 void
6682 extended_remote_target::post_attach (int pid)
6684 /* Get text, data & bss offsets. */
6685 get_offsets ();
6687 /* In certain cases GDB might not have had the chance to start
6688 symbol lookup up until now. This could happen if the debugged
6689 binary is not using shared libraries, the vsyscall page is not
6690 present (on Linux) and the binary itself hadn't changed since the
6691 debugging process was started. */
6692 if (current_program_space->symfile_object_file != NULL)
6693 remote_check_symbols();
6697 /* Check for the availability of vCont. This function should also check
6698 the response. */
6700 void
6701 remote_target::remote_vcont_probe ()
6703 remote_state *rs = get_remote_state ();
6704 char *buf;
6706 strcpy (rs->buf.data (), "vCont?");
6707 putpkt (rs->buf);
6708 getpkt (&rs->buf);
6709 buf = rs->buf.data ();
6711 /* Make sure that the features we assume are supported. */
6712 if (startswith (buf, "vCont"))
6714 char *p = &buf[5];
6715 int support_c, support_C;
6717 rs->supports_vCont.s = 0;
6718 rs->supports_vCont.S = 0;
6719 support_c = 0;
6720 support_C = 0;
6721 rs->supports_vCont.t = 0;
6722 rs->supports_vCont.r = 0;
6723 while (p && *p == ';')
6725 p++;
6726 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6727 rs->supports_vCont.s = 1;
6728 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6729 rs->supports_vCont.S = 1;
6730 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6731 support_c = 1;
6732 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6733 support_C = 1;
6734 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6735 rs->supports_vCont.t = 1;
6736 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6737 rs->supports_vCont.r = 1;
6739 p = strchr (p, ';');
6742 /* If c, and C are not all supported, we can't use vCont. Clearing
6743 BUF will make packet_ok disable the packet. */
6744 if (!support_c || !support_C)
6745 buf[0] = 0;
6748 m_features.packet_ok (rs->buf, PACKET_vCont);
6751 /* Helper function for building "vCont" resumptions. Write a
6752 resumption to P. ENDP points to one-passed-the-end of the buffer
6753 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6754 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6755 resumed thread should be single-stepped and/or signalled. If PTID
6756 equals minus_one_ptid, then all threads are resumed; if PTID
6757 represents a process, then all threads of the process are
6758 resumed. */
6760 char *
6761 remote_target::append_resumption (char *p, char *endp,
6762 ptid_t ptid, int step, gdb_signal siggnal)
6764 struct remote_state *rs = get_remote_state ();
6766 if (step && siggnal != GDB_SIGNAL_0)
6767 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6768 else if (step
6769 /* GDB is willing to range step. */
6770 && use_range_stepping
6771 /* Target supports range stepping. */
6772 && rs->supports_vCont.r
6773 /* We don't currently support range stepping multiple
6774 threads with a wildcard (though the protocol allows it,
6775 so stubs shouldn't make an active effort to forbid
6776 it). */
6777 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6779 struct thread_info *tp;
6781 if (ptid == minus_one_ptid)
6783 /* If we don't know about the target thread's tid, then
6784 we're resuming magic_null_ptid (see caller). */
6785 tp = this->find_thread (magic_null_ptid);
6787 else
6788 tp = this->find_thread (ptid);
6789 gdb_assert (tp != NULL);
6791 if (tp->control.may_range_step)
6793 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6795 p += xsnprintf (p, endp - p, ";r%s,%s",
6796 phex_nz (tp->control.step_range_start,
6797 addr_size),
6798 phex_nz (tp->control.step_range_end,
6799 addr_size));
6801 else
6802 p += xsnprintf (p, endp - p, ";s");
6804 else if (step)
6805 p += xsnprintf (p, endp - p, ";s");
6806 else if (siggnal != GDB_SIGNAL_0)
6807 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6808 else
6809 p += xsnprintf (p, endp - p, ";c");
6811 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6813 ptid_t nptid;
6815 /* All (-1) threads of process. */
6816 nptid = ptid_t (ptid.pid (), -1);
6818 p += xsnprintf (p, endp - p, ":");
6819 p = write_ptid (p, endp, nptid);
6821 else if (ptid != minus_one_ptid)
6823 p += xsnprintf (p, endp - p, ":");
6824 p = write_ptid (p, endp, ptid);
6827 return p;
6830 /* Clear the thread's private info on resume. */
6832 static void
6833 resume_clear_thread_private_info (struct thread_info *thread)
6835 if (thread->priv != NULL)
6837 remote_thread_info *priv = get_remote_thread_info (thread);
6839 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6840 priv->watch_data_address = 0;
6844 /* Append a vCont continue-with-signal action for threads that have a
6845 non-zero stop signal. */
6847 char *
6848 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6849 ptid_t ptid)
6851 for (thread_info *thread : all_non_exited_threads (this, ptid))
6852 if (inferior_ptid != thread->ptid
6853 && thread->stop_signal () != GDB_SIGNAL_0)
6855 p = append_resumption (p, endp, thread->ptid,
6856 0, thread->stop_signal ());
6857 thread->set_stop_signal (GDB_SIGNAL_0);
6858 resume_clear_thread_private_info (thread);
6861 return p;
6864 /* Set the target running, using the packets that use Hc
6865 (c/s/C/S). */
6867 void
6868 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6869 gdb_signal siggnal)
6871 struct remote_state *rs = get_remote_state ();
6872 char *buf;
6874 rs->last_sent_signal = siggnal;
6875 rs->last_sent_step = step;
6877 /* The c/s/C/S resume packets use Hc, so set the continue
6878 thread. */
6879 if (ptid == minus_one_ptid)
6880 set_continue_thread (any_thread_ptid);
6881 else
6882 set_continue_thread (ptid);
6884 for (thread_info *thread : all_non_exited_threads (this))
6885 resume_clear_thread_private_info (thread);
6887 buf = rs->buf.data ();
6888 if (::execution_direction == EXEC_REVERSE)
6890 /* We don't pass signals to the target in reverse exec mode. */
6891 if (info_verbose && siggnal != GDB_SIGNAL_0)
6892 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6893 siggnal);
6895 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6896 error (_("Remote reverse-step not supported."));
6897 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6898 error (_("Remote reverse-continue not supported."));
6900 strcpy (buf, step ? "bs" : "bc");
6902 else if (siggnal != GDB_SIGNAL_0)
6904 buf[0] = step ? 'S' : 'C';
6905 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6906 buf[2] = tohex (((int) siggnal) & 0xf);
6907 buf[3] = '\0';
6909 else
6910 strcpy (buf, step ? "s" : "c");
6912 putpkt (buf);
6915 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6916 STEP, and SIGGNAL have the same meaning as in target_resume. This
6917 function returns non-zero iff it resumes the inferior.
6919 This function issues a strict subset of all possible vCont commands
6920 at the moment. */
6923 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6924 enum gdb_signal siggnal)
6926 struct remote_state *rs = get_remote_state ();
6927 char *p;
6928 char *endp;
6930 /* No reverse execution actions defined for vCont. */
6931 if (::execution_direction == EXEC_REVERSE)
6932 return 0;
6934 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6935 return 0;
6937 p = rs->buf.data ();
6938 endp = p + get_remote_packet_size ();
6940 /* If we could generate a wider range of packets, we'd have to worry
6941 about overflowing BUF. Should there be a generic
6942 "multi-part-packet" packet? */
6944 p += xsnprintf (p, endp - p, "vCont");
6946 if (scope_ptid == magic_null_ptid)
6948 /* MAGIC_NULL_PTID means that we don't have any active threads,
6949 so we don't have any TID numbers the inferior will
6950 understand. Make sure to only send forms that do not specify
6951 a TID. */
6952 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6954 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6956 /* Resume all threads (of all processes, or of a single
6957 process), with preference for INFERIOR_PTID. This assumes
6958 inferior_ptid belongs to the set of all threads we are about
6959 to resume. */
6960 if (step || siggnal != GDB_SIGNAL_0)
6962 /* Step inferior_ptid, with or without signal. */
6963 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6966 /* Also pass down any pending signaled resumption for other
6967 threads not the current. */
6968 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6970 /* And continue others without a signal. */
6971 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6973 else
6975 /* Scheduler locking; resume only SCOPE_PTID. */
6976 append_resumption (p, endp, scope_ptid, step, siggnal);
6979 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6980 putpkt (rs->buf);
6982 if (target_is_non_stop_p ())
6984 /* In non-stop, the stub replies to vCont with "OK". The stop
6985 reply will be reported asynchronously by means of a `%Stop'
6986 notification. */
6987 getpkt (&rs->buf);
6988 if (strcmp (rs->buf.data (), "OK") != 0)
6989 error (_("Unexpected vCont reply in non-stop mode: %s"),
6990 rs->buf.data ());
6993 return 1;
6996 /* Tell the remote machine to resume. */
6998 void
6999 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
7001 struct remote_state *rs = get_remote_state ();
7003 /* When connected in non-stop mode, the core resumes threads
7004 individually. Resuming remote threads directly in target_resume
7005 would thus result in sending one packet per thread. Instead, to
7006 minimize roundtrip latency, here we just store the resume
7007 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
7008 resumption will be done in remote_target::commit_resume, where we'll be
7009 able to do vCont action coalescing. */
7010 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
7012 remote_thread_info *remote_thr
7013 = get_remote_thread_info (inferior_thread ());
7015 /* We don't expect the core to ask to resume an already resumed (from
7016 its point of view) thread. */
7017 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
7019 remote_thr->set_resumed_pending_vcont (step, siggnal);
7021 /* There's actually nothing that says that the core can't
7022 request a wildcard resume in non-stop mode, though. It's
7023 just that we know it doesn't currently, so we don't bother
7024 with it. */
7025 gdb_assert (scope_ptid == inferior_ptid);
7026 return;
7029 commit_requested_thread_options ();
7031 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
7032 (explained in remote-notif.c:handle_notification) so
7033 remote_notif_process is not called. We need find a place where
7034 it is safe to start a 'vNotif' sequence. It is good to do it
7035 before resuming inferior, because inferior was stopped and no RSP
7036 traffic at that moment. */
7037 if (!target_is_non_stop_p ())
7038 remote_notif_process (rs->notif_state, &notif_client_stop);
7040 rs->last_resume_exec_dir = ::execution_direction;
7042 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
7043 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
7044 remote_resume_with_hc (scope_ptid, step, siggnal);
7046 /* Update resumed state tracked by the remote target. */
7047 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
7048 get_remote_thread_info (tp)->set_resumed ();
7050 /* We've just told the target to resume. The remote server will
7051 wait for the inferior to stop, and then send a stop reply. In
7052 the mean time, we can't start another command/query ourselves
7053 because the stub wouldn't be ready to process it. This applies
7054 only to the base all-stop protocol, however. In non-stop (which
7055 only supports vCont), the stub replies with an "OK", and is
7056 immediate able to process further serial input. */
7057 if (!target_is_non_stop_p ())
7058 rs->waiting_for_stop_reply = 1;
7061 /* Private per-inferior info for target remote processes. */
7063 struct remote_inferior : public private_inferior
7065 /* Whether we can send a wildcard vCont for this process. */
7066 bool may_wildcard_vcont = true;
7069 /* Get the remote private inferior data associated to INF. */
7071 static remote_inferior *
7072 get_remote_inferior (inferior *inf)
7074 if (inf->priv == NULL)
7075 inf->priv.reset (new remote_inferior);
7077 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
7080 /* Class used to track the construction of a vCont packet in the
7081 outgoing packet buffer. This is used to send multiple vCont
7082 packets if we have more actions than would fit a single packet. */
7084 class vcont_builder
7086 public:
7087 explicit vcont_builder (remote_target *remote)
7088 : m_remote (remote)
7090 restart ();
7093 void flush ();
7094 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
7096 private:
7097 void restart ();
7099 /* The remote target. */
7100 remote_target *m_remote;
7102 /* Pointer to the first action. P points here if no action has been
7103 appended yet. */
7104 char *m_first_action;
7106 /* Where the next action will be appended. */
7107 char *m_p;
7109 /* The end of the buffer. Must never write past this. */
7110 char *m_endp;
7113 /* Prepare the outgoing buffer for a new vCont packet. */
7115 void
7116 vcont_builder::restart ()
7118 struct remote_state *rs = m_remote->get_remote_state ();
7120 m_p = rs->buf.data ();
7121 m_endp = m_p + m_remote->get_remote_packet_size ();
7122 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7123 m_first_action = m_p;
7126 /* If the vCont packet being built has any action, send it to the
7127 remote end. */
7129 void
7130 vcont_builder::flush ()
7132 struct remote_state *rs;
7134 if (m_p == m_first_action)
7135 return;
7137 rs = m_remote->get_remote_state ();
7138 m_remote->putpkt (rs->buf);
7139 m_remote->getpkt (&rs->buf);
7140 if (strcmp (rs->buf.data (), "OK") != 0)
7141 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7144 /* The largest action is range-stepping, with its two addresses. This
7145 is more than sufficient. If a new, bigger action is created, it'll
7146 quickly trigger a failed assertion in append_resumption (and we'll
7147 just bump this). */
7148 #define MAX_ACTION_SIZE 200
7150 /* Append a new vCont action in the outgoing packet being built. If
7151 the action doesn't fit the packet along with previous actions, push
7152 what we've got so far to the remote end and start over a new vCont
7153 packet (with the new action). */
7155 void
7156 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7158 char buf[MAX_ACTION_SIZE + 1];
7160 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7161 ptid, step, siggnal);
7163 /* Check whether this new action would fit in the vCont packet along
7164 with previous actions. If not, send what we've got so far and
7165 start a new vCont packet. */
7166 size_t rsize = endp - buf;
7167 if (rsize > m_endp - m_p)
7169 flush ();
7170 restart ();
7172 /* Should now fit. */
7173 gdb_assert (rsize <= m_endp - m_p);
7176 memcpy (m_p, buf, rsize);
7177 m_p += rsize;
7178 *m_p = '\0';
7181 /* to_commit_resume implementation. */
7183 void
7184 remote_target::commit_resumed ()
7186 /* If connected in all-stop mode, we'd send the remote resume
7187 request directly from remote_resume. Likewise if
7188 reverse-debugging, as there are no defined vCont actions for
7189 reverse execution. */
7190 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7191 return;
7193 commit_requested_thread_options ();
7195 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7196 instead of resuming all threads of each process individually.
7197 However, if any thread of a process must remain halted, we can't
7198 send wildcard resumes and must send one action per thread.
7200 Care must be taken to not resume threads/processes the server
7201 side already told us are stopped, but the core doesn't know about
7202 yet, because the events are still in the vStopped notification
7203 queue. For example:
7205 #1 => vCont s:p1.1;c
7206 #2 <= OK
7207 #3 <= %Stopped T05 p1.1
7208 #4 => vStopped
7209 #5 <= T05 p1.2
7210 #6 => vStopped
7211 #7 <= OK
7212 #8 (infrun handles the stop for p1.1 and continues stepping)
7213 #9 => vCont s:p1.1;c
7215 The last vCont above would resume thread p1.2 by mistake, because
7216 the server has no idea that the event for p1.2 had not been
7217 handled yet.
7219 The server side must similarly ignore resume actions for the
7220 thread that has a pending %Stopped notification (and any other
7221 threads with events pending), until GDB acks the notification
7222 with vStopped. Otherwise, e.g., the following case is
7223 mishandled:
7225 #1 => g (or any other packet)
7226 #2 <= [registers]
7227 #3 <= %Stopped T05 p1.2
7228 #4 => vCont s:p1.1;c
7229 #5 <= OK
7231 Above, the server must not resume thread p1.2. GDB can't know
7232 that p1.2 stopped until it acks the %Stopped notification, and
7233 since from GDB's perspective all threads should be running, it
7234 sends a "c" action.
7236 Finally, special care must also be given to handling fork/vfork
7237 events. A (v)fork event actually tells us that two processes
7238 stopped -- the parent and the child. Until we follow the fork,
7239 we must not resume the child. Therefore, if we have a pending
7240 fork follow, we must not send a global wildcard resume action
7241 (vCont;c). We can still send process-wide wildcards though. */
7243 /* Start by assuming a global wildcard (vCont;c) is possible. */
7244 bool may_global_wildcard_vcont = true;
7246 /* And assume every process is individually wildcard-able too. */
7247 for (inferior *inf : all_non_exited_inferiors (this))
7249 remote_inferior *priv = get_remote_inferior (inf);
7251 priv->may_wildcard_vcont = true;
7254 /* Check for any pending events (not reported or processed yet) and
7255 disable process and global wildcard resumes appropriately. */
7256 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7258 bool any_pending_vcont_resume = false;
7260 for (thread_info *tp : all_non_exited_threads (this))
7262 remote_thread_info *priv = get_remote_thread_info (tp);
7264 /* If a thread of a process is not meant to be resumed, then we
7265 can't wildcard that process. */
7266 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7268 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7270 /* And if we can't wildcard a process, we can't wildcard
7271 everything either. */
7272 may_global_wildcard_vcont = false;
7273 continue;
7276 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7277 any_pending_vcont_resume = true;
7279 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7280 then we can't do a global wildcard, as that would resume the
7281 pending child. */
7282 if (thread_pending_child_status (tp) != nullptr)
7283 may_global_wildcard_vcont = false;
7286 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7287 do. */
7288 if (!any_pending_vcont_resume)
7289 return;
7291 /* Now let's build the vCont packet(s). Actions must be appended
7292 from narrower to wider scopes (thread -> process -> global). If
7293 we end up with too many actions for a single packet vcont_builder
7294 flushes the current vCont packet to the remote side and starts a
7295 new one. */
7296 struct vcont_builder vcont_builder (this);
7298 /* Threads first. */
7299 for (thread_info *tp : all_non_exited_threads (this))
7301 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7303 /* If the thread was previously vCont-resumed, no need to send a specific
7304 action for it. If we didn't receive a resume request for it, don't
7305 send an action for it either. */
7306 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7307 continue;
7309 gdb_assert (!thread_is_in_step_over_chain (tp));
7311 /* We should never be commit-resuming a thread that has a stop reply.
7312 Otherwise, we would end up reporting a stop event for a thread while
7313 it is running on the remote target. */
7314 remote_state *rs = get_remote_state ();
7315 for (const auto &stop_reply : rs->stop_reply_queue)
7316 gdb_assert (stop_reply->ptid != tp->ptid);
7318 const resumed_pending_vcont_info &info
7319 = remote_thr->resumed_pending_vcont_info ();
7321 /* Check if we need to send a specific action for this thread. If not,
7322 it will be included in a wildcard resume instead. */
7323 if (info.step || info.sig != GDB_SIGNAL_0
7324 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7325 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7327 remote_thr->set_resumed ();
7330 /* Now check whether we can send any process-wide wildcard. This is
7331 to avoid sending a global wildcard in the case nothing is
7332 supposed to be resumed. */
7333 bool any_process_wildcard = false;
7335 for (inferior *inf : all_non_exited_inferiors (this))
7337 if (get_remote_inferior (inf)->may_wildcard_vcont)
7339 any_process_wildcard = true;
7340 break;
7344 if (any_process_wildcard)
7346 /* If all processes are wildcard-able, then send a single "c"
7347 action, otherwise, send an "all (-1) threads of process"
7348 continue action for each running process, if any. */
7349 if (may_global_wildcard_vcont)
7351 vcont_builder.push_action (minus_one_ptid,
7352 false, GDB_SIGNAL_0);
7354 else
7356 for (inferior *inf : all_non_exited_inferiors (this))
7358 if (get_remote_inferior (inf)->may_wildcard_vcont)
7360 vcont_builder.push_action (ptid_t (inf->pid),
7361 false, GDB_SIGNAL_0);
7367 vcont_builder.flush ();
7370 /* Implementation of target_has_pending_events. */
7372 bool
7373 remote_target::has_pending_events ()
7375 if (target_can_async_p ())
7377 remote_state *rs = get_remote_state ();
7379 if (rs->async_event_handler_marked ())
7380 return true;
7382 /* Note that BUFCNT can be negative, indicating sticky
7383 error. */
7384 if (rs->remote_desc->bufcnt != 0)
7385 return true;
7387 return false;
7392 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7393 thread, all threads of a remote process, or all threads of all
7394 processes. */
7396 void
7397 remote_target::remote_stop_ns (ptid_t ptid)
7399 struct remote_state *rs = get_remote_state ();
7400 char *p = rs->buf.data ();
7401 char *endp = p + get_remote_packet_size ();
7403 /* If any thread that needs to stop was resumed but pending a vCont
7404 resume, generate a phony stop_reply. However, first check
7405 whether the thread wasn't resumed with a signal. Generating a
7406 phony stop in that case would result in losing the signal. */
7407 bool needs_commit = false;
7408 for (thread_info *tp : all_non_exited_threads (this, ptid))
7410 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7412 if (remote_thr->get_resume_state ()
7413 == resume_state::RESUMED_PENDING_VCONT)
7415 const resumed_pending_vcont_info &info
7416 = remote_thr->resumed_pending_vcont_info ();
7417 if (info.sig != GDB_SIGNAL_0)
7419 /* This signal must be forwarded to the inferior. We
7420 could commit-resume just this thread, but its simpler
7421 to just commit-resume everything. */
7422 needs_commit = true;
7423 break;
7428 if (needs_commit)
7429 commit_resumed ();
7430 else
7431 for (thread_info *tp : all_non_exited_threads (this, ptid))
7433 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7435 if (remote_thr->get_resume_state ()
7436 == resume_state::RESUMED_PENDING_VCONT)
7438 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7439 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7440 tp->ptid.lwp (),
7441 pulongest (tp->ptid.tid ()));
7443 /* Check that the thread wasn't resumed with a signal.
7444 Generating a phony stop would result in losing the
7445 signal. */
7446 const resumed_pending_vcont_info &info
7447 = remote_thr->resumed_pending_vcont_info ();
7448 gdb_assert (info.sig == GDB_SIGNAL_0);
7450 stop_reply_up sr = std::make_unique<stop_reply> ();
7451 sr->ptid = tp->ptid;
7452 sr->rs = rs;
7453 sr->ws.set_stopped (GDB_SIGNAL_0);
7454 sr->arch = tp->inf->arch ();
7455 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7456 sr->watch_data_address = 0;
7457 sr->core = 0;
7458 this->push_stop_reply (std::move (sr));
7460 /* Pretend that this thread was actually resumed on the
7461 remote target, then stopped. If we leave it in the
7462 RESUMED_PENDING_VCONT state and the commit_resumed
7463 method is called while the stop reply is still in the
7464 queue, we'll end up reporting a stop event to the core
7465 for that thread while it is running on the remote
7466 target... that would be bad. */
7467 remote_thr->set_resumed ();
7471 if (!rs->supports_vCont.t)
7472 error (_("Remote server does not support stopping threads"));
7474 if (ptid == minus_one_ptid
7475 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7476 p += xsnprintf (p, endp - p, "vCont;t");
7477 else
7479 ptid_t nptid;
7481 p += xsnprintf (p, endp - p, "vCont;t:");
7483 if (ptid.is_pid ())
7484 /* All (-1) threads of process. */
7485 nptid = ptid_t (ptid.pid (), -1);
7486 else
7488 /* Small optimization: if we already have a stop reply for
7489 this thread, no use in telling the stub we want this
7490 stopped. */
7491 if (peek_stop_reply (ptid))
7492 return;
7494 nptid = ptid;
7497 write_ptid (p, endp, nptid);
7500 /* In non-stop, we get an immediate OK reply. The stop reply will
7501 come in asynchronously by notification. */
7502 putpkt (rs->buf);
7503 getpkt (&rs->buf);
7504 if (strcmp (rs->buf.data (), "OK") != 0)
7505 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7506 rs->buf.data ());
7509 /* All-stop version of target_interrupt. Sends a break or a ^C to
7510 interrupt the remote target. It is undefined which thread of which
7511 process reports the interrupt. */
7513 void
7514 remote_target::remote_interrupt_as ()
7516 struct remote_state *rs = get_remote_state ();
7518 rs->ctrlc_pending_p = 1;
7520 /* If the inferior is stopped already, but the core didn't know
7521 about it yet, just ignore the request. The pending stop events
7522 will be collected in remote_wait. */
7523 if (stop_reply_queue_length () > 0)
7524 return;
7526 /* Send interrupt_sequence to remote target. */
7527 send_interrupt_sequence ();
7530 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7531 the remote target. It is undefined which thread of which process
7532 reports the interrupt. Throws an error if the packet is not
7533 supported by the server. */
7535 void
7536 remote_target::remote_interrupt_ns ()
7538 struct remote_state *rs = get_remote_state ();
7539 char *p = rs->buf.data ();
7540 char *endp = p + get_remote_packet_size ();
7542 xsnprintf (p, endp - p, "vCtrlC");
7544 /* In non-stop, we get an immediate OK reply. The stop reply will
7545 come in asynchronously by notification. */
7546 putpkt (rs->buf);
7547 getpkt (&rs->buf);
7549 packet_result result = m_features.packet_ok (rs->buf, PACKET_vCtrlC);
7550 switch (result.status ())
7552 case PACKET_OK:
7553 break;
7554 case PACKET_UNKNOWN:
7555 error (_("No support for interrupting the remote target."));
7556 case PACKET_ERROR:
7557 error (_("Interrupting target failed: %s"), result.err_msg ());
7561 /* Implement the to_stop function for the remote targets. */
7563 void
7564 remote_target::stop (ptid_t ptid)
7566 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7568 if (target_is_non_stop_p ())
7569 remote_stop_ns (ptid);
7570 else
7572 /* We don't currently have a way to transparently pause the
7573 remote target in all-stop mode. Interrupt it instead. */
7574 remote_interrupt_as ();
7578 /* Implement the to_interrupt function for the remote targets. */
7580 void
7581 remote_target::interrupt ()
7583 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7585 if (target_is_non_stop_p ())
7586 remote_interrupt_ns ();
7587 else
7588 remote_interrupt_as ();
7591 /* Implement the to_pass_ctrlc function for the remote targets. */
7593 void
7594 remote_target::pass_ctrlc ()
7596 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7598 struct remote_state *rs = get_remote_state ();
7600 /* If we're starting up, we're not fully synced yet. Quit
7601 immediately. */
7602 if (rs->starting_up)
7603 quit ();
7604 /* If ^C has already been sent once, offer to disconnect. */
7605 else if (rs->ctrlc_pending_p)
7606 interrupt_query ();
7607 else
7608 target_interrupt ();
7611 /* Ask the user what to do when an interrupt is received. */
7613 void
7614 remote_target::interrupt_query ()
7616 struct remote_state *rs = get_remote_state ();
7618 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7620 if (query (_("The target is not responding to interrupt requests.\n"
7621 "Stop debugging it? ")))
7623 remote_unpush_target (this);
7624 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7627 else
7629 if (query (_("Interrupted while waiting for the program.\n"
7630 "Give up waiting? ")))
7631 quit ();
7635 /* Enable/disable target terminal ownership. Most targets can use
7636 terminal groups to control terminal ownership. Remote targets are
7637 different in that explicit transfer of ownership to/from GDB/target
7638 is required. */
7640 void
7641 remote_target::terminal_inferior ()
7643 /* NOTE: At this point we could also register our selves as the
7644 recipient of all input. Any characters typed could then be
7645 passed on down to the target. */
7648 void
7649 remote_target::terminal_ours ()
7653 static void
7654 remote_console_output (const char *msg, ui_file *stream)
7656 const char *p;
7658 for (p = msg; p[0] && p[1]; p += 2)
7660 char tb[2];
7661 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7663 tb[0] = c;
7664 tb[1] = 0;
7665 stream->puts (tb);
7667 stream->flush ();
7670 /* Return the length of the stop reply queue. */
7673 remote_target::stop_reply_queue_length ()
7675 remote_state *rs = get_remote_state ();
7676 return rs->stop_reply_queue.size ();
7679 static void
7680 remote_notif_stop_parse (remote_target *remote,
7681 const notif_client *self, const char *buf,
7682 struct notif_event *event)
7684 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7687 static void
7688 remote_notif_stop_ack (remote_target *remote,
7689 const notif_client *self, const char *buf,
7690 notif_event_up event)
7692 stop_reply_up stop_reply = as_stop_reply_up (std::move (event));
7694 /* acknowledge */
7695 putpkt (remote, self->ack_command);
7697 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7698 the notification. It was left in the queue because we need to
7699 acknowledge it and pull the rest of the notifications out. */
7700 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7701 remote->push_stop_reply (std::move (stop_reply));
7704 static int
7705 remote_notif_stop_can_get_pending_events (remote_target *remote,
7706 const notif_client *self)
7708 /* We can't get pending events in remote_notif_process for
7709 notification stop, and we have to do this in remote_wait_ns
7710 instead. If we fetch all queued events from stub, remote stub
7711 may exit and we have no chance to process them back in
7712 remote_wait_ns. */
7713 remote_state *rs = remote->get_remote_state ();
7714 rs->mark_async_event_handler ();
7715 return 0;
7718 static notif_event_up
7719 remote_notif_stop_alloc_reply ()
7721 return notif_event_up (new struct stop_reply ());
7724 /* A client of notification Stop. */
7726 const notif_client notif_client_stop =
7728 "Stop",
7729 "vStopped",
7730 remote_notif_stop_parse,
7731 remote_notif_stop_ack,
7732 remote_notif_stop_can_get_pending_events,
7733 remote_notif_stop_alloc_reply,
7734 REMOTE_NOTIF_STOP,
7737 /* If CONTEXT contains any fork/vfork/clone child threads that have
7738 not been reported yet, remove them from the CONTEXT list. If such
7739 a thread exists it is because we are stopped at a fork/vfork/clone
7740 catchpoint and have not yet called follow_fork/follow_clone, which
7741 will set up the host-side data structures for the new child. */
7743 void
7744 remote_target::remove_new_children (threads_listing_context *context)
7746 const notif_client *notif = &notif_client_stop;
7748 /* For any threads stopped at a (v)fork/clone event, remove the
7749 corresponding child threads from the CONTEXT list. */
7750 for (thread_info *thread : all_non_exited_threads (this))
7752 const target_waitstatus *ws = thread_pending_child_status (thread);
7754 if (ws == nullptr)
7755 continue;
7757 context->remove_thread (ws->child_ptid ());
7760 /* Check for any pending (v)fork/clone events (not reported or
7761 processed yet) in process PID and remove those child threads from
7762 the CONTEXT list as well. */
7763 remote_notif_get_pending_events (notif);
7764 for (auto &event : get_remote_state ()->stop_reply_queue)
7765 if (is_new_child_status (event->ws.kind ()))
7766 context->remove_thread (event->ws.child_ptid ());
7767 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7768 context->remove_thread (event->ptid);
7771 /* Check whether any event pending in the vStopped queue would prevent a
7772 global or process wildcard vCont action. Set *may_global_wildcard to
7773 false if we can't do a global wildcard (vCont;c), and clear the event
7774 inferior's may_wildcard_vcont flag if we can't do a process-wide
7775 wildcard resume (vCont;c:pPID.-1). */
7777 void
7778 remote_target::check_pending_events_prevent_wildcard_vcont
7779 (bool *may_global_wildcard)
7781 const notif_client *notif = &notif_client_stop;
7783 remote_notif_get_pending_events (notif);
7784 for (auto &event : get_remote_state ()->stop_reply_queue)
7786 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7787 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7788 continue;
7790 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7791 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7792 *may_global_wildcard = false;
7794 /* This may be the first time we heard about this process.
7795 Regardless, we must not do a global wildcard resume, otherwise
7796 we'd resume this process too. */
7797 *may_global_wildcard = false;
7798 if (event->ptid != null_ptid)
7800 inferior *inf = find_inferior_ptid (this, event->ptid);
7801 if (inf != NULL)
7802 get_remote_inferior (inf)->may_wildcard_vcont = false;
7807 /* Discard all pending stop replies of inferior INF. */
7809 void
7810 remote_target::discard_pending_stop_replies (struct inferior *inf)
7812 struct remote_state *rs = get_remote_state ();
7813 struct remote_notif_state *rns = rs->notif_state;
7815 /* This function can be notified when an inferior exists. When the
7816 target is not remote, the notification state is NULL. */
7817 if (rs->remote_desc == NULL)
7818 return;
7820 struct notif_event *notif_event
7821 = rns->pending_event[notif_client_stop.id].get ();
7822 auto *reply = static_cast<stop_reply *> (notif_event);
7824 /* Discard the in-flight notification. */
7825 if (reply != NULL && reply->ptid.pid () == inf->pid)
7827 /* Leave the notification pending, since the server expects that
7828 we acknowledge it with vStopped. But clear its contents, so
7829 that later on when we acknowledge it, we also discard it. */
7830 remote_debug_printf
7831 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7832 reply->ptid.to_string().c_str(),
7833 reply->ws.to_string ().c_str ());
7834 reply->ws.set_ignore ();
7837 /* Discard the stop replies we have already pulled with
7838 vStopped. */
7839 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7840 rs->stop_reply_queue.end (),
7841 [=] (const stop_reply_up &event)
7843 return event->ptid.pid () == inf->pid;
7845 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7846 remote_debug_printf
7847 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7848 (*it)->ptid.to_string().c_str(),
7849 (*it)->ws.to_string ().c_str ());
7850 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7853 /* Discard the stop replies for RS in stop_reply_queue. */
7855 void
7856 remote_target::discard_pending_stop_replies_in_queue ()
7858 remote_state *rs = get_remote_state ();
7860 /* Discard the stop replies we have already pulled with
7861 vStopped. */
7862 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7863 rs->stop_reply_queue.end (),
7864 [=] (const stop_reply_up &event)
7866 return event->rs == rs;
7868 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7871 /* Remove the first reply in 'stop_reply_queue' which matches
7872 PTID. */
7874 stop_reply_up
7875 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7877 remote_state *rs = get_remote_state ();
7879 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7880 rs->stop_reply_queue.end (),
7881 [=] (const stop_reply_up &event)
7883 return event->ptid.matches (ptid);
7885 stop_reply_up result;
7886 if (iter != rs->stop_reply_queue.end ())
7888 result = std::move (*iter);
7889 rs->stop_reply_queue.erase (iter);
7892 if (notif_debug)
7893 gdb_printf (gdb_stdlog,
7894 "notif: discard queued event: 'Stop' in %s\n",
7895 ptid.to_string ().c_str ());
7897 return result;
7900 /* Look for a queued stop reply belonging to PTID. If one is found,
7901 remove it from the queue, and return it. Returns NULL if none is
7902 found. If there are still queued events left to process, tell the
7903 event loop to get back to target_wait soon. */
7905 stop_reply_up
7906 remote_target::queued_stop_reply (ptid_t ptid)
7908 remote_state *rs = get_remote_state ();
7909 stop_reply_up r = remote_notif_remove_queued_reply (ptid);
7911 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7913 /* There's still at least an event left. */
7914 rs->mark_async_event_handler ();
7917 return r;
7920 /* Push a fully parsed stop reply in the stop reply queue. Since we
7921 know that we now have at least one queued event left to pass to the
7922 core side, tell the event loop to get back to target_wait soon. */
7924 void
7925 remote_target::push_stop_reply (stop_reply_up new_event)
7927 remote_state *rs = get_remote_state ();
7928 rs->stop_reply_queue.push_back (std::move (new_event));
7930 if (notif_debug)
7931 gdb_printf (gdb_stdlog,
7932 "notif: push 'Stop' %s to queue %d\n",
7933 new_event->ptid.to_string ().c_str (),
7934 int (rs->stop_reply_queue.size ()));
7936 /* Mark the pending event queue only if async mode is currently enabled.
7937 If async mode is not currently enabled, then, if it later becomes
7938 enabled, and there are events in this queue, we will mark the event
7939 token at that point, see remote_target::async. */
7940 if (target_is_async_p ())
7941 rs->mark_async_event_handler ();
7944 /* Returns true if we have a stop reply for PTID. */
7947 remote_target::peek_stop_reply (ptid_t ptid)
7949 remote_state *rs = get_remote_state ();
7950 for (auto &event : rs->stop_reply_queue)
7951 if (ptid == event->ptid
7952 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7953 return 1;
7954 return 0;
7957 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7958 starting with P and ending with PEND matches PREFIX. */
7960 static int
7961 strprefix (const char *p, const char *pend, const char *prefix)
7963 for ( ; p < pend; p++, prefix++)
7964 if (*p != *prefix)
7965 return 0;
7966 return *prefix == '\0';
7969 /* Parse the stop reply in BUF. Either the function succeeds, and the
7970 result is stored in EVENT, or throws an error. */
7972 void
7973 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7975 remote_arch_state *rsa = NULL;
7976 ULONGEST addr;
7977 const char *p;
7978 int skipregs = 0;
7980 event->ptid = null_ptid;
7981 event->rs = get_remote_state ();
7982 event->ws.set_ignore ();
7983 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7984 event->regcache.clear ();
7985 event->core = -1;
7987 switch (buf[0])
7989 case 'T': /* Status with PC, SP, FP, ... */
7990 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7991 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7992 ss = signal number
7993 n... = register number
7994 r... = register contents
7997 p = &buf[3]; /* after Txx */
7998 while (*p)
8000 const char *p1;
8001 int fieldsize;
8003 p1 = strchr (p, ':');
8004 if (p1 == NULL)
8005 error (_("Malformed packet(a) (missing colon): %s\n\
8006 Packet: '%s'\n"),
8007 p, buf);
8008 if (p == p1)
8009 error (_("Malformed packet(a) (missing register number): %s\n\
8010 Packet: '%s'\n"),
8011 p, buf);
8013 /* Some "registers" are actually extended stop information.
8014 Note if you're adding a new entry here: GDB 7.9 and
8015 earlier assume that all register "numbers" that start
8016 with an hex digit are real register numbers. Make sure
8017 the server only sends such a packet if it knows the
8018 client understands it. */
8020 if (strprefix (p, p1, "thread"))
8021 event->ptid = read_ptid (++p1, &p);
8022 else if (strprefix (p, p1, "syscall_entry"))
8024 ULONGEST sysno;
8026 p = unpack_varlen_hex (++p1, &sysno);
8027 event->ws.set_syscall_entry ((int) sysno);
8029 else if (strprefix (p, p1, "syscall_return"))
8031 ULONGEST sysno;
8033 p = unpack_varlen_hex (++p1, &sysno);
8034 event->ws.set_syscall_return ((int) sysno);
8036 else if (strprefix (p, p1, "watch")
8037 || strprefix (p, p1, "rwatch")
8038 || strprefix (p, p1, "awatch"))
8040 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
8041 p = unpack_varlen_hex (++p1, &addr);
8042 event->watch_data_address = (CORE_ADDR) addr;
8044 else if (strprefix (p, p1, "swbreak"))
8046 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
8048 /* Make sure the stub doesn't forget to indicate support
8049 with qSupported. */
8050 if (m_features.packet_support (PACKET_swbreak_feature)
8051 != PACKET_ENABLE)
8052 error (_("Unexpected swbreak stop reason"));
8054 /* The value part is documented as "must be empty",
8055 though we ignore it, in case we ever decide to make
8056 use of it in a backward compatible way. */
8057 p = strchrnul (p1 + 1, ';');
8059 else if (strprefix (p, p1, "hwbreak"))
8061 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
8063 /* Make sure the stub doesn't forget to indicate support
8064 with qSupported. */
8065 if (m_features.packet_support (PACKET_hwbreak_feature)
8066 != PACKET_ENABLE)
8067 error (_("Unexpected hwbreak stop reason"));
8069 /* See above. */
8070 p = strchrnul (p1 + 1, ';');
8072 else if (strprefix (p, p1, "library"))
8074 event->ws.set_loaded ();
8075 p = strchrnul (p1 + 1, ';');
8077 else if (strprefix (p, p1, "replaylog"))
8079 event->ws.set_no_history ();
8080 /* p1 will indicate "begin" or "end", but it makes
8081 no difference for now, so ignore it. */
8082 p = strchrnul (p1 + 1, ';');
8084 else if (strprefix (p, p1, "core"))
8086 ULONGEST c;
8088 p = unpack_varlen_hex (++p1, &c);
8089 event->core = c;
8091 else if (strprefix (p, p1, "fork"))
8092 event->ws.set_forked (read_ptid (++p1, &p));
8093 else if (strprefix (p, p1, "vfork"))
8094 event->ws.set_vforked (read_ptid (++p1, &p));
8095 else if (strprefix (p, p1, "clone"))
8096 event->ws.set_thread_cloned (read_ptid (++p1, &p));
8097 else if (strprefix (p, p1, "vforkdone"))
8099 event->ws.set_vfork_done ();
8100 p = strchrnul (p1 + 1, ';');
8102 else if (strprefix (p, p1, "exec"))
8104 ULONGEST ignored;
8105 int pathlen;
8107 /* Determine the length of the execd pathname. */
8108 p = unpack_varlen_hex (++p1, &ignored);
8109 pathlen = (p - p1) / 2;
8111 /* Save the pathname for event reporting and for
8112 the next run command. */
8113 gdb::unique_xmalloc_ptr<char> pathname
8114 ((char *) xmalloc (pathlen + 1));
8115 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8116 pathname.get ()[pathlen] = '\0';
8118 /* This is freed during event handling. */
8119 event->ws.set_execd (std::move (pathname));
8121 /* Skip the registers included in this packet, since
8122 they may be for an architecture different from the
8123 one used by the original program. */
8124 skipregs = 1;
8126 else if (strprefix (p, p1, "create"))
8128 event->ws.set_thread_created ();
8129 p = strchrnul (p1 + 1, ';');
8131 else
8133 ULONGEST pnum;
8134 const char *p_temp;
8136 if (skipregs)
8138 p = strchrnul (p1 + 1, ';');
8139 p++;
8140 continue;
8143 /* Maybe a real ``P'' register number. */
8144 p_temp = unpack_varlen_hex (p, &pnum);
8145 /* If the first invalid character is the colon, we got a
8146 register number. Otherwise, it's an unknown stop
8147 reason. */
8148 if (p_temp == p1)
8150 /* If we haven't parsed the event's thread yet, find
8151 it now, in order to find the architecture of the
8152 reported expedited registers. */
8153 if (event->ptid == null_ptid)
8155 /* If there is no thread-id information then leave
8156 the event->ptid as null_ptid. Later in
8157 process_stop_reply we will pick a suitable
8158 thread. */
8159 const char *thr = strstr (p1 + 1, ";thread:");
8160 if (thr != NULL)
8161 event->ptid = read_ptid (thr + strlen (";thread:"),
8162 NULL);
8165 if (rsa == NULL)
8167 inferior *inf
8168 = (event->ptid == null_ptid
8169 ? NULL
8170 : find_inferior_ptid (this, event->ptid));
8171 /* If this is the first time we learn anything
8172 about this process, skip the registers
8173 included in this packet, since we don't yet
8174 know which architecture to use to parse them.
8175 We'll determine the architecture later when
8176 we process the stop reply and retrieve the
8177 target description, via
8178 remote_notice_new_inferior ->
8179 post_create_inferior. */
8180 if (inf == NULL)
8182 p = strchrnul (p1 + 1, ';');
8183 p++;
8184 continue;
8187 event->arch = inf->arch ();
8188 rsa = event->rs->get_remote_arch_state (event->arch);
8191 packet_reg *reg
8192 = packet_reg_from_pnum (event->arch, rsa, pnum);
8193 cached_reg_t cached_reg;
8195 if (reg == NULL)
8196 error (_("Remote sent bad register number %s: %s\n\
8197 Packet: '%s'\n"),
8198 hex_string (pnum), p, buf);
8200 cached_reg.num = reg->regnum;
8201 cached_reg.data.reset ((gdb_byte *)
8202 xmalloc (register_size (event->arch,
8203 reg->regnum)));
8205 p = p1 + 1;
8206 fieldsize = hex2bin (p, cached_reg.data.get (),
8207 register_size (event->arch, reg->regnum));
8208 p += 2 * fieldsize;
8209 if (fieldsize < register_size (event->arch, reg->regnum))
8210 warning (_("Remote reply is too short: %s"), buf);
8212 event->regcache.push_back (std::move (cached_reg));
8214 else
8216 /* Not a number. Silently skip unknown optional
8217 info. */
8218 p = strchrnul (p1 + 1, ';');
8222 if (*p != ';')
8223 error (_("Remote register badly formatted: %s\nhere: %s"),
8224 buf, p);
8225 ++p;
8228 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8229 break;
8231 [[fallthrough]];
8232 case 'S': /* Old style status, just signal only. */
8234 int sig;
8236 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8237 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8238 event->ws.set_stopped ((enum gdb_signal) sig);
8239 else
8240 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8242 break;
8243 case 'w': /* Thread exited. */
8245 ULONGEST value;
8247 p = unpack_varlen_hex (&buf[1], &value);
8248 event->ws.set_thread_exited (value);
8249 if (*p != ';')
8250 error (_("stop reply packet badly formatted: %s"), buf);
8251 event->ptid = read_ptid (++p, NULL);
8252 break;
8254 case 'W': /* Target exited. */
8255 case 'X':
8257 ULONGEST value;
8259 /* GDB used to accept only 2 hex chars here. Stubs should
8260 only send more if they detect GDB supports multi-process
8261 support. */
8262 p = unpack_varlen_hex (&buf[1], &value);
8264 if (buf[0] == 'W')
8266 /* The remote process exited. */
8267 event->ws.set_exited (value);
8269 else
8271 /* The remote process exited with a signal. */
8272 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8273 event->ws.set_signalled ((enum gdb_signal) value);
8274 else
8275 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8278 /* If no process is specified, return null_ptid, and let the
8279 caller figure out the right process to use. */
8280 int pid = 0;
8281 if (*p == '\0')
8283 else if (*p == ';')
8285 p++;
8287 if (*p == '\0')
8289 else if (startswith (p, "process:"))
8291 ULONGEST upid;
8293 p += sizeof ("process:") - 1;
8294 unpack_varlen_hex (p, &upid);
8295 pid = upid;
8297 else
8298 error (_("unknown stop reply packet: %s"), buf);
8300 else
8301 error (_("unknown stop reply packet: %s"), buf);
8302 event->ptid = ptid_t (pid);
8304 break;
8305 case 'N':
8306 event->ws.set_no_resumed ();
8307 event->ptid = minus_one_ptid;
8308 break;
8312 /* When the stub wants to tell GDB about a new notification reply, it
8313 sends a notification (%Stop, for example). Those can come it at
8314 any time, hence, we have to make sure that any pending
8315 putpkt/getpkt sequence we're making is finished, before querying
8316 the stub for more events with the corresponding ack command
8317 (vStopped, for example). E.g., if we started a vStopped sequence
8318 immediately upon receiving the notification, something like this
8319 could happen:
8321 1.1) --> Hg 1
8322 1.2) <-- OK
8323 1.3) --> g
8324 1.4) <-- %Stop
8325 1.5) --> vStopped
8326 1.6) <-- (registers reply to step #1.3)
8328 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8329 query.
8331 To solve this, whenever we parse a %Stop notification successfully,
8332 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8333 doing whatever we were doing:
8335 2.1) --> Hg 1
8336 2.2) <-- OK
8337 2.3) --> g
8338 2.4) <-- %Stop
8339 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8340 2.5) <-- (registers reply to step #2.3)
8342 Eventually after step #2.5, we return to the event loop, which
8343 notices there's an event on the
8344 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8345 associated callback --- the function below. At this point, we're
8346 always safe to start a vStopped sequence. :
8348 2.6) --> vStopped
8349 2.7) <-- T05 thread:2
8350 2.8) --> vStopped
8351 2.9) --> OK
8354 void
8355 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8357 struct remote_state *rs = get_remote_state ();
8359 if (rs->notif_state->pending_event[nc->id] != NULL)
8361 if (notif_debug)
8362 gdb_printf (gdb_stdlog,
8363 "notif: process: '%s' ack pending event\n",
8364 nc->name);
8366 /* acknowledge */
8367 nc->ack (this, nc, rs->buf.data (),
8368 std::move (rs->notif_state->pending_event[nc->id]));
8370 while (1)
8372 getpkt (&rs->buf);
8373 if (strcmp (rs->buf.data (), "OK") == 0)
8374 break;
8375 else
8376 remote_notif_ack (this, nc, rs->buf.data ());
8379 else
8381 if (notif_debug)
8382 gdb_printf (gdb_stdlog,
8383 "notif: process: '%s' no pending reply\n",
8384 nc->name);
8388 /* Wrapper around remote_target::remote_notif_get_pending_events to
8389 avoid having to export the whole remote_target class. */
8391 void
8392 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8394 remote->remote_notif_get_pending_events (nc);
8397 /* Called from process_stop_reply when the stop packet we are responding
8398 to didn't include a process-id or thread-id. STATUS is the stop event
8399 we are responding to.
8401 It is the task of this function to select a suitable thread (or process)
8402 and return its ptid, this is the thread (or process) we will assume the
8403 stop event came from.
8405 In some cases there isn't really any choice about which thread (or
8406 process) is selected, a basic remote with a single process containing a
8407 single thread might choose not to send any process-id or thread-id in
8408 its stop packets, this function will select and return the one and only
8409 thread.
8411 However, if a target supports multiple threads (or processes) and still
8412 doesn't include a thread-id (or process-id) in its stop packet then
8413 first, this is a badly behaving target, and second, we're going to have
8414 to select a thread (or process) at random and use that. This function
8415 will print a warning to the user if it detects that there is the
8416 possibility that GDB is guessing which thread (or process) to
8417 report.
8419 Note that this is called before GDB fetches the updated thread list from the
8420 target. So it's possible for the stop reply to be ambiguous and for GDB to
8421 not realize it. For example, if there's initially one thread, the target
8422 spawns a second thread, and then sends a stop reply without an id that
8423 concerns the first thread. GDB will assume the stop reply is about the
8424 first thread - the only thread it knows about - without printing a warning.
8425 Anyway, if the remote meant for the stop reply to be about the second thread,
8426 then it would be really broken, because GDB doesn't know about that thread
8427 yet. */
8429 ptid_t
8430 remote_target::select_thread_for_ambiguous_stop_reply
8431 (const target_waitstatus &status)
8433 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8435 /* Some stop events apply to all threads in an inferior, while others
8436 only apply to a single thread. */
8437 bool process_wide_stop
8438 = (status.kind () == TARGET_WAITKIND_EXITED
8439 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8441 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8443 thread_info *first_resumed_thread = nullptr;
8444 bool ambiguous = false;
8446 /* Consider all non-exited threads of the target, find the first resumed
8447 one. */
8448 for (thread_info *thr : all_non_exited_threads (this))
8450 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8452 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8453 continue;
8455 if (first_resumed_thread == nullptr)
8456 first_resumed_thread = thr;
8457 else if (!process_wide_stop
8458 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8459 ambiguous = true;
8462 gdb_assert (first_resumed_thread != nullptr);
8464 remote_debug_printf ("first resumed thread is %s",
8465 pid_to_str (first_resumed_thread->ptid).c_str ());
8466 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8468 /* Warn if the remote target is sending ambiguous stop replies. */
8469 if (ambiguous)
8471 static bool warned = false;
8473 if (!warned)
8475 /* If you are seeing this warning then the remote target has
8476 stopped without specifying a thread-id, but the target
8477 does have multiple threads (or inferiors), and so GDB is
8478 having to guess which thread stopped.
8480 Examples of what might cause this are the target sending
8481 and 'S' stop packet, or a 'T' stop packet and not
8482 including a thread-id.
8484 Additionally, the target might send a 'W' or 'X packet
8485 without including a process-id, when the target has
8486 multiple running inferiors. */
8487 if (process_wide_stop)
8488 warning (_("multi-inferior target stopped without "
8489 "sending a process-id, using first "
8490 "non-exited inferior"));
8491 else
8492 warning (_("multi-threaded target stopped without "
8493 "sending a thread-id, using first "
8494 "non-exited thread"));
8495 warned = true;
8499 /* If this is a stop for all threads then don't use a particular threads
8500 ptid, instead create a new ptid where only the pid field is set. */
8501 if (process_wide_stop)
8502 return ptid_t (first_resumed_thread->ptid.pid ());
8503 else
8504 return first_resumed_thread->ptid;
8507 /* Called when it is decided that STOP_REPLY holds the info of the
8508 event that is to be returned to the core. This function always
8509 destroys STOP_REPLY. */
8511 ptid_t
8512 remote_target::process_stop_reply (stop_reply_up stop_reply,
8513 struct target_waitstatus *status)
8515 *status = stop_reply->ws;
8516 ptid_t ptid = stop_reply->ptid;
8518 /* If no thread/process was reported by the stub then select a suitable
8519 thread/process. */
8520 if (ptid == null_ptid)
8521 ptid = select_thread_for_ambiguous_stop_reply (*status);
8522 gdb_assert (ptid != null_ptid);
8524 if (status->kind () != TARGET_WAITKIND_EXITED
8525 && status->kind () != TARGET_WAITKIND_SIGNALLED
8526 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8528 remote_notice_new_inferior (ptid, false);
8530 /* Expedited registers. */
8531 if (!stop_reply->regcache.empty ())
8533 /* 'w' stop replies don't cary expedited registers (which
8534 wouldn't make any sense for a thread that is gone
8535 already). */
8536 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8538 regcache *regcache
8539 = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
8540 stop_reply->arch);
8542 for (cached_reg_t &reg : stop_reply->regcache)
8543 regcache->raw_supply (reg.num, reg.data.get ());
8546 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8547 remote_thr->core = stop_reply->core;
8548 remote_thr->stop_reason = stop_reply->stop_reason;
8549 remote_thr->watch_data_address = stop_reply->watch_data_address;
8551 if (target_is_non_stop_p ())
8553 /* If the target works in non-stop mode, a stop-reply indicates that
8554 only this thread stopped. */
8555 remote_thr->set_not_resumed ();
8557 else
8559 /* If the target works in all-stop mode, a stop-reply indicates that
8560 all the target's threads stopped. */
8561 for (thread_info *tp : all_non_exited_threads (this))
8562 get_remote_thread_info (tp)->set_not_resumed ();
8566 return ptid;
8569 /* The non-stop mode version of target_wait. */
8571 ptid_t
8572 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8573 target_wait_flags options)
8575 struct remote_state *rs = get_remote_state ();
8576 int ret;
8577 bool is_notif = false;
8579 /* If in non-stop mode, get out of getpkt even if a
8580 notification is received. */
8582 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8583 while (1)
8585 if (ret != -1 && !is_notif)
8586 switch (rs->buf[0])
8588 case 'E': /* Error of some sort. */
8589 /* We're out of sync with the target now. Did it continue
8590 or not? We can't tell which thread it was in non-stop,
8591 so just ignore this. */
8592 warning (_("Remote failure reply: %s"), rs->buf.data ());
8593 break;
8594 case 'O': /* Console output. */
8595 remote_console_output (&rs->buf[1], gdb_stdtarg);
8596 break;
8597 default:
8598 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8599 break;
8602 /* Acknowledge a pending stop reply that may have arrived in the
8603 mean time. */
8604 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8605 remote_notif_get_pending_events (&notif_client_stop);
8607 /* If indeed we noticed a stop reply, we're done. */
8608 stop_reply_up stop_reply = queued_stop_reply (ptid);
8609 if (stop_reply != NULL)
8610 return process_stop_reply (std::move (stop_reply), status);
8612 /* Still no event. If we're just polling for an event, then
8613 return to the event loop. */
8614 if (options & TARGET_WNOHANG)
8616 status->set_ignore ();
8617 return minus_one_ptid;
8620 /* Otherwise do a blocking wait. */
8621 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8625 /* Return the first resumed thread. */
8627 static ptid_t
8628 first_remote_resumed_thread (remote_target *target)
8630 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8631 if (tp->resumed ())
8632 return tp->ptid;
8633 return null_ptid;
8636 /* Wait until the remote machine stops, then return, storing status in
8637 STATUS just as `wait' would. */
8639 ptid_t
8640 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8641 target_wait_flags options)
8643 struct remote_state *rs = get_remote_state ();
8644 ptid_t event_ptid = null_ptid;
8645 char *buf;
8646 stop_reply_up stop_reply;
8648 again:
8650 status->set_ignore ();
8652 stop_reply = queued_stop_reply (ptid);
8653 if (stop_reply != NULL)
8655 /* None of the paths that push a stop reply onto the queue should
8656 have set the waiting_for_stop_reply flag. */
8657 gdb_assert (!rs->waiting_for_stop_reply);
8658 event_ptid = process_stop_reply (std::move (stop_reply), status);
8660 else
8662 bool forever = ((options & TARGET_WNOHANG) == 0
8663 && rs->wait_forever_enabled_p);
8665 if (!rs->waiting_for_stop_reply)
8667 status->set_no_resumed ();
8668 return minus_one_ptid;
8671 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8672 _never_ wait for ever -> test on target_is_async_p().
8673 However, before we do that we need to ensure that the caller
8674 knows how to take the target into/out of async mode. */
8675 bool is_notif;
8676 int ret = getpkt (&rs->buf, forever, &is_notif);
8678 /* GDB gets a notification. Return to core as this event is
8679 not interesting. */
8680 if (ret != -1 && is_notif)
8681 return minus_one_ptid;
8683 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8684 return minus_one_ptid;
8686 buf = rs->buf.data ();
8688 /* Assume that the target has acknowledged Ctrl-C unless we receive
8689 an 'F' or 'O' packet. */
8690 if (buf[0] != 'F' && buf[0] != 'O')
8691 rs->ctrlc_pending_p = 0;
8693 switch (buf[0])
8695 case 'E': /* Error of some sort. */
8696 /* We're out of sync with the target now. Did it continue or
8697 not? Not is more likely, so report a stop. */
8698 rs->waiting_for_stop_reply = 0;
8700 warning (_("Remote failure reply: %s"), buf);
8701 status->set_stopped (GDB_SIGNAL_0);
8702 break;
8703 case 'F': /* File-I/O request. */
8704 /* GDB may access the inferior memory while handling the File-I/O
8705 request, but we don't want GDB accessing memory while waiting
8706 for a stop reply. See the comments in putpkt_binary. Set
8707 waiting_for_stop_reply to 0 temporarily. */
8708 rs->waiting_for_stop_reply = 0;
8709 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8710 rs->ctrlc_pending_p = 0;
8711 /* GDB handled the File-I/O request, and the target is running
8712 again. Keep waiting for events. */
8713 rs->waiting_for_stop_reply = 1;
8714 break;
8715 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8717 /* There is a stop reply to handle. */
8718 rs->waiting_for_stop_reply = 0;
8720 stop_reply
8721 = as_stop_reply_up (remote_notif_parse (this,
8722 &notif_client_stop,
8723 rs->buf.data ()));
8725 event_ptid = process_stop_reply (std::move (stop_reply), status);
8726 break;
8728 case 'O': /* Console output. */
8729 remote_console_output (buf + 1, gdb_stdtarg);
8730 break;
8731 case '\0':
8732 if (rs->last_sent_signal != GDB_SIGNAL_0)
8734 /* Zero length reply means that we tried 'S' or 'C' and the
8735 remote system doesn't support it. */
8736 target_terminal::ours_for_output ();
8737 gdb_printf
8738 ("Can't send signals to this remote system. %s not sent.\n",
8739 gdb_signal_to_name (rs->last_sent_signal));
8740 rs->last_sent_signal = GDB_SIGNAL_0;
8741 target_terminal::inferior ();
8743 strcpy (buf, rs->last_sent_step ? "s" : "c");
8744 putpkt (buf);
8745 break;
8747 [[fallthrough]];
8748 default:
8749 warning (_("Invalid remote reply: %s"), buf);
8750 break;
8754 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8755 return minus_one_ptid;
8756 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8758 /* Nothing interesting happened. If we're doing a non-blocking
8759 poll, we're done. Otherwise, go back to waiting. */
8760 if (options & TARGET_WNOHANG)
8761 return minus_one_ptid;
8762 else
8763 goto again;
8765 else if (status->kind () != TARGET_WAITKIND_EXITED
8766 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8768 if (event_ptid != null_ptid)
8769 record_currthread (rs, event_ptid);
8770 else
8771 event_ptid = first_remote_resumed_thread (this);
8773 else
8775 /* A process exit. Invalidate our notion of current thread. */
8776 record_currthread (rs, minus_one_ptid);
8777 /* It's possible that the packet did not include a pid. */
8778 if (event_ptid == null_ptid)
8779 event_ptid = first_remote_resumed_thread (this);
8780 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8781 if (event_ptid == null_ptid)
8782 event_ptid = magic_null_ptid;
8785 return event_ptid;
8788 /* Wait until the remote machine stops, then return, storing status in
8789 STATUS just as `wait' would. */
8791 ptid_t
8792 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8793 target_wait_flags options)
8795 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8797 remote_state *rs = get_remote_state ();
8799 /* Start by clearing the flag that asks for our wait method to be called,
8800 we'll mark it again at the end if needed. If the target is not in
8801 async mode then the async token should not be marked. */
8802 if (target_is_async_p ())
8803 rs->clear_async_event_handler ();
8804 else
8805 gdb_assert (!rs->async_event_handler_marked ());
8807 ptid_t event_ptid;
8809 if (target_is_non_stop_p ())
8810 event_ptid = wait_ns (ptid, status, options);
8811 else
8812 event_ptid = wait_as (ptid, status, options);
8814 if (target_is_async_p ())
8816 /* If there are events left in the queue, or unacknowledged
8817 notifications, then tell the event loop to call us again. */
8818 if (!rs->stop_reply_queue.empty ()
8819 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8820 rs->mark_async_event_handler ();
8823 return event_ptid;
8826 /* Fetch a single register using a 'p' packet. */
8829 remote_target::fetch_register_using_p (struct regcache *regcache,
8830 packet_reg *reg)
8832 struct gdbarch *gdbarch = regcache->arch ();
8833 struct remote_state *rs = get_remote_state ();
8834 char *buf, *p;
8835 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8836 int i;
8838 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8839 return 0;
8841 if (reg->pnum == -1)
8842 return 0;
8844 p = rs->buf.data ();
8845 *p++ = 'p';
8846 p += hexnumstr (p, reg->pnum);
8847 *p++ = '\0';
8848 putpkt (rs->buf);
8849 getpkt (&rs->buf);
8851 buf = rs->buf.data ();
8853 packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
8854 switch (result.status ())
8856 case PACKET_OK:
8857 break;
8858 case PACKET_UNKNOWN:
8859 return 0;
8860 case PACKET_ERROR:
8861 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8862 gdbarch_register_name (regcache->arch (), reg->regnum),
8863 result.err_msg ());
8866 /* If this register is unfetchable, tell the regcache. */
8867 if (buf[0] == 'x')
8869 regcache->raw_supply (reg->regnum, NULL);
8870 return 1;
8873 /* Otherwise, parse and supply the value. */
8874 p = buf;
8875 i = 0;
8876 while (p[0] != 0)
8878 if (p[1] == 0)
8879 error (_("fetch_register_using_p: early buf termination"));
8881 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8882 p += 2;
8884 regcache->raw_supply (reg->regnum, regp);
8885 return 1;
8888 /* Fetch the registers included in the target's 'g' packet. */
8891 remote_target::send_g_packet ()
8893 struct remote_state *rs = get_remote_state ();
8894 int buf_len;
8896 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8897 putpkt (rs->buf);
8898 getpkt (&rs->buf);
8899 packet_result result = packet_check_result (rs->buf);
8900 if (result.status () == PACKET_ERROR)
8901 error (_("Could not read registers; remote failure reply '%s'"),
8902 result.err_msg ());
8904 /* We can get out of synch in various cases. If the first character
8905 in the buffer is not a hex character, assume that has happened
8906 and try to fetch another packet to read. */
8907 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8908 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8909 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8910 && rs->buf[0] != 'x') /* New: unavailable register value. */
8912 remote_debug_printf ("Bad register packet; fetching a new packet");
8913 getpkt (&rs->buf);
8916 buf_len = strlen (rs->buf.data ());
8918 /* Sanity check the received packet. */
8919 if (buf_len % 2 != 0)
8920 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8922 return buf_len / 2;
8925 void
8926 remote_target::process_g_packet (struct regcache *regcache)
8928 struct gdbarch *gdbarch = regcache->arch ();
8929 struct remote_state *rs = get_remote_state ();
8930 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8931 int i, buf_len;
8932 char *p;
8933 char *regs;
8935 buf_len = strlen (rs->buf.data ());
8937 /* Further sanity checks, with knowledge of the architecture. */
8938 if (buf_len > 2 * rsa->sizeof_g_packet)
8939 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8940 "bytes): %s"),
8941 rsa->sizeof_g_packet, buf_len / 2,
8942 rs->buf.data ());
8944 /* Save the size of the packet sent to us by the target. It is used
8945 as a heuristic when determining the max size of packets that the
8946 target can safely receive. */
8947 if (rsa->actual_register_packet_size == 0)
8948 rsa->actual_register_packet_size = buf_len;
8950 /* If this is smaller than we guessed the 'g' packet would be,
8951 update our records. A 'g' reply that doesn't include a register's
8952 value implies either that the register is not available, or that
8953 the 'p' packet must be used. */
8954 if (buf_len < 2 * rsa->sizeof_g_packet)
8956 long sizeof_g_packet = buf_len / 2;
8958 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8960 long offset = rsa->regs[i].offset;
8961 long reg_size = register_size (gdbarch, i);
8963 if (rsa->regs[i].pnum == -1)
8964 continue;
8966 if (offset >= sizeof_g_packet)
8967 rsa->regs[i].in_g_packet = 0;
8968 else if (offset + reg_size > sizeof_g_packet)
8969 error (_("Truncated register %d in remote 'g' packet"), i);
8970 else
8971 rsa->regs[i].in_g_packet = 1;
8974 /* Looks valid enough, we can assume this is the correct length
8975 for a 'g' packet. It's important not to adjust
8976 rsa->sizeof_g_packet if we have truncated registers otherwise
8977 this "if" won't be run the next time the method is called
8978 with a packet of the same size and one of the internal errors
8979 below will trigger instead. */
8980 rsa->sizeof_g_packet = sizeof_g_packet;
8983 regs = (char *) alloca (rsa->sizeof_g_packet);
8985 /* Unimplemented registers read as all bits zero. */
8986 memset (regs, 0, rsa->sizeof_g_packet);
8988 /* Reply describes registers byte by byte, each byte encoded as two
8989 hex characters. Suck them all up, then supply them to the
8990 register cacheing/storage mechanism. */
8992 p = rs->buf.data ();
8993 for (i = 0; i < rsa->sizeof_g_packet; i++)
8995 if (p[0] == 0 || p[1] == 0)
8996 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8997 internal_error (_("unexpected end of 'g' packet reply"));
8999 if (p[0] == 'x' && p[1] == 'x')
9000 regs[i] = 0; /* 'x' */
9001 else
9002 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
9003 p += 2;
9006 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9008 struct packet_reg *r = &rsa->regs[i];
9009 long reg_size = register_size (gdbarch, i);
9011 if (r->in_g_packet)
9013 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
9014 /* This shouldn't happen - we adjusted in_g_packet above. */
9015 internal_error (_("unexpected end of 'g' packet reply"));
9016 else if (rs->buf[r->offset * 2] == 'x')
9018 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
9019 /* The register isn't available, mark it as such (at
9020 the same time setting the value to zero). */
9021 regcache->raw_supply (r->regnum, NULL);
9023 else
9024 regcache->raw_supply (r->regnum, regs + r->offset);
9029 void
9030 remote_target::fetch_registers_using_g (struct regcache *regcache)
9032 send_g_packet ();
9033 process_g_packet (regcache);
9036 /* Make the remote selected traceframe match GDB's selected
9037 traceframe. */
9039 void
9040 remote_target::set_remote_traceframe ()
9042 int newnum;
9043 struct remote_state *rs = get_remote_state ();
9045 if (rs->remote_traceframe_number == get_traceframe_number ())
9046 return;
9048 /* Avoid recursion, remote_trace_find calls us again. */
9049 rs->remote_traceframe_number = get_traceframe_number ();
9051 newnum = target_trace_find (tfind_number,
9052 get_traceframe_number (), 0, 0, NULL);
9054 /* Should not happen. If it does, all bets are off. */
9055 if (newnum != get_traceframe_number ())
9056 warning (_("could not set remote traceframe"));
9059 void
9060 remote_target::fetch_registers (struct regcache *regcache, int regnum)
9062 struct gdbarch *gdbarch = regcache->arch ();
9063 struct remote_state *rs = get_remote_state ();
9064 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9065 int i;
9067 set_remote_traceframe ();
9068 set_general_thread (regcache->ptid ());
9070 if (regnum >= 0)
9072 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9074 gdb_assert (reg != NULL);
9076 /* If this register might be in the 'g' packet, try that first -
9077 we are likely to read more than one register. If this is the
9078 first 'g' packet, we might be overly optimistic about its
9079 contents, so fall back to 'p'. */
9080 if (reg->in_g_packet)
9082 fetch_registers_using_g (regcache);
9083 if (reg->in_g_packet)
9084 return;
9087 if (fetch_register_using_p (regcache, reg))
9088 return;
9090 /* This register is not available. */
9091 regcache->raw_supply (reg->regnum, NULL);
9093 return;
9096 fetch_registers_using_g (regcache);
9098 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9099 if (!rsa->regs[i].in_g_packet)
9100 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
9102 /* This register is not available. */
9103 regcache->raw_supply (i, NULL);
9107 /* Prepare to store registers. Since we may send them all (using a
9108 'G' request), we have to read out the ones we don't want to change
9109 first. */
9111 void
9112 remote_target::prepare_to_store (struct regcache *regcache)
9114 struct remote_state *rs = get_remote_state ();
9115 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9116 int i;
9118 /* Make sure the entire registers array is valid. */
9119 switch (m_features.packet_support (PACKET_P))
9121 case PACKET_DISABLE:
9122 case PACKET_SUPPORT_UNKNOWN:
9123 /* Make sure all the necessary registers are cached. */
9124 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9125 if (rsa->regs[i].in_g_packet)
9126 regcache->raw_update (rsa->regs[i].regnum);
9127 break;
9128 case PACKET_ENABLE:
9129 break;
9133 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9134 packet was not recognized. */
9137 remote_target::store_register_using_P (const struct regcache *regcache,
9138 packet_reg *reg)
9140 struct gdbarch *gdbarch = regcache->arch ();
9141 struct remote_state *rs = get_remote_state ();
9142 /* Try storing a single register. */
9143 char *buf = rs->buf.data ();
9144 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9145 char *p;
9147 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9148 return 0;
9150 if (reg->pnum == -1)
9151 return 0;
9153 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9154 p = buf + strlen (buf);
9155 regcache->raw_collect (reg->regnum, regp);
9156 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9157 putpkt (rs->buf);
9158 getpkt (&rs->buf);
9160 packet_result result = m_features.packet_ok (rs->buf, PACKET_P);
9161 switch (result.status ())
9163 case PACKET_OK:
9164 return 1;
9165 case PACKET_ERROR:
9166 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9167 gdbarch_register_name (gdbarch, reg->regnum), result.err_msg ());
9168 case PACKET_UNKNOWN:
9169 return 0;
9170 default:
9171 internal_error (_("Bad result from packet_ok"));
9175 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9176 contents of the register cache buffer. FIXME: ignores errors. */
9178 void
9179 remote_target::store_registers_using_G (const struct regcache *regcache)
9181 struct remote_state *rs = get_remote_state ();
9182 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9183 gdb_byte *regs;
9184 char *p;
9186 /* Extract all the registers in the regcache copying them into a
9187 local buffer. */
9189 int i;
9191 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9192 memset (regs, 0, rsa->sizeof_g_packet);
9193 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9195 struct packet_reg *r = &rsa->regs[i];
9197 if (r->in_g_packet)
9198 regcache->raw_collect (r->regnum, regs + r->offset);
9202 /* Command describes registers byte by byte,
9203 each byte encoded as two hex characters. */
9204 p = rs->buf.data ();
9205 *p++ = 'G';
9206 bin2hex (regs, p, rsa->sizeof_g_packet);
9207 putpkt (rs->buf);
9208 getpkt (&rs->buf);
9209 packet_result pkt_status = packet_check_result (rs->buf);
9210 if (pkt_status.status () == PACKET_ERROR)
9211 error (_("Could not write registers; remote failure reply '%s'"),
9212 pkt_status.err_msg ());
9215 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9216 of the register cache buffer. FIXME: ignores errors. */
9218 void
9219 remote_target::store_registers (struct regcache *regcache, int regnum)
9221 struct gdbarch *gdbarch = regcache->arch ();
9222 struct remote_state *rs = get_remote_state ();
9223 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9224 int i;
9226 set_remote_traceframe ();
9227 set_general_thread (regcache->ptid ());
9229 if (regnum >= 0)
9231 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9233 gdb_assert (reg != NULL);
9235 /* Always prefer to store registers using the 'P' packet if
9236 possible; we often change only a small number of registers.
9237 Sometimes we change a larger number; we'd need help from a
9238 higher layer to know to use 'G'. */
9239 if (store_register_using_P (regcache, reg))
9240 return;
9242 /* For now, don't complain if we have no way to write the
9243 register. GDB loses track of unavailable registers too
9244 easily. Some day, this may be an error. We don't have
9245 any way to read the register, either... */
9246 if (!reg->in_g_packet)
9247 return;
9249 store_registers_using_G (regcache);
9250 return;
9253 store_registers_using_G (regcache);
9255 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9256 if (!rsa->regs[i].in_g_packet)
9257 if (!store_register_using_P (regcache, &rsa->regs[i]))
9258 /* See above for why we do not issue an error here. */
9259 continue;
9263 /* Return the number of hex digits in num. */
9265 static int
9266 hexnumlen (ULONGEST num)
9268 int i;
9270 for (i = 0; num != 0; i++)
9271 num >>= 4;
9273 return std::max (i, 1);
9276 /* Set BUF to the minimum number of hex digits representing NUM. */
9278 static int
9279 hexnumstr (char *buf, ULONGEST num)
9281 int len = hexnumlen (num);
9283 return hexnumnstr (buf, num, len);
9287 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9289 static int
9290 hexnumnstr (char *buf, ULONGEST num, int width)
9292 int i;
9294 buf[width] = '\0';
9296 for (i = width - 1; i >= 0; i--)
9298 buf[i] = "0123456789abcdef"[(num & 0xf)];
9299 num >>= 4;
9302 return width;
9305 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9307 static CORE_ADDR
9308 remote_address_masked (CORE_ADDR addr)
9310 unsigned int address_size = remote_address_size;
9312 /* If "remoteaddresssize" was not set, default to target address size. */
9313 if (!address_size)
9314 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9316 if (address_size > 0
9317 && address_size < (sizeof (ULONGEST) * 8))
9319 /* Only create a mask when that mask can safely be constructed
9320 in a ULONGEST variable. */
9321 ULONGEST mask = 1;
9323 mask = (mask << address_size) - 1;
9324 addr &= mask;
9326 return addr;
9329 /* Determine whether the remote target supports binary downloading.
9330 This is accomplished by sending a no-op memory write of zero length
9331 to the target at the specified address. It does not suffice to send
9332 the whole packet, since many stubs strip the eighth bit and
9333 subsequently compute a wrong checksum, which causes real havoc with
9334 remote_write_bytes.
9336 NOTE: This can still lose if the serial line is not eight-bit
9337 clean. In cases like this, the user should clear "remote
9338 X-packet". */
9340 void
9341 remote_target::check_binary_download (CORE_ADDR addr)
9343 struct remote_state *rs = get_remote_state ();
9345 switch (m_features.packet_support (PACKET_X))
9347 case PACKET_DISABLE:
9348 break;
9349 case PACKET_ENABLE:
9350 break;
9351 case PACKET_SUPPORT_UNKNOWN:
9353 char *p;
9355 p = rs->buf.data ();
9356 *p++ = 'X';
9357 p += hexnumstr (p, (ULONGEST) addr);
9358 *p++ = ',';
9359 p += hexnumstr (p, (ULONGEST) 0);
9360 *p++ = ':';
9361 *p = '\0';
9363 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9364 getpkt (&rs->buf);
9366 if (rs->buf[0] == '\0')
9368 remote_debug_printf ("binary downloading NOT supported by target");
9369 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9371 else
9373 remote_debug_printf ("binary downloading supported by target");
9374 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9376 break;
9381 /* Helper function to resize the payload in order to try to get a good
9382 alignment. We try to write an amount of data such that the next write will
9383 start on an address aligned on REMOTE_ALIGN_WRITES. */
9385 static int
9386 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9388 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9391 /* Write memory data directly to the remote machine.
9392 This does not inform the data cache; the data cache uses this.
9393 HEADER is the starting part of the packet.
9394 MEMADDR is the address in the remote memory space.
9395 MYADDR is the address of the buffer in our space.
9396 LEN_UNITS is the number of addressable units to write.
9397 UNIT_SIZE is the length in bytes of an addressable unit.
9398 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9399 should send data as binary ('X'), or hex-encoded ('M').
9401 The function creates packet of the form
9402 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9404 where encoding of <DATA> is terminated by PACKET_FORMAT.
9406 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9407 are omitted.
9409 Return the transferred status, error or OK (an
9410 'enum target_xfer_status' value). Save the number of addressable units
9411 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9413 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9414 exchange between gdb and the stub could look like (?? in place of the
9415 checksum):
9417 -> $m1000,4#??
9418 <- aaaabbbbccccdddd
9420 -> $M1000,3:eeeeffffeeee#??
9421 <- OK
9423 -> $m1000,4#??
9424 <- eeeeffffeeeedddd */
9426 target_xfer_status
9427 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9428 const gdb_byte *myaddr,
9429 ULONGEST len_units,
9430 int unit_size,
9431 ULONGEST *xfered_len_units,
9432 char packet_format, int use_length)
9434 struct remote_state *rs = get_remote_state ();
9435 char *p;
9436 char *plen = NULL;
9437 int plenlen = 0;
9438 int todo_units;
9439 int units_written;
9440 int payload_capacity_bytes;
9441 int payload_length_bytes;
9443 if (packet_format != 'X' && packet_format != 'M')
9444 internal_error (_("remote_write_bytes_aux: bad packet format"));
9446 if (len_units == 0)
9447 return TARGET_XFER_EOF;
9449 payload_capacity_bytes = get_memory_write_packet_size ();
9451 /* The packet buffer will be large enough for the payload;
9452 get_memory_packet_size ensures this. */
9453 rs->buf[0] = '\0';
9455 /* Compute the size of the actual payload by subtracting out the
9456 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9458 payload_capacity_bytes -= strlen ("$,:#NN");
9459 if (!use_length)
9460 /* The comma won't be used. */
9461 payload_capacity_bytes += 1;
9462 payload_capacity_bytes -= strlen (header);
9463 payload_capacity_bytes -= hexnumlen (memaddr);
9465 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9467 strcat (rs->buf.data (), header);
9468 p = rs->buf.data () + strlen (header);
9470 /* Compute a best guess of the number of bytes actually transfered. */
9471 if (packet_format == 'X')
9473 /* Best guess at number of bytes that will fit. */
9474 todo_units = std::min (len_units,
9475 (ULONGEST) payload_capacity_bytes / unit_size);
9476 if (use_length)
9477 payload_capacity_bytes -= hexnumlen (todo_units);
9478 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9480 else
9482 /* Number of bytes that will fit. */
9483 todo_units
9484 = std::min (len_units,
9485 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9486 if (use_length)
9487 payload_capacity_bytes -= hexnumlen (todo_units);
9488 todo_units = std::min (todo_units,
9489 (payload_capacity_bytes / unit_size) / 2);
9492 if (todo_units <= 0)
9493 internal_error (_("minimum packet size too small to write data"));
9495 /* If we already need another packet, then try to align the end
9496 of this packet to a useful boundary. */
9497 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9498 todo_units = align_for_efficient_write (todo_units, memaddr);
9500 /* Append "<memaddr>". */
9501 memaddr = remote_address_masked (memaddr);
9502 p += hexnumstr (p, (ULONGEST) memaddr);
9504 if (use_length)
9506 /* Append ",". */
9507 *p++ = ',';
9509 /* Append the length and retain its location and size. It may need to be
9510 adjusted once the packet body has been created. */
9511 plen = p;
9512 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9513 p += plenlen;
9516 /* Append ":". */
9517 *p++ = ':';
9518 *p = '\0';
9520 /* Append the packet body. */
9521 if (packet_format == 'X')
9523 /* Binary mode. Send target system values byte by byte, in
9524 increasing byte addresses. Only escape certain critical
9525 characters. */
9526 payload_length_bytes =
9527 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9528 &units_written, payload_capacity_bytes);
9530 /* If not all TODO units fit, then we'll need another packet. Make
9531 a second try to keep the end of the packet aligned. Don't do
9532 this if the packet is tiny. */
9533 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9535 int new_todo_units;
9537 new_todo_units = align_for_efficient_write (units_written, memaddr);
9539 if (new_todo_units != units_written)
9540 payload_length_bytes =
9541 remote_escape_output (myaddr, new_todo_units, unit_size,
9542 (gdb_byte *) p, &units_written,
9543 payload_capacity_bytes);
9546 p += payload_length_bytes;
9547 if (use_length && units_written < todo_units)
9549 /* Escape chars have filled up the buffer prematurely,
9550 and we have actually sent fewer units than planned.
9551 Fix-up the length field of the packet. Use the same
9552 number of characters as before. */
9553 plen += hexnumnstr (plen, (ULONGEST) units_written,
9554 plenlen);
9555 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9558 else
9560 /* Normal mode: Send target system values byte by byte, in
9561 increasing byte addresses. Each byte is encoded as a two hex
9562 value. */
9563 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9564 units_written = todo_units;
9567 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9568 getpkt (&rs->buf);
9570 if (rs->buf[0] == 'E')
9571 return TARGET_XFER_E_IO;
9573 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9574 send fewer units than we'd planned. */
9575 *xfered_len_units = (ULONGEST) units_written;
9576 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9579 /* Write memory data directly to the remote machine.
9580 This does not inform the data cache; the data cache uses this.
9581 MEMADDR is the address in the remote memory space.
9582 MYADDR is the address of the buffer in our space.
9583 LEN is the number of bytes.
9585 Return the transferred status, error or OK (an
9586 'enum target_xfer_status' value). Save the number of bytes
9587 transferred in *XFERED_LEN. Only transfer a single packet. */
9589 target_xfer_status
9590 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9591 ULONGEST len, int unit_size,
9592 ULONGEST *xfered_len)
9594 const char *packet_format = NULL;
9596 /* Check whether the target supports binary download. */
9597 check_binary_download (memaddr);
9599 switch (m_features.packet_support (PACKET_X))
9601 case PACKET_ENABLE:
9602 packet_format = "X";
9603 break;
9604 case PACKET_DISABLE:
9605 packet_format = "M";
9606 break;
9607 case PACKET_SUPPORT_UNKNOWN:
9608 internal_error (_("remote_write_bytes: bad internal state"));
9609 default:
9610 internal_error (_("bad switch"));
9613 return remote_write_bytes_aux (packet_format,
9614 memaddr, myaddr, len, unit_size, xfered_len,
9615 packet_format[0], 1);
9618 /* Read memory data directly from the remote machine.
9619 This does not use the data cache; the data cache uses this.
9620 MEMADDR is the address in the remote memory space.
9621 MYADDR is the address of the buffer in our space.
9622 LEN_UNITS is the number of addressable memory units to read..
9623 UNIT_SIZE is the length in bytes of an addressable unit.
9625 Return the transferred status, error or OK (an
9626 'enum target_xfer_status' value). Save the number of bytes
9627 transferred in *XFERED_LEN_UNITS.
9629 See the comment of remote_write_bytes_aux for an example of
9630 memory read/write exchange between gdb and the stub. */
9632 target_xfer_status
9633 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9634 ULONGEST len_units,
9635 int unit_size, ULONGEST *xfered_len_units)
9637 struct remote_state *rs = get_remote_state ();
9638 int buf_size_bytes; /* Max size of packet output buffer. */
9639 char *p;
9640 int todo_units;
9641 int decoded_bytes;
9643 buf_size_bytes = get_memory_read_packet_size ();
9644 /* The packet buffer will be large enough for the payload;
9645 get_memory_packet_size ensures this. */
9647 /* Number of units that will fit. */
9648 todo_units = std::min (len_units,
9649 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9651 /* Construct "m"<memaddr>","<len>". */
9652 memaddr = remote_address_masked (memaddr);
9653 p = rs->buf.data ();
9654 *p++ = 'm';
9655 p += hexnumstr (p, (ULONGEST) memaddr);
9656 *p++ = ',';
9657 p += hexnumstr (p, (ULONGEST) todo_units);
9658 *p = '\0';
9659 putpkt (rs->buf);
9660 getpkt (&rs->buf);
9661 packet_result result = packet_check_result (rs->buf);
9662 if (result.status () == PACKET_ERROR)
9663 return TARGET_XFER_E_IO;
9664 /* Reply describes memory byte by byte, each byte encoded as two hex
9665 characters. */
9666 p = rs->buf.data ();
9667 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9668 /* Return what we have. Let higher layers handle partial reads. */
9669 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9670 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9673 /* Using the set of read-only target sections of remote, read live
9674 read-only memory.
9676 For interface/parameters/return description see target.h,
9677 to_xfer_partial. */
9679 target_xfer_status
9680 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9681 ULONGEST memaddr,
9682 ULONGEST len,
9683 int unit_size,
9684 ULONGEST *xfered_len)
9686 const struct target_section *secp;
9688 secp = target_section_by_addr (this, memaddr);
9689 if (secp != NULL
9690 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9692 ULONGEST memend = memaddr + len;
9694 const std::vector<target_section> *table
9695 = target_get_section_table (this);
9696 for (const target_section &p : *table)
9698 if (memaddr >= p.addr)
9700 if (memend <= p.endaddr)
9702 /* Entire transfer is within this section. */
9703 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9704 xfered_len);
9706 else if (memaddr >= p.endaddr)
9708 /* This section ends before the transfer starts. */
9709 continue;
9711 else
9713 /* This section overlaps the transfer. Just do half. */
9714 len = p.endaddr - memaddr;
9715 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9716 xfered_len);
9722 return TARGET_XFER_EOF;
9725 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9726 first if the requested memory is unavailable in traceframe.
9727 Otherwise, fall back to remote_read_bytes_1. */
9729 target_xfer_status
9730 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9731 gdb_byte *myaddr, ULONGEST len, int unit_size,
9732 ULONGEST *xfered_len)
9734 if (len == 0)
9735 return TARGET_XFER_EOF;
9737 if (get_traceframe_number () != -1)
9739 std::vector<mem_range> available;
9741 /* If we fail to get the set of available memory, then the
9742 target does not support querying traceframe info, and so we
9743 attempt reading from the traceframe anyway (assuming the
9744 target implements the old QTro packet then). */
9745 if (traceframe_available_memory (&available, memaddr, len))
9747 if (available.empty () || available[0].start != memaddr)
9749 enum target_xfer_status res;
9751 /* Don't read into the traceframe's available
9752 memory. */
9753 if (!available.empty ())
9755 LONGEST oldlen = len;
9757 len = available[0].start - memaddr;
9758 gdb_assert (len <= oldlen);
9761 /* This goes through the topmost target again. */
9762 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9763 len, unit_size, xfered_len);
9764 if (res == TARGET_XFER_OK)
9765 return TARGET_XFER_OK;
9766 else
9768 /* No use trying further, we know some memory starting
9769 at MEMADDR isn't available. */
9770 *xfered_len = len;
9771 return (*xfered_len != 0) ?
9772 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9776 /* Don't try to read more than how much is available, in
9777 case the target implements the deprecated QTro packet to
9778 cater for older GDBs (the target's knowledge of read-only
9779 sections may be outdated by now). */
9780 len = available[0].length;
9784 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9789 /* Sends a packet with content determined by the printf format string
9790 FORMAT and the remaining arguments, then gets the reply. Returns
9791 whether the packet was a success, a failure, or unknown. */
9793 packet_status
9794 remote_target::remote_send_printf (const char *format, ...)
9796 struct remote_state *rs = get_remote_state ();
9797 int max_size = get_remote_packet_size ();
9798 va_list ap;
9800 va_start (ap, format);
9802 rs->buf[0] = '\0';
9803 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9805 va_end (ap);
9807 if (size >= max_size)
9808 internal_error (_("Too long remote packet."));
9810 if (putpkt (rs->buf) < 0)
9811 error (_("Communication problem with target."));
9813 rs->buf[0] = '\0';
9814 getpkt (&rs->buf);
9816 return packet_check_result (rs->buf).status ();
9819 /* Flash writing can take quite some time. We'll set
9820 effectively infinite timeout for flash operations.
9821 In future, we'll need to decide on a better approach. */
9822 static const int remote_flash_timeout = 1000;
9824 void
9825 remote_target::flash_erase (ULONGEST address, LONGEST length)
9827 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9828 enum packet_status ret;
9829 scoped_restore restore_timeout
9830 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9832 ret = remote_send_printf ("vFlashErase:%s,%s",
9833 phex (address, addr_size),
9834 phex (length, 4));
9835 switch (ret)
9837 case PACKET_UNKNOWN:
9838 error (_("Remote target does not support flash erase"));
9839 case PACKET_ERROR:
9840 error (_("Error erasing flash with vFlashErase packet"));
9841 default:
9842 break;
9846 target_xfer_status
9847 remote_target::remote_flash_write (ULONGEST address,
9848 ULONGEST length, ULONGEST *xfered_len,
9849 const gdb_byte *data)
9851 scoped_restore restore_timeout
9852 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9853 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9854 xfered_len,'X', 0);
9857 void
9858 remote_target::flash_done ()
9860 int ret;
9862 scoped_restore restore_timeout
9863 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9865 ret = remote_send_printf ("vFlashDone");
9867 switch (ret)
9869 case PACKET_UNKNOWN:
9870 error (_("Remote target does not support vFlashDone"));
9871 case PACKET_ERROR:
9872 error (_("Error finishing flash operation"));
9873 default:
9874 break;
9879 /* Stuff for dealing with the packets which are part of this protocol.
9880 See comment at top of file for details. */
9882 /* Read a single character from the remote end. The current quit
9883 handler is overridden to avoid quitting in the middle of packet
9884 sequence, as that would break communication with the remote server.
9885 See remote_serial_quit_handler for more detail. */
9888 remote_target::readchar (int timeout)
9890 int ch;
9891 struct remote_state *rs = get_remote_state ();
9895 scoped_restore restore_quit_target
9896 = make_scoped_restore (&curr_quit_handler_target, this);
9897 scoped_restore restore_quit
9898 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9900 rs->got_ctrlc_during_io = 0;
9902 ch = serial_readchar (rs->remote_desc, timeout);
9904 if (rs->got_ctrlc_during_io)
9905 set_quit_flag ();
9907 catch (const gdb_exception_error &ex)
9909 remote_unpush_target (this);
9910 throw_error (TARGET_CLOSE_ERROR,
9911 _("Remote communication error. "
9912 "Target disconnected: %s"),
9913 ex.what ());
9916 if (ch >= 0)
9917 return ch;
9919 if (ch == SERIAL_EOF)
9921 remote_unpush_target (this);
9922 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9925 return ch;
9928 /* Wrapper for serial_write that closes the target and throws if
9929 writing fails. The current quit handler is overridden to avoid
9930 quitting in the middle of packet sequence, as that would break
9931 communication with the remote server. See
9932 remote_serial_quit_handler for more detail. */
9934 void
9935 remote_target::remote_serial_write (const char *str, int len)
9937 struct remote_state *rs = get_remote_state ();
9939 scoped_restore restore_quit_target
9940 = make_scoped_restore (&curr_quit_handler_target, this);
9941 scoped_restore restore_quit
9942 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9944 rs->got_ctrlc_during_io = 0;
9948 serial_write (rs->remote_desc, str, len);
9950 catch (const gdb_exception_error &ex)
9952 remote_unpush_target (this);
9953 throw_error (TARGET_CLOSE_ERROR,
9954 _("Remote communication error. "
9955 "Target disconnected: %s"),
9956 ex.what ());
9959 if (rs->got_ctrlc_during_io)
9960 set_quit_flag ();
9963 void
9964 remote_target::remote_serial_send_break ()
9966 struct remote_state *rs = get_remote_state ();
9970 serial_send_break (rs->remote_desc);
9972 catch (const gdb_exception_error &ex)
9974 remote_unpush_target (this);
9975 throw_error (TARGET_CLOSE_ERROR,
9976 _("Remote communication error. "
9977 "Target disconnected: %s"),
9978 ex.what ());
9982 /* Return a string representing an escaped version of BUF, of len N.
9983 E.g. \n is converted to \\n, \t to \\t, etc. */
9985 static std::string
9986 escape_buffer (const char *buf, int n)
9988 string_file stb;
9990 stb.putstrn (buf, n, '\\');
9991 return stb.release ();
9995 remote_target::putpkt (const char *buf)
9997 return putpkt_binary (buf, strlen (buf));
10000 /* Wrapper around remote_target::putpkt to avoid exporting
10001 remote_target. */
10004 putpkt (remote_target *remote, const char *buf)
10006 return remote->putpkt (buf);
10009 /* Send a packet to the remote machine, with error checking. The data
10010 of the packet is in BUF. The string in BUF can be at most
10011 get_remote_packet_size () - 5 to account for the $, # and checksum,
10012 and for a possible /0 if we are debugging (remote_debug) and want
10013 to print the sent packet as a string. */
10016 remote_target::putpkt_binary (const char *buf, int cnt)
10018 struct remote_state *rs = get_remote_state ();
10019 int i;
10020 unsigned char csum = 0;
10021 gdb::def_vector<char> data (cnt + 6);
10022 char *buf2 = data.data ();
10024 int ch;
10025 int tcount = 0;
10026 char *p;
10028 /* Catch cases like trying to read memory or listing threads while
10029 we're waiting for a stop reply. The remote server wouldn't be
10030 ready to handle this request, so we'd hang and timeout. We don't
10031 have to worry about this in synchronous mode, because in that
10032 case it's not possible to issue a command while the target is
10033 running. This is not a problem in non-stop mode, because in that
10034 case, the stub is always ready to process serial input. */
10035 if (!target_is_non_stop_p ()
10036 && target_is_async_p ()
10037 && rs->waiting_for_stop_reply)
10039 error (_("Cannot execute this command while the target is running.\n"
10040 "Use the \"interrupt\" command to stop the target\n"
10041 "and then try again."));
10044 /* Copy the packet into buffer BUF2, encapsulating it
10045 and giving it a checksum. */
10047 p = buf2;
10048 *p++ = '$';
10050 for (i = 0; i < cnt; i++)
10052 csum += buf[i];
10053 *p++ = buf[i];
10055 *p++ = '#';
10056 *p++ = tohex ((csum >> 4) & 0xf);
10057 *p++ = tohex (csum & 0xf);
10059 /* Send it over and over until we get a positive ack. */
10061 while (1)
10063 if (remote_debug)
10065 *p = '\0';
10067 int len = (int) (p - buf2);
10068 int max_chars;
10070 if (remote_packet_max_chars < 0)
10071 max_chars = len;
10072 else
10073 max_chars = remote_packet_max_chars;
10075 std::string str
10076 = escape_buffer (buf2, std::min (len, max_chars));
10078 if (len > max_chars)
10079 remote_debug_printf_nofunc
10080 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
10081 len - max_chars);
10082 else
10083 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
10085 remote_serial_write (buf2, p - buf2);
10087 /* If this is a no acks version of the remote protocol, send the
10088 packet and move on. */
10089 if (rs->noack_mode)
10090 break;
10092 /* Read until either a timeout occurs (-2) or '+' is read.
10093 Handle any notification that arrives in the mean time. */
10094 while (1)
10096 ch = readchar (remote_timeout);
10098 switch (ch)
10100 case '+':
10101 remote_debug_printf_nofunc ("Received Ack");
10102 return 1;
10103 case '-':
10104 remote_debug_printf_nofunc ("Received Nak");
10105 [[fallthrough]];
10106 case SERIAL_TIMEOUT:
10107 tcount++;
10108 if (tcount > 3)
10109 return 0;
10110 break; /* Retransmit buffer. */
10111 case '$':
10113 remote_debug_printf ("Packet instead of Ack, ignoring it");
10114 /* It's probably an old response sent because an ACK
10115 was lost. Gobble up the packet and ack it so it
10116 doesn't get retransmitted when we resend this
10117 packet. */
10118 skip_frame ();
10119 remote_serial_write ("+", 1);
10120 continue; /* Now, go look for +. */
10123 case '%':
10125 int val;
10127 /* If we got a notification, handle it, and go back to looking
10128 for an ack. */
10129 /* We've found the start of a notification. Now
10130 collect the data. */
10131 val = read_frame (&rs->buf);
10132 if (val >= 0)
10134 remote_debug_printf_nofunc
10135 (" Notification received: %s",
10136 escape_buffer (rs->buf.data (), val).c_str ());
10138 handle_notification (rs->notif_state, rs->buf.data ());
10139 /* We're in sync now, rewait for the ack. */
10140 tcount = 0;
10142 else
10143 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10144 rs->buf.data ());
10145 continue;
10147 default:
10148 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10149 rs->buf.data ());
10150 continue;
10152 break; /* Here to retransmit. */
10155 #if 0
10156 /* This is wrong. If doing a long backtrace, the user should be
10157 able to get out next time we call QUIT, without anything as
10158 violent as interrupt_query. If we want to provide a way out of
10159 here without getting to the next QUIT, it should be based on
10160 hitting ^C twice as in remote_wait. */
10161 if (quit_flag)
10163 quit_flag = 0;
10164 interrupt_query ();
10166 #endif
10169 return 0;
10172 /* Come here after finding the start of a frame when we expected an
10173 ack. Do our best to discard the rest of this packet. */
10175 void
10176 remote_target::skip_frame ()
10178 int c;
10180 while (1)
10182 c = readchar (remote_timeout);
10183 switch (c)
10185 case SERIAL_TIMEOUT:
10186 /* Nothing we can do. */
10187 return;
10188 case '#':
10189 /* Discard the two bytes of checksum and stop. */
10190 c = readchar (remote_timeout);
10191 if (c >= 0)
10192 c = readchar (remote_timeout);
10194 return;
10195 case '*': /* Run length encoding. */
10196 /* Discard the repeat count. */
10197 c = readchar (remote_timeout);
10198 if (c < 0)
10199 return;
10200 break;
10201 default:
10202 /* A regular character. */
10203 break;
10208 /* Come here after finding the start of the frame. Collect the rest
10209 into *BUF, verifying the checksum, length, and handling run-length
10210 compression. NUL terminate the buffer. If there is not enough room,
10211 expand *BUF.
10213 Returns -1 on error, number of characters in buffer (ignoring the
10214 trailing NULL) on success. (could be extended to return one of the
10215 SERIAL status indications). */
10217 long
10218 remote_target::read_frame (gdb::char_vector *buf_p)
10220 unsigned char csum;
10221 long bc;
10222 int c;
10223 char *buf = buf_p->data ();
10224 struct remote_state *rs = get_remote_state ();
10226 csum = 0;
10227 bc = 0;
10229 while (1)
10231 c = readchar (remote_timeout);
10232 switch (c)
10234 case SERIAL_TIMEOUT:
10235 remote_debug_printf ("Timeout in mid-packet, retrying");
10236 return -1;
10238 case '$':
10239 remote_debug_printf ("Saw new packet start in middle of old one");
10240 return -1; /* Start a new packet, count retries. */
10242 case '#':
10244 unsigned char pktcsum;
10245 int check_0 = 0;
10246 int check_1 = 0;
10248 buf[bc] = '\0';
10250 check_0 = readchar (remote_timeout);
10251 if (check_0 >= 0)
10252 check_1 = readchar (remote_timeout);
10254 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10256 remote_debug_printf ("Timeout in checksum, retrying");
10257 return -1;
10259 else if (check_0 < 0 || check_1 < 0)
10261 remote_debug_printf ("Communication error in checksum");
10262 return -1;
10265 /* Don't recompute the checksum; with no ack packets we
10266 don't have any way to indicate a packet retransmission
10267 is necessary. */
10268 if (rs->noack_mode)
10269 return bc;
10271 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10272 if (csum == pktcsum)
10273 return bc;
10275 remote_debug_printf
10276 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10277 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10279 /* Number of characters in buffer ignoring trailing
10280 NULL. */
10281 return -1;
10283 case '*': /* Run length encoding. */
10285 int repeat;
10287 csum += c;
10288 c = readchar (remote_timeout);
10289 csum += c;
10290 repeat = c - ' ' + 3; /* Compute repeat count. */
10292 /* The character before ``*'' is repeated. */
10294 if (repeat > 0 && repeat <= 255 && bc > 0)
10296 if (bc + repeat - 1 >= buf_p->size () - 1)
10298 /* Make some more room in the buffer. */
10299 buf_p->resize (buf_p->size () + repeat);
10300 buf = buf_p->data ();
10303 memset (&buf[bc], buf[bc - 1], repeat);
10304 bc += repeat;
10305 continue;
10308 buf[bc] = '\0';
10309 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10310 return -1;
10312 default:
10313 if (bc >= buf_p->size () - 1)
10315 /* Make some more room in the buffer. */
10316 buf_p->resize (buf_p->size () * 2);
10317 buf = buf_p->data ();
10320 buf[bc++] = c;
10321 csum += c;
10322 continue;
10327 /* Set this to the maximum number of seconds to wait instead of waiting forever
10328 in target_wait(). If this timer times out, then it generates an error and
10329 the command is aborted. This replaces most of the need for timeouts in the
10330 GDB test suite, and makes it possible to distinguish between a hung target
10331 and one with slow communications. */
10333 static int watchdog = 0;
10334 static void
10335 show_watchdog (struct ui_file *file, int from_tty,
10336 struct cmd_list_element *c, const char *value)
10338 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10341 /* Read a packet from the remote machine, with error checking, and
10342 store it in *BUF. Resize *BUF if necessary to hold the result. If
10343 FOREVER, wait forever rather than timing out; this is used (in
10344 synchronous mode) to wait for a target that is is executing user
10345 code to stop. If FOREVER == false, this function is allowed to time
10346 out gracefully and return an indication of this to the caller.
10347 Otherwise return the number of bytes read. If IS_NOTIF is not
10348 NULL, then consider receiving a notification enough reason to
10349 return to the caller. In this case, *IS_NOTIF is an output boolean
10350 that indicates whether *BUF holds a notification or not (a regular
10351 packet). */
10354 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10356 struct remote_state *rs = get_remote_state ();
10357 int c;
10358 int tries;
10359 int timeout;
10360 int val = -1;
10362 strcpy (buf->data (), "timeout");
10364 if (forever)
10365 timeout = watchdog > 0 ? watchdog : -1;
10366 else if (is_notif != nullptr)
10367 timeout = 0; /* There should already be a char in the buffer. If
10368 not, bail out. */
10369 else
10370 timeout = remote_timeout;
10372 #define MAX_TRIES 3
10374 /* Process any number of notifications, and then return when
10375 we get a packet. */
10376 for (;;)
10378 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10379 times. */
10380 for (tries = 1; tries <= MAX_TRIES; tries++)
10382 /* This can loop forever if the remote side sends us
10383 characters continuously, but if it pauses, we'll get
10384 SERIAL_TIMEOUT from readchar because of timeout. Then
10385 we'll count that as a retry.
10387 Note that even when forever is set, we will only wait
10388 forever prior to the start of a packet. After that, we
10389 expect characters to arrive at a brisk pace. They should
10390 show up within remote_timeout intervals. */
10392 c = readchar (timeout);
10393 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10395 if (c == SERIAL_TIMEOUT)
10397 if (is_notif != nullptr)
10398 return -1; /* Don't complain, it's normal to not get
10399 anything in this case. */
10401 if (forever) /* Watchdog went off? Kill the target. */
10403 remote_unpush_target (this);
10404 throw_error (TARGET_CLOSE_ERROR,
10405 _("Watchdog timeout has expired. "
10406 "Target detached."));
10409 remote_debug_printf ("Timed out.");
10411 else
10413 /* We've found the start of a packet or notification.
10414 Now collect the data. */
10415 val = read_frame (buf);
10416 if (val >= 0)
10417 break;
10420 remote_serial_write ("-", 1);
10423 if (tries > MAX_TRIES)
10425 /* We have tried hard enough, and just can't receive the
10426 packet/notification. Give up. */
10427 gdb_printf (_("Ignoring packet error, continuing...\n"));
10429 /* Skip the ack char if we're in no-ack mode. */
10430 if (!rs->noack_mode)
10431 remote_serial_write ("+", 1);
10432 return -1;
10435 /* If we got an ordinary packet, return that to our caller. */
10436 if (c == '$')
10438 if (remote_debug)
10440 int max_chars;
10442 if (remote_packet_max_chars < 0)
10443 max_chars = val;
10444 else
10445 max_chars = remote_packet_max_chars;
10447 std::string str
10448 = escape_buffer (buf->data (),
10449 std::min (val, max_chars));
10451 if (val > max_chars)
10452 remote_debug_printf_nofunc
10453 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10454 val - max_chars);
10455 else
10456 remote_debug_printf_nofunc ("Packet received: %s",
10457 str.c_str ());
10460 /* Skip the ack char if we're in no-ack mode. */
10461 if (!rs->noack_mode)
10462 remote_serial_write ("+", 1);
10463 if (is_notif != NULL)
10464 *is_notif = false;
10465 return val;
10468 /* If we got a notification, handle it, and go back to looking
10469 for a packet. */
10470 else
10472 gdb_assert (c == '%');
10474 remote_debug_printf_nofunc
10475 (" Notification received: %s",
10476 escape_buffer (buf->data (), val).c_str ());
10478 if (is_notif != NULL)
10479 *is_notif = true;
10481 handle_notification (rs->notif_state, buf->data ());
10483 /* Notifications require no acknowledgement. */
10485 if (is_notif != nullptr)
10486 return val;
10491 /* Kill any new fork children of inferior INF that haven't been
10492 processed by follow_fork. */
10494 void
10495 remote_target::kill_new_fork_children (inferior *inf)
10497 remote_state *rs = get_remote_state ();
10498 const notif_client *notif = &notif_client_stop;
10500 /* Kill the fork child threads of any threads in inferior INF that are stopped
10501 at a fork event. */
10502 for (thread_info *thread : inf->non_exited_threads ())
10504 const target_waitstatus *ws = thread_pending_fork_status (thread);
10506 if (ws == nullptr)
10507 continue;
10509 int child_pid = ws->child_ptid ().pid ();
10510 int res = remote_vkill (child_pid);
10512 if (res != 0)
10513 error (_("Can't kill fork child process %d"), child_pid);
10516 /* Check for any pending fork events (not reported or processed yet)
10517 in inferior INF and kill those fork child threads as well. */
10518 remote_notif_get_pending_events (notif);
10519 for (auto &event : rs->stop_reply_queue)
10521 if (event->ptid.pid () != inf->pid)
10522 continue;
10524 if (!is_fork_status (event->ws.kind ()))
10525 continue;
10527 int child_pid = event->ws.child_ptid ().pid ();
10528 int res = remote_vkill (child_pid);
10530 if (res != 0)
10531 error (_("Can't kill fork child process %d"), child_pid);
10536 /* Target hook to kill the current inferior. */
10538 void
10539 remote_target::kill ()
10541 int res = -1;
10542 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10544 gdb_assert (inf != nullptr);
10546 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10548 /* If we're stopped while forking and we haven't followed yet,
10549 kill the child task. We need to do this before killing the
10550 parent task because if this is a vfork then the parent will
10551 be sleeping. */
10552 kill_new_fork_children (inf);
10554 res = remote_vkill (inf->pid);
10555 if (res == 0)
10557 target_mourn_inferior (inferior_ptid);
10558 return;
10562 /* If we are in 'target remote' mode and we are killing the only
10563 inferior, then we will tell gdbserver to exit and unpush the
10564 target. */
10565 if (res == -1 && !m_features.remote_multi_process_p ()
10566 && number_of_live_inferiors (this) == 1)
10568 remote_kill_k ();
10570 /* We've killed the remote end, we get to mourn it. If we are
10571 not in extended mode, mourning the inferior also unpushes
10572 remote_ops from the target stack, which closes the remote
10573 connection. */
10574 target_mourn_inferior (inferior_ptid);
10576 return;
10579 error (_("Can't kill process"));
10582 /* Send a kill request to the target using the 'vKill' packet. */
10585 remote_target::remote_vkill (int pid)
10587 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10588 return -1;
10590 remote_state *rs = get_remote_state ();
10592 /* Tell the remote target to detach. */
10593 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10594 putpkt (rs->buf);
10595 getpkt (&rs->buf);
10597 switch ((m_features.packet_ok (rs->buf, PACKET_vKill)).status ())
10599 case PACKET_OK:
10600 return 0;
10601 case PACKET_ERROR:
10602 return 1;
10603 case PACKET_UNKNOWN:
10604 return -1;
10605 default:
10606 internal_error (_("Bad result from packet_ok"));
10610 /* Send a kill request to the target using the 'k' packet. */
10612 void
10613 remote_target::remote_kill_k ()
10615 /* Catch errors so the user can quit from gdb even when we
10616 aren't on speaking terms with the remote system. */
10619 putpkt ("k");
10621 catch (const gdb_exception_error &ex)
10623 if (ex.error == TARGET_CLOSE_ERROR)
10625 /* If we got an (EOF) error that caused the target
10626 to go away, then we're done, that's what we wanted.
10627 "k" is susceptible to cause a premature EOF, given
10628 that the remote server isn't actually required to
10629 reply to "k", and it can happen that it doesn't
10630 even get to reply ACK to the "k". */
10631 return;
10634 /* Otherwise, something went wrong. We didn't actually kill
10635 the target. Just propagate the exception, and let the
10636 user or higher layers decide what to do. */
10637 throw;
10641 void
10642 remote_target::mourn_inferior ()
10644 struct remote_state *rs = get_remote_state ();
10646 /* We're no longer interested in notification events of an inferior
10647 that exited or was killed/detached. */
10648 discard_pending_stop_replies (current_inferior ());
10650 /* In 'target remote' mode with one inferior, we close the connection. */
10651 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10653 remote_unpush_target (this);
10654 return;
10657 /* In case we got here due to an error, but we're going to stay
10658 connected. */
10659 rs->waiting_for_stop_reply = 0;
10661 /* If the current general thread belonged to the process we just
10662 detached from or has exited, the remote side current general
10663 thread becomes undefined. Considering a case like this:
10665 - We just got here due to a detach.
10666 - The process that we're detaching from happens to immediately
10667 report a global breakpoint being hit in non-stop mode, in the
10668 same thread we had selected before.
10669 - GDB attaches to this process again.
10670 - This event happens to be the next event we handle.
10672 GDB would consider that the current general thread didn't need to
10673 be set on the stub side (with Hg), since for all it knew,
10674 GENERAL_THREAD hadn't changed.
10676 Notice that although in all-stop mode, the remote server always
10677 sets the current thread to the thread reporting the stop event,
10678 that doesn't happen in non-stop mode; in non-stop, the stub *must
10679 not* change the current thread when reporting a breakpoint hit,
10680 due to the decoupling of event reporting and event handling.
10682 To keep things simple, we always invalidate our notion of the
10683 current thread. */
10684 record_currthread (rs, minus_one_ptid);
10686 /* Call common code to mark the inferior as not running. */
10687 generic_mourn_inferior ();
10690 bool
10691 extended_remote_target::supports_disable_randomization ()
10693 return (m_features.packet_support (PACKET_QDisableRandomization)
10694 == PACKET_ENABLE);
10697 void
10698 remote_target::extended_remote_disable_randomization (int val)
10700 struct remote_state *rs = get_remote_state ();
10701 char *reply;
10703 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10704 "QDisableRandomization:%x", val);
10705 putpkt (rs->buf);
10706 reply = remote_get_noisy_reply ();
10707 if (*reply == '\0')
10708 error (_("Target does not support QDisableRandomization."));
10709 if (strcmp (reply, "OK") != 0)
10710 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10714 remote_target::extended_remote_run (const std::string &args)
10716 struct remote_state *rs = get_remote_state ();
10717 int len;
10718 const char *remote_exec_file = get_remote_exec_file ();
10720 /* If the user has disabled vRun support, or we have detected that
10721 support is not available, do not try it. */
10722 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10723 return -1;
10725 strcpy (rs->buf.data (), "vRun;");
10726 len = strlen (rs->buf.data ());
10728 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10729 error (_("Remote file name too long for run packet"));
10730 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10731 strlen (remote_exec_file));
10733 if (!args.empty ())
10735 int i;
10737 gdb_argv argv (args.c_str ());
10738 for (i = 0; argv[i] != NULL; i++)
10740 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10741 error (_("Argument list too long for run packet"));
10742 rs->buf[len++] = ';';
10743 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10744 strlen (argv[i]));
10748 rs->buf[len++] = '\0';
10750 putpkt (rs->buf);
10751 getpkt (&rs->buf);
10753 packet_result result = m_features.packet_ok (rs->buf, PACKET_vRun);
10754 switch (result.status ())
10756 case PACKET_OK:
10757 /* We have a wait response. All is well. */
10758 return 0;
10759 case PACKET_UNKNOWN:
10760 return -1;
10761 case PACKET_ERROR:
10762 /* If we have a textual error message, print just that. This
10763 makes remote debugging output the same as native output, when
10764 possible. */
10765 if (result.textual_err_msg ())
10766 error (("%s"), result.err_msg ());
10767 if (remote_exec_file[0] == '\0')
10768 error (_("Running the default executable on the remote target failed; "
10769 "try \"set remote exec-file\"?"));
10770 else
10771 error (_("Running \"%s\" on the remote target failed"),
10772 remote_exec_file);
10773 default:
10774 gdb_assert_not_reached ("bad switch");
10778 /* Helper function to send set/unset environment packets. ACTION is
10779 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10780 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10781 sent. */
10783 void
10784 remote_target::send_environment_packet (const char *action,
10785 const char *packet,
10786 const char *value)
10788 remote_state *rs = get_remote_state ();
10790 /* Convert the environment variable to an hex string, which
10791 is the best format to be transmitted over the wire. */
10792 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10793 strlen (value));
10795 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10796 "%s:%s", packet, encoded_value.c_str ());
10798 putpkt (rs->buf);
10799 getpkt (&rs->buf);
10800 if (strcmp (rs->buf.data (), "OK") != 0)
10801 warning (_("Unable to %s environment variable '%s' on remote."),
10802 action, value);
10805 /* Helper function to handle the QEnvironment* packets. */
10807 void
10808 remote_target::extended_remote_environment_support ()
10810 remote_state *rs = get_remote_state ();
10812 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10814 putpkt ("QEnvironmentReset");
10815 getpkt (&rs->buf);
10816 if (strcmp (rs->buf.data (), "OK") != 0)
10817 warning (_("Unable to reset environment on remote."));
10820 gdb_environ *e = &current_inferior ()->environment;
10822 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10823 != PACKET_DISABLE)
10825 for (const std::string &el : e->user_set_env ())
10826 send_environment_packet ("set", "QEnvironmentHexEncoded",
10827 el.c_str ());
10831 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10832 for (const std::string &el : e->user_unset_env ())
10833 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10836 /* Helper function to set the current working directory for the
10837 inferior in the remote target. */
10839 void
10840 remote_target::extended_remote_set_inferior_cwd ()
10842 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10844 const std::string &inferior_cwd = current_inferior ()->cwd ();
10845 remote_state *rs = get_remote_state ();
10847 if (!inferior_cwd.empty ())
10849 std::string hexpath
10850 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10851 inferior_cwd.size ());
10853 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10854 "QSetWorkingDir:%s", hexpath.c_str ());
10856 else
10858 /* An empty inferior_cwd means that the user wants us to
10859 reset the remote server's inferior's cwd. */
10860 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10861 "QSetWorkingDir:");
10864 putpkt (rs->buf);
10865 getpkt (&rs->buf);
10866 packet_result result = m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir);
10867 if (result.status () == PACKET_ERROR)
10868 error (_("\
10869 Remote replied unexpectedly while setting the inferior's working\n\
10870 directory: %s"),
10871 result.err_msg ());
10872 if (result.status () == PACKET_UNKNOWN)
10873 error (_("Remote target failed to process setting the inferior's working directory"));
10878 /* In the extended protocol we want to be able to do things like
10879 "run" and have them basically work as expected. So we need
10880 a special create_inferior function. We support changing the
10881 executable file and the command line arguments, but not the
10882 environment. */
10884 void
10885 extended_remote_target::create_inferior (const char *exec_file,
10886 const std::string &args,
10887 char **env, int from_tty)
10889 int run_worked;
10890 char *stop_reply;
10891 struct remote_state *rs = get_remote_state ();
10892 const char *remote_exec_file = get_remote_exec_file ();
10894 /* If running asynchronously, register the target file descriptor
10895 with the event loop. */
10896 if (target_can_async_p ())
10897 target_async (true);
10899 /* Disable address space randomization if requested (and supported). */
10900 if (supports_disable_randomization ())
10901 extended_remote_disable_randomization (disable_randomization);
10903 /* If startup-with-shell is on, we inform gdbserver to start the
10904 remote inferior using a shell. */
10905 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10907 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10908 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10909 putpkt (rs->buf);
10910 getpkt (&rs->buf);
10911 if (strcmp (rs->buf.data (), "OK") != 0)
10912 error (_("\
10913 Remote replied unexpectedly while setting startup-with-shell: %s"),
10914 rs->buf.data ());
10917 extended_remote_environment_support ();
10919 extended_remote_set_inferior_cwd ();
10921 /* Now restart the remote server. */
10922 run_worked = extended_remote_run (args) != -1;
10923 if (!run_worked)
10925 /* vRun was not supported. Fail if we need it to do what the
10926 user requested. */
10927 if (remote_exec_file[0])
10928 error (_("Remote target does not support \"set remote exec-file\""));
10929 if (!args.empty ())
10930 error (_("Remote target does not support \"set args\" or run ARGS"));
10932 /* Fall back to "R". */
10933 extended_remote_restart ();
10936 /* vRun's success return is a stop reply. */
10937 stop_reply = run_worked ? rs->buf.data () : NULL;
10938 add_current_inferior_and_thread (stop_reply);
10940 /* Get updated offsets, if the stub uses qOffsets. */
10941 get_offsets ();
10945 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10946 the list of conditions (in agent expression bytecode format), if any, the
10947 target needs to evaluate. The output is placed into the packet buffer
10948 started from BUF and ended at BUF_END. */
10950 static int
10951 remote_add_target_side_condition (struct gdbarch *gdbarch,
10952 struct bp_target_info *bp_tgt, char *buf,
10953 char *buf_end)
10955 if (bp_tgt->conditions.empty ())
10956 return 0;
10958 buf += strlen (buf);
10959 xsnprintf (buf, buf_end - buf, "%s", ";");
10960 buf++;
10962 /* Send conditions to the target. */
10963 for (agent_expr *aexpr : bp_tgt->conditions)
10965 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10966 buf += strlen (buf);
10967 for (int i = 0; i < aexpr->buf.size (); ++i)
10968 buf = pack_hex_byte (buf, aexpr->buf[i]);
10969 *buf = '\0';
10971 return 0;
10974 static void
10975 remote_add_target_side_commands (struct gdbarch *gdbarch,
10976 struct bp_target_info *bp_tgt, char *buf)
10978 if (bp_tgt->tcommands.empty ())
10979 return;
10981 buf += strlen (buf);
10983 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10984 buf += strlen (buf);
10986 /* Concatenate all the agent expressions that are commands into the
10987 cmds parameter. */
10988 for (agent_expr *aexpr : bp_tgt->tcommands)
10990 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10991 buf += strlen (buf);
10992 for (int i = 0; i < aexpr->buf.size (); ++i)
10993 buf = pack_hex_byte (buf, aexpr->buf[i]);
10994 *buf = '\0';
10998 /* Insert a breakpoint. On targets that have software breakpoint
10999 support, we ask the remote target to do the work; on targets
11000 which don't, we insert a traditional memory breakpoint. */
11003 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
11004 struct bp_target_info *bp_tgt)
11006 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
11007 If it succeeds, then set the support to PACKET_ENABLE. If it
11008 fails, and the user has explicitly requested the Z support then
11009 report an error, otherwise, mark it disabled and go on. */
11011 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11013 CORE_ADDR addr = bp_tgt->reqstd_address;
11014 struct remote_state *rs;
11015 char *p, *endbuf;
11017 /* Make sure the remote is pointing at the right process, if
11018 necessary. */
11019 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11020 set_general_process ();
11022 rs = get_remote_state ();
11023 p = rs->buf.data ();
11024 endbuf = p + get_remote_packet_size ();
11026 *(p++) = 'Z';
11027 *(p++) = '0';
11028 *(p++) = ',';
11029 addr = (ULONGEST) remote_address_masked (addr);
11030 p += hexnumstr (p, addr);
11031 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11033 if (supports_evaluation_of_breakpoint_conditions ())
11034 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11036 if (can_run_breakpoint_commands ())
11037 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11039 putpkt (rs->buf);
11040 getpkt (&rs->buf);
11042 switch ((m_features.packet_ok (rs->buf, PACKET_Z0)).status ())
11044 case PACKET_ERROR:
11045 return -1;
11046 case PACKET_OK:
11047 return 0;
11048 case PACKET_UNKNOWN:
11049 break;
11053 /* If this breakpoint has target-side commands but this stub doesn't
11054 support Z0 packets, throw error. */
11055 if (!bp_tgt->tcommands.empty ())
11056 throw_error (NOT_SUPPORTED_ERROR, _("\
11057 Target doesn't support breakpoints that have target side commands."));
11059 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
11063 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
11064 struct bp_target_info *bp_tgt,
11065 enum remove_bp_reason reason)
11067 CORE_ADDR addr = bp_tgt->placed_address;
11068 struct remote_state *rs = get_remote_state ();
11070 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11072 char *p = rs->buf.data ();
11073 char *endbuf = p + get_remote_packet_size ();
11075 /* Make sure the remote is pointing at the right process, if
11076 necessary. */
11077 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11078 set_general_process ();
11080 *(p++) = 'z';
11081 *(p++) = '0';
11082 *(p++) = ',';
11084 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
11085 p += hexnumstr (p, addr);
11086 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11088 putpkt (rs->buf);
11089 getpkt (&rs->buf);
11091 return (rs->buf[0] == 'E');
11094 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
11097 static enum Z_packet_type
11098 watchpoint_to_Z_packet (int type)
11100 switch (type)
11102 case hw_write:
11103 return Z_PACKET_WRITE_WP;
11104 break;
11105 case hw_read:
11106 return Z_PACKET_READ_WP;
11107 break;
11108 case hw_access:
11109 return Z_PACKET_ACCESS_WP;
11110 break;
11111 default:
11112 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
11117 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
11118 enum target_hw_bp_type type, struct expression *cond)
11120 struct remote_state *rs = get_remote_state ();
11121 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11122 char *p;
11123 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11125 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11126 + to_underlying (packet))) == PACKET_DISABLE)
11127 return 1;
11129 /* Make sure the remote is pointing at the right process, if
11130 necessary. */
11131 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11132 set_general_process ();
11134 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11135 p = strchr (rs->buf.data (), '\0');
11136 addr = remote_address_masked (addr);
11137 p += hexnumstr (p, (ULONGEST) addr);
11138 xsnprintf (p, endbuf - p, ",%x", len);
11140 putpkt (rs->buf);
11141 getpkt (&rs->buf);
11143 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11144 + to_underlying (packet)))).status ())
11146 case PACKET_ERROR:
11147 return -1;
11148 case PACKET_UNKNOWN:
11149 return 1;
11150 case PACKET_OK:
11151 return 0;
11153 internal_error (_("remote_insert_watchpoint: reached end of function"));
11156 bool
11157 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11158 CORE_ADDR start, int length)
11160 CORE_ADDR diff = remote_address_masked (addr - start);
11162 return diff < length;
11167 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11168 enum target_hw_bp_type type, struct expression *cond)
11170 struct remote_state *rs = get_remote_state ();
11171 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11172 char *p;
11173 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11175 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11176 + to_underlying (packet))) == PACKET_DISABLE)
11177 return -1;
11179 /* Make sure the remote is pointing at the right process, if
11180 necessary. */
11181 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11182 set_general_process ();
11184 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11185 p = strchr (rs->buf.data (), '\0');
11186 addr = remote_address_masked (addr);
11187 p += hexnumstr (p, (ULONGEST) addr);
11188 xsnprintf (p, endbuf - p, ",%x", len);
11189 putpkt (rs->buf);
11190 getpkt (&rs->buf);
11192 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11193 + to_underlying (packet)))).status ())
11195 case PACKET_ERROR:
11196 case PACKET_UNKNOWN:
11197 return -1;
11198 case PACKET_OK:
11199 return 0;
11201 internal_error (_("remote_remove_watchpoint: reached end of function"));
11205 static int remote_hw_watchpoint_limit = -1;
11206 static int remote_hw_watchpoint_length_limit = -1;
11207 static int remote_hw_breakpoint_limit = -1;
11210 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11212 if (remote_hw_watchpoint_length_limit == 0)
11213 return 0;
11214 else if (remote_hw_watchpoint_length_limit < 0)
11215 return 1;
11216 else if (len <= remote_hw_watchpoint_length_limit)
11217 return 1;
11218 else
11219 return 0;
11223 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11225 if (type == bp_hardware_breakpoint)
11227 if (remote_hw_breakpoint_limit == 0)
11228 return 0;
11229 else if (remote_hw_breakpoint_limit < 0)
11230 return 1;
11231 else if (cnt <= remote_hw_breakpoint_limit)
11232 return 1;
11234 else
11236 if (remote_hw_watchpoint_limit == 0)
11237 return 0;
11238 else if (remote_hw_watchpoint_limit < 0)
11239 return 1;
11240 else if (ot)
11241 return -1;
11242 else if (cnt <= remote_hw_watchpoint_limit)
11243 return 1;
11245 return -1;
11248 /* The to_stopped_by_sw_breakpoint method of target remote. */
11250 bool
11251 remote_target::stopped_by_sw_breakpoint ()
11253 struct thread_info *thread = inferior_thread ();
11255 return (thread->priv != NULL
11256 && (get_remote_thread_info (thread)->stop_reason
11257 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11260 /* The to_supports_stopped_by_sw_breakpoint method of target
11261 remote. */
11263 bool
11264 remote_target::supports_stopped_by_sw_breakpoint ()
11266 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11269 /* The to_stopped_by_hw_breakpoint method of target remote. */
11271 bool
11272 remote_target::stopped_by_hw_breakpoint ()
11274 struct thread_info *thread = inferior_thread ();
11276 return (thread->priv != NULL
11277 && (get_remote_thread_info (thread)->stop_reason
11278 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11281 /* The to_supports_stopped_by_hw_breakpoint method of target
11282 remote. */
11284 bool
11285 remote_target::supports_stopped_by_hw_breakpoint ()
11287 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11290 bool
11291 remote_target::stopped_by_watchpoint ()
11293 struct thread_info *thread = inferior_thread ();
11295 return (thread->priv != NULL
11296 && (get_remote_thread_info (thread)->stop_reason
11297 == TARGET_STOPPED_BY_WATCHPOINT));
11300 bool
11301 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11303 struct thread_info *thread = inferior_thread ();
11305 if (thread->priv != NULL
11306 && (get_remote_thread_info (thread)->stop_reason
11307 == TARGET_STOPPED_BY_WATCHPOINT))
11309 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11310 return true;
11313 return false;
11318 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11319 struct bp_target_info *bp_tgt)
11321 CORE_ADDR addr = bp_tgt->reqstd_address;
11322 struct remote_state *rs;
11323 char *p, *endbuf;
11325 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11326 return -1;
11328 /* Make sure the remote is pointing at the right process, if
11329 necessary. */
11330 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11331 set_general_process ();
11333 rs = get_remote_state ();
11334 p = rs->buf.data ();
11335 endbuf = p + get_remote_packet_size ();
11337 *(p++) = 'Z';
11338 *(p++) = '1';
11339 *(p++) = ',';
11341 addr = remote_address_masked (addr);
11342 p += hexnumstr (p, (ULONGEST) addr);
11343 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11345 if (supports_evaluation_of_breakpoint_conditions ())
11346 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11348 if (can_run_breakpoint_commands ())
11349 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11351 putpkt (rs->buf);
11352 getpkt (&rs->buf);
11354 packet_result result = m_features.packet_ok (rs->buf, PACKET_Z1);
11355 switch (result.status ())
11357 case PACKET_ERROR:
11358 error (_("Remote failure reply: %s"), result.err_msg ());
11359 case PACKET_UNKNOWN:
11360 return -1;
11361 case PACKET_OK:
11362 return 0;
11364 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11369 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11370 struct bp_target_info *bp_tgt)
11372 CORE_ADDR addr;
11373 struct remote_state *rs = get_remote_state ();
11374 char *p = rs->buf.data ();
11375 char *endbuf = p + get_remote_packet_size ();
11377 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11378 return -1;
11380 /* Make sure the remote is pointing at the right process, if
11381 necessary. */
11382 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11383 set_general_process ();
11385 *(p++) = 'z';
11386 *(p++) = '1';
11387 *(p++) = ',';
11389 addr = remote_address_masked (bp_tgt->placed_address);
11390 p += hexnumstr (p, (ULONGEST) addr);
11391 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11393 putpkt (rs->buf);
11394 getpkt (&rs->buf);
11396 switch ((m_features.packet_ok (rs->buf, PACKET_Z1)).status ())
11398 case PACKET_ERROR:
11399 case PACKET_UNKNOWN:
11400 return -1;
11401 case PACKET_OK:
11402 return 0;
11404 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11407 /* Verify memory using the "qCRC:" request. */
11410 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11412 struct remote_state *rs = get_remote_state ();
11413 unsigned long host_crc, target_crc;
11414 char *tmp;
11416 /* It doesn't make sense to use qCRC if the remote target is
11417 connected but not running. */
11418 if (target_has_execution ()
11419 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11421 enum packet_status status;
11423 /* Make sure the remote is pointing at the right process. */
11424 set_general_process ();
11426 /* FIXME: assumes lma can fit into long. */
11427 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11428 (long) lma, (long) size);
11429 putpkt (rs->buf);
11431 /* Be clever; compute the host_crc before waiting for target
11432 reply. */
11433 host_crc = xcrc32 (data, size, 0xffffffff);
11435 getpkt (&rs->buf);
11437 status = (m_features.packet_ok (rs->buf, PACKET_qCRC)).status ();
11438 if (status == PACKET_ERROR)
11439 return -1;
11440 else if (status == PACKET_OK)
11442 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11443 target_crc = target_crc * 16 + fromhex (*tmp);
11445 return (host_crc == target_crc);
11449 return simple_verify_memory (this, data, lma, size);
11452 /* compare-sections command
11454 With no arguments, compares each loadable section in the exec bfd
11455 with the same memory range on the target, and reports mismatches.
11456 Useful for verifying the image on the target against the exec file. */
11458 static void
11459 compare_sections_command (const char *args, int from_tty)
11461 asection *s;
11462 const char *sectname;
11463 bfd_size_type size;
11464 bfd_vma lma;
11465 int matched = 0;
11466 int mismatched = 0;
11467 int res;
11468 int read_only = 0;
11470 if (!current_program_space->exec_bfd ())
11471 error (_("command cannot be used without an exec file"));
11473 if (args != NULL && strcmp (args, "-r") == 0)
11475 read_only = 1;
11476 args = NULL;
11479 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11481 if (!(s->flags & SEC_LOAD))
11482 continue; /* Skip non-loadable section. */
11484 if (read_only && (s->flags & SEC_READONLY) == 0)
11485 continue; /* Skip writeable sections */
11487 size = bfd_section_size (s);
11488 if (size == 0)
11489 continue; /* Skip zero-length section. */
11491 sectname = bfd_section_name (s);
11492 if (args && strcmp (args, sectname) != 0)
11493 continue; /* Not the section selected by user. */
11495 matched = 1; /* Do this section. */
11496 lma = s->lma;
11498 gdb::byte_vector sectdata (size);
11499 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11500 sectdata.data (), 0, size);
11502 res = target_verify_memory (sectdata.data (), lma, size);
11504 if (res == -1)
11505 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11506 paddress (current_inferior ()->arch (), lma),
11507 paddress (current_inferior ()->arch (), lma + size));
11509 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11510 paddress (current_inferior ()->arch (), lma),
11511 paddress (current_inferior ()->arch (), lma + size));
11512 if (res)
11513 gdb_printf ("matched.\n");
11514 else
11516 gdb_printf ("MIS-MATCHED!\n");
11517 mismatched++;
11520 if (mismatched > 0)
11521 warning (_("One or more sections of the target image does "
11522 "not match the loaded file"));
11523 if (args && !matched)
11524 gdb_printf (_("No loaded section named '%s'.\n"), args);
11527 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11528 into remote target. The number of bytes written to the remote
11529 target is returned, or -1 for error. */
11531 target_xfer_status
11532 remote_target::remote_write_qxfer (const char *object_name,
11533 const char *annex, const gdb_byte *writebuf,
11534 ULONGEST offset, LONGEST len,
11535 ULONGEST *xfered_len,
11536 const unsigned int which_packet)
11538 int i, buf_len;
11539 ULONGEST n;
11540 struct remote_state *rs = get_remote_state ();
11541 int max_size = get_memory_write_packet_size ();
11543 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11544 return TARGET_XFER_E_IO;
11546 /* Insert header. */
11547 i = snprintf (rs->buf.data (), max_size,
11548 "qXfer:%s:write:%s:%s:",
11549 object_name, annex ? annex : "",
11550 phex_nz (offset, sizeof offset));
11551 max_size -= (i + 1);
11553 /* Escape as much data as fits into rs->buf. */
11554 buf_len = remote_escape_output
11555 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11557 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11558 || getpkt (&rs->buf) < 0
11559 || (m_features.packet_ok (rs->buf, which_packet)).status () != PACKET_OK)
11560 return TARGET_XFER_E_IO;
11562 unpack_varlen_hex (rs->buf.data (), &n);
11564 *xfered_len = n;
11565 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11568 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11569 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11570 number of bytes read is returned, or 0 for EOF, or -1 for error.
11571 The number of bytes read may be less than LEN without indicating an
11572 EOF. PACKET is checked and updated to indicate whether the remote
11573 target supports this object. */
11575 target_xfer_status
11576 remote_target::remote_read_qxfer (const char *object_name,
11577 const char *annex,
11578 gdb_byte *readbuf, ULONGEST offset,
11579 LONGEST len,
11580 ULONGEST *xfered_len,
11581 const unsigned int which_packet)
11583 struct remote_state *rs = get_remote_state ();
11584 LONGEST i, n, packet_len;
11586 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11587 return TARGET_XFER_E_IO;
11589 /* Check whether we've cached an end-of-object packet that matches
11590 this request. */
11591 if (rs->finished_object)
11593 if (strcmp (object_name, rs->finished_object) == 0
11594 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11595 && offset == rs->finished_offset)
11596 return TARGET_XFER_EOF;
11599 /* Otherwise, we're now reading something different. Discard
11600 the cache. */
11601 xfree (rs->finished_object);
11602 xfree (rs->finished_annex);
11603 rs->finished_object = NULL;
11604 rs->finished_annex = NULL;
11607 /* Request only enough to fit in a single packet. The actual data
11608 may not, since we don't know how much of it will need to be escaped;
11609 the target is free to respond with slightly less data. We subtract
11610 five to account for the response type and the protocol frame. */
11611 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11612 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11613 "qXfer:%s:read:%s:%s,%s",
11614 object_name, annex ? annex : "",
11615 phex_nz (offset, sizeof offset),
11616 phex_nz (n, sizeof n));
11617 i = putpkt (rs->buf);
11618 if (i < 0)
11619 return TARGET_XFER_E_IO;
11621 rs->buf[0] = '\0';
11622 packet_len = getpkt (&rs->buf);
11623 if (packet_len < 0
11624 || m_features.packet_ok (rs->buf, which_packet).status () != PACKET_OK)
11625 return TARGET_XFER_E_IO;
11627 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11628 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11630 /* 'm' means there is (or at least might be) more data after this
11631 batch. That does not make sense unless there's at least one byte
11632 of data in this reply. */
11633 if (rs->buf[0] == 'm' && packet_len == 1)
11634 error (_("Remote qXfer reply contained no data."));
11636 /* Got some data. */
11637 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11638 packet_len - 1, readbuf, n);
11640 /* 'l' is an EOF marker, possibly including a final block of data,
11641 or possibly empty. If we have the final block of a non-empty
11642 object, record this fact to bypass a subsequent partial read. */
11643 if (rs->buf[0] == 'l' && offset + i > 0)
11645 rs->finished_object = xstrdup (object_name);
11646 rs->finished_annex = xstrdup (annex ? annex : "");
11647 rs->finished_offset = offset + i;
11650 if (i == 0)
11651 return TARGET_XFER_EOF;
11652 else
11654 *xfered_len = i;
11655 return TARGET_XFER_OK;
11659 enum target_xfer_status
11660 remote_target::xfer_partial (enum target_object object,
11661 const char *annex, gdb_byte *readbuf,
11662 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11663 ULONGEST *xfered_len)
11665 struct remote_state *rs;
11666 int i;
11667 char *p2;
11668 char query_type;
11669 int unit_size
11670 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11672 set_remote_traceframe ();
11673 set_general_thread (inferior_ptid);
11675 rs = get_remote_state ();
11677 /* Handle memory using the standard memory routines. */
11678 if (object == TARGET_OBJECT_MEMORY)
11680 /* If the remote target is connected but not running, we should
11681 pass this request down to a lower stratum (e.g. the executable
11682 file). */
11683 if (!target_has_execution ())
11684 return TARGET_XFER_EOF;
11686 if (writebuf != NULL)
11687 return remote_write_bytes (offset, writebuf, len, unit_size,
11688 xfered_len);
11689 else
11690 return remote_read_bytes (offset, readbuf, len, unit_size,
11691 xfered_len);
11694 /* Handle extra signal info using qxfer packets. */
11695 if (object == TARGET_OBJECT_SIGNAL_INFO)
11697 if (readbuf)
11698 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11699 xfered_len, PACKET_qXfer_siginfo_read);
11700 else
11701 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11702 xfered_len, PACKET_qXfer_siginfo_write);
11705 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11707 if (readbuf)
11708 return remote_read_qxfer ("statictrace", annex,
11709 readbuf, offset, len, xfered_len,
11710 PACKET_qXfer_statictrace_read);
11711 else
11712 return TARGET_XFER_E_IO;
11715 /* Only handle flash writes. */
11716 if (writebuf != NULL)
11718 switch (object)
11720 case TARGET_OBJECT_FLASH:
11721 return remote_flash_write (offset, len, xfered_len,
11722 writebuf);
11724 default:
11725 return TARGET_XFER_E_IO;
11729 /* Map pre-existing objects onto letters. DO NOT do this for new
11730 objects!!! Instead specify new query packets. */
11731 switch (object)
11733 case TARGET_OBJECT_AVR:
11734 query_type = 'R';
11735 break;
11737 case TARGET_OBJECT_AUXV:
11738 gdb_assert (annex == NULL);
11739 return remote_read_qxfer
11740 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11742 case TARGET_OBJECT_AVAILABLE_FEATURES:
11743 return remote_read_qxfer
11744 ("features", annex, readbuf, offset, len, xfered_len,
11745 PACKET_qXfer_features);
11747 case TARGET_OBJECT_LIBRARIES:
11748 return remote_read_qxfer
11749 ("libraries", annex, readbuf, offset, len, xfered_len,
11750 PACKET_qXfer_libraries);
11752 case TARGET_OBJECT_LIBRARIES_SVR4:
11753 return remote_read_qxfer
11754 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11755 PACKET_qXfer_libraries_svr4);
11757 case TARGET_OBJECT_MEMORY_MAP:
11758 gdb_assert (annex == NULL);
11759 return remote_read_qxfer
11760 ("memory-map", annex, readbuf, offset, len, xfered_len,
11761 PACKET_qXfer_memory_map);
11763 case TARGET_OBJECT_OSDATA:
11764 /* Should only get here if we're connected. */
11765 gdb_assert (rs->remote_desc);
11766 return remote_read_qxfer
11767 ("osdata", annex, readbuf, offset, len, xfered_len,
11768 PACKET_qXfer_osdata);
11770 case TARGET_OBJECT_THREADS:
11771 gdb_assert (annex == NULL);
11772 return remote_read_qxfer
11773 ("threads", annex, readbuf, offset, len, xfered_len,
11774 PACKET_qXfer_threads);
11776 case TARGET_OBJECT_TRACEFRAME_INFO:
11777 gdb_assert (annex == NULL);
11778 return remote_read_qxfer
11779 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11780 PACKET_qXfer_traceframe_info);
11782 case TARGET_OBJECT_FDPIC:
11783 return remote_read_qxfer
11784 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11786 case TARGET_OBJECT_OPENVMS_UIB:
11787 return remote_read_qxfer
11788 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11790 case TARGET_OBJECT_BTRACE:
11791 return remote_read_qxfer
11792 ("btrace", annex, readbuf, offset, len, xfered_len,
11793 PACKET_qXfer_btrace);
11795 case TARGET_OBJECT_BTRACE_CONF:
11796 return remote_read_qxfer
11797 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11798 PACKET_qXfer_btrace_conf);
11800 case TARGET_OBJECT_EXEC_FILE:
11801 return remote_read_qxfer
11802 ("exec-file", annex, readbuf, offset, len, xfered_len,
11803 PACKET_qXfer_exec_file);
11805 default:
11806 return TARGET_XFER_E_IO;
11809 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11810 large enough let the caller deal with it. */
11811 if (len < get_remote_packet_size ())
11812 return TARGET_XFER_E_IO;
11813 len = get_remote_packet_size ();
11815 /* Except for querying the minimum buffer size, target must be open. */
11816 if (!rs->remote_desc)
11817 error (_("remote query is only available after target open"));
11819 gdb_assert (annex != NULL);
11820 gdb_assert (readbuf != NULL);
11822 p2 = rs->buf.data ();
11823 *p2++ = 'q';
11824 *p2++ = query_type;
11826 /* We used one buffer char for the remote protocol q command and
11827 another for the query type. As the remote protocol encapsulation
11828 uses 4 chars plus one extra in case we are debugging
11829 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11830 string. */
11831 i = 0;
11832 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11834 /* Bad caller may have sent forbidden characters. */
11835 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11836 *p2++ = annex[i];
11837 i++;
11839 *p2 = '\0';
11840 gdb_assert (annex[i] == '\0');
11842 i = putpkt (rs->buf);
11843 if (i < 0)
11844 return TARGET_XFER_E_IO;
11846 getpkt (&rs->buf);
11847 strcpy ((char *) readbuf, rs->buf.data ());
11849 *xfered_len = strlen ((char *) readbuf);
11850 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11853 /* Implementation of to_get_memory_xfer_limit. */
11855 ULONGEST
11856 remote_target::get_memory_xfer_limit ()
11858 return get_memory_write_packet_size ();
11862 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11863 const gdb_byte *pattern, ULONGEST pattern_len,
11864 CORE_ADDR *found_addrp)
11866 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11867 struct remote_state *rs = get_remote_state ();
11868 int max_size = get_memory_write_packet_size ();
11870 /* Number of packet bytes used to encode the pattern;
11871 this could be more than PATTERN_LEN due to escape characters. */
11872 int escaped_pattern_len;
11873 /* Amount of pattern that was encodable in the packet. */
11874 int used_pattern_len;
11875 int i;
11876 int found;
11877 ULONGEST found_addr;
11879 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11881 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11882 == len);
11885 /* Don't go to the target if we don't have to. This is done before
11886 checking packet_support to avoid the possibility that a success for this
11887 edge case means the facility works in general. */
11888 if (pattern_len > search_space_len)
11889 return 0;
11890 if (pattern_len == 0)
11892 *found_addrp = start_addr;
11893 return 1;
11896 /* If we already know the packet isn't supported, fall back to the simple
11897 way of searching memory. */
11899 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11901 /* Target doesn't provided special support, fall back and use the
11902 standard support (copy memory and do the search here). */
11903 return simple_search_memory (read_memory, start_addr, search_space_len,
11904 pattern, pattern_len, found_addrp);
11907 /* Make sure the remote is pointing at the right process. */
11908 set_general_process ();
11910 /* Insert header. */
11911 i = snprintf (rs->buf.data (), max_size,
11912 "qSearch:memory:%s;%s;",
11913 phex_nz (start_addr, addr_size),
11914 phex_nz (search_space_len, sizeof (search_space_len)));
11915 max_size -= (i + 1);
11917 /* Escape as much data as fits into rs->buf. */
11918 escaped_pattern_len =
11919 remote_escape_output (pattern, pattern_len, 1,
11920 (gdb_byte *) rs->buf.data () + i,
11921 &used_pattern_len, max_size);
11923 /* Bail if the pattern is too large. */
11924 if (used_pattern_len != pattern_len)
11925 error (_("Pattern is too large to transmit to remote target."));
11927 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11928 || getpkt (&rs->buf) < 0
11929 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory).status ()
11930 != PACKET_OK)
11932 /* The request may not have worked because the command is not
11933 supported. If so, fall back to the simple way. */
11934 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11936 return simple_search_memory (read_memory, start_addr, search_space_len,
11937 pattern, pattern_len, found_addrp);
11939 return -1;
11942 if (rs->buf[0] == '0')
11943 found = 0;
11944 else if (rs->buf[0] == '1')
11946 found = 1;
11947 if (rs->buf[1] != ',')
11948 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11949 unpack_varlen_hex (&rs->buf[2], &found_addr);
11950 *found_addrp = found_addr;
11952 else
11953 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11955 return found;
11958 void
11959 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11961 struct remote_state *rs = get_remote_state ();
11962 char *p = rs->buf.data ();
11964 if (!rs->remote_desc)
11965 error (_("remote rcmd is only available after target open"));
11967 /* Send a NULL command across as an empty command. */
11968 if (command == NULL)
11969 command = "";
11971 /* The query prefix. */
11972 strcpy (rs->buf.data (), "qRcmd,");
11973 p = strchr (rs->buf.data (), '\0');
11975 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11976 > get_remote_packet_size ())
11977 error (_("\"monitor\" command ``%s'' is too long."), command);
11979 /* Encode the actual command. */
11980 bin2hex ((const gdb_byte *) command, p, strlen (command));
11982 if (putpkt (rs->buf) < 0)
11983 error (_("Communication problem with target."));
11985 /* get/display the response */
11986 while (1)
11988 char *buf;
11990 /* XXX - see also remote_get_noisy_reply(). */
11991 QUIT; /* Allow user to bail out with ^C. */
11992 rs->buf[0] = '\0';
11993 if (getpkt (&rs->buf) == -1)
11995 /* Timeout. Continue to (try to) read responses.
11996 This is better than stopping with an error, assuming the stub
11997 is still executing the (long) monitor command.
11998 If needed, the user can interrupt gdb using C-c, obtaining
11999 an effect similar to stop on timeout. */
12000 continue;
12002 buf = rs->buf.data ();
12003 if (buf[0] == 'O' && buf[1] != 'K')
12005 /* 'O' message from stub. */
12006 remote_console_output (buf + 1, outbuf);
12007 continue;
12009 packet_result result = packet_check_result (buf);
12010 switch (result.status ())
12012 case PACKET_UNKNOWN:
12013 error (_("Target does not support this command."));
12014 case PACKET_ERROR:
12015 error (_("Protocol error with Rcmd: %s."), result.err_msg ());
12016 case PACKET_OK:
12017 break;
12020 if (strcmp (buf, "OK") != 0)
12022 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
12024 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
12025 gdb_putc (c, outbuf);
12028 break;
12032 std::vector<mem_region>
12033 remote_target::memory_map ()
12035 std::vector<mem_region> result;
12036 std::optional<gdb::char_vector> text
12037 = target_read_stralloc (current_inferior ()->top_target (),
12038 TARGET_OBJECT_MEMORY_MAP, NULL);
12040 if (text)
12041 result = parse_memory_map (text->data ());
12043 return result;
12046 /* Set of callbacks used to implement the 'maint packet' command. */
12048 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
12050 /* Called before the packet is sent. BUF is the packet content before
12051 the protocol specific prefix, suffix, and escaping is added. */
12053 void sending (gdb::array_view<const char> &buf) override
12055 gdb_puts ("sending: ");
12056 print_packet (buf);
12057 gdb_puts ("\n");
12060 /* Called with BUF, the reply from the remote target. */
12062 void received (gdb::array_view<const char> &buf) override
12064 gdb_puts ("received: \"");
12065 print_packet (buf);
12066 gdb_puts ("\"\n");
12069 private:
12071 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
12072 '\x??' with '??' replaced by the hexadecimal value of the byte. */
12074 static void
12075 print_packet (gdb::array_view<const char> &buf)
12077 string_file stb;
12079 for (int i = 0; i < buf.size (); ++i)
12081 gdb_byte c = buf[i];
12082 if (isprint (c))
12083 gdb_putc (c, &stb);
12084 else
12085 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
12088 gdb_puts (stb.string ().c_str ());
12092 /* See remote.h. */
12094 void
12095 send_remote_packet (gdb::array_view<const char> &buf,
12096 send_remote_packet_callbacks *callbacks)
12098 if (buf.size () == 0 || buf.data ()[0] == '\0')
12099 error (_("a remote packet must not be empty"));
12101 remote_target *remote = get_current_remote_target ();
12102 if (remote == nullptr)
12103 error (_("packets can only be sent to a remote target"));
12105 callbacks->sending (buf);
12107 remote->putpkt_binary (buf.data (), buf.size ());
12108 remote_state *rs = remote->get_remote_state ();
12109 int bytes = remote->getpkt (&rs->buf);
12111 if (bytes < 0)
12112 error (_("error while fetching packet from remote target"));
12114 gdb::array_view<const char> view (&rs->buf[0], bytes);
12115 callbacks->received (view);
12118 /* Entry point for the 'maint packet' command. */
12120 static void
12121 cli_packet_command (const char *args, int from_tty)
12123 cli_packet_command_callbacks cb;
12124 gdb::array_view<const char> view
12125 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
12126 send_remote_packet (view, &cb);
12129 #if 0
12130 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12132 static void display_thread_info (struct gdb_ext_thread_info *info);
12134 static void threadset_test_cmd (char *cmd, int tty);
12136 static void threadalive_test (char *cmd, int tty);
12138 static void threadlist_test_cmd (char *cmd, int tty);
12140 int get_and_display_threadinfo (threadref *ref);
12142 static void threadinfo_test_cmd (char *cmd, int tty);
12144 static int thread_display_step (threadref *ref, void *context);
12146 static void threadlist_update_test_cmd (char *cmd, int tty);
12148 static void init_remote_threadtests (void);
12150 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12152 static void
12153 threadset_test_cmd (const char *cmd, int tty)
12155 int sample_thread = SAMPLE_THREAD;
12157 gdb_printf (_("Remote threadset test\n"));
12158 set_general_thread (sample_thread);
12162 static void
12163 threadalive_test (const char *cmd, int tty)
12165 int sample_thread = SAMPLE_THREAD;
12166 int pid = inferior_ptid.pid ();
12167 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12169 if (remote_thread_alive (ptid))
12170 gdb_printf ("PASS: Thread alive test\n");
12171 else
12172 gdb_printf ("FAIL: Thread alive test\n");
12175 void output_threadid (char *title, threadref *ref);
12177 void
12178 output_threadid (char *title, threadref *ref)
12180 char hexid[20];
12182 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12183 hexid[16] = 0;
12184 gdb_printf ("%s %s\n", title, (&hexid[0]));
12187 static void
12188 threadlist_test_cmd (const char *cmd, int tty)
12190 int startflag = 1;
12191 threadref nextthread;
12192 int done, result_count;
12193 threadref threadlist[3];
12195 gdb_printf ("Remote Threadlist test\n");
12196 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12197 &result_count, &threadlist[0]))
12198 gdb_printf ("FAIL: threadlist test\n");
12199 else
12201 threadref *scan = threadlist;
12202 threadref *limit = scan + result_count;
12204 while (scan < limit)
12205 output_threadid (" thread ", scan++);
12209 void
12210 display_thread_info (struct gdb_ext_thread_info *info)
12212 output_threadid ("Threadid: ", &info->threadid);
12213 gdb_printf ("Name: %s\n ", info->shortname);
12214 gdb_printf ("State: %s\n", info->display);
12215 gdb_printf ("other: %s\n\n", info->more_display);
12219 get_and_display_threadinfo (threadref *ref)
12221 int result;
12222 int set;
12223 struct gdb_ext_thread_info threadinfo;
12225 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12226 | TAG_MOREDISPLAY | TAG_DISPLAY;
12227 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12228 display_thread_info (&threadinfo);
12229 return result;
12232 static void
12233 threadinfo_test_cmd (const char *cmd, int tty)
12235 int athread = SAMPLE_THREAD;
12236 threadref thread;
12237 int set;
12239 int_to_threadref (&thread, athread);
12240 gdb_printf ("Remote Threadinfo test\n");
12241 if (!get_and_display_threadinfo (&thread))
12242 gdb_printf ("FAIL cannot get thread info\n");
12245 static int
12246 thread_display_step (threadref *ref, void *context)
12248 /* output_threadid(" threadstep ",ref); *//* simple test */
12249 return get_and_display_threadinfo (ref);
12252 static void
12253 threadlist_update_test_cmd (const char *cmd, int tty)
12255 gdb_printf ("Remote Threadlist update test\n");
12256 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12259 static void
12260 init_remote_threadtests (void)
12262 add_com ("tlist", class_obscure, threadlist_test_cmd,
12263 _("Fetch and print the remote list of "
12264 "thread identifiers, one pkt only."));
12265 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12266 _("Fetch and display info about one thread."));
12267 add_com ("tset", class_obscure, threadset_test_cmd,
12268 _("Test setting to a different thread."));
12269 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12270 _("Iterate through updating all remote thread info."));
12271 add_com ("talive", class_obscure, threadalive_test,
12272 _("Remote thread alive test."));
12275 #endif /* 0 */
12277 /* Convert a thread ID to a string. */
12279 std::string
12280 remote_target::pid_to_str (ptid_t ptid)
12282 if (ptid == null_ptid)
12283 return normal_pid_to_str (ptid);
12284 else if (ptid.is_pid ())
12286 /* Printing an inferior target id. */
12288 /* When multi-process extensions are off, there's no way in the
12289 remote protocol to know the remote process id, if there's any
12290 at all. There's one exception --- when we're connected with
12291 target extended-remote, and we manually attached to a process
12292 with "attach PID". We don't record anywhere a flag that
12293 allows us to distinguish that case from the case of
12294 connecting with extended-remote and the stub already being
12295 attached to a process, and reporting yes to qAttached, hence
12296 no smart special casing here. */
12297 if (!m_features.remote_multi_process_p ())
12298 return "Remote target";
12300 return normal_pid_to_str (ptid);
12302 else
12304 if (magic_null_ptid == ptid)
12305 return "Thread <main>";
12306 else if (m_features.remote_multi_process_p ())
12307 if (ptid.lwp () == 0)
12308 return normal_pid_to_str (ptid);
12309 else
12310 return string_printf ("Thread %d.%ld",
12311 ptid.pid (), ptid.lwp ());
12312 else
12313 return string_printf ("Thread %ld", ptid.lwp ());
12317 /* Get the address of the thread local variable in OBJFILE which is
12318 stored at OFFSET within the thread local storage for thread PTID. */
12320 CORE_ADDR
12321 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12322 CORE_ADDR offset)
12324 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12326 struct remote_state *rs = get_remote_state ();
12327 char *p = rs->buf.data ();
12328 char *endp = p + get_remote_packet_size ();
12330 strcpy (p, "qGetTLSAddr:");
12331 p += strlen (p);
12332 p = write_ptid (p, endp, ptid);
12333 *p++ = ',';
12334 p += hexnumstr (p, offset);
12335 *p++ = ',';
12336 p += hexnumstr (p, lm);
12337 *p++ = '\0';
12339 putpkt (rs->buf);
12340 getpkt (&rs->buf);
12341 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12342 if (result.status () == PACKET_OK)
12344 ULONGEST addr;
12346 unpack_varlen_hex (rs->buf.data (), &addr);
12347 return addr;
12349 else if (result.status () == PACKET_UNKNOWN)
12350 throw_error (TLS_GENERIC_ERROR,
12351 _("Remote target doesn't support qGetTLSAddr packet"));
12352 else
12353 throw_error (TLS_GENERIC_ERROR,
12354 _("Remote target failed to process qGetTLSAddr request"));
12356 else
12357 throw_error (TLS_GENERIC_ERROR,
12358 _("TLS not supported or disabled on this target"));
12359 /* Not reached. */
12360 return 0;
12363 /* Provide thread local base, i.e. Thread Information Block address.
12364 Returns 1 if ptid is found and thread_local_base is non zero. */
12366 bool
12367 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12369 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12371 struct remote_state *rs = get_remote_state ();
12372 char *p = rs->buf.data ();
12373 char *endp = p + get_remote_packet_size ();
12375 strcpy (p, "qGetTIBAddr:");
12376 p += strlen (p);
12377 p = write_ptid (p, endp, ptid);
12378 *p++ = '\0';
12380 putpkt (rs->buf);
12381 getpkt (&rs->buf);
12382 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12383 if (result.status () == PACKET_OK)
12385 ULONGEST val;
12386 unpack_varlen_hex (rs->buf.data (), &val);
12387 if (addr)
12388 *addr = (CORE_ADDR) val;
12389 return true;
12391 else if (result.status () == PACKET_UNKNOWN)
12392 error (_("Remote target doesn't support qGetTIBAddr packet"));
12393 else
12394 error (_("Remote target failed to process qGetTIBAddr request, %s"),
12395 result.err_msg ());
12397 else
12398 error (_("qGetTIBAddr not supported or disabled on this target"));
12399 /* Not reached. */
12400 return false;
12403 /* Support for inferring a target description based on the current
12404 architecture and the size of a 'g' packet. While the 'g' packet
12405 can have any size (since optional registers can be left off the
12406 end), some sizes are easily recognizable given knowledge of the
12407 approximate architecture. */
12409 struct remote_g_packet_guess
12411 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12412 : bytes (bytes_),
12413 tdesc (tdesc_)
12417 int bytes;
12418 const struct target_desc *tdesc;
12421 struct remote_g_packet_data
12423 std::vector<remote_g_packet_guess> guesses;
12426 static const registry<gdbarch>::key<struct remote_g_packet_data>
12427 remote_g_packet_data_handle;
12429 static struct remote_g_packet_data *
12430 get_g_packet_data (struct gdbarch *gdbarch)
12432 struct remote_g_packet_data *data
12433 = remote_g_packet_data_handle.get (gdbarch);
12434 if (data == nullptr)
12435 data = remote_g_packet_data_handle.emplace (gdbarch);
12436 return data;
12439 void
12440 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12441 const struct target_desc *tdesc)
12443 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12445 gdb_assert (tdesc != NULL);
12447 for (const remote_g_packet_guess &guess : data->guesses)
12448 if (guess.bytes == bytes)
12449 internal_error (_("Duplicate g packet description added for size %d"),
12450 bytes);
12452 data->guesses.emplace_back (bytes, tdesc);
12455 /* Return true if remote_read_description would do anything on this target
12456 and architecture, false otherwise. */
12458 static bool
12459 remote_read_description_p (struct target_ops *target)
12461 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12463 return !data->guesses.empty ();
12466 const struct target_desc *
12467 remote_target::read_description ()
12469 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12471 /* Do not try this during initial connection, when we do not know
12472 whether there is a running but stopped thread. */
12473 if (!target_has_execution () || inferior_ptid == null_ptid)
12474 return beneath ()->read_description ();
12476 if (!data->guesses.empty ())
12478 int bytes = send_g_packet ();
12480 for (const remote_g_packet_guess &guess : data->guesses)
12481 if (guess.bytes == bytes)
12482 return guess.tdesc;
12484 /* We discard the g packet. A minor optimization would be to
12485 hold on to it, and fill the register cache once we have selected
12486 an architecture, but it's too tricky to do safely. */
12489 return beneath ()->read_description ();
12492 /* Remote file transfer support. This is host-initiated I/O, not
12493 target-initiated; for target-initiated, see remote-fileio.c. */
12495 /* If *LEFT is at least the length of STRING, copy STRING to
12496 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12497 decrease *LEFT. Otherwise raise an error. */
12499 static void
12500 remote_buffer_add_string (char **buffer, int *left, const char *string)
12502 int len = strlen (string);
12504 if (len > *left)
12505 error (_("Packet too long for target."));
12507 memcpy (*buffer, string, len);
12508 *buffer += len;
12509 *left -= len;
12511 /* NUL-terminate the buffer as a convenience, if there is
12512 room. */
12513 if (*left)
12514 **buffer = '\0';
12517 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12518 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12519 decrease *LEFT. Otherwise raise an error. */
12521 static void
12522 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12523 int len)
12525 if (2 * len > *left)
12526 error (_("Packet too long for target."));
12528 bin2hex (bytes, *buffer, len);
12529 *buffer += 2 * len;
12530 *left -= 2 * len;
12532 /* NUL-terminate the buffer as a convenience, if there is
12533 room. */
12534 if (*left)
12535 **buffer = '\0';
12538 /* If *LEFT is large enough, convert VALUE to hex and add it to
12539 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12540 decrease *LEFT. Otherwise raise an error. */
12542 static void
12543 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12545 int len = hexnumlen (value);
12547 if (len > *left)
12548 error (_("Packet too long for target."));
12550 hexnumstr (*buffer, value);
12551 *buffer += len;
12552 *left -= len;
12554 /* NUL-terminate the buffer as a convenience, if there is
12555 room. */
12556 if (*left)
12557 **buffer = '\0';
12560 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12561 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12562 was included, and *ATTACHMENT to point to the start of the annex
12563 if any. The length of the packet isn't needed here; there may
12564 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12566 Return 0 if the packet could be parsed, -1 if it could not. If
12567 -1 is returned, the other variables may not be initialized. */
12569 static int
12570 remote_hostio_parse_result (const char *buffer, int *retcode,
12571 fileio_error *remote_errno, const char **attachment)
12573 char *p, *p2;
12575 *remote_errno = FILEIO_SUCCESS;
12576 *attachment = NULL;
12578 if (buffer[0] != 'F')
12579 return -1;
12581 errno = 0;
12582 *retcode = strtol (&buffer[1], &p, 16);
12583 if (errno != 0 || p == &buffer[1])
12584 return -1;
12586 /* Check for ",errno". */
12587 if (*p == ',')
12589 errno = 0;
12590 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12591 if (errno != 0 || p + 1 == p2)
12592 return -1;
12593 p = p2;
12596 /* Check for ";attachment". If there is no attachment, the
12597 packet should end here. */
12598 if (*p == ';')
12600 *attachment = p + 1;
12601 return 0;
12603 else if (*p == '\0')
12604 return 0;
12605 else
12606 return -1;
12609 /* Send a prepared I/O packet to the target and read its response.
12610 The prepared packet is in the global RS->BUF before this function
12611 is called, and the answer is there when we return.
12613 COMMAND_BYTES is the length of the request to send, which may include
12614 binary data. WHICH_PACKET is the packet configuration to check
12615 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12616 is set to the error number and -1 is returned. Otherwise the value
12617 returned by the function is returned.
12619 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12620 attachment is expected; an error will be reported if there's a
12621 mismatch. If one is found, *ATTACHMENT will be set to point into
12622 the packet buffer and *ATTACHMENT_LEN will be set to the
12623 attachment's length. */
12626 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12627 fileio_error *remote_errno, const char **attachment,
12628 int *attachment_len)
12630 struct remote_state *rs = get_remote_state ();
12631 int ret, bytes_read;
12632 const char *attachment_tmp;
12634 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12636 *remote_errno = FILEIO_ENOSYS;
12637 return -1;
12640 putpkt_binary (rs->buf.data (), command_bytes);
12641 bytes_read = getpkt (&rs->buf);
12643 /* If it timed out, something is wrong. Don't try to parse the
12644 buffer. */
12645 if (bytes_read < 0)
12647 *remote_errno = FILEIO_EINVAL;
12648 return -1;
12651 switch (m_features.packet_ok (rs->buf, which_packet).status ())
12653 case PACKET_ERROR:
12654 *remote_errno = FILEIO_EINVAL;
12655 return -1;
12656 case PACKET_UNKNOWN:
12657 *remote_errno = FILEIO_ENOSYS;
12658 return -1;
12659 case PACKET_OK:
12660 break;
12663 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12664 &attachment_tmp))
12666 *remote_errno = FILEIO_EINVAL;
12667 return -1;
12670 if (*remote_errno != FILEIO_SUCCESS)
12671 return -1;
12673 /* Make sure we saw an attachment if and only if we expected one. */
12674 if ((attachment_tmp == NULL && attachment != NULL)
12675 || (attachment_tmp != NULL && attachment == NULL))
12677 *remote_errno = FILEIO_EINVAL;
12678 return -1;
12681 /* If an attachment was found, it must point into the packet buffer;
12682 work out how many bytes there were. */
12683 if (attachment_tmp != NULL)
12685 *attachment = attachment_tmp;
12686 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12689 return ret;
12692 /* See declaration.h. */
12694 void
12695 readahead_cache::invalidate ()
12697 this->fd = -1;
12700 /* See declaration.h. */
12702 void
12703 readahead_cache::invalidate_fd (int fd)
12705 if (this->fd == fd)
12706 this->fd = -1;
12709 /* Set the filesystem remote_hostio functions that take FILENAME
12710 arguments will use. Return 0 on success, or -1 if an error
12711 occurs (and set *REMOTE_ERRNO). */
12714 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12715 fileio_error *remote_errno)
12717 struct remote_state *rs = get_remote_state ();
12718 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12719 char *p = rs->buf.data ();
12720 int left = get_remote_packet_size () - 1;
12721 char arg[9];
12722 int ret;
12724 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12725 return 0;
12727 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12728 return 0;
12730 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12732 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12733 remote_buffer_add_string (&p, &left, arg);
12735 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12736 remote_errno, NULL, NULL);
12738 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12739 return 0;
12741 if (ret == 0)
12742 rs->fs_pid = required_pid;
12744 return ret;
12747 /* Implementation of to_fileio_open. */
12750 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12751 int flags, int mode, int warn_if_slow,
12752 fileio_error *remote_errno)
12754 struct remote_state *rs = get_remote_state ();
12755 char *p = rs->buf.data ();
12756 int left = get_remote_packet_size () - 1;
12758 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12759 return -1;
12761 remote_buffer_add_string (&p, &left, "vFile:open:");
12763 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12764 strlen (filename));
12765 remote_buffer_add_string (&p, &left, ",");
12767 remote_buffer_add_int (&p, &left, flags);
12768 remote_buffer_add_string (&p, &left, ",");
12770 remote_buffer_add_int (&p, &left, mode);
12772 int res = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12773 remote_errno, nullptr, nullptr);
12775 if (warn_if_slow && res != -1)
12777 static int warning_issued = 0;
12779 gdb_printf (_("Reading %ps from remote target...\n"),
12780 styled_string (file_name_style.style (), filename));
12782 if (!warning_issued)
12784 warning (_("File transfers from remote targets can be slow."
12785 " Use \"set sysroot\" to access files locally"
12786 " instead."));
12787 warning_issued = 1;
12791 return res;
12795 remote_target::fileio_open (struct inferior *inf, const char *filename,
12796 int flags, int mode, int warn_if_slow,
12797 fileio_error *remote_errno)
12799 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12800 remote_errno);
12803 /* Implementation of to_fileio_pwrite. */
12806 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12807 ULONGEST offset, fileio_error *remote_errno)
12809 struct remote_state *rs = get_remote_state ();
12810 char *p = rs->buf.data ();
12811 int left = get_remote_packet_size ();
12812 int out_len;
12814 rs->readahead_cache.invalidate_fd (fd);
12816 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12818 remote_buffer_add_int (&p, &left, fd);
12819 remote_buffer_add_string (&p, &left, ",");
12821 remote_buffer_add_int (&p, &left, offset);
12822 remote_buffer_add_string (&p, &left, ",");
12824 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12825 (get_remote_packet_size ()
12826 - (p - rs->buf.data ())));
12828 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12829 remote_errno, NULL, NULL);
12833 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12834 ULONGEST offset, fileio_error *remote_errno)
12836 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12839 /* Helper for the implementation of to_fileio_pread. Read the file
12840 from the remote side with vFile:pread. */
12843 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12844 ULONGEST offset, fileio_error *remote_errno)
12846 struct remote_state *rs = get_remote_state ();
12847 char *p = rs->buf.data ();
12848 const char *attachment;
12849 int left = get_remote_packet_size ();
12850 int ret, attachment_len;
12851 int read_len;
12853 remote_buffer_add_string (&p, &left, "vFile:pread:");
12855 remote_buffer_add_int (&p, &left, fd);
12856 remote_buffer_add_string (&p, &left, ",");
12858 remote_buffer_add_int (&p, &left, len);
12859 remote_buffer_add_string (&p, &left, ",");
12861 remote_buffer_add_int (&p, &left, offset);
12863 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12864 remote_errno, &attachment,
12865 &attachment_len);
12867 if (ret < 0)
12868 return ret;
12870 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12871 read_buf, len);
12872 if (read_len != ret)
12873 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12875 return ret;
12878 /* See declaration.h. */
12881 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12882 ULONGEST offset)
12884 if (this->fd == fd
12885 && this->offset <= offset
12886 && offset < this->offset + this->buf.size ())
12888 ULONGEST max = this->offset + this->buf.size ();
12890 if (offset + len > max)
12891 len = max - offset;
12893 memcpy (read_buf, &this->buf[offset - this->offset], len);
12894 return len;
12897 return 0;
12900 /* Implementation of to_fileio_pread. */
12903 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12904 ULONGEST offset, fileio_error *remote_errno)
12906 int ret;
12907 struct remote_state *rs = get_remote_state ();
12908 readahead_cache *cache = &rs->readahead_cache;
12910 ret = cache->pread (fd, read_buf, len, offset);
12911 if (ret > 0)
12913 cache->hit_count++;
12915 remote_debug_printf ("readahead cache hit %s",
12916 pulongest (cache->hit_count));
12917 return ret;
12920 cache->miss_count++;
12922 remote_debug_printf ("readahead cache miss %s",
12923 pulongest (cache->miss_count));
12925 cache->fd = fd;
12926 cache->offset = offset;
12927 cache->buf.resize (get_remote_packet_size ());
12929 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12930 cache->buf.size (),
12931 cache->offset, remote_errno);
12932 if (ret <= 0)
12934 cache->invalidate_fd (fd);
12935 return ret;
12938 cache->buf.resize (ret);
12939 return cache->pread (fd, read_buf, len, offset);
12943 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12944 ULONGEST offset, fileio_error *remote_errno)
12946 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12949 /* Implementation of to_fileio_close. */
12952 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12954 struct remote_state *rs = get_remote_state ();
12955 char *p = rs->buf.data ();
12956 int left = get_remote_packet_size () - 1;
12958 rs->readahead_cache.invalidate_fd (fd);
12960 remote_buffer_add_string (&p, &left, "vFile:close:");
12962 remote_buffer_add_int (&p, &left, fd);
12964 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12965 remote_errno, NULL, NULL);
12969 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12971 return remote_hostio_close (fd, remote_errno);
12974 /* Implementation of to_fileio_unlink. */
12977 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12978 fileio_error *remote_errno)
12980 struct remote_state *rs = get_remote_state ();
12981 char *p = rs->buf.data ();
12982 int left = get_remote_packet_size () - 1;
12984 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12985 return -1;
12987 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12989 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12990 strlen (filename));
12992 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12993 remote_errno, NULL, NULL);
12997 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12998 fileio_error *remote_errno)
13000 return remote_hostio_unlink (inf, filename, remote_errno);
13003 /* Implementation of to_fileio_readlink. */
13005 std::optional<std::string>
13006 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
13007 fileio_error *remote_errno)
13009 struct remote_state *rs = get_remote_state ();
13010 char *p = rs->buf.data ();
13011 const char *attachment;
13012 int left = get_remote_packet_size ();
13013 int len, attachment_len;
13014 int read_len;
13016 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13017 return {};
13019 remote_buffer_add_string (&p, &left, "vFile:readlink:");
13021 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13022 strlen (filename));
13024 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
13025 remote_errno, &attachment,
13026 &attachment_len);
13028 if (len < 0)
13029 return {};
13031 std::string ret (len, '\0');
13033 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13034 (gdb_byte *) &ret[0], len);
13035 if (read_len != len)
13036 error (_("Readlink returned %d, but %d bytes."), len, read_len);
13038 return ret;
13041 /* Helper function to handle ::fileio_fstat and ::fileio_stat result
13042 processing. When this function is called the remote syscall has been
13043 performed and we know we didn't get an error back.
13045 ATTACHMENT and ATTACHMENT_LEN are the attachment data extracted from the
13046 remote syscall reply. EXPECTED_LEN is the length returned from the
13047 fstat or stat call, this the length of the returned data (in ATTACHMENT)
13048 once it has been decoded. The fstat/stat result (from the ATTACHMENT
13049 data) is to be placed in ST. */
13051 static int
13052 fileio_process_fstat_and_stat_reply (const char *attachment,
13053 int attachment_len,
13054 int expected_len,
13055 struct stat *st)
13057 struct fio_stat fst;
13059 int read_len
13060 = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13061 (gdb_byte *) &fst, sizeof (fst));
13063 if (read_len != expected_len)
13064 error (_("vFile:fstat returned %d, but %d bytes."),
13065 expected_len, read_len);
13067 if (read_len != sizeof (fst))
13068 error (_("vFile:fstat returned %d bytes, but expecting %d."),
13069 read_len, (int) sizeof (fst));
13071 remote_fileio_to_host_stat (&fst, st);
13073 return 0;
13076 /* Implementation of to_fileio_fstat. */
13079 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
13081 struct remote_state *rs = get_remote_state ();
13082 char *p = rs->buf.data ();
13083 int left = get_remote_packet_size ();
13084 int attachment_len, ret;
13085 const char *attachment;
13087 remote_buffer_add_string (&p, &left, "vFile:fstat:");
13089 remote_buffer_add_int (&p, &left, fd);
13091 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
13092 remote_errno, &attachment,
13093 &attachment_len);
13094 if (ret < 0)
13096 if (*remote_errno != FILEIO_ENOSYS)
13097 return ret;
13099 /* Strictly we should return -1, ENOSYS here, but when
13100 "set sysroot remote:" was implemented in August 2008
13101 BFD's need for a stat function was sidestepped with
13102 this hack. This was not remedied until March 2015
13103 so we retain the previous behavior to avoid breaking
13104 compatibility.
13106 Note that the memset is a March 2015 addition; older
13107 GDBs set st_size *and nothing else* so the structure
13108 would have garbage in all other fields. This might
13109 break something but retaining the previous behavior
13110 here would be just too wrong. */
13112 memset (st, 0, sizeof (struct stat));
13113 st->st_size = INT_MAX;
13114 return 0;
13117 return fileio_process_fstat_and_stat_reply (attachment, attachment_len,
13118 ret, st);
13121 /* Implementation of to_fileio_stat. */
13124 remote_target::fileio_stat (struct inferior *inf, const char *filename,
13125 struct stat *st, fileio_error *remote_errno)
13127 struct remote_state *rs = get_remote_state ();
13128 char *p = rs->buf.data ();
13129 int left = get_remote_packet_size () - 1;
13131 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13132 return {};
13134 remote_buffer_add_string (&p, &left, "vFile:stat:");
13136 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13137 strlen (filename));
13139 int attachment_len;
13140 const char *attachment;
13141 int ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_stat,
13142 remote_errno, &attachment,
13143 &attachment_len);
13145 /* Unlike ::fileio_fstat, the stat fileio call was added later on, and
13146 has none of the legacy bfd issues, so we can just return the error. */
13147 if (ret < 0)
13148 return ret;
13150 return fileio_process_fstat_and_stat_reply (attachment, attachment_len,
13151 ret, st);
13154 /* Implementation of to_filesystem_is_local. */
13156 bool
13157 remote_target::filesystem_is_local ()
13159 /* Valgrind GDB presents itself as a remote target but works
13160 on the local filesystem: it does not implement remote get
13161 and users are not expected to set a sysroot. To handle
13162 this case we treat the remote filesystem as local if the
13163 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
13164 does not support vFile:open. */
13165 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
13167 packet_support ps = m_features.packet_support (PACKET_vFile_open);
13169 if (ps == PACKET_SUPPORT_UNKNOWN)
13171 int fd;
13172 fileio_error remote_errno;
13174 /* Try opening a file to probe support. The supplied
13175 filename is irrelevant, we only care about whether
13176 the stub recognizes the packet or not. */
13177 fd = remote_hostio_open (NULL, "just probing",
13178 FILEIO_O_RDONLY, 0700, 0,
13179 &remote_errno);
13181 if (fd >= 0)
13182 remote_hostio_close (fd, &remote_errno);
13184 ps = m_features.packet_support (PACKET_vFile_open);
13187 if (ps == PACKET_DISABLE)
13189 static int warning_issued = 0;
13191 if (!warning_issued)
13193 warning (_("remote target does not support file"
13194 " transfer, attempting to access files"
13195 " from local filesystem."));
13196 warning_issued = 1;
13199 return true;
13203 return false;
13206 static char *
13207 remote_hostio_error (fileio_error errnum)
13209 int host_error = fileio_error_to_host (errnum);
13211 if (host_error == -1)
13212 error (_("Unknown remote I/O error %d"), errnum);
13213 else
13214 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13217 /* A RAII wrapper around a remote file descriptor. */
13219 class scoped_remote_fd
13221 public:
13222 scoped_remote_fd (remote_target *remote, int fd)
13223 : m_remote (remote), m_fd (fd)
13227 ~scoped_remote_fd ()
13229 if (m_fd != -1)
13233 fileio_error remote_errno;
13234 m_remote->remote_hostio_close (m_fd, &remote_errno);
13236 catch (...)
13238 /* Swallow exception before it escapes the dtor. If
13239 something goes wrong, likely the connection is gone,
13240 and there's nothing else that can be done. */
13245 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13247 /* Release ownership of the file descriptor, and return it. */
13248 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13250 int fd = m_fd;
13251 m_fd = -1;
13252 return fd;
13255 /* Return the owned file descriptor. */
13256 int get () const noexcept
13258 return m_fd;
13261 private:
13262 /* The remote target. */
13263 remote_target *m_remote;
13265 /* The owned remote I/O file descriptor. */
13266 int m_fd;
13269 void
13270 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13272 remote_target *remote = get_current_remote_target ();
13274 if (remote == nullptr)
13275 error (_("command can only be used with remote target"));
13277 remote->remote_file_put (local_file, remote_file, from_tty);
13280 void
13281 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13282 int from_tty)
13284 int retcode, bytes, io_size;
13285 fileio_error remote_errno;
13286 int bytes_in_buffer;
13287 int saw_eof;
13288 ULONGEST offset;
13290 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13291 if (file == NULL)
13292 perror_with_name (local_file);
13294 scoped_remote_fd fd
13295 (this, remote_hostio_open (NULL,
13296 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13297 | FILEIO_O_TRUNC),
13298 0700, 0, &remote_errno));
13299 if (fd.get () == -1)
13300 remote_hostio_error (remote_errno);
13302 /* Send up to this many bytes at once. They won't all fit in the
13303 remote packet limit, so we'll transfer slightly fewer. */
13304 io_size = get_remote_packet_size ();
13305 gdb::byte_vector buffer (io_size);
13307 bytes_in_buffer = 0;
13308 saw_eof = 0;
13309 offset = 0;
13310 while (bytes_in_buffer || !saw_eof)
13312 if (!saw_eof)
13314 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13315 io_size - bytes_in_buffer,
13316 file.get ());
13317 if (bytes == 0)
13319 if (ferror (file.get ()))
13320 error (_("Error reading %s."), local_file);
13321 else
13323 /* EOF. Unless there is something still in the
13324 buffer from the last iteration, we are done. */
13325 saw_eof = 1;
13326 if (bytes_in_buffer == 0)
13327 break;
13331 else
13332 bytes = 0;
13334 bytes += bytes_in_buffer;
13335 bytes_in_buffer = 0;
13337 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13338 offset, &remote_errno);
13340 if (retcode < 0)
13341 remote_hostio_error (remote_errno);
13342 else if (retcode == 0)
13343 error (_("Remote write of %d bytes returned 0!"), bytes);
13344 else if (retcode < bytes)
13346 /* Short write. Save the rest of the read data for the next
13347 write. */
13348 bytes_in_buffer = bytes - retcode;
13349 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13352 offset += retcode;
13355 if (remote_hostio_close (fd.release (), &remote_errno))
13356 remote_hostio_error (remote_errno);
13358 if (from_tty)
13359 gdb_printf (_("Successfully sent file \"%ps\".\n"),
13360 styled_string (file_name_style.style (), local_file));
13363 void
13364 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13366 remote_target *remote = get_current_remote_target ();
13368 if (remote == nullptr)
13369 error (_("command can only be used with remote target"));
13371 remote->remote_file_get (remote_file, local_file, from_tty);
13374 void
13375 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13376 int from_tty)
13378 fileio_error remote_errno;
13379 int bytes, io_size;
13380 ULONGEST offset;
13382 scoped_remote_fd fd
13383 (this, remote_hostio_open (NULL,
13384 remote_file, FILEIO_O_RDONLY, 0, 0,
13385 &remote_errno));
13386 if (fd.get () == -1)
13387 remote_hostio_error (remote_errno);
13389 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13390 if (file == NULL)
13391 perror_with_name (local_file);
13393 /* Send up to this many bytes at once. They won't all fit in the
13394 remote packet limit, so we'll transfer slightly fewer. */
13395 io_size = get_remote_packet_size ();
13396 gdb::byte_vector buffer (io_size);
13398 offset = 0;
13399 while (1)
13401 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13402 &remote_errno);
13403 if (bytes == 0)
13404 /* Success, but no bytes, means end-of-file. */
13405 break;
13406 if (bytes == -1)
13407 remote_hostio_error (remote_errno);
13409 offset += bytes;
13411 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13412 if (bytes == 0)
13413 perror_with_name (local_file);
13416 if (remote_hostio_close (fd.release (), &remote_errno))
13417 remote_hostio_error (remote_errno);
13419 if (from_tty)
13420 gdb_printf (_("Successfully fetched file \"%ps\".\n"),
13421 styled_string (file_name_style.style (), remote_file));
13424 void
13425 remote_file_delete (const char *remote_file, int from_tty)
13427 remote_target *remote = get_current_remote_target ();
13429 if (remote == nullptr)
13430 error (_("command can only be used with remote target"));
13432 remote->remote_file_delete (remote_file, from_tty);
13435 void
13436 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13438 int retcode;
13439 fileio_error remote_errno;
13441 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13442 if (retcode == -1)
13443 remote_hostio_error (remote_errno);
13445 if (from_tty)
13446 gdb_printf (_("Successfully deleted file \"%ps\".\n"),
13447 styled_string (file_name_style.style (), remote_file));
13450 static void
13451 remote_put_command (const char *args, int from_tty)
13453 if (args == NULL)
13454 error_no_arg (_("file to put"));
13456 gdb_argv argv (args);
13457 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13458 error (_("Invalid parameters to remote put"));
13460 remote_file_put (argv[0], argv[1], from_tty);
13463 static void
13464 remote_get_command (const char *args, int from_tty)
13466 if (args == NULL)
13467 error_no_arg (_("file to get"));
13469 gdb_argv argv (args);
13470 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13471 error (_("Invalid parameters to remote get"));
13473 remote_file_get (argv[0], argv[1], from_tty);
13476 static void
13477 remote_delete_command (const char *args, int from_tty)
13479 if (args == NULL)
13480 error_no_arg (_("file to delete"));
13482 gdb_argv argv (args);
13483 if (argv[0] == NULL || argv[1] != NULL)
13484 error (_("Invalid parameters to remote delete"));
13486 remote_file_delete (argv[0], from_tty);
13489 bool
13490 remote_target::can_execute_reverse ()
13492 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13493 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13494 return true;
13495 else
13496 return false;
13499 bool
13500 remote_target::supports_non_stop ()
13502 return true;
13505 bool
13506 remote_target::supports_disable_randomization ()
13508 /* Only supported in extended mode. */
13509 return false;
13512 bool
13513 remote_target::supports_multi_process ()
13515 return m_features.remote_multi_process_p ();
13519 remote_target::remote_supports_cond_tracepoints ()
13521 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13522 == PACKET_ENABLE);
13525 bool
13526 remote_target::supports_evaluation_of_breakpoint_conditions ()
13528 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13529 == PACKET_ENABLE);
13533 remote_target::remote_supports_fast_tracepoints ()
13535 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13539 remote_target::remote_supports_static_tracepoints ()
13541 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13545 remote_target::remote_supports_install_in_trace ()
13547 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13550 bool
13551 remote_target::supports_enable_disable_tracepoint ()
13553 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13554 == PACKET_ENABLE);
13557 bool
13558 remote_target::supports_string_tracing ()
13560 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13563 bool
13564 remote_target::can_run_breakpoint_commands ()
13566 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13569 void
13570 remote_target::trace_init ()
13572 struct remote_state *rs = get_remote_state ();
13574 putpkt ("QTinit");
13575 remote_get_noisy_reply ();
13576 if (strcmp (rs->buf.data (), "OK") != 0)
13577 error (_("Target does not support this command."));
13580 /* Recursive routine to walk through command list including loops, and
13581 download packets for each command. */
13583 void
13584 remote_target::remote_download_command_source (int num, ULONGEST addr,
13585 struct command_line *cmds)
13587 struct remote_state *rs = get_remote_state ();
13588 struct command_line *cmd;
13590 for (cmd = cmds; cmd; cmd = cmd->next)
13592 QUIT; /* Allow user to bail out with ^C. */
13593 strcpy (rs->buf.data (), "QTDPsrc:");
13594 encode_source_string (num, addr, "cmd", cmd->line,
13595 rs->buf.data () + strlen (rs->buf.data ()),
13596 rs->buf.size () - strlen (rs->buf.data ()));
13597 putpkt (rs->buf);
13598 remote_get_noisy_reply ();
13599 if (strcmp (rs->buf.data (), "OK"))
13600 warning (_("Target does not support source download."));
13602 if (cmd->control_type == while_control
13603 || cmd->control_type == while_stepping_control)
13605 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13607 QUIT; /* Allow user to bail out with ^C. */
13608 strcpy (rs->buf.data (), "QTDPsrc:");
13609 encode_source_string (num, addr, "cmd", "end",
13610 rs->buf.data () + strlen (rs->buf.data ()),
13611 rs->buf.size () - strlen (rs->buf.data ()));
13612 putpkt (rs->buf);
13613 remote_get_noisy_reply ();
13614 if (strcmp (rs->buf.data (), "OK"))
13615 warning (_("Target does not support source download."));
13620 void
13621 remote_target::download_tracepoint (struct bp_location *loc)
13623 CORE_ADDR tpaddr;
13624 char addrbuf[40];
13625 std::vector<std::string> tdp_actions;
13626 std::vector<std::string> stepping_actions;
13627 char *pkt;
13628 struct breakpoint *b = loc->owner;
13629 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13630 struct remote_state *rs = get_remote_state ();
13631 int ret;
13632 const char *err_msg = _("Tracepoint packet too large for target.");
13633 size_t size_left;
13635 /* We use a buffer other than rs->buf because we'll build strings
13636 across multiple statements, and other statements in between could
13637 modify rs->buf. */
13638 gdb::char_vector buf (get_remote_packet_size ());
13640 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13642 tpaddr = loc->address;
13643 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13644 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13645 b->number, addrbuf, /* address */
13646 (b->enable_state == bp_enabled ? 'E' : 'D'),
13647 t->step_count, t->pass_count);
13649 if (ret < 0 || ret >= buf.size ())
13650 error ("%s", err_msg);
13652 /* Fast tracepoints are mostly handled by the target, but we can
13653 tell the target how big of an instruction block should be moved
13654 around. */
13655 if (b->type == bp_fast_tracepoint)
13657 /* Only test for support at download time; we may not know
13658 target capabilities at definition time. */
13659 if (remote_supports_fast_tracepoints ())
13661 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13662 NULL))
13664 size_left = buf.size () - strlen (buf.data ());
13665 ret = snprintf (buf.data () + strlen (buf.data ()),
13666 size_left, ":F%x",
13667 gdb_insn_length (loc->gdbarch, tpaddr));
13669 if (ret < 0 || ret >= size_left)
13670 error ("%s", err_msg);
13672 else
13673 /* If it passed validation at definition but fails now,
13674 something is very wrong. */
13675 internal_error (_("Fast tracepoint not valid during download"));
13677 else
13678 /* Fast tracepoints are functionally identical to regular
13679 tracepoints, so don't take lack of support as a reason to
13680 give up on the trace run. */
13681 warning (_("Target does not support fast tracepoints, "
13682 "downloading %d as regular tracepoint"), b->number);
13684 else if (b->type == bp_static_tracepoint
13685 || b->type == bp_static_marker_tracepoint)
13687 /* Only test for support at download time; we may not know
13688 target capabilities at definition time. */
13689 if (remote_supports_static_tracepoints ())
13691 struct static_tracepoint_marker marker;
13693 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13695 size_left = buf.size () - strlen (buf.data ());
13696 ret = snprintf (buf.data () + strlen (buf.data ()),
13697 size_left, ":S");
13699 if (ret < 0 || ret >= size_left)
13700 error ("%s", err_msg);
13702 else
13703 error (_("Static tracepoint not valid during download"));
13705 else
13706 /* Fast tracepoints are functionally identical to regular
13707 tracepoints, so don't take lack of support as a reason
13708 to give up on the trace run. */
13709 error (_("Target does not support static tracepoints"));
13711 /* If the tracepoint has a conditional, make it into an agent
13712 expression and append to the definition. */
13713 if (loc->cond)
13715 /* Only test support at download time, we may not know target
13716 capabilities at definition time. */
13717 if (remote_supports_cond_tracepoints ())
13719 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13720 loc->cond.get ());
13722 size_left = buf.size () - strlen (buf.data ());
13724 ret = snprintf (buf.data () + strlen (buf.data ()),
13725 size_left, ":X%x,", (int) aexpr->buf.size ());
13727 if (ret < 0 || ret >= size_left)
13728 error ("%s", err_msg);
13730 size_left = buf.size () - strlen (buf.data ());
13732 /* Two bytes to encode each aexpr byte, plus the terminating
13733 null byte. */
13734 if (aexpr->buf.size () * 2 + 1 > size_left)
13735 error ("%s", err_msg);
13737 pkt = buf.data () + strlen (buf.data ());
13739 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13740 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13741 *pkt = '\0';
13743 else
13744 warning (_("Target does not support conditional tracepoints, "
13745 "ignoring tp %d cond"), b->number);
13748 if (b->commands || !default_collect.empty ())
13750 size_left = buf.size () - strlen (buf.data ());
13752 ret = snprintf (buf.data () + strlen (buf.data ()),
13753 size_left, "-");
13755 if (ret < 0 || ret >= size_left)
13756 error ("%s", err_msg);
13759 putpkt (buf.data ());
13760 remote_get_noisy_reply ();
13761 if (strcmp (rs->buf.data (), "OK"))
13762 error (_("Target does not support tracepoints."));
13764 /* do_single_steps (t); */
13765 for (auto action_it = tdp_actions.begin ();
13766 action_it != tdp_actions.end (); action_it++)
13768 QUIT; /* Allow user to bail out with ^C. */
13770 bool has_more = ((action_it + 1) != tdp_actions.end ()
13771 || !stepping_actions.empty ());
13773 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13774 b->number, addrbuf, /* address */
13775 action_it->c_str (),
13776 has_more ? '-' : 0);
13778 if (ret < 0 || ret >= buf.size ())
13779 error ("%s", err_msg);
13781 putpkt (buf.data ());
13782 remote_get_noisy_reply ();
13783 if (strcmp (rs->buf.data (), "OK"))
13784 error (_("Error on target while setting tracepoints."));
13787 for (auto action_it = stepping_actions.begin ();
13788 action_it != stepping_actions.end (); action_it++)
13790 QUIT; /* Allow user to bail out with ^C. */
13792 bool is_first = action_it == stepping_actions.begin ();
13793 bool has_more = (action_it + 1) != stepping_actions.end ();
13795 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13796 b->number, addrbuf, /* address */
13797 is_first ? "S" : "",
13798 action_it->c_str (),
13799 has_more ? "-" : "");
13801 if (ret < 0 || ret >= buf.size ())
13802 error ("%s", err_msg);
13804 putpkt (buf.data ());
13805 remote_get_noisy_reply ();
13806 if (strcmp (rs->buf.data (), "OK"))
13807 error (_("Error on target while setting tracepoints."));
13810 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13812 if (b->locspec != nullptr)
13814 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13816 if (ret < 0 || ret >= buf.size ())
13817 error ("%s", err_msg);
13819 const char *str = b->locspec->to_string ();
13820 encode_source_string (b->number, loc->address, "at", str,
13821 buf.data () + strlen (buf.data ()),
13822 buf.size () - strlen (buf.data ()));
13823 putpkt (buf.data ());
13824 remote_get_noisy_reply ();
13825 if (strcmp (rs->buf.data (), "OK"))
13826 warning (_("Target does not support source download."));
13828 if (b->cond_string)
13830 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13832 if (ret < 0 || ret >= buf.size ())
13833 error ("%s", err_msg);
13835 encode_source_string (b->number, loc->address,
13836 "cond", b->cond_string.get (),
13837 buf.data () + strlen (buf.data ()),
13838 buf.size () - strlen (buf.data ()));
13839 putpkt (buf.data ());
13840 remote_get_noisy_reply ();
13841 if (strcmp (rs->buf.data (), "OK"))
13842 warning (_("Target does not support source download."));
13844 remote_download_command_source (b->number, loc->address,
13845 breakpoint_commands (b));
13849 bool
13850 remote_target::can_download_tracepoint ()
13852 struct remote_state *rs = get_remote_state ();
13853 struct trace_status *ts;
13854 int status;
13856 /* Don't try to install tracepoints until we've relocated our
13857 symbols, and fetched and merged the target's tracepoint list with
13858 ours. */
13859 if (rs->starting_up)
13860 return false;
13862 ts = current_trace_status ();
13863 status = get_trace_status (ts);
13865 if (status == -1 || !ts->running_known || !ts->running)
13866 return false;
13868 /* If we are in a tracing experiment, but remote stub doesn't support
13869 installing tracepoint in trace, we have to return. */
13870 if (!remote_supports_install_in_trace ())
13871 return false;
13873 return true;
13877 void
13878 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13880 struct remote_state *rs = get_remote_state ();
13881 char *p;
13883 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13884 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13885 tsv.builtin);
13886 p = rs->buf.data () + strlen (rs->buf.data ());
13887 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13888 >= get_remote_packet_size ())
13889 error (_("Trace state variable name too long for tsv definition packet"));
13890 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13891 *p++ = '\0';
13892 putpkt (rs->buf);
13893 remote_get_noisy_reply ();
13894 if (rs->buf[0] == '\0')
13895 error (_("Target does not support this command."));
13896 if (strcmp (rs->buf.data (), "OK") != 0)
13897 error (_("Error on target while downloading trace state variable."));
13900 void
13901 remote_target::enable_tracepoint (struct bp_location *location)
13903 struct remote_state *rs = get_remote_state ();
13905 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13906 location->owner->number,
13907 phex (location->address, sizeof (CORE_ADDR)));
13908 putpkt (rs->buf);
13909 remote_get_noisy_reply ();
13910 if (rs->buf[0] == '\0')
13911 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13912 if (strcmp (rs->buf.data (), "OK") != 0)
13913 error (_("Error on target while enabling tracepoint."));
13916 void
13917 remote_target::disable_tracepoint (struct bp_location *location)
13919 struct remote_state *rs = get_remote_state ();
13921 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13922 location->owner->number,
13923 phex (location->address, sizeof (CORE_ADDR)));
13924 putpkt (rs->buf);
13925 remote_get_noisy_reply ();
13926 if (rs->buf[0] == '\0')
13927 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13928 if (strcmp (rs->buf.data (), "OK") != 0)
13929 error (_("Error on target while disabling tracepoint."));
13932 void
13933 remote_target::trace_set_readonly_regions ()
13935 asection *s;
13936 bfd_size_type size;
13937 bfd_vma vma;
13938 int anysecs = 0;
13939 int offset = 0;
13940 bfd *abfd = current_program_space->exec_bfd ();
13942 if (!abfd)
13943 return; /* No information to give. */
13945 struct remote_state *rs = get_remote_state ();
13947 strcpy (rs->buf.data (), "QTro");
13948 offset = strlen (rs->buf.data ());
13949 for (s = abfd->sections; s; s = s->next)
13951 char tmp1[40], tmp2[40];
13952 int sec_length;
13954 if ((s->flags & SEC_LOAD) == 0
13955 /* || (s->flags & SEC_CODE) == 0 */
13956 || (s->flags & SEC_READONLY) == 0)
13957 continue;
13959 anysecs = 1;
13960 vma = bfd_section_vma (s);
13961 size = bfd_section_size (s);
13962 bfd_sprintf_vma (abfd, tmp1, vma);
13963 bfd_sprintf_vma (abfd, tmp2, vma + size);
13964 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13965 if (offset + sec_length + 1 > rs->buf.size ())
13967 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13968 != PACKET_ENABLE)
13969 warning (_("\
13970 Too many sections for read-only sections definition packet."));
13971 break;
13973 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13974 tmp1, tmp2);
13975 offset += sec_length;
13977 if (anysecs)
13979 putpkt (rs->buf);
13980 getpkt (&rs->buf);
13984 void
13985 remote_target::trace_start ()
13987 struct remote_state *rs = get_remote_state ();
13989 putpkt ("QTStart");
13990 remote_get_noisy_reply ();
13991 if (rs->buf[0] == '\0')
13992 error (_("Target does not support this command."));
13993 if (strcmp (rs->buf.data (), "OK") != 0)
13994 error (_("Bogus reply from target: %s"), rs->buf.data ());
13998 remote_target::get_trace_status (struct trace_status *ts)
14000 /* Initialize it just to avoid a GCC false warning. */
14001 char *p = NULL;
14002 struct remote_state *rs = get_remote_state ();
14004 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
14005 return -1;
14007 /* FIXME we need to get register block size some other way. */
14008 trace_regblock_size
14009 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
14011 putpkt ("qTStatus");
14015 p = remote_get_noisy_reply ();
14017 catch (const gdb_exception_error &ex)
14019 if (ex.error != TARGET_CLOSE_ERROR)
14021 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
14022 return -1;
14024 throw;
14027 packet_result result = m_features.packet_ok (p, PACKET_qTStatus);
14029 switch (result.status ())
14031 case PACKET_ERROR:
14032 error (_("Remote failure reply: %s"), result.err_msg ());
14033 /* If the remote target doesn't do tracing, flag it. */
14034 case PACKET_UNKNOWN:
14035 return -1;
14038 /* We're working with a live target. */
14039 ts->filename = NULL;
14041 if (*p++ != 'T')
14042 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
14044 /* Function 'parse_trace_status' sets default value of each field of
14045 'ts' at first, so we don't have to do it here. */
14046 parse_trace_status (p, ts);
14048 return ts->running;
14051 void
14052 remote_target::get_tracepoint_status (tracepoint *tp,
14053 struct uploaded_tp *utp)
14055 struct remote_state *rs = get_remote_state ();
14056 char *reply;
14057 size_t size = get_remote_packet_size ();
14059 if (tp)
14061 tp->hit_count = 0;
14062 tp->traceframe_usage = 0;
14063 for (bp_location &loc : tp->locations ())
14065 /* If the tracepoint was never downloaded, don't go asking for
14066 any status. */
14067 if (tp->number_on_target == 0)
14068 continue;
14069 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
14070 phex_nz (loc.address, 0));
14071 putpkt (rs->buf);
14072 reply = remote_get_noisy_reply ();
14073 if (reply && *reply)
14075 if (*reply == 'V')
14076 parse_tracepoint_status (reply + 1, tp, utp);
14080 else if (utp)
14082 utp->hit_count = 0;
14083 utp->traceframe_usage = 0;
14084 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
14085 phex_nz (utp->addr, 0));
14086 putpkt (rs->buf);
14087 reply = remote_get_noisy_reply ();
14088 if (reply && *reply)
14090 if (*reply == 'V')
14091 parse_tracepoint_status (reply + 1, tp, utp);
14096 void
14097 remote_target::trace_stop ()
14099 struct remote_state *rs = get_remote_state ();
14101 putpkt ("QTStop");
14102 remote_get_noisy_reply ();
14103 if (rs->buf[0] == '\0')
14104 error (_("Target does not support this command."));
14105 if (strcmp (rs->buf.data (), "OK") != 0)
14106 error (_("Bogus reply from target: %s"), rs->buf.data ());
14110 remote_target::trace_find (enum trace_find_type type, int num,
14111 CORE_ADDR addr1, CORE_ADDR addr2,
14112 int *tpp)
14114 struct remote_state *rs = get_remote_state ();
14115 char *endbuf = rs->buf.data () + get_remote_packet_size ();
14116 char *p, *reply;
14117 int target_frameno = -1, target_tracept = -1;
14119 /* Lookups other than by absolute frame number depend on the current
14120 trace selected, so make sure it is correct on the remote end
14121 first. */
14122 if (type != tfind_number)
14123 set_remote_traceframe ();
14125 p = rs->buf.data ();
14126 strcpy (p, "QTFrame:");
14127 p = strchr (p, '\0');
14128 switch (type)
14130 case tfind_number:
14131 xsnprintf (p, endbuf - p, "%x", num);
14132 break;
14133 case tfind_pc:
14134 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
14135 break;
14136 case tfind_tp:
14137 xsnprintf (p, endbuf - p, "tdp:%x", num);
14138 break;
14139 case tfind_range:
14140 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
14141 phex_nz (addr2, 0));
14142 break;
14143 case tfind_outside:
14144 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
14145 phex_nz (addr2, 0));
14146 break;
14147 default:
14148 error (_("Unknown trace find type %d"), type);
14151 putpkt (rs->buf);
14152 reply = remote_get_noisy_reply ();
14153 if (*reply == '\0')
14154 error (_("Target does not support this command."));
14156 while (reply && *reply)
14157 switch (*reply)
14159 case 'F':
14160 p = ++reply;
14161 target_frameno = (int) strtol (p, &reply, 16);
14162 if (reply == p)
14163 error (_("Unable to parse trace frame number"));
14164 /* Don't update our remote traceframe number cache on failure
14165 to select a remote traceframe. */
14166 if (target_frameno == -1)
14167 return -1;
14168 break;
14169 case 'T':
14170 p = ++reply;
14171 target_tracept = (int) strtol (p, &reply, 16);
14172 if (reply == p)
14173 error (_("Unable to parse tracepoint number"));
14174 break;
14175 case 'O': /* "OK"? */
14176 if (reply[1] == 'K' && reply[2] == '\0')
14177 reply += 2;
14178 else
14179 error (_("Bogus reply from target: %s"), reply);
14180 break;
14181 default:
14182 error (_("Bogus reply from target: %s"), reply);
14184 if (tpp)
14185 *tpp = target_tracept;
14187 rs->remote_traceframe_number = target_frameno;
14188 return target_frameno;
14191 bool
14192 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
14194 struct remote_state *rs = get_remote_state ();
14195 char *reply;
14196 ULONGEST uval;
14198 set_remote_traceframe ();
14200 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
14201 putpkt (rs->buf);
14202 reply = remote_get_noisy_reply ();
14203 if (reply && *reply)
14205 if (*reply == 'V')
14207 unpack_varlen_hex (reply + 1, &uval);
14208 *val = (LONGEST) uval;
14209 return true;
14212 return false;
14216 remote_target::save_trace_data (const char *filename)
14218 struct remote_state *rs = get_remote_state ();
14219 char *p, *reply;
14221 p = rs->buf.data ();
14222 strcpy (p, "QTSave:");
14223 p += strlen (p);
14224 if ((p - rs->buf.data ()) + strlen (filename) * 2
14225 >= get_remote_packet_size ())
14226 error (_("Remote file name too long for trace save packet"));
14227 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14228 *p++ = '\0';
14229 putpkt (rs->buf);
14230 reply = remote_get_noisy_reply ();
14231 if (*reply == '\0')
14232 error (_("Target does not support this command."));
14233 if (strcmp (reply, "OK") != 0)
14234 error (_("Bogus reply from target: %s"), reply);
14235 return 0;
14238 /* This is basically a memory transfer, but needs to be its own packet
14239 because we don't know how the target actually organizes its trace
14240 memory, plus we want to be able to ask for as much as possible, but
14241 not be unhappy if we don't get as much as we ask for. */
14243 LONGEST
14244 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14246 struct remote_state *rs = get_remote_state ();
14247 char *reply;
14248 char *p;
14249 int rslt;
14251 p = rs->buf.data ();
14252 strcpy (p, "qTBuffer:");
14253 p += strlen (p);
14254 p += hexnumstr (p, offset);
14255 *p++ = ',';
14256 p += hexnumstr (p, len);
14257 *p++ = '\0';
14259 putpkt (rs->buf);
14260 reply = remote_get_noisy_reply ();
14261 if (reply && *reply)
14263 /* 'l' by itself means we're at the end of the buffer and
14264 there is nothing more to get. */
14265 if (*reply == 'l')
14266 return 0;
14268 /* Convert the reply into binary. Limit the number of bytes to
14269 convert according to our passed-in buffer size, rather than
14270 what was returned in the packet; if the target is
14271 unexpectedly generous and gives us a bigger reply than we
14272 asked for, we don't want to crash. */
14273 rslt = hex2bin (reply, buf, len);
14274 return rslt;
14277 /* Something went wrong, flag as an error. */
14278 return -1;
14281 void
14282 remote_target::set_disconnected_tracing (int val)
14284 struct remote_state *rs = get_remote_state ();
14286 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14287 == PACKET_ENABLE)
14289 char *reply;
14291 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14292 "QTDisconnected:%x", val);
14293 putpkt (rs->buf);
14294 reply = remote_get_noisy_reply ();
14295 if (*reply == '\0')
14296 error (_("Target does not support this command."));
14297 if (strcmp (reply, "OK") != 0)
14298 error (_("Bogus reply from target: %s"), reply);
14300 else if (val)
14301 warning (_("Target does not support disconnected tracing."));
14305 remote_target::core_of_thread (ptid_t ptid)
14307 thread_info *info = this->find_thread (ptid);
14309 if (info != NULL && info->priv != NULL)
14310 return get_remote_thread_info (info)->core;
14312 return -1;
14315 void
14316 remote_target::set_circular_trace_buffer (int val)
14318 struct remote_state *rs = get_remote_state ();
14319 char *reply;
14321 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14322 "QTBuffer:circular:%x", val);
14323 putpkt (rs->buf);
14324 reply = remote_get_noisy_reply ();
14325 if (*reply == '\0')
14326 error (_("Target does not support this command."));
14327 if (strcmp (reply, "OK") != 0)
14328 error (_("Bogus reply from target: %s"), reply);
14331 traceframe_info_up
14332 remote_target::traceframe_info ()
14334 std::optional<gdb::char_vector> text
14335 = target_read_stralloc (current_inferior ()->top_target (),
14336 TARGET_OBJECT_TRACEFRAME_INFO,
14337 NULL);
14338 if (text)
14339 return parse_traceframe_info (text->data ());
14341 return NULL;
14344 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14345 instruction on which a fast tracepoint may be placed. Returns -1
14346 if the packet is not supported, and 0 if the minimum instruction
14347 length is unknown. */
14350 remote_target::get_min_fast_tracepoint_insn_len ()
14352 struct remote_state *rs = get_remote_state ();
14353 char *reply;
14355 /* If we're not debugging a process yet, the IPA can't be
14356 loaded. */
14357 if (!target_has_execution ())
14358 return 0;
14360 /* Make sure the remote is pointing at the right process. */
14361 set_general_process ();
14363 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14364 putpkt (rs->buf);
14365 reply = remote_get_noisy_reply ();
14366 if (*reply == '\0')
14367 return -1;
14368 else
14370 ULONGEST min_insn_len;
14372 unpack_varlen_hex (reply, &min_insn_len);
14374 return (int) min_insn_len;
14378 void
14379 remote_target::set_trace_buffer_size (LONGEST val)
14381 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14383 struct remote_state *rs = get_remote_state ();
14384 char *buf = rs->buf.data ();
14385 char *endbuf = buf + get_remote_packet_size ();
14387 gdb_assert (val >= 0 || val == -1);
14388 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14389 /* Send -1 as literal "-1" to avoid host size dependency. */
14390 if (val < 0)
14392 *buf++ = '-';
14393 buf += hexnumstr (buf, (ULONGEST) -val);
14395 else
14396 buf += hexnumstr (buf, (ULONGEST) val);
14398 putpkt (rs->buf);
14399 remote_get_noisy_reply ();
14400 packet_result result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14401 switch (result.status ())
14403 case PACKET_ERROR:
14404 warning (_("Error reply from target: %s"), result.err_msg ());
14405 break;
14406 case PACKET_UNKNOWN:
14407 warning (_("Remote target failed to process the request "));
14412 bool
14413 remote_target::set_trace_notes (const char *user, const char *notes,
14414 const char *stop_notes)
14416 struct remote_state *rs = get_remote_state ();
14417 char *reply;
14418 char *buf = rs->buf.data ();
14419 char *endbuf = buf + get_remote_packet_size ();
14420 int nbytes;
14422 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14423 if (user)
14425 buf += xsnprintf (buf, endbuf - buf, "user:");
14426 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14427 buf += 2 * nbytes;
14428 *buf++ = ';';
14430 if (notes)
14432 buf += xsnprintf (buf, endbuf - buf, "notes:");
14433 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14434 buf += 2 * nbytes;
14435 *buf++ = ';';
14437 if (stop_notes)
14439 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14440 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14441 buf += 2 * nbytes;
14442 *buf++ = ';';
14444 /* Ensure the buffer is terminated. */
14445 *buf = '\0';
14447 putpkt (rs->buf);
14448 reply = remote_get_noisy_reply ();
14449 if (*reply == '\0')
14450 return false;
14452 if (strcmp (reply, "OK") != 0)
14453 error (_("Bogus reply from target: %s"), reply);
14455 return true;
14458 bool
14459 remote_target::use_agent (bool use)
14461 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14463 struct remote_state *rs = get_remote_state ();
14465 /* If the stub supports QAgent. */
14466 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14467 putpkt (rs->buf);
14468 getpkt (&rs->buf);
14470 if (strcmp (rs->buf.data (), "OK") == 0)
14472 ::use_agent = use;
14473 return true;
14477 return false;
14480 bool
14481 remote_target::can_use_agent ()
14483 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14486 #if defined (HAVE_LIBEXPAT)
14488 /* Check the btrace document version. */
14490 static void
14491 check_xml_btrace_version (struct gdb_xml_parser *parser,
14492 const struct gdb_xml_element *element,
14493 void *user_data,
14494 std::vector<gdb_xml_value> &attributes)
14496 const char *version
14497 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14499 if (strcmp (version, "1.0") != 0)
14500 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14503 /* Parse a btrace "block" xml record. */
14505 static void
14506 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14507 const struct gdb_xml_element *element,
14508 void *user_data,
14509 std::vector<gdb_xml_value> &attributes)
14511 struct btrace_data *btrace;
14512 ULONGEST *begin, *end;
14514 btrace = (struct btrace_data *) user_data;
14516 switch (btrace->format)
14518 case BTRACE_FORMAT_BTS:
14519 break;
14521 case BTRACE_FORMAT_NONE:
14522 btrace->format = BTRACE_FORMAT_BTS;
14523 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14524 break;
14526 default:
14527 gdb_xml_error (parser, _("Btrace format error."));
14530 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14531 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14532 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14535 /* Parse a "raw" xml record. */
14537 static void
14538 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14539 gdb_byte **pdata, size_t *psize)
14541 gdb_byte *bin;
14542 size_t len, size;
14544 len = strlen (body_text);
14545 if (len % 2 != 0)
14546 gdb_xml_error (parser, _("Bad raw data size."));
14548 size = len / 2;
14550 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14551 bin = data.get ();
14553 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14554 while (len > 0)
14556 char hi, lo;
14558 hi = *body_text++;
14559 lo = *body_text++;
14561 if (hi == 0 || lo == 0)
14562 gdb_xml_error (parser, _("Bad hex encoding."));
14564 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14565 len -= 2;
14568 *pdata = data.release ();
14569 *psize = size;
14572 /* Parse a btrace pt-config "cpu" xml record. */
14574 static void
14575 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14576 const struct gdb_xml_element *element,
14577 void *user_data,
14578 std::vector<gdb_xml_value> &attributes)
14580 struct btrace_data *btrace;
14581 const char *vendor;
14582 ULONGEST *family, *model, *stepping;
14584 vendor
14585 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14586 family
14587 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14588 model
14589 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14590 stepping
14591 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14593 btrace = (struct btrace_data *) user_data;
14595 if (strcmp (vendor, "GenuineIntel") == 0)
14596 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14598 btrace->variant.pt.config.cpu.family = *family;
14599 btrace->variant.pt.config.cpu.model = *model;
14600 btrace->variant.pt.config.cpu.stepping = *stepping;
14603 /* Parse a btrace pt "raw" xml record. */
14605 static void
14606 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14607 const struct gdb_xml_element *element,
14608 void *user_data, const char *body_text)
14610 struct btrace_data *btrace;
14612 btrace = (struct btrace_data *) user_data;
14613 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14614 &btrace->variant.pt.size);
14617 /* Parse a btrace "pt" xml record. */
14619 static void
14620 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14621 const struct gdb_xml_element *element,
14622 void *user_data,
14623 std::vector<gdb_xml_value> &attributes)
14625 struct btrace_data *btrace;
14627 btrace = (struct btrace_data *) user_data;
14628 btrace->format = BTRACE_FORMAT_PT;
14629 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14630 btrace->variant.pt.data = NULL;
14631 btrace->variant.pt.size = 0;
14634 static const struct gdb_xml_attribute block_attributes[] = {
14635 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14636 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14637 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14640 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14641 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14642 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14643 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14644 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14645 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14648 static const struct gdb_xml_element btrace_pt_config_children[] = {
14649 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14650 parse_xml_btrace_pt_config_cpu, NULL },
14651 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14654 static const struct gdb_xml_element btrace_pt_children[] = {
14655 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14656 NULL },
14657 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14658 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14661 static const struct gdb_xml_attribute btrace_attributes[] = {
14662 { "version", GDB_XML_AF_NONE, NULL, NULL },
14663 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14666 static const struct gdb_xml_element btrace_children[] = {
14667 { "block", block_attributes, NULL,
14668 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14669 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14670 NULL },
14671 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14674 static const struct gdb_xml_element btrace_elements[] = {
14675 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14676 check_xml_btrace_version, NULL },
14677 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14680 #endif /* defined (HAVE_LIBEXPAT) */
14682 /* Parse a branch trace xml document XML into DATA. */
14684 static void
14685 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14687 #if defined (HAVE_LIBEXPAT)
14689 int errcode;
14690 btrace_data result;
14691 result.format = BTRACE_FORMAT_NONE;
14693 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14694 buffer, &result);
14695 if (errcode != 0)
14696 error (_("Error parsing branch trace."));
14698 /* Keep parse results. */
14699 *btrace = std::move (result);
14701 #else /* !defined (HAVE_LIBEXPAT) */
14703 error (_("Cannot process branch trace. XML support was disabled at "
14704 "compile time."));
14706 #endif /* !defined (HAVE_LIBEXPAT) */
14709 #if defined (HAVE_LIBEXPAT)
14711 /* Parse a btrace-conf "bts" xml record. */
14713 static void
14714 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14715 const struct gdb_xml_element *element,
14716 void *user_data,
14717 std::vector<gdb_xml_value> &attributes)
14719 struct btrace_config *conf;
14720 struct gdb_xml_value *size;
14722 conf = (struct btrace_config *) user_data;
14723 conf->format = BTRACE_FORMAT_BTS;
14724 conf->bts.size = 0;
14726 size = xml_find_attribute (attributes, "size");
14727 if (size != NULL)
14728 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14731 /* Parse a btrace-conf "pt" xml record. */
14733 static void
14734 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14735 const struct gdb_xml_element *element,
14736 void *user_data,
14737 std::vector<gdb_xml_value> &attributes)
14739 struct btrace_config *conf;
14740 struct gdb_xml_value *size;
14742 conf = (struct btrace_config *) user_data;
14743 conf->format = BTRACE_FORMAT_PT;
14744 conf->pt.size = 0;
14746 size = xml_find_attribute (attributes, "size");
14747 if (size != NULL)
14748 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14751 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14752 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14753 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14756 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14757 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14758 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14761 static const struct gdb_xml_element btrace_conf_children[] = {
14762 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14763 parse_xml_btrace_conf_bts, NULL },
14764 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14765 parse_xml_btrace_conf_pt, NULL },
14766 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14769 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14770 { "version", GDB_XML_AF_NONE, NULL, NULL },
14771 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14774 static const struct gdb_xml_element btrace_conf_elements[] = {
14775 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14776 GDB_XML_EF_NONE, NULL, NULL },
14777 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14780 #endif /* defined (HAVE_LIBEXPAT) */
14782 /* Parse a branch trace configuration xml document XML into CONF. */
14784 static void
14785 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14787 #if defined (HAVE_LIBEXPAT)
14789 int errcode;
14790 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14791 btrace_conf_elements, xml, conf);
14792 if (errcode != 0)
14793 error (_("Error parsing branch trace configuration."));
14795 #else /* !defined (HAVE_LIBEXPAT) */
14797 error (_("Cannot process the branch trace configuration. XML support "
14798 "was disabled at compile time."));
14800 #endif /* !defined (HAVE_LIBEXPAT) */
14803 /* Reset our idea of our target's btrace configuration. */
14805 static void
14806 remote_btrace_reset (remote_state *rs)
14808 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14811 /* Synchronize the configuration with the target. */
14813 void
14814 remote_target::btrace_sync_conf (const btrace_config *conf)
14816 struct remote_state *rs;
14817 char *buf, *pos, *endbuf;
14819 rs = get_remote_state ();
14820 buf = rs->buf.data ();
14821 endbuf = buf + get_remote_packet_size ();
14823 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14824 && conf->bts.size != rs->btrace_config.bts.size)
14826 pos = buf;
14827 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14828 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14829 conf->bts.size);
14831 putpkt (buf);
14832 getpkt (&rs->buf);
14834 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size);
14835 if (result.status () == PACKET_ERROR)
14836 error (_("Failed to configure the BTS buffer size: %s"), result.err_msg ());
14838 rs->btrace_config.bts.size = conf->bts.size;
14841 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14842 && conf->pt.size != rs->btrace_config.pt.size)
14844 pos = buf;
14845 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14846 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14847 conf->pt.size);
14849 putpkt (buf);
14850 getpkt (&rs->buf);
14852 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size);
14853 if (result.status () == PACKET_ERROR)
14854 error (_("Failed to configure the trace buffer size: %s"), result.err_msg ());
14856 rs->btrace_config.pt.size = conf->pt.size;
14860 /* Read TP's btrace configuration from the target and store it into CONF. */
14862 static void
14863 btrace_read_config (thread_info *tp, btrace_config *conf)
14865 /* target_read_stralloc relies on INFERIOR_PTID. */
14866 scoped_restore_current_thread restore_thread;
14867 switch_to_thread (tp);
14869 std::optional<gdb::char_vector> xml
14870 = target_read_stralloc (current_inferior ()->top_target (),
14871 TARGET_OBJECT_BTRACE_CONF, "");
14872 if (xml)
14873 parse_xml_btrace_conf (conf, xml->data ());
14876 /* Maybe reopen target btrace. */
14878 void
14879 remote_target::remote_btrace_maybe_reopen ()
14881 struct remote_state *rs = get_remote_state ();
14882 int btrace_target_pushed = 0;
14883 #if !defined (HAVE_LIBIPT)
14884 int warned = 0;
14885 #endif
14887 /* Don't bother walking the entirety of the remote thread list when
14888 we know the feature isn't supported by the remote. */
14889 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14890 return;
14892 for (thread_info *tp : all_non_exited_threads (this))
14894 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14895 btrace_read_config (tp, &rs->btrace_config);
14897 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14898 continue;
14900 #if !defined (HAVE_LIBIPT)
14901 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14903 if (!warned)
14905 warned = 1;
14906 warning (_("Target is recording using Intel Processor Trace "
14907 "but support was disabled at compile time."));
14910 continue;
14912 #endif /* !defined (HAVE_LIBIPT) */
14914 /* Push target, once, but before anything else happens. This way our
14915 changes to the threads will be cleaned up by unpushing the target
14916 in case btrace_read_config () throws. */
14917 if (!btrace_target_pushed)
14919 btrace_target_pushed = 1;
14920 record_btrace_push_target ();
14921 gdb_printf (_("Target is recording using %s.\n"),
14922 btrace_format_string (rs->btrace_config.format));
14925 tp->btrace.target
14926 = new btrace_target_info { tp->ptid, rs->btrace_config };
14930 /* Enable branch tracing. */
14932 struct btrace_target_info *
14933 remote_target::enable_btrace (thread_info *tp,
14934 const struct btrace_config *conf)
14936 struct packet_config *packet = NULL;
14937 struct remote_state *rs = get_remote_state ();
14938 char *buf = rs->buf.data ();
14939 char *endbuf = buf + get_remote_packet_size ();
14941 unsigned int which_packet;
14942 switch (conf->format)
14944 case BTRACE_FORMAT_BTS:
14945 which_packet = PACKET_Qbtrace_bts;
14946 break;
14947 case BTRACE_FORMAT_PT:
14948 which_packet = PACKET_Qbtrace_pt;
14949 break;
14950 default:
14951 internal_error (_("Bad branch btrace format: %u."),
14952 (unsigned int) conf->format);
14955 packet = &m_features.m_protocol_packets[which_packet];
14956 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14957 error (_("Target does not support branch tracing."));
14959 btrace_sync_conf (conf);
14961 ptid_t ptid = tp->ptid;
14962 set_general_thread (ptid);
14964 buf += xsnprintf (buf, endbuf - buf, "%s",
14965 packets_descriptions[which_packet].name);
14966 putpkt (rs->buf);
14967 getpkt (&rs->buf);
14969 packet_result result = m_features.packet_ok (rs->buf, which_packet);
14970 if (result.status () == PACKET_ERROR)
14971 error (_("Could not enable branch tracing for %s: %s"),
14972 target_pid_to_str (ptid).c_str (), result.err_msg ());
14974 btrace_target_info *tinfo = new btrace_target_info { ptid };
14976 /* If we fail to read the configuration, we lose some information, but the
14977 tracing itself is not impacted. */
14980 btrace_read_config (tp, &tinfo->conf);
14982 catch (const gdb_exception_error &err)
14984 if (err.message != NULL)
14985 warning ("%s", err.what ());
14988 return tinfo;
14991 /* Disable branch tracing. */
14993 void
14994 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14996 struct remote_state *rs = get_remote_state ();
14997 char *buf = rs->buf.data ();
14998 char *endbuf = buf + get_remote_packet_size ();
15000 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
15001 error (_("Target does not support branch tracing."));
15003 set_general_thread (tinfo->ptid);
15005 buf += xsnprintf (buf, endbuf - buf, "%s",
15006 packets_descriptions[PACKET_Qbtrace_off].name);
15007 putpkt (rs->buf);
15008 getpkt (&rs->buf);
15010 packet_result result = m_features.packet_ok (rs->buf, PACKET_Qbtrace_off);
15011 if (result.status () == PACKET_ERROR)
15012 error (_("Could not disable branch tracing for %s: %s"),
15013 target_pid_to_str (tinfo->ptid).c_str (), result.err_msg ());
15015 delete tinfo;
15018 /* Teardown branch tracing. */
15020 void
15021 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
15023 /* We must not talk to the target during teardown. */
15024 delete tinfo;
15027 /* Read the branch trace. */
15029 enum btrace_error
15030 remote_target::read_btrace (struct btrace_data *btrace,
15031 struct btrace_target_info *tinfo,
15032 enum btrace_read_type type)
15034 const char *annex;
15036 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
15037 error (_("Target does not support branch tracing."));
15039 #if !defined(HAVE_LIBEXPAT)
15040 error (_("Cannot process branch tracing result. XML parsing not supported."));
15041 #endif
15043 switch (type)
15045 case BTRACE_READ_ALL:
15046 annex = "all";
15047 break;
15048 case BTRACE_READ_NEW:
15049 annex = "new";
15050 break;
15051 case BTRACE_READ_DELTA:
15052 annex = "delta";
15053 break;
15054 default:
15055 internal_error (_("Bad branch tracing read type: %u."),
15056 (unsigned int) type);
15059 std::optional<gdb::char_vector> xml
15060 = target_read_stralloc (current_inferior ()->top_target (),
15061 TARGET_OBJECT_BTRACE, annex);
15062 if (!xml)
15063 return BTRACE_ERR_UNKNOWN;
15065 parse_xml_btrace (btrace, xml->data ());
15067 return BTRACE_ERR_NONE;
15070 const struct btrace_config *
15071 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
15073 return &tinfo->conf;
15076 bool
15077 remote_target::augmented_libraries_svr4_read ()
15079 return
15080 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
15081 == PACKET_ENABLE);
15084 /* Implementation of to_load. */
15086 void
15087 remote_target::load (const char *name, int from_tty)
15089 generic_load (name, from_tty);
15092 /* Accepts an integer PID; returns a string representing a file that
15093 can be opened on the remote side to get the symbols for the child
15094 process. Returns NULL if the operation is not supported. */
15096 const char *
15097 remote_target::pid_to_exec_file (int pid)
15099 static std::optional<gdb::char_vector> filename;
15100 char *annex = NULL;
15102 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
15103 return NULL;
15105 inferior *inf = find_inferior_pid (this, pid);
15106 if (inf == NULL)
15107 internal_error (_("not currently attached to process %d"), pid);
15109 if (!inf->fake_pid_p)
15111 const int annex_size = 9;
15113 annex = (char *) alloca (annex_size);
15114 xsnprintf (annex, annex_size, "%x", pid);
15117 filename = target_read_stralloc (current_inferior ()->top_target (),
15118 TARGET_OBJECT_EXEC_FILE, annex);
15120 return filename ? filename->data () : nullptr;
15123 /* Implement the to_can_do_single_step target_ops method. */
15126 remote_target::can_do_single_step ()
15128 /* We can only tell whether target supports single step or not by
15129 supported s and S vCont actions if the stub supports vContSupported
15130 feature. If the stub doesn't support vContSupported feature,
15131 we have conservatively to think target doesn't supports single
15132 step. */
15133 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
15135 struct remote_state *rs = get_remote_state ();
15137 return rs->supports_vCont.s && rs->supports_vCont.S;
15139 else
15140 return 0;
15143 /* Implementation of the to_execution_direction method for the remote
15144 target. */
15146 enum exec_direction_kind
15147 remote_target::execution_direction ()
15149 struct remote_state *rs = get_remote_state ();
15151 return rs->last_resume_exec_dir;
15154 /* Return pointer to the thread_info struct which corresponds to
15155 THREAD_HANDLE (having length HANDLE_LEN). */
15157 thread_info *
15158 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
15159 int handle_len,
15160 inferior *inf)
15162 for (thread_info *tp : all_non_exited_threads (this))
15164 remote_thread_info *priv = get_remote_thread_info (tp);
15166 if (tp->inf == inf && priv != NULL)
15168 if (handle_len != priv->thread_handle.size ())
15169 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15170 handle_len, priv->thread_handle.size ());
15171 if (memcmp (thread_handle, priv->thread_handle.data (),
15172 handle_len) == 0)
15173 return tp;
15177 return NULL;
15180 gdb::array_view<const gdb_byte>
15181 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15183 remote_thread_info *priv = get_remote_thread_info (tp);
15184 return priv->thread_handle;
15187 bool
15188 remote_target::can_async_p ()
15190 /* This flag should be checked in the common target.c code. */
15191 gdb_assert (target_async_permitted);
15193 /* We're async whenever the serial device can. */
15194 return get_remote_state ()->can_async_p ();
15197 bool
15198 remote_target::is_async_p ()
15200 /* We're async whenever the serial device is. */
15201 return get_remote_state ()->is_async_p ();
15204 /* Pass the SERIAL event on and up to the client. One day this code
15205 will be able to delay notifying the client of an event until the
15206 point where an entire packet has been received. */
15208 static serial_event_ftype remote_async_serial_handler;
15210 static void
15211 remote_async_serial_handler (struct serial *scb, void *context)
15213 /* Don't propogate error information up to the client. Instead let
15214 the client find out about the error by querying the target. */
15215 inferior_event_handler (INF_REG_EVENT);
15219 remote_target::async_wait_fd ()
15221 struct remote_state *rs = get_remote_state ();
15222 return rs->remote_desc->fd;
15225 void
15226 remote_target::async (bool enable)
15228 struct remote_state *rs = get_remote_state ();
15230 if (enable)
15232 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15234 /* If there are pending events in the stop reply queue tell the
15235 event loop to process them. */
15236 if (!rs->stop_reply_queue.empty ())
15237 rs->mark_async_event_handler ();
15239 /* For simplicity, below we clear the pending events token
15240 without remembering whether it is marked, so here we always
15241 mark it. If there's actually no pending notification to
15242 process, this ends up being a no-op (other than a spurious
15243 event-loop wakeup). */
15244 if (target_is_non_stop_p ())
15245 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15247 else
15249 serial_async (rs->remote_desc, NULL, NULL);
15250 /* If the core is disabling async, it doesn't want to be
15251 disturbed with target events. Clear all async event sources
15252 too. */
15253 rs->clear_async_event_handler ();
15255 if (target_is_non_stop_p ())
15256 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15260 /* Implementation of the to_thread_events method. */
15262 void
15263 remote_target::thread_events (bool enable)
15265 struct remote_state *rs = get_remote_state ();
15266 size_t size = get_remote_packet_size ();
15268 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15269 return;
15271 if (rs->last_thread_events == enable)
15272 return;
15274 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15275 putpkt (rs->buf);
15276 getpkt (&rs->buf);
15278 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadEvents);
15279 switch (result.status ())
15281 case PACKET_OK:
15282 if (strcmp (rs->buf.data (), "OK") != 0)
15283 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15284 rs->last_thread_events = enable;
15285 break;
15286 case PACKET_ERROR:
15287 warning (_("Remote failure reply: %s"), result.err_msg ());
15288 break;
15289 case PACKET_UNKNOWN:
15290 break;
15294 /* Implementation of the supports_set_thread_options target
15295 method. */
15297 bool
15298 remote_target::supports_set_thread_options (gdb_thread_options options)
15300 remote_state *rs = get_remote_state ();
15301 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15302 && (rs->supported_thread_options & options) == options);
15305 /* For coalescing reasons, actually sending the options to the target
15306 happens at resume time, via this function. See target_resume for
15307 all-stop, and target_commit_resumed for non-stop. */
15309 void
15310 remote_target::commit_requested_thread_options ()
15312 struct remote_state *rs = get_remote_state ();
15314 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15315 return;
15317 char *p = rs->buf.data ();
15318 char *endp = p + get_remote_packet_size ();
15320 /* Clear options for all threads by default. Note that unlike
15321 vCont, the rightmost options that match a thread apply, so we
15322 don't have to worry about whether we can use wildcard ptids. */
15323 strcpy (p, "QThreadOptions;0");
15324 p += strlen (p);
15326 /* Send the QThreadOptions packet stored in P. */
15327 auto flush = [&] ()
15329 *p++ = '\0';
15331 putpkt (rs->buf);
15332 getpkt (&rs->buf, 0);
15334 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadOptions);
15335 switch (result.status ())
15337 case PACKET_OK:
15338 if (strcmp (rs->buf.data (), "OK") != 0)
15339 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15340 break;
15341 case PACKET_ERROR:
15342 error (_("Remote failure reply: %s"), result.err_msg ());
15343 case PACKET_UNKNOWN:
15344 gdb_assert_not_reached ("PACKET_UNKNOWN");
15345 break;
15349 /* Prepare P for another QThreadOptions packet. */
15350 auto restart = [&] ()
15352 p = rs->buf.data ();
15353 strcpy (p, "QThreadOptions");
15354 p += strlen (p);
15357 /* Now set non-zero options for threads that need them. We don't
15358 bother with the case of all threads of a process wanting the same
15359 non-zero options as that's not an expected scenario. */
15360 for (thread_info *tp : all_non_exited_threads (this))
15362 gdb_thread_options options = tp->thread_options ();
15364 if (options == 0)
15365 continue;
15367 /* It might be possible to we have more threads with options
15368 than can fit a single QThreadOptions packet. So build each
15369 options/thread pair in this separate buffer to make sure it
15370 fits. */
15371 constexpr size_t max_options_size = 100;
15372 char obuf[max_options_size];
15373 char *obuf_p = obuf;
15374 char *obuf_endp = obuf + max_options_size;
15376 *obuf_p++ = ';';
15377 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15378 phex_nz (options, sizeof (options)));
15379 if (tp->ptid != magic_null_ptid)
15381 *obuf_p++ = ':';
15382 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15385 size_t osize = obuf_p - obuf;
15386 if (osize > endp - p)
15388 /* This new options/thread pair doesn't fit the packet
15389 buffer. Send what we have already. */
15390 flush ();
15391 restart ();
15393 /* Should now fit. */
15394 gdb_assert (osize <= endp - p);
15397 memcpy (p, obuf, osize);
15398 p += osize;
15401 flush ();
15404 static void
15405 show_remote_cmd (const char *args, int from_tty)
15407 /* We can't just use cmd_show_list here, because we want to skip
15408 the redundant "show remote Z-packet" and the legacy aliases. */
15409 struct cmd_list_element *list = remote_show_cmdlist;
15410 struct ui_out *uiout = current_uiout;
15412 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15413 for (; list != NULL; list = list->next)
15414 if (strcmp (list->name, "Z-packet") == 0)
15415 continue;
15416 else if (list->type == not_set_cmd)
15417 /* Alias commands are exactly like the original, except they
15418 don't have the normal type. */
15419 continue;
15420 else
15422 ui_out_emit_tuple option_emitter (uiout, "option");
15424 uiout->field_string ("name", list->name);
15425 uiout->text (": ");
15426 if (list->type == show_cmd)
15427 do_show_command (NULL, from_tty, list);
15428 else
15429 cmd_func (list, NULL, from_tty);
15433 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15434 offer all inferiors using that program space a change to look up symbols. */
15436 static void
15437 remote_objfile_changed_check_symbols (program_space *pspace)
15439 /* The affected program space is possibly shared by multiple inferiors.
15440 Consider sending a qSymbol packet for each of the inferiors using that
15441 program space. */
15442 for (inferior *inf : all_inferiors ())
15444 if (inf->pspace != pspace)
15445 continue;
15447 /* Check whether the inferior's process target is a remote target. */
15448 remote_target *remote = as_remote_target (inf->process_target ());
15449 if (remote == nullptr)
15450 continue;
15452 /* When we are attaching or handling a fork child and the shared library
15453 subsystem reads the list of loaded libraries, we receive new objfile
15454 events in between each found library. The libraries are read in an
15455 undefined order, so if we gave the remote side a chance to look up
15456 symbols between each objfile, we might give it an inconsistent picture
15457 of the inferior. It could appear that a library A appears loaded but
15458 a library B does not, even though library A requires library B. That
15459 would present a state that couldn't normally exist in the inferior.
15461 So, skip these events, we'll give the remote a chance to look up
15462 symbols once all the loaded libraries and their symbols are known to
15463 GDB. */
15464 if (inf->in_initial_library_scan)
15465 continue;
15467 if (!remote->has_execution (inf))
15468 continue;
15470 /* Need to switch to a specific thread, because remote_check_symbols will
15471 set the general thread using INFERIOR_PTID.
15473 It's possible to have inferiors with no thread here, because we are
15474 called very early in the connection process, while the inferior is
15475 being set up, before threads are added. Just skip it, start_remote_1
15476 also calls remote_check_symbols when it's done setting things up. */
15477 thread_info *thread = any_thread_of_inferior (inf);
15478 if (thread != nullptr)
15480 scoped_restore_current_thread restore_thread;
15481 switch_to_thread (thread);
15482 remote->remote_check_symbols ();
15487 /* Function to be called whenever a new objfile (shlib) is detected. */
15489 static void
15490 remote_new_objfile (struct objfile *objfile)
15492 remote_objfile_changed_check_symbols (objfile->pspace ());
15495 /* Pull all the tracepoints defined on the target and create local
15496 data structures representing them. We don't want to create real
15497 tracepoints yet, we don't want to mess up the user's existing
15498 collection. */
15501 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15503 struct remote_state *rs = get_remote_state ();
15504 char *p;
15506 /* Ask for a first packet of tracepoint definition. */
15507 putpkt ("qTfP");
15508 getpkt (&rs->buf);
15509 p = rs->buf.data ();
15510 while (*p && *p != 'l')
15512 parse_tracepoint_definition (p, utpp);
15513 /* Ask for another packet of tracepoint definition. */
15514 putpkt ("qTsP");
15515 getpkt (&rs->buf);
15516 p = rs->buf.data ();
15518 return 0;
15522 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15524 struct remote_state *rs = get_remote_state ();
15525 char *p;
15527 /* Ask for a first packet of variable definition. */
15528 putpkt ("qTfV");
15529 getpkt (&rs->buf);
15530 p = rs->buf.data ();
15531 while (*p && *p != 'l')
15533 parse_tsv_definition (p, utsvp);
15534 /* Ask for another packet of variable definition. */
15535 putpkt ("qTsV");
15536 getpkt (&rs->buf);
15537 p = rs->buf.data ();
15539 return 0;
15542 /* The "set/show range-stepping" show hook. */
15544 static void
15545 show_range_stepping (struct ui_file *file, int from_tty,
15546 struct cmd_list_element *c,
15547 const char *value)
15549 gdb_printf (file,
15550 _("Debugger's willingness to use range stepping "
15551 "is %s.\n"), value);
15554 /* Return true if the vCont;r action is supported by the remote
15555 stub. */
15557 bool
15558 remote_target::vcont_r_supported ()
15560 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15561 && get_remote_state ()->supports_vCont.r);
15564 /* The "set/show range-stepping" set hook. */
15566 static void
15567 set_range_stepping (const char *ignore_args, int from_tty,
15568 struct cmd_list_element *c)
15570 /* When enabling, check whether range stepping is actually supported
15571 by the target, and warn if not. */
15572 if (use_range_stepping)
15574 remote_target *remote = get_current_remote_target ();
15575 if (remote == NULL
15576 || !remote->vcont_r_supported ())
15577 warning (_("Range stepping is not supported by the current target"));
15581 static void
15582 show_remote_debug (struct ui_file *file, int from_tty,
15583 struct cmd_list_element *c, const char *value)
15585 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15586 value);
15589 static void
15590 show_remote_timeout (struct ui_file *file, int from_tty,
15591 struct cmd_list_element *c, const char *value)
15593 gdb_printf (file,
15594 _("Timeout limit to wait for target to respond is %s.\n"),
15595 value);
15598 /* Implement the "supports_memory_tagging" target_ops method. */
15600 bool
15601 remote_target::supports_memory_tagging ()
15603 return m_features.remote_memory_tagging_p ();
15606 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15608 static void
15609 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15610 size_t len, int type)
15612 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15614 std::string request = string_printf ("qMemTags:%s,%s:%s",
15615 phex_nz (address, addr_size),
15616 phex_nz (len, sizeof (len)),
15617 phex_nz (type, sizeof (type)));
15619 strcpy (packet.data (), request.c_str ());
15622 /* Parse the qMemTags packet reply into TAGS.
15624 Return true if successful, false otherwise. */
15626 static bool
15627 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15628 gdb::byte_vector &tags)
15630 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15631 return false;
15633 /* Copy the tag data. */
15634 tags = hex2bin (reply.data () + 1);
15636 return true;
15639 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15641 static void
15642 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15643 size_t len, int type,
15644 const gdb::byte_vector &tags)
15646 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15648 /* Put together the main packet, address and length. */
15649 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15650 phex_nz (address, addr_size),
15651 phex_nz (len, sizeof (len)),
15652 phex_nz (type, sizeof (type)));
15653 request += bin2hex (tags.data (), tags.size ());
15655 /* Check if we have exceeded the maximum packet size. */
15656 if (packet.size () < request.length ())
15657 error (_("Contents too big for packet QMemTags."));
15659 strcpy (packet.data (), request.c_str ());
15662 static void
15663 create_is_address_tagged_request (gdbarch *gdbarch, gdb::char_vector &packet,
15664 CORE_ADDR address)
15666 int addr_size;
15667 std::string request;
15669 addr_size = gdbarch_addr_bit (gdbarch) / 8;
15670 request = string_printf ("qIsAddressTagged:%s", phex_nz (address, addr_size));
15672 if (packet.size () < request.length () + 1)
15673 error (_("Contents too big for packet qIsAddressTagged."));
15675 strcpy (packet.data (), request.c_str ());
15678 static bool
15679 check_is_address_tagged_reply (remote_target *remote, gdb::char_vector &packet,
15680 bool &tagged)
15682 gdb_assert (remote != nullptr);
15683 /* Check reply and disable qIsAddressTagged usage if it's not supported. */
15684 packet_result result = remote->m_features.packet_ok (packet,
15685 PACKET_qIsAddressTagged);
15687 /* Return false on error (Exx), empty reply (packet not supported), or reply
15688 size doesn't match 2 hex digits. */
15689 if ((result.status () != PACKET_OK) || (strlen (packet.data ()) != 2))
15690 return false;
15692 gdb_byte reply;
15693 /* Convert only 2 hex digits, i.e. 1 byte in hex format. */
15694 hex2bin (packet.data (), &reply, 1);
15696 if (reply == 0x00 || reply == 0x01)
15698 tagged = !!reply;
15699 return true;
15702 /* Invalid reply. */
15703 return false;
15706 /* Implement the "fetch_memtags" target_ops method. */
15708 bool
15709 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15710 gdb::byte_vector &tags, int type)
15712 /* Make sure the qMemTags packet is supported. */
15713 if (!m_features.remote_memory_tagging_p ())
15714 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15716 struct remote_state *rs = get_remote_state ();
15718 create_fetch_memtags_request (rs->buf, address, len, type);
15720 putpkt (rs->buf);
15721 getpkt (&rs->buf);
15723 return parse_fetch_memtags_reply (rs->buf, tags);
15726 /* Implement the "store_memtags" target_ops method. */
15728 bool
15729 remote_target::store_memtags (CORE_ADDR address, size_t len,
15730 const gdb::byte_vector &tags, int type)
15732 /* Make sure the QMemTags packet is supported. */
15733 if (!m_features.remote_memory_tagging_p ())
15734 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15736 struct remote_state *rs = get_remote_state ();
15738 create_store_memtags_request (rs->buf, address, len, type, tags);
15740 putpkt (rs->buf);
15741 getpkt (&rs->buf);
15743 /* Verify if the request was successful. */
15744 return packet_check_result (rs->buf).status () == PACKET_OK;
15747 /* Implement the "is_address_tagged" target_ops method. */
15749 bool
15750 remote_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
15752 /* Firstly, attempt to check the address using the qIsAddressTagged
15753 packet. */
15754 if (m_features.packet_support (PACKET_qIsAddressTagged) != PACKET_DISABLE)
15756 remote_target *remote = get_current_remote_target ();
15757 struct remote_state *rs = get_remote_state ();
15758 bool is_addr_tagged;
15760 create_is_address_tagged_request (gdbarch, rs->buf, address);
15762 putpkt (rs->buf);
15763 getpkt (&rs->buf);
15765 /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
15766 set to PACKET_DISABLE so no further attempt is made to check addresses
15767 using this packet and the fallback mechanism below will be used
15768 instead. Also, if the check fails due to an error (Exx reply) the
15769 fallback is used too. Otherwise, the qIsAddressTagged query succeeded
15770 and is_addr_tagged is valid. */
15771 if (check_is_address_tagged_reply (remote, rs->buf, is_addr_tagged))
15772 return is_addr_tagged;
15775 /* Fallback to arch-specific method of checking whether an address is tagged
15776 in case check via qIsAddressTagged fails. */
15777 return gdbarch_tagged_address_p (gdbarch, address);
15780 /* Return true if remote target T is non-stop. */
15782 bool
15783 remote_target_is_non_stop_p (remote_target *t)
15785 scoped_restore_current_thread restore_thread;
15786 switch_to_target_no_thread (t);
15788 return target_is_non_stop_p ();
15791 #if GDB_SELF_TEST
15793 namespace selftests {
15795 static void
15796 test_memory_tagging_functions ()
15798 remote_target remote;
15800 struct packet_config *config
15801 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15803 scoped_restore restore_memtag_support_
15804 = make_scoped_restore (&config->support);
15806 struct gdbarch *gdbarch = current_inferior ()->arch ();
15808 /* Test memory tagging packet support. */
15809 config->support = PACKET_SUPPORT_UNKNOWN;
15810 SELF_CHECK (remote.supports_memory_tagging () == false);
15811 config->support = PACKET_DISABLE;
15812 SELF_CHECK (remote.supports_memory_tagging () == false);
15813 config->support = PACKET_ENABLE;
15814 SELF_CHECK (remote.supports_memory_tagging () == true);
15816 /* Setup testing. */
15817 gdb::char_vector packet;
15818 gdb::byte_vector tags, bv;
15819 std::string expected, reply;
15820 packet.resize (32000);
15822 /* Test creating a qMemTags request. */
15824 expected = "qMemTags:0,0:0";
15825 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15826 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15828 expected = "qMemTags:deadbeef,10:1";
15829 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15830 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15832 /* Test parsing a qMemTags reply. */
15834 /* Error reply, tags vector unmodified. */
15835 reply = "E00";
15836 strcpy (packet.data (), reply.c_str ());
15837 tags.resize (0);
15838 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15839 SELF_CHECK (tags.size () == 0);
15841 /* Valid reply, tags vector updated. */
15842 tags.resize (0);
15843 bv.resize (0);
15845 for (int i = 0; i < 5; i++)
15846 bv.push_back (i);
15848 reply = "m" + bin2hex (bv.data (), bv.size ());
15849 strcpy (packet.data (), reply.c_str ());
15851 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15852 SELF_CHECK (tags.size () == 5);
15854 for (int i = 0; i < 5; i++)
15855 SELF_CHECK (tags[i] == i);
15857 /* Test creating a QMemTags request. */
15859 /* Empty tag data. */
15860 tags.resize (0);
15861 expected = "QMemTags:0,0:0:";
15862 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15863 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15864 expected.length ()) == 0);
15866 /* Non-empty tag data. */
15867 tags.resize (0);
15868 for (int i = 0; i < 5; i++)
15869 tags.push_back (i);
15870 expected = "QMemTags:deadbeef,ff:1:0001020304";
15871 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15872 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15873 expected.length ()) == 0);
15875 /* Test creating a qIsAddressTagged request. */
15876 expected = "qIsAddressTagged:deadbeef";
15877 create_is_address_tagged_request (gdbarch, packet, 0xdeadbeef);
15878 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15880 /* Test error reply on qIsAddressTagged request. */
15881 reply = "E00";
15882 strcpy (packet.data (), reply.c_str ());
15883 /* is_tagged must not change, hence it's tested too. */
15884 bool is_tagged = false;
15885 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15886 false);
15887 SELF_CHECK (is_tagged == false);
15889 /* Test 'tagged' as reply. */
15890 reply = "01";
15891 strcpy (packet.data (), reply.c_str ());
15892 /* Because the byte is 01, is_tagged should be set to true. */
15893 is_tagged = false;
15894 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15895 true);
15896 SELF_CHECK (is_tagged == true);
15898 /* Test 'not tagged' as reply. */
15899 reply = "00";
15900 strcpy (packet.data (), reply.c_str ());
15901 /* Because the byte is 00, is_tagged should be set to false. */
15902 is_tagged = true;
15903 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15904 true);
15905 SELF_CHECK (is_tagged == false);
15907 /* Test an invalid reply (neither 00 nor 01). */
15908 reply = "04";
15909 strcpy (packet.data (), reply.c_str ());
15910 /* Because the byte is invalid is_tagged must not change. */
15911 is_tagged = false;
15912 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15913 false);
15914 SELF_CHECK (is_tagged == false);
15916 /* Test malformed reply of incorrect length. */
15917 reply = "0104A590001234006";
15918 strcpy (packet.data (), reply.c_str ());
15919 /* Because this is a malformed reply is_tagged must not change. */
15920 is_tagged = false;
15921 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15922 false);
15923 SELF_CHECK (is_tagged == false);
15925 /* Test empty reply. */
15926 reply = "";
15927 strcpy (packet.data (), reply.c_str ());
15928 /* is_tagged must not change, hence it's tested too. */
15929 is_tagged = true;
15930 /* On the previous tests, qIsAddressTagged packet was auto detected and set
15931 as supported. But an empty reply means the packet is unsupported, so for
15932 testing the empty reply the support is reset to unknown state, otherwise
15933 packet_ok will complain. */
15934 remote.m_features.m_protocol_packets[PACKET_qIsAddressTagged].support =
15935 PACKET_SUPPORT_UNKNOWN;
15936 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15937 false);
15938 SELF_CHECK (is_tagged == true);
15941 static void
15942 test_packet_check_result ()
15944 std::string buf = "E.msg";
15945 packet_result result = packet_check_result (buf.data ());
15947 SELF_CHECK (result.status () == PACKET_ERROR);
15948 SELF_CHECK (strcmp(result.err_msg (), "msg") == 0);
15950 result = packet_check_result ("E01");
15951 SELF_CHECK (result.status () == PACKET_ERROR);
15952 SELF_CHECK (strcmp(result.err_msg (), "01") == 0);
15954 SELF_CHECK (packet_check_result ("E1").status () == PACKET_OK);
15956 SELF_CHECK (packet_check_result ("E000").status () == PACKET_OK);
15958 result = packet_check_result ("E.");
15959 SELF_CHECK (result.status () == PACKET_ERROR);
15960 SELF_CHECK (strcmp(result.err_msg (), "no error provided") == 0);
15962 SELF_CHECK (packet_check_result ("some response").status () == PACKET_OK);
15964 SELF_CHECK (packet_check_result ("").status () == PACKET_UNKNOWN);
15966 } // namespace selftests
15967 #endif /* GDB_SELF_TEST */
15969 void _initialize_remote ();
15970 void
15971 _initialize_remote ()
15973 add_target (remote_target_info, remote_target::open);
15974 add_target (extended_remote_target_info, extended_remote_target::open);
15976 /* Hook into new objfile notification. */
15977 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15978 gdb::observers::all_objfiles_removed.attach
15979 (remote_objfile_changed_check_symbols, "remote");
15981 #if 0
15982 init_remote_threadtests ();
15983 #endif
15985 /* set/show remote ... */
15987 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15988 Remote protocol specific variables.\n\
15989 Configure various remote-protocol specific variables such as\n\
15990 the packets being used."),
15991 &remote_set_cmdlist,
15992 0 /* allow-unknown */, &setlist);
15993 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15994 Remote protocol specific variables.\n\
15995 Configure various remote-protocol specific variables such as\n\
15996 the packets being used."),
15997 &remote_show_cmdlist,
15998 0 /* allow-unknown */, &showlist);
16000 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
16001 Compare section data on target to the exec file.\n\
16002 Argument is a single section name (default: all loaded sections).\n\
16003 To compare only read-only loaded sections, specify the -r option."),
16004 &cmdlist);
16006 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
16007 Send an arbitrary packet to a remote target.\n\
16008 maintenance packet TEXT\n\
16009 If GDB is talking to an inferior via the GDB serial protocol, then\n\
16010 this command sends the string TEXT to the inferior, and displays the\n\
16011 response packet. GDB supplies the initial `$' character, and the\n\
16012 terminating `#' character and checksum."),
16013 &maintenancelist);
16015 set_show_commands remotebreak_cmds
16016 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
16017 Set whether to send break if interrupted."), _("\
16018 Show whether to send break if interrupted."), _("\
16019 If set, a break, instead of a cntrl-c, is sent to the remote target."),
16020 set_remotebreak, show_remotebreak,
16021 &setlist, &showlist);
16022 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
16023 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
16025 add_setshow_enum_cmd ("interrupt-sequence", class_support,
16026 interrupt_sequence_modes, &interrupt_sequence_mode,
16027 _("\
16028 Set interrupt sequence to remote target."), _("\
16029 Show interrupt sequence to remote target."), _("\
16030 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
16031 NULL, show_interrupt_sequence,
16032 &remote_set_cmdlist,
16033 &remote_show_cmdlist);
16035 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
16036 &interrupt_on_connect, _("\
16037 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16038 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16039 If set, interrupt sequence is sent to remote target."),
16040 NULL, NULL,
16041 &remote_set_cmdlist, &remote_show_cmdlist);
16043 /* Install commands for configuring memory read/write packets. */
16045 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
16046 Set the maximum number of bytes per memory write packet (deprecated)."),
16047 &setlist);
16048 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
16049 Show the maximum number of bytes per memory write packet (deprecated)."),
16050 &showlist);
16051 add_cmd ("memory-write-packet-size", no_class,
16052 set_memory_write_packet_size, _("\
16053 Set the maximum number of bytes per memory-write packet.\n\
16054 Specify the number of bytes in a packet or 0 (zero) for the\n\
16055 default packet size. The actual limit is further reduced\n\
16056 dependent on the target. Specify \"fixed\" to disable the\n\
16057 further restriction and \"limit\" to enable that restriction."),
16058 &remote_set_cmdlist);
16059 add_cmd ("memory-read-packet-size", no_class,
16060 set_memory_read_packet_size, _("\
16061 Set the maximum number of bytes per memory-read packet.\n\
16062 Specify the number of bytes in a packet or 0 (zero) for the\n\
16063 default packet size. The actual limit is further reduced\n\
16064 dependent on the target. Specify \"fixed\" to disable the\n\
16065 further restriction and \"limit\" to enable that restriction."),
16066 &remote_set_cmdlist);
16067 add_cmd ("memory-write-packet-size", no_class,
16068 show_memory_write_packet_size,
16069 _("Show the maximum number of bytes per memory-write packet."),
16070 &remote_show_cmdlist);
16071 add_cmd ("memory-read-packet-size", no_class,
16072 show_memory_read_packet_size,
16073 _("Show the maximum number of bytes per memory-read packet."),
16074 &remote_show_cmdlist);
16076 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
16077 &remote_hw_watchpoint_limit, _("\
16078 Set the maximum number of target hardware watchpoints."), _("\
16079 Show the maximum number of target hardware watchpoints."), _("\
16080 Specify \"unlimited\" for unlimited hardware watchpoints."),
16081 NULL, show_hardware_watchpoint_limit,
16082 &remote_set_cmdlist,
16083 &remote_show_cmdlist);
16084 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
16085 no_class,
16086 &remote_hw_watchpoint_length_limit, _("\
16087 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
16088 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
16089 Specify \"unlimited\" to allow watchpoints of unlimited size."),
16090 NULL, show_hardware_watchpoint_length_limit,
16091 &remote_set_cmdlist, &remote_show_cmdlist);
16092 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
16093 &remote_hw_breakpoint_limit, _("\
16094 Set the maximum number of target hardware breakpoints."), _("\
16095 Show the maximum number of target hardware breakpoints."), _("\
16096 Specify \"unlimited\" for unlimited hardware breakpoints."),
16097 NULL, show_hardware_breakpoint_limit,
16098 &remote_set_cmdlist, &remote_show_cmdlist);
16100 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
16101 &remote_address_size, _("\
16102 Set the maximum size of the address (in bits) in a memory packet."), _("\
16103 Show the maximum size of the address (in bits) in a memory packet."), NULL,
16104 NULL,
16105 NULL, /* FIXME: i18n: */
16106 &setlist, &showlist);
16108 init_all_packet_configs ();
16110 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
16112 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
16114 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
16117 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
16118 "catch-syscalls", 0);
16120 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
16121 "program-signals", 0);
16123 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
16124 "set-working-dir", 0);
16126 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
16127 "startup-with-shell", 0);
16129 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
16130 "environment-hex-encoded", 0);
16132 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
16133 "environment-reset", 0);
16135 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
16136 "environment-unset", 0);
16138 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
16140 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
16142 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
16144 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
16146 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
16148 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
16150 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
16152 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
16154 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
16155 "read-aux-vector", 0);
16157 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
16158 "pid-to-exec-file", 0);
16160 add_packet_config_cmd (PACKET_qXfer_features,
16161 "qXfer:features:read", "target-features", 0);
16163 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
16164 "library-info", 0);
16166 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
16167 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
16169 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
16170 "memory-map", 0);
16172 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
16174 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
16177 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
16178 "read-siginfo-object", 0);
16180 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
16181 "write-siginfo-object", 0);
16183 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
16184 "qXfer:traceframe-info:read", "traceframe-info", 0);
16186 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
16187 "unwind-info-block", 0);
16189 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
16190 "get-thread-local-storage-address", 0);
16192 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
16193 "get-thread-information-block-address", 0);
16195 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
16197 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
16199 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
16202 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
16203 "search-memory", 0);
16205 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
16207 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
16209 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
16211 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
16213 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
16216 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
16218 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
16221 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
16222 "hostio-readlink", 0);
16224 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
16226 add_packet_config_cmd (PACKET_vFile_stat, "vFile:stat", "hostio-stat", 0);
16228 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
16230 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
16232 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
16234 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
16236 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
16238 add_packet_config_cmd (PACKET_ConditionalTracepoints,
16239 "ConditionalTracepoints", "conditional-tracepoints",
16242 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
16243 "ConditionalBreakpoints", "conditional-breakpoints",
16246 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
16247 "breakpoint-commands", 0);
16249 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
16250 "fast-tracepoints", 0);
16252 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
16253 "TracepointSource", 0);
16255 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
16257 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
16258 "static-tracepoints", 0);
16260 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
16261 "install-in-trace", 0);
16263 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
16264 "qXfer:statictrace:read", "read-sdata-object", 0);
16266 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
16267 "read-fdpic-loadmap", 0);
16269 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
16270 "disable-randomization", 0);
16272 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
16274 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
16275 "trace-buffer-size", 0);
16277 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
16280 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
16283 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
16286 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
16288 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
16289 "read-btrace-conf", 0);
16291 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
16292 "btrace-conf-bts-size", 0);
16294 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
16295 "multiprocess-feature", 0);
16297 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
16298 "swbreak-feature", 0);
16300 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
16301 "hwbreak-feature", 0);
16303 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
16304 "fork-event-feature", 0);
16306 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
16307 "vfork-event-feature", 0);
16309 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
16310 "btrace-conf-pt-size", 0);
16312 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
16313 "verbose-resume-supported", 0);
16315 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
16316 "exec-event-feature", 0);
16318 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
16320 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
16323 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
16324 "thread-options", 0);
16326 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
16327 "no-resumed-stop-reply", 0);
16329 add_packet_config_cmd (PACKET_memory_tagging_feature,
16330 "memory-tagging-feature", "memory-tagging-feature", 0);
16332 add_packet_config_cmd (PACKET_qIsAddressTagged,
16333 "qIsAddressTagged", "memory-tagging-address-check", 0);
16335 add_packet_config_cmd (PACKET_accept_error_message,
16336 "error-message", "error-message", 0);
16338 /* Assert that we've registered "set remote foo-packet" commands
16339 for all packet configs. */
16341 int i;
16343 for (i = 0; i < PACKET_MAX; i++)
16345 /* Ideally all configs would have a command associated. Some
16346 still don't though. */
16347 int excepted;
16349 switch (i)
16351 case PACKET_QNonStop:
16352 case PACKET_EnableDisableTracepoints_feature:
16353 case PACKET_tracenz_feature:
16354 case PACKET_DisconnectedTracing_feature:
16355 case PACKET_augmented_libraries_svr4_read_feature:
16356 case PACKET_qCRC:
16357 /* Additions to this list need to be well justified:
16358 pre-existing packets are OK; new packets are not. */
16359 excepted = 1;
16360 break;
16361 default:
16362 excepted = 0;
16363 break;
16366 /* This catches both forgetting to add a config command, and
16367 forgetting to remove a packet from the exception list. */
16368 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16372 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16373 Z sub-packet has its own set and show commands, but users may
16374 have sets to this variable in their .gdbinit files (or in their
16375 documentation). */
16376 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16377 &remote_Z_packet_detect, _("\
16378 Set use of remote protocol `Z' packets."), _("\
16379 Show use of remote protocol `Z' packets."), _("\
16380 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16381 packets."),
16382 set_remote_protocol_Z_packet_cmd,
16383 show_remote_protocol_Z_packet_cmd,
16384 /* FIXME: i18n: Use of remote protocol
16385 `Z' packets is %s. */
16386 &remote_set_cmdlist, &remote_show_cmdlist);
16388 add_basic_prefix_cmd ("remote", class_files, _("\
16389 Manipulate files on the remote system.\n\
16390 Transfer files to and from the remote target system."),
16391 &remote_cmdlist,
16392 0 /* allow-unknown */, &cmdlist);
16394 add_cmd ("put", class_files, remote_put_command,
16395 _("Copy a local file to the remote system."),
16396 &remote_cmdlist);
16398 add_cmd ("get", class_files, remote_get_command,
16399 _("Copy a remote file to the local system."),
16400 &remote_cmdlist);
16402 add_cmd ("delete", class_files, remote_delete_command,
16403 _("Delete a remote file."),
16404 &remote_cmdlist);
16406 add_setshow_string_noescape_cmd ("exec-file", class_files,
16407 &remote_exec_file_var, _("\
16408 Set the remote pathname for \"run\"."), _("\
16409 Show the remote pathname for \"run\"."), NULL,
16410 set_remote_exec_file,
16411 show_remote_exec_file,
16412 &remote_set_cmdlist,
16413 &remote_show_cmdlist);
16415 add_setshow_boolean_cmd ("range-stepping", class_run,
16416 &use_range_stepping, _("\
16417 Enable or disable range stepping."), _("\
16418 Show whether target-assisted range stepping is enabled."), _("\
16419 If on, and the target supports it, when stepping a source line, GDB\n\
16420 tells the target to step the corresponding range of addresses itself instead\n\
16421 of issuing multiple single-steps. This speeds up source level\n\
16422 stepping. If off, GDB always issues single-steps, even if range\n\
16423 stepping is supported by the target. The default is on."),
16424 set_range_stepping,
16425 show_range_stepping,
16426 &setlist,
16427 &showlist);
16429 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16430 Set watchdog timer."), _("\
16431 Show watchdog timer."), _("\
16432 When non-zero, this timeout is used instead of waiting forever for a target\n\
16433 to finish a low-level step or continue operation. If the specified amount\n\
16434 of time passes without a response from the target, an error occurs."),
16435 NULL,
16436 show_watchdog,
16437 &setlist, &showlist);
16439 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16440 &remote_packet_max_chars, _("\
16441 Set the maximum number of characters to display for each remote packet."), _("\
16442 Show the maximum number of characters to display for each remote packet."), _("\
16443 Specify \"unlimited\" to display all the characters."),
16444 NULL, show_remote_packet_max_chars,
16445 &setdebuglist, &showdebuglist);
16447 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16448 _("Set debugging of remote protocol."),
16449 _("Show debugging of remote protocol."),
16450 _("\
16451 When enabled, each packet sent or received with the remote target\n\
16452 is displayed."),
16453 NULL,
16454 show_remote_debug,
16455 &setdebuglist, &showdebuglist);
16457 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16458 &remote_timeout, _("\
16459 Set timeout limit to wait for target to respond."), _("\
16460 Show timeout limit to wait for target to respond."), _("\
16461 This value is used to set the time limit for gdb to wait for a response\n\
16462 from the target."),
16463 NULL,
16464 show_remote_timeout,
16465 &setlist, &showlist);
16467 /* Eventually initialize fileio. See fileio.c */
16468 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16470 #if GDB_SELF_TEST
16471 selftests::register_test ("remote_memory_tagging",
16472 selftests::test_memory_tagging_functions);
16473 selftests::register_test ("packet_check_result",
16474 selftests::test_packet_check_result);
16475 #endif