Automatic date update in version.in
[binutils-gdb.git] / gdb / remote.c
blob2c3988cb5075655e8a799d1cc5d4760ad8ed426e
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 the Qbtrace-conf:pt:ptwrite packet. */
365 PACKET_Qbtrace_conf_pt_ptwrite,
367 /* Support for exec events. */
368 PACKET_exec_event_feature,
370 /* Support for query supported vCont actions. */
371 PACKET_vContSupported,
373 /* Support remote CTRL-C. */
374 PACKET_vCtrlC,
376 /* Support TARGET_WAITKIND_NO_RESUMED. */
377 PACKET_no_resumed,
379 /* Support for memory tagging, allocation tag fetch/store
380 packets and the tag violation stop replies. */
381 PACKET_memory_tagging_feature,
383 /* Support for the qIsAddressTagged packet. */
384 PACKET_qIsAddressTagged,
386 /* Support for accepting error message in a E.errtext format.
387 This allows every remote packet to return E.errtext.
389 This feature only exists to fix a backwards compatibility issue
390 with the qRcmd and m packets. Historically, these two packets didn't
391 support E.errtext style errors, but when this feature is on
392 these two packets can receive E.errtext style errors.
394 All new packets should be written to always accept E.errtext style
395 errors, and so they should not need to check for this feature. */
396 PACKET_accept_error_message,
398 PACKET_MAX
401 struct threads_listing_context;
403 /* Stub vCont actions support.
405 Each field is a boolean flag indicating whether the stub reports
406 support for the corresponding action. */
408 struct vCont_action_support
410 /* vCont;t */
411 bool t = false;
413 /* vCont;r */
414 bool r = false;
416 /* vCont;s */
417 bool s = false;
419 /* vCont;S */
420 bool S = false;
423 /* About this many threadids fit in a packet. */
425 #define MAXTHREADLISTRESULTS 32
427 /* Data for the vFile:pread readahead cache. */
429 struct readahead_cache
431 /* Invalidate the readahead cache. */
432 void invalidate ();
434 /* Invalidate the readahead cache if it is holding data for FD. */
435 void invalidate_fd (int fd);
437 /* Serve pread from the readahead cache. Returns number of bytes
438 read, or 0 if the request can't be served from the cache. */
439 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
441 /* The file descriptor for the file that is being cached. -1 if the
442 cache is invalid. */
443 int fd = -1;
445 /* The offset into the file that the cache buffer corresponds
446 to. */
447 ULONGEST offset = 0;
449 /* The buffer holding the cache contents. */
450 gdb::byte_vector buf;
452 /* Cache hit and miss counters. */
453 ULONGEST hit_count = 0;
454 ULONGEST miss_count = 0;
457 /* Description of the remote protocol for a given architecture. */
459 struct packet_reg
461 long offset; /* Offset into G packet. */
462 long regnum; /* GDB's internal register number. */
463 LONGEST pnum; /* Remote protocol register number. */
464 int in_g_packet; /* Always part of G packet. */
465 /* long size in bytes; == register_size (arch, regnum);
466 at present. */
467 /* char *name; == gdbarch_register_name (arch, regnum);
468 at present. */
471 struct remote_arch_state
473 explicit remote_arch_state (struct gdbarch *gdbarch);
475 /* Description of the remote protocol registers. */
476 long sizeof_g_packet;
478 /* Description of the remote protocol registers indexed by REGNUM
479 (making an array gdbarch_num_regs in size). */
480 std::unique_ptr<packet_reg[]> regs;
482 /* This is the size (in chars) of the first response to the ``g''
483 packet. It is used as a heuristic when determining the maximum
484 size of memory-read and memory-write packets. A target will
485 typically only reserve a buffer large enough to hold the ``g''
486 packet. The size does not include packet overhead (headers and
487 trailers). */
488 long actual_register_packet_size;
490 /* This is the maximum size (in chars) of a non read/write packet.
491 It is also used as a cap on the size of read/write packets. */
492 long remote_packet_size;
495 /* Description of the remote protocol state for the currently
496 connected target. This is per-target state, and independent of the
497 selected architecture. */
499 class remote_state
501 public:
503 remote_state ();
504 ~remote_state ();
506 /* Get the remote arch state for GDBARCH. */
507 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
509 void create_async_event_handler ()
511 gdb_assert (m_async_event_handler_token == nullptr);
512 m_async_event_handler_token
513 = ::create_async_event_handler ([] (gdb_client_data data)
515 inferior_event_handler (INF_REG_EVENT);
517 nullptr, "remote");
520 void mark_async_event_handler ()
522 gdb_assert (this->is_async_p ());
523 ::mark_async_event_handler (m_async_event_handler_token);
526 void clear_async_event_handler ()
527 { ::clear_async_event_handler (m_async_event_handler_token); }
529 bool async_event_handler_marked () const
530 { return ::async_event_handler_marked (m_async_event_handler_token); }
532 void delete_async_event_handler ()
534 if (m_async_event_handler_token != nullptr)
535 ::delete_async_event_handler (&m_async_event_handler_token);
538 bool is_async_p () const
540 /* We're async whenever the serial device is. */
541 gdb_assert (this->remote_desc != nullptr);
542 return serial_is_async_p (this->remote_desc);
545 bool can_async_p () const
547 /* We can async whenever the serial device can. */
548 gdb_assert (this->remote_desc != nullptr);
549 return serial_can_async_p (this->remote_desc);
552 public: /* data */
554 /* A buffer to use for incoming packets, and its current size. The
555 buffer is grown dynamically for larger incoming packets.
556 Outgoing packets may also be constructed in this buffer.
557 The size of the buffer is always at least REMOTE_PACKET_SIZE;
558 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
559 packets. */
560 gdb::char_vector buf;
562 /* True if we're going through initial connection setup (finding out
563 about the remote side's threads, relocating symbols, etc.). */
564 bool starting_up = false;
566 /* If we negotiated packet size explicitly (and thus can bypass
567 heuristics for the largest packet size that will not overflow
568 a buffer in the stub), this will be set to that packet size.
569 Otherwise zero, meaning to use the guessed size. */
570 long explicit_packet_size = 0;
572 /* True, if in no ack mode. That is, neither GDB nor the stub will
573 expect acks from each other. The connection is assumed to be
574 reliable. */
575 bool noack_mode = false;
577 /* True if we're connected in extended remote mode. */
578 bool extended = false;
580 /* True if we resumed the target and we're waiting for the target to
581 stop. In the mean time, we can't start another command/query.
582 The remote server wouldn't be ready to process it, so we'd
583 timeout waiting for a reply that would never come and eventually
584 we'd close the connection. This can happen in asynchronous mode
585 because we allow GDB commands while the target is running. */
586 bool waiting_for_stop_reply = false;
588 /* The status of the stub support for the various vCont actions. */
589 vCont_action_support supports_vCont;
591 /* True if the user has pressed Ctrl-C, but the target hasn't
592 responded to that. */
593 bool ctrlc_pending_p = false;
595 /* True if we saw a Ctrl-C while reading or writing from/to the
596 remote descriptor. At that point it is not safe to send a remote
597 interrupt packet, so we instead remember we saw the Ctrl-C and
598 process it once we're done with sending/receiving the current
599 packet, which should be shortly. If however that takes too long,
600 and the user presses Ctrl-C again, we offer to disconnect. */
601 bool got_ctrlc_during_io = false;
603 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
604 remote_open knows that we don't have a file open when the program
605 starts. */
606 struct serial *remote_desc = nullptr;
608 /* These are the threads which we last sent to the remote system. The
609 TID member will be -1 for all or -2 for not sent yet. */
610 ptid_t general_thread = null_ptid;
611 ptid_t continue_thread = null_ptid;
613 /* This is the traceframe which we last selected on the remote system.
614 It will be -1 if no traceframe is selected. */
615 int remote_traceframe_number = -1;
617 char *last_pass_packet = nullptr;
619 /* The last QProgramSignals packet sent to the target. We bypass
620 sending a new program signals list down to the target if the new
621 packet is exactly the same as the last we sent. IOW, we only let
622 the target know about program signals list changes. */
623 char *last_program_signals_packet = nullptr;
625 /* Similarly, the last QThreadEvents state we sent to the
626 target. */
627 bool last_thread_events = false;
629 gdb_signal last_sent_signal = GDB_SIGNAL_0;
631 bool last_sent_step = false;
633 /* The execution direction of the last resume we got. */
634 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
636 char *finished_object = nullptr;
637 char *finished_annex = nullptr;
638 ULONGEST finished_offset = 0;
640 /* Should we try the 'ThreadInfo' query packet?
642 This variable (NOT available to the user: auto-detect only!)
643 determines whether GDB will use the new, simpler "ThreadInfo"
644 query or the older, more complex syntax for thread queries.
645 This is an auto-detect variable (set to true at each connect,
646 and set to false when the target fails to recognize it). */
647 bool use_threadinfo_query = false;
648 bool use_threadextra_query = false;
650 threadref echo_nextthread {};
651 threadref nextthread {};
652 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
654 /* The state of remote notification. */
655 struct remote_notif_state *notif_state = nullptr;
657 /* The branch trace configuration. */
658 struct btrace_config btrace_config {};
660 /* The argument to the last "vFile:setfs:" packet we sent, used
661 to avoid sending repeated unnecessary "vFile:setfs:" packets.
662 Initialized to -1 to indicate that no "vFile:setfs:" packet
663 has yet been sent. */
664 int fs_pid = -1;
666 /* A readahead cache for vFile:pread. Often, reading a binary
667 involves a sequence of small reads. E.g., when parsing an ELF
668 file. A readahead cache helps mostly the case of remote
669 debugging on a connection with higher latency, due to the
670 request/reply nature of the RSP. We only cache data for a single
671 file descriptor at a time. */
672 struct readahead_cache readahead_cache;
674 /* The list of already fetched and acknowledged stop events. This
675 queue is used for notification Stop, and other notifications
676 don't need queue for their events, because the notification
677 events of Stop can't be consumed immediately, so that events
678 should be queued first, and be consumed by remote_wait_{ns,as}
679 one per time. Other notifications can consume their events
680 immediately, so queue is not needed for them. */
681 std::vector<stop_reply_up> stop_reply_queue;
683 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
684 ``forever'' still use the normal timeout mechanism. This is
685 currently used by the ASYNC code to guarentee that target reads
686 during the initial connect always time-out. Once getpkt has been
687 modified to return a timeout indication and, in turn
688 remote_wait()/wait_for_inferior() have gained a timeout parameter
689 this can go away. */
690 bool wait_forever_enabled_p = true;
692 /* The set of thread options the target reported it supports, via
693 qSupported. */
694 gdb_thread_options supported_thread_options = 0;
696 private:
697 /* Asynchronous signal handle registered as event loop source for
698 when we have pending events ready to be passed to the core. */
699 async_event_handler *m_async_event_handler_token = nullptr;
701 /* Mapping of remote protocol data for each gdbarch. Usually there
702 is only one entry here, though we may see more with stubs that
703 support multi-process. */
704 std::unordered_map<struct gdbarch *, remote_arch_state>
705 m_arch_states;
708 static const target_info remote_target_info = {
709 "remote",
710 N_("Remote target using gdb-specific protocol"),
711 remote_doc
714 /* Description of a remote packet. */
716 struct packet_description
718 /* Name of the packet used for gdb output. */
719 const char *name;
721 /* Title of the packet, used by the set/show remote name-packet
722 commands to identify the individual packages and gdb output. */
723 const char *title;
726 /* Configuration of a remote packet. */
728 struct packet_config
730 /* If auto, GDB auto-detects support for this packet or feature,
731 either through qSupported, or by trying the packet and looking
732 at the response. If true, GDB assumes the target supports this
733 packet. If false, the packet is disabled. Configs that don't
734 have an associated command always have this set to auto. */
735 enum auto_boolean detect;
737 /* Does the target support this packet? */
738 enum packet_support support;
741 /* User configurable variables for the number of characters in a
742 memory read/write packet. MIN (rsa->remote_packet_size,
743 rsa->sizeof_g_packet) is the default. Some targets need smaller
744 values (fifo overruns, et.al.) and some users need larger values
745 (speed up transfers). The variables ``preferred_*'' (the user
746 request), ``current_*'' (what was actually set) and ``forced_*''
747 (Positive - a soft limit, negative - a hard limit). */
749 struct memory_packet_config
751 const char *name;
752 long size;
753 int fixed_p;
756 /* These global variables contain the default configuration for every new
757 remote_feature object. */
758 static memory_packet_config memory_read_packet_config =
760 "memory-read-packet-size",
762 static memory_packet_config memory_write_packet_config =
764 "memory-write-packet-size",
767 /* This global array contains packet descriptions (name and title). */
768 static packet_description packets_descriptions[PACKET_MAX];
769 /* This global array contains the default configuration for every new
770 per-remote target array. */
771 static packet_config remote_protocol_packets[PACKET_MAX];
773 /* Description of a remote target's features. It stores the configuration
774 and provides functions to determine supported features of the target. */
776 struct remote_features
778 remote_features ()
780 m_memory_read_packet_config = memory_read_packet_config;
781 m_memory_write_packet_config = memory_write_packet_config;
783 std::copy (std::begin (remote_protocol_packets),
784 std::end (remote_protocol_packets),
785 std::begin (m_protocol_packets));
787 ~remote_features () = default;
789 DISABLE_COPY_AND_ASSIGN (remote_features);
791 /* Returns whether a given packet defined by its enum value is supported. */
792 enum packet_support packet_support (int) const;
794 /* Returns the packet's corresponding "set remote foo-packet" command
795 state. See struct packet_config for more details. */
796 enum auto_boolean packet_set_cmd_state (int packet) const
797 { return m_protocol_packets[packet].detect; }
799 /* Returns true if the multi-process extensions are in effect. */
800 int remote_multi_process_p () const
801 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
803 /* Returns true if fork events are supported. */
804 int remote_fork_event_p () const
805 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
807 /* Returns true if vfork events are supported. */
808 int remote_vfork_event_p () const
809 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
811 /* Returns true if exec events are supported. */
812 int remote_exec_event_p () const
813 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
815 /* Returns true if memory tagging is supported, false otherwise. */
816 bool remote_memory_tagging_p () const
817 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
819 /* Reset all packets back to "unknown support". Called when opening a
820 new connection to a remote target. */
821 void reset_all_packet_configs_support ();
823 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
824 support configuration accordingly. */
825 packet_result packet_ok (const char *buf, const int which_packet);
826 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
828 /* Configuration of a remote target's memory read packet. */
829 memory_packet_config m_memory_read_packet_config;
830 /* Configuration of a remote target's memory write packet. */
831 memory_packet_config m_memory_write_packet_config;
833 /* The per-remote target array which stores a remote's packet
834 configurations. */
835 packet_config m_protocol_packets[PACKET_MAX];
838 class remote_target : public process_stratum_target
840 public:
841 remote_target () = default;
842 ~remote_target () override;
844 const target_info &info () const override
845 { return remote_target_info; }
847 const char *connection_string () override;
849 thread_control_capabilities get_thread_control_capabilities () override
850 { return tc_schedlock; }
852 /* Open a remote connection. */
853 static void open (const char *, int);
855 void close () override;
857 void detach (inferior *, int) override;
858 void disconnect (const char *, int) override;
860 void commit_requested_thread_options ();
862 void commit_resumed () override;
863 void resume (ptid_t, int, enum gdb_signal) override;
864 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
865 bool has_pending_events () override;
867 void fetch_registers (struct regcache *, int) override;
868 void store_registers (struct regcache *, int) override;
869 void prepare_to_store (struct regcache *) override;
871 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
873 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
874 enum remove_bp_reason) override;
877 bool stopped_by_sw_breakpoint () override;
878 bool supports_stopped_by_sw_breakpoint () override;
880 bool stopped_by_hw_breakpoint () override;
882 bool supports_stopped_by_hw_breakpoint () override;
884 bool stopped_by_watchpoint () override;
886 bool stopped_data_address (CORE_ADDR *) override;
888 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
890 int can_use_hw_breakpoint (enum bptype, int, int) override;
892 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
894 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
896 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
898 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
899 struct expression *) override;
901 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
902 struct expression *) override;
904 void kill () override;
906 void load (const char *, int) override;
908 void mourn_inferior () override;
910 void pass_signals (gdb::array_view<const unsigned char>) override;
912 int set_syscall_catchpoint (int, bool, int,
913 gdb::array_view<const int>) override;
915 void program_signals (gdb::array_view<const unsigned char>) override;
917 bool thread_alive (ptid_t ptid) override;
919 const char *thread_name (struct thread_info *) override;
921 void update_thread_list () override;
923 std::string pid_to_str (ptid_t) override;
925 const char *extra_thread_info (struct thread_info *) override;
927 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
929 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
930 int handle_len,
931 inferior *inf) override;
933 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
934 override;
936 void stop (ptid_t) override;
938 void interrupt () override;
940 void pass_ctrlc () override;
942 enum target_xfer_status xfer_partial (enum target_object object,
943 const char *annex,
944 gdb_byte *readbuf,
945 const gdb_byte *writebuf,
946 ULONGEST offset, ULONGEST len,
947 ULONGEST *xfered_len) override;
949 ULONGEST get_memory_xfer_limit () override;
951 void rcmd (const char *command, struct ui_file *output) override;
953 const char *pid_to_exec_file (int pid) override;
955 void log_command (const char *cmd) override
957 serial_log_command (this, cmd);
960 CORE_ADDR get_thread_local_address (ptid_t ptid,
961 CORE_ADDR load_module_addr,
962 CORE_ADDR offset) override;
964 bool can_execute_reverse () override;
966 std::vector<mem_region> memory_map () override;
968 void flash_erase (ULONGEST address, LONGEST length) override;
970 void flash_done () override;
972 const struct target_desc *read_description () override;
974 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
975 const gdb_byte *pattern, ULONGEST pattern_len,
976 CORE_ADDR *found_addrp) override;
978 bool can_async_p () override;
980 bool is_async_p () override;
982 void async (bool) override;
984 int async_wait_fd () override;
986 void thread_events (bool) override;
988 bool supports_set_thread_options (gdb_thread_options) override;
990 int can_do_single_step () override;
992 void terminal_inferior () override;
994 void terminal_ours () override;
996 bool supports_non_stop () override;
998 bool supports_multi_process () override;
1000 bool supports_disable_randomization () override;
1002 bool filesystem_is_local () override;
1005 int fileio_open (struct inferior *inf, const char *filename,
1006 int flags, int mode, int warn_if_slow,
1007 fileio_error *target_errno) override;
1009 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
1010 ULONGEST offset, fileio_error *target_errno) override;
1012 int fileio_pread (int fd, gdb_byte *read_buf, int len,
1013 ULONGEST offset, fileio_error *target_errno) override;
1015 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
1017 int fileio_stat (struct inferior *inf, const char *filename,
1018 struct stat *sb, fileio_error *target_errno) override;
1020 int fileio_close (int fd, fileio_error *target_errno) override;
1022 int fileio_unlink (struct inferior *inf,
1023 const char *filename,
1024 fileio_error *target_errno) override;
1026 std::optional<std::string>
1027 fileio_readlink (struct inferior *inf,
1028 const char *filename,
1029 fileio_error *target_errno) override;
1031 bool supports_enable_disable_tracepoint () override;
1033 bool supports_string_tracing () override;
1035 int remote_supports_cond_tracepoints ();
1037 bool supports_evaluation_of_breakpoint_conditions () override;
1039 int remote_supports_fast_tracepoints ();
1041 int remote_supports_static_tracepoints ();
1043 int remote_supports_install_in_trace ();
1045 bool can_run_breakpoint_commands () override;
1047 void trace_init () override;
1049 void download_tracepoint (struct bp_location *location) override;
1051 bool can_download_tracepoint () override;
1053 void download_trace_state_variable (const trace_state_variable &tsv) override;
1055 void enable_tracepoint (struct bp_location *location) override;
1057 void disable_tracepoint (struct bp_location *location) override;
1059 void trace_set_readonly_regions () override;
1061 void trace_start () override;
1063 int get_trace_status (struct trace_status *ts) override;
1065 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
1066 override;
1068 void trace_stop () override;
1070 int trace_find (enum trace_find_type type, int num,
1071 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
1073 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
1075 int save_trace_data (const char *filename) override;
1077 int upload_tracepoints (struct uploaded_tp **utpp) override;
1079 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
1081 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
1083 int get_min_fast_tracepoint_insn_len () override;
1085 void set_disconnected_tracing (int val) override;
1087 void set_circular_trace_buffer (int val) override;
1089 void set_trace_buffer_size (LONGEST val) override;
1091 bool set_trace_notes (const char *user, const char *notes,
1092 const char *stopnotes) override;
1094 int core_of_thread (ptid_t ptid) override;
1096 int verify_memory (const gdb_byte *data,
1097 CORE_ADDR memaddr, ULONGEST size) override;
1100 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
1102 void set_permissions () override;
1104 bool static_tracepoint_marker_at (CORE_ADDR,
1105 struct static_tracepoint_marker *marker)
1106 override;
1108 std::vector<static_tracepoint_marker>
1109 static_tracepoint_markers_by_strid (const char *id) override;
1111 traceframe_info_up traceframe_info () override;
1113 bool use_agent (bool use) override;
1114 bool can_use_agent () override;
1116 struct btrace_target_info *
1117 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1119 void disable_btrace (struct btrace_target_info *tinfo) override;
1121 void teardown_btrace (struct btrace_target_info *tinfo) override;
1123 enum btrace_error read_btrace (struct btrace_data *data,
1124 struct btrace_target_info *btinfo,
1125 enum btrace_read_type type) override;
1127 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1128 bool augmented_libraries_svr4_read () override;
1129 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1130 void follow_clone (ptid_t child_ptid) override;
1131 void follow_exec (inferior *, ptid_t, const char *) override;
1132 int insert_fork_catchpoint (int) override;
1133 int remove_fork_catchpoint (int) override;
1134 int insert_vfork_catchpoint (int) override;
1135 int remove_vfork_catchpoint (int) override;
1136 int insert_exec_catchpoint (int) override;
1137 int remove_exec_catchpoint (int) override;
1138 enum exec_direction_kind execution_direction () override;
1140 bool supports_memory_tagging () override;
1142 bool fetch_memtags (CORE_ADDR address, size_t len,
1143 gdb::byte_vector &tags, int type) override;
1145 bool store_memtags (CORE_ADDR address, size_t len,
1146 const gdb::byte_vector &tags, int type) override;
1148 bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
1150 public: /* Remote specific methods. */
1152 void remote_download_command_source (int num, ULONGEST addr,
1153 struct command_line *cmds);
1155 void remote_file_put (const char *local_file, const char *remote_file,
1156 int from_tty);
1157 void remote_file_get (const char *remote_file, const char *local_file,
1158 int from_tty);
1159 void remote_file_delete (const char *remote_file, int from_tty);
1161 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1162 ULONGEST offset, fileio_error *remote_errno);
1163 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1164 ULONGEST offset, fileio_error *remote_errno);
1165 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1166 ULONGEST offset, fileio_error *remote_errno);
1168 int remote_hostio_send_command (int command_bytes, int which_packet,
1169 fileio_error *remote_errno, const char **attachment,
1170 int *attachment_len);
1171 int remote_hostio_set_filesystem (struct inferior *inf,
1172 fileio_error *remote_errno);
1173 /* We should get rid of this and use fileio_open directly. */
1174 int remote_hostio_open (struct inferior *inf, const char *filename,
1175 int flags, int mode, int warn_if_slow,
1176 fileio_error *remote_errno);
1177 int remote_hostio_close (int fd, fileio_error *remote_errno);
1179 int remote_hostio_unlink (inferior *inf, const char *filename,
1180 fileio_error *remote_errno);
1182 struct remote_state *get_remote_state ();
1184 long get_remote_packet_size (void);
1185 long get_memory_packet_size (struct memory_packet_config *config);
1187 long get_memory_write_packet_size ();
1188 long get_memory_read_packet_size ();
1190 char *append_pending_thread_resumptions (char *p, char *endp,
1191 ptid_t ptid);
1192 static void open_1 (const char *name, int from_tty, int extended_p);
1193 void start_remote (int from_tty, int extended_p);
1194 void remote_detach_1 (struct inferior *inf, int from_tty);
1196 char *append_resumption (char *p, char *endp,
1197 ptid_t ptid, int step, gdb_signal siggnal);
1198 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1199 gdb_signal siggnal);
1201 thread_info *add_current_inferior_and_thread (const char *wait_status);
1203 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1204 target_wait_flags options);
1205 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1206 target_wait_flags options);
1208 ptid_t process_stop_reply (stop_reply_up stop_reply,
1209 target_waitstatus *status);
1211 ptid_t select_thread_for_ambiguous_stop_reply
1212 (const struct target_waitstatus &status);
1214 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1216 void print_one_stopped_thread (thread_info *thread);
1217 void process_initial_stop_replies (int from_tty);
1219 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1220 bool silent_p);
1222 void btrace_sync_conf (const btrace_config *conf);
1224 void remote_btrace_maybe_reopen ();
1226 void remove_new_children (threads_listing_context *context);
1227 void kill_new_fork_children (inferior *inf);
1228 void discard_pending_stop_replies (struct inferior *inf);
1229 int stop_reply_queue_length ();
1231 void check_pending_events_prevent_wildcard_vcont
1232 (bool *may_global_wildcard_vcont);
1234 void discard_pending_stop_replies_in_queue ();
1235 stop_reply_up remote_notif_remove_queued_reply (ptid_t ptid);
1236 stop_reply_up queued_stop_reply (ptid_t ptid);
1237 int peek_stop_reply (ptid_t ptid);
1238 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1240 void remote_stop_ns (ptid_t ptid);
1241 void remote_interrupt_as ();
1242 void remote_interrupt_ns ();
1244 char *remote_get_noisy_reply ();
1245 int remote_query_attached (int pid);
1246 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1247 int try_open_exec);
1249 ptid_t remote_current_thread (ptid_t oldpid);
1250 ptid_t get_current_thread (const char *wait_status);
1252 void set_thread (ptid_t ptid, int gen);
1253 void set_general_thread (ptid_t ptid);
1254 void set_continue_thread (ptid_t ptid);
1255 void set_general_process ();
1257 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1259 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1260 gdb_ext_thread_info *info);
1261 int remote_get_threadinfo (threadref *threadid, int fieldset,
1262 gdb_ext_thread_info *info);
1264 int parse_threadlist_response (const char *pkt, int result_limit,
1265 threadref *original_echo,
1266 threadref *resultlist,
1267 int *doneflag);
1268 int remote_get_threadlist (int startflag, threadref *nextthread,
1269 int result_limit, int *done, int *result_count,
1270 threadref *threadlist);
1272 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1273 void *context, int looplimit);
1275 int remote_get_threads_with_ql (threads_listing_context *context);
1276 int remote_get_threads_with_qxfer (threads_listing_context *context);
1277 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1279 void extended_remote_restart ();
1281 void get_offsets ();
1283 void remote_check_symbols ();
1285 void remote_supported_packet (const struct protocol_feature *feature,
1286 enum packet_support support,
1287 const char *argument);
1289 void remote_query_supported ();
1291 void remote_packet_size (const protocol_feature *feature,
1292 packet_support support, const char *value);
1293 void remote_supported_thread_options (const protocol_feature *feature,
1294 enum packet_support support,
1295 const char *value);
1297 void remote_serial_quit_handler ();
1299 void remote_detach_pid (int pid);
1301 void remote_vcont_probe ();
1303 void remote_resume_with_hc (ptid_t ptid, int step,
1304 gdb_signal siggnal);
1306 void send_interrupt_sequence ();
1307 void interrupt_query ();
1309 void remote_notif_get_pending_events (const notif_client *nc);
1311 int fetch_register_using_p (struct regcache *regcache,
1312 packet_reg *reg);
1313 int send_g_packet ();
1314 void process_g_packet (struct regcache *regcache);
1315 void fetch_registers_using_g (struct regcache *regcache);
1316 int store_register_using_P (const struct regcache *regcache,
1317 packet_reg *reg);
1318 void store_registers_using_G (const struct regcache *regcache);
1320 void set_remote_traceframe ();
1322 void check_binary_download (CORE_ADDR addr);
1324 target_xfer_status remote_write_bytes_aux (const char *header,
1325 CORE_ADDR memaddr,
1326 const gdb_byte *myaddr,
1327 ULONGEST len_units,
1328 int unit_size,
1329 ULONGEST *xfered_len_units,
1330 char packet_format,
1331 int use_length);
1333 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1334 const gdb_byte *myaddr, ULONGEST len,
1335 int unit_size, ULONGEST *xfered_len);
1337 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1338 ULONGEST len_units,
1339 int unit_size, ULONGEST *xfered_len_units);
1341 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1342 ULONGEST memaddr,
1343 ULONGEST len,
1344 int unit_size,
1345 ULONGEST *xfered_len);
1347 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1348 gdb_byte *myaddr, ULONGEST len,
1349 int unit_size,
1350 ULONGEST *xfered_len);
1352 packet_status remote_send_printf (const char *format, ...)
1353 ATTRIBUTE_PRINTF (2, 3);
1355 target_xfer_status remote_flash_write (ULONGEST address,
1356 ULONGEST length, ULONGEST *xfered_len,
1357 const gdb_byte *data);
1359 int readchar (int timeout);
1361 void remote_serial_write (const char *str, int len);
1362 void remote_serial_send_break ();
1364 int putpkt (const char *buf);
1365 int putpkt_binary (const char *buf, int cnt);
1367 int putpkt (const gdb::char_vector &buf)
1369 return putpkt (buf.data ());
1372 void skip_frame ();
1373 long read_frame (gdb::char_vector *buf_p);
1374 int getpkt (gdb::char_vector *buf, bool forever = false,
1375 bool *is_notif = nullptr);
1376 int remote_vkill (int pid);
1377 void remote_kill_k ();
1379 void extended_remote_disable_randomization (int val);
1380 int extended_remote_run (const std::string &args);
1382 void send_environment_packet (const char *action,
1383 const char *packet,
1384 const char *value);
1386 void extended_remote_environment_support ();
1387 void extended_remote_set_inferior_cwd ();
1389 target_xfer_status remote_write_qxfer (const char *object_name,
1390 const char *annex,
1391 const gdb_byte *writebuf,
1392 ULONGEST offset, LONGEST len,
1393 ULONGEST *xfered_len,
1394 const unsigned int which_packet);
1396 target_xfer_status remote_read_qxfer (const char *object_name,
1397 const char *annex,
1398 gdb_byte *readbuf, ULONGEST offset,
1399 LONGEST len,
1400 ULONGEST *xfered_len,
1401 const unsigned int which_packet);
1403 void push_stop_reply (stop_reply_up new_event);
1405 bool vcont_r_supported ();
1407 remote_features m_features;
1409 private:
1411 bool start_remote_1 (int from_tty, int extended_p);
1413 /* The remote state. Don't reference this directly. Use the
1414 get_remote_state method instead. */
1415 remote_state m_remote_state;
1418 static const target_info extended_remote_target_info = {
1419 "extended-remote",
1420 N_("Extended remote target using gdb-specific protocol"),
1421 remote_doc
1424 /* Set up the extended remote target by extending the standard remote
1425 target and adding to it. */
1427 class extended_remote_target final : public remote_target
1429 public:
1430 const target_info &info () const override
1431 { return extended_remote_target_info; }
1433 /* Open an extended-remote connection. */
1434 static void open (const char *, int);
1436 bool can_create_inferior () override { return true; }
1437 void create_inferior (const char *, const std::string &,
1438 char **, int) override;
1440 void detach (inferior *, int) override;
1442 bool can_attach () override { return true; }
1443 void attach (const char *, int) override;
1445 void post_attach (int) override;
1446 bool supports_disable_randomization () override;
1449 struct stop_reply : public notif_event
1451 /* The identifier of the thread about this event */
1452 ptid_t ptid;
1454 /* The remote state this event is associated with. When the remote
1455 connection, represented by a remote_state object, is closed,
1456 all the associated stop_reply events should be released. */
1457 struct remote_state *rs;
1459 struct target_waitstatus ws;
1461 /* The architecture associated with the expedited registers. */
1462 gdbarch *arch;
1464 /* Expedited registers. This makes remote debugging a bit more
1465 efficient for those targets that provide critical registers as
1466 part of their normal status mechanism (as another roundtrip to
1467 fetch them is avoided). */
1468 std::vector<cached_reg_t> regcache;
1470 enum target_stop_reason stop_reason;
1472 CORE_ADDR watch_data_address;
1474 int core;
1477 /* Return TARGET as a remote_target if it is one, else nullptr. */
1479 static remote_target *
1480 as_remote_target (process_stratum_target *target)
1482 return dynamic_cast<remote_target *> (target);
1485 /* See remote.h. */
1487 bool
1488 is_remote_target (process_stratum_target *target)
1490 return as_remote_target (target) != nullptr;
1493 /* Per-program-space data key. */
1494 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1495 remote_pspace_data;
1497 /* The variable registered as the control variable used by the
1498 remote exec-file commands. While the remote exec-file setting is
1499 per-program-space, the set/show machinery uses this as the
1500 location of the remote exec-file value. */
1501 static std::string remote_exec_file_var;
1503 /* The size to align memory write packets, when practical. The protocol
1504 does not guarantee any alignment, and gdb will generate short
1505 writes and unaligned writes, but even as a best-effort attempt this
1506 can improve bulk transfers. For instance, if a write is misaligned
1507 relative to the target's data bus, the stub may need to make an extra
1508 round trip fetching data from the target. This doesn't make a
1509 huge difference, but it's easy to do, so we try to be helpful.
1511 The alignment chosen is arbitrary; usually data bus width is
1512 important here, not the possibly larger cache line size. */
1513 enum { REMOTE_ALIGN_WRITES = 16 };
1515 /* Prototypes for local functions. */
1517 static int hexnumlen (ULONGEST num);
1519 static int stubhex (int ch);
1521 static int hexnumstr (char *, ULONGEST);
1523 static int hexnumnstr (char *, ULONGEST, int);
1525 static CORE_ADDR remote_address_masked (CORE_ADDR);
1527 static int stub_unpack_int (const char *buff, int fieldlength);
1529 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1530 cmd_list_element *c);
1532 static void show_packet_config_cmd (ui_file *file,
1533 const unsigned int which_packet,
1534 remote_target *remote);
1536 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1537 int from_tty,
1538 struct cmd_list_element *c,
1539 const char *value);
1541 static ptid_t read_ptid (const char *buf, const char **obuf);
1543 static bool remote_read_description_p (struct target_ops *target);
1545 static void remote_console_output (const char *msg, ui_file *stream);
1547 static void remote_btrace_reset (remote_state *rs);
1549 [[noreturn]] static void remote_unpush_and_throw (remote_target *target);
1551 /* For "remote". */
1553 static struct cmd_list_element *remote_cmdlist;
1555 /* For "set remote" and "show remote". */
1557 static struct cmd_list_element *remote_set_cmdlist;
1558 static struct cmd_list_element *remote_show_cmdlist;
1560 /* Controls whether GDB is willing to use range stepping. */
1562 static bool use_range_stepping = true;
1564 /* From the remote target's point of view, each thread is in one of these three
1565 states. */
1566 enum class resume_state
1568 /* Not resumed - we haven't been asked to resume this thread. */
1569 NOT_RESUMED,
1571 /* We have been asked to resume this thread, but haven't sent a vCont action
1572 for it yet. We'll need to consider it next time commit_resume is
1573 called. */
1574 RESUMED_PENDING_VCONT,
1576 /* We have been asked to resume this thread, and we have sent a vCont action
1577 for it. */
1578 RESUMED,
1581 /* Information about a thread's pending vCont-resume. Used when a thread is in
1582 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1583 stores this information which is then picked up by
1584 remote_target::commit_resume to know which is the proper action for this
1585 thread to include in the vCont packet. */
1586 struct resumed_pending_vcont_info
1588 /* True if the last resume call for this thread was a step request, false
1589 if a continue request. */
1590 bool step;
1592 /* The signal specified in the last resume call for this thread. */
1593 gdb_signal sig;
1596 /* Private data that we'll store in (struct thread_info)->priv. */
1597 struct remote_thread_info : public private_thread_info
1599 std::string extra;
1600 std::string name;
1601 int core = -1;
1603 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1604 sequence of bytes. */
1605 gdb::byte_vector thread_handle;
1607 /* Whether the target stopped for a breakpoint/watchpoint. */
1608 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1610 /* This is set to the data address of the access causing the target
1611 to stop for a watchpoint. */
1612 CORE_ADDR watch_data_address = 0;
1614 /* Get the thread's resume state. */
1615 enum resume_state get_resume_state () const
1617 return m_resume_state;
1620 /* Put the thread in the NOT_RESUMED state. */
1621 void set_not_resumed ()
1623 m_resume_state = resume_state::NOT_RESUMED;
1626 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1627 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1629 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1630 m_resumed_pending_vcont_info.step = step;
1631 m_resumed_pending_vcont_info.sig = sig;
1634 /* Get the information this thread's pending vCont-resumption.
1636 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1637 state. */
1638 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1640 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1642 return m_resumed_pending_vcont_info;
1645 /* Put the thread in the VCONT_RESUMED state. */
1646 void set_resumed ()
1648 m_resume_state = resume_state::RESUMED;
1651 private:
1652 /* Resume state for this thread. This is used to implement vCont action
1653 coalescing (only when the target operates in non-stop mode).
1655 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1656 which notes that this thread must be considered in the next commit_resume
1657 call.
1659 remote_target::commit_resume sends a vCont packet with actions for the
1660 threads in the RESUMED_PENDING_VCONT state and moves them to the
1661 VCONT_RESUMED state.
1663 When reporting a stop to the core for a thread, that thread is moved back
1664 to the NOT_RESUMED state. */
1665 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1667 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1668 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1671 remote_state::remote_state ()
1672 : buf (400)
1676 remote_state::~remote_state ()
1678 xfree (this->last_pass_packet);
1679 xfree (this->last_program_signals_packet);
1680 xfree (this->finished_object);
1681 xfree (this->finished_annex);
1684 /* Utility: generate error from an incoming stub packet. */
1685 static void
1686 trace_error (char *buf)
1688 if (*buf++ != 'E')
1689 return; /* not an error msg */
1690 switch (*buf)
1692 case '1': /* malformed packet error */
1693 if (*++buf == '0') /* general case: */
1694 error (_("remote.c: error in outgoing packet."));
1695 else
1696 error (_("remote.c: error in outgoing packet at field #%ld."),
1697 strtol (buf, NULL, 16));
1698 default:
1699 error (_("Target returns error code '%s'."), buf);
1703 /* Utility: wait for reply from stub, while accepting "O" packets. */
1705 char *
1706 remote_target::remote_get_noisy_reply ()
1708 struct remote_state *rs = get_remote_state ();
1710 do /* Loop on reply from remote stub. */
1712 char *buf;
1714 QUIT; /* Allow user to bail out with ^C. */
1715 getpkt (&rs->buf);
1716 buf = rs->buf.data ();
1717 if (buf[0] == 'E')
1718 trace_error (buf);
1719 else if (startswith (buf, "qRelocInsn:"))
1721 ULONGEST ul;
1722 CORE_ADDR from, to, org_to;
1723 const char *p, *pp;
1724 int adjusted_size = 0;
1725 int relocated = 0;
1727 p = buf + strlen ("qRelocInsn:");
1728 pp = unpack_varlen_hex (p, &ul);
1729 if (*pp != ';')
1730 error (_("invalid qRelocInsn packet: %s"), buf);
1731 from = ul;
1733 p = pp + 1;
1734 unpack_varlen_hex (p, &ul);
1735 to = ul;
1737 org_to = to;
1741 gdbarch_relocate_instruction (current_inferior ()->arch (),
1742 &to, from);
1743 relocated = 1;
1745 catch (const gdb_exception &ex)
1747 if (ex.error == MEMORY_ERROR)
1749 /* Propagate memory errors silently back to the
1750 target. The stub may have limited the range of
1751 addresses we can write to, for example. */
1753 else
1755 /* Something unexpectedly bad happened. Be verbose
1756 so we can tell what, and propagate the error back
1757 to the stub, so it doesn't get stuck waiting for
1758 a response. */
1759 exception_fprintf (gdb_stderr, ex,
1760 _("warning: relocating instruction: "));
1762 putpkt ("E01");
1765 if (relocated)
1767 adjusted_size = to - org_to;
1769 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1770 putpkt (buf);
1773 else if (buf[0] == 'O' && buf[1] != 'K')
1775 /* 'O' message from stub */
1776 remote_console_output (buf + 1, gdb_stdtarg);
1778 else
1779 return buf; /* Here's the actual reply. */
1781 while (1);
1784 struct remote_arch_state *
1785 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1787 remote_arch_state *rsa;
1789 auto it = this->m_arch_states.find (gdbarch);
1790 if (it == this->m_arch_states.end ())
1792 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1793 std::forward_as_tuple (gdbarch),
1794 std::forward_as_tuple (gdbarch));
1795 rsa = &p.first->second;
1797 /* Make sure that the packet buffer is plenty big enough for
1798 this architecture. */
1799 if (this->buf.size () < rsa->remote_packet_size)
1800 this->buf.resize (2 * rsa->remote_packet_size);
1802 else
1803 rsa = &it->second;
1805 return rsa;
1808 /* Fetch the global remote target state. */
1810 remote_state *
1811 remote_target::get_remote_state ()
1813 /* Make sure that the remote architecture state has been
1814 initialized, because doing so might reallocate rs->buf. Any
1815 function which calls getpkt also needs to be mindful of changes
1816 to rs->buf, but this call limits the number of places which run
1817 into trouble. */
1818 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1820 return &m_remote_state;
1823 /* Fetch the remote exec-file from the current program space. */
1825 static const char *
1826 get_remote_exec_file (void)
1828 char *remote_exec_file;
1830 remote_exec_file = remote_pspace_data.get (current_program_space);
1831 if (remote_exec_file == NULL)
1832 return "";
1834 return remote_exec_file;
1837 /* Set the remote exec file for PSPACE. */
1839 static void
1840 set_pspace_remote_exec_file (struct program_space *pspace,
1841 const char *remote_exec_file)
1843 char *old_file = remote_pspace_data.get (pspace);
1845 xfree (old_file);
1846 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1849 /* The "set/show remote exec-file" set command hook. */
1851 static void
1852 set_remote_exec_file (const char *ignored, int from_tty,
1853 struct cmd_list_element *c)
1855 set_pspace_remote_exec_file (current_program_space,
1856 remote_exec_file_var.c_str ());
1859 /* The "set/show remote exec-file" show command hook. */
1861 static void
1862 show_remote_exec_file (struct ui_file *file, int from_tty,
1863 struct cmd_list_element *cmd, const char *value)
1865 gdb_printf (file, "%s\n", get_remote_exec_file ());
1868 static int
1869 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1871 int regnum, num_remote_regs, offset;
1872 struct packet_reg **remote_regs;
1874 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1876 struct packet_reg *r = &regs[regnum];
1878 if (register_size (gdbarch, regnum) == 0)
1879 /* Do not try to fetch zero-sized (placeholder) registers. */
1880 r->pnum = -1;
1881 else
1882 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1884 r->regnum = regnum;
1887 /* Define the g/G packet format as the contents of each register
1888 with a remote protocol number, in order of ascending protocol
1889 number. */
1891 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1892 for (num_remote_regs = 0, regnum = 0;
1893 regnum < gdbarch_num_regs (gdbarch);
1894 regnum++)
1895 if (regs[regnum].pnum != -1)
1896 remote_regs[num_remote_regs++] = &regs[regnum];
1898 std::sort (remote_regs, remote_regs + num_remote_regs,
1899 [] (const packet_reg *a, const packet_reg *b)
1900 { return a->pnum < b->pnum; });
1902 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1904 remote_regs[regnum]->in_g_packet = 1;
1905 remote_regs[regnum]->offset = offset;
1906 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1909 return offset;
1912 /* Given the architecture described by GDBARCH, return the remote
1913 protocol register's number and the register's offset in the g/G
1914 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1915 If the target does not have a mapping for REGNUM, return false,
1916 otherwise, return true. */
1919 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1920 int *pnum, int *poffset)
1922 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1924 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1926 map_regcache_remote_table (gdbarch, regs.data ());
1928 *pnum = regs[regnum].pnum;
1929 *poffset = regs[regnum].offset;
1931 return *pnum != -1;
1934 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1936 /* Use the architecture to build a regnum<->pnum table, which will be
1937 1:1 unless a feature set specifies otherwise. */
1938 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1940 /* Record the maximum possible size of the g packet - it may turn out
1941 to be smaller. */
1942 this->sizeof_g_packet
1943 = map_regcache_remote_table (gdbarch, this->regs.get ());
1945 /* Default maximum number of characters in a packet body. Many
1946 remote stubs have a hardwired buffer size of 400 bytes
1947 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1948 as the maximum packet-size to ensure that the packet and an extra
1949 NUL character can always fit in the buffer. This stops GDB
1950 trashing stubs that try to squeeze an extra NUL into what is
1951 already a full buffer (As of 1999-12-04 that was most stubs). */
1952 this->remote_packet_size = 400 - 1;
1954 /* This one is filled in when a ``g'' packet is received. */
1955 this->actual_register_packet_size = 0;
1957 /* Should rsa->sizeof_g_packet needs more space than the
1958 default, adjust the size accordingly. Remember that each byte is
1959 encoded as two characters. 32 is the overhead for the packet
1960 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1961 (``$NN:G...#NN'') is a better guess, the below has been padded a
1962 little. */
1963 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1964 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1967 /* Get a pointer to the current remote target. If not connected to a
1968 remote target, return NULL. */
1970 static remote_target *
1971 get_current_remote_target ()
1973 target_ops *proc_target = current_inferior ()->process_target ();
1974 return dynamic_cast<remote_target *> (proc_target);
1977 /* Return the current allowed size of a remote packet. This is
1978 inferred from the current architecture, and should be used to
1979 limit the length of outgoing packets. */
1980 long
1981 remote_target::get_remote_packet_size ()
1983 struct remote_state *rs = get_remote_state ();
1984 remote_arch_state *rsa
1985 = rs->get_remote_arch_state (current_inferior ()->arch ());
1987 if (rs->explicit_packet_size)
1988 return rs->explicit_packet_size;
1990 return rsa->remote_packet_size;
1993 static struct packet_reg *
1994 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1995 long regnum)
1997 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1998 return NULL;
1999 else
2001 struct packet_reg *r = &rsa->regs[regnum];
2003 gdb_assert (r->regnum == regnum);
2004 return r;
2008 static struct packet_reg *
2009 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
2010 LONGEST pnum)
2012 int i;
2014 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
2016 struct packet_reg *r = &rsa->regs[i];
2018 if (r->pnum == pnum)
2019 return r;
2021 return NULL;
2024 /* Allow the user to specify what sequence to send to the remote
2025 when he requests a program interruption: Although ^C is usually
2026 what remote systems expect (this is the default, here), it is
2027 sometimes preferable to send a break. On other systems such
2028 as the Linux kernel, a break followed by g, which is Magic SysRq g
2029 is required in order to interrupt the execution. */
2030 const char interrupt_sequence_control_c[] = "Ctrl-C";
2031 const char interrupt_sequence_break[] = "BREAK";
2032 const char interrupt_sequence_break_g[] = "BREAK-g";
2033 static const char *const interrupt_sequence_modes[] =
2035 interrupt_sequence_control_c,
2036 interrupt_sequence_break,
2037 interrupt_sequence_break_g,
2038 NULL
2040 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
2042 static void
2043 show_interrupt_sequence (struct ui_file *file, int from_tty,
2044 struct cmd_list_element *c,
2045 const char *value)
2047 if (interrupt_sequence_mode == interrupt_sequence_control_c)
2048 gdb_printf (file,
2049 _("Send the ASCII ETX character (Ctrl-c) "
2050 "to the remote target to interrupt the "
2051 "execution of the program.\n"));
2052 else if (interrupt_sequence_mode == interrupt_sequence_break)
2053 gdb_printf (file,
2054 _("send a break signal to the remote target "
2055 "to interrupt the execution of the program.\n"));
2056 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
2057 gdb_printf (file,
2058 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
2059 "the remote target to interrupt the execution "
2060 "of Linux kernel.\n"));
2061 else
2062 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
2063 interrupt_sequence_mode);
2066 /* This boolean variable specifies whether interrupt_sequence is sent
2067 to the remote target when gdb connects to it.
2068 This is mostly needed when you debug the Linux kernel: The Linux kernel
2069 expects BREAK g which is Magic SysRq g for connecting gdb. */
2070 static bool interrupt_on_connect = false;
2072 /* This variable is used to implement the "set/show remotebreak" commands.
2073 Since these commands are now deprecated in favor of "set/show remote
2074 interrupt-sequence", it no longer has any effect on the code. */
2075 static bool remote_break;
2077 static void
2078 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
2080 if (remote_break)
2081 interrupt_sequence_mode = interrupt_sequence_break;
2082 else
2083 interrupt_sequence_mode = interrupt_sequence_control_c;
2086 static void
2087 show_remotebreak (struct ui_file *file, int from_tty,
2088 struct cmd_list_element *c,
2089 const char *value)
2093 /* This variable sets the number of bits in an address that are to be
2094 sent in a memory ("M" or "m") packet. Normally, after stripping
2095 leading zeros, the entire address would be sent. This variable
2096 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2097 initial implementation of remote.c restricted the address sent in
2098 memory packets to ``host::sizeof long'' bytes - (typically 32
2099 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2100 address was never sent. Since fixing this bug may cause a break in
2101 some remote targets this variable is principally provided to
2102 facilitate backward compatibility. */
2104 static unsigned int remote_address_size;
2107 /* The default max memory-write-packet-size, when the setting is
2108 "fixed". The 16k is historical. (It came from older GDB's using
2109 alloca for buffers and the knowledge (folklore?) that some hosts
2110 don't cope very well with large alloca calls.) */
2111 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2113 /* The minimum remote packet size for memory transfers. Ensures we
2114 can write at least one byte. */
2115 #define MIN_MEMORY_PACKET_SIZE 20
2117 /* Get the memory packet size, assuming it is fixed. */
2119 static long
2120 get_fixed_memory_packet_size (struct memory_packet_config *config)
2122 gdb_assert (config->fixed_p);
2124 if (config->size <= 0)
2125 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2126 else
2127 return config->size;
2130 /* Compute the current size of a read/write packet. Since this makes
2131 use of ``actual_register_packet_size'' the computation is dynamic. */
2133 long
2134 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2136 struct remote_state *rs = get_remote_state ();
2137 remote_arch_state *rsa
2138 = rs->get_remote_arch_state (current_inferior ()->arch ());
2140 long what_they_get;
2141 if (config->fixed_p)
2142 what_they_get = get_fixed_memory_packet_size (config);
2143 else
2145 what_they_get = get_remote_packet_size ();
2146 /* Limit the packet to the size specified by the user. */
2147 if (config->size > 0
2148 && what_they_get > config->size)
2149 what_they_get = config->size;
2151 /* Limit it to the size of the targets ``g'' response unless we have
2152 permission from the stub to use a larger packet size. */
2153 if (rs->explicit_packet_size == 0
2154 && rsa->actual_register_packet_size > 0
2155 && what_they_get > rsa->actual_register_packet_size)
2156 what_they_get = rsa->actual_register_packet_size;
2158 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2159 what_they_get = MIN_MEMORY_PACKET_SIZE;
2161 /* Make sure there is room in the global buffer for this packet
2162 (including its trailing NUL byte). */
2163 if (rs->buf.size () < what_they_get + 1)
2164 rs->buf.resize (2 * what_they_get);
2166 return what_they_get;
2169 /* Update the size of a read/write packet. If they user wants
2170 something really big then do a sanity check. */
2172 static void
2173 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2174 bool target_connected)
2176 int fixed_p = config->fixed_p;
2177 long size = config->size;
2179 if (args == NULL)
2180 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2181 else if (strcmp (args, "hard") == 0
2182 || strcmp (args, "fixed") == 0)
2183 fixed_p = 1;
2184 else if (strcmp (args, "soft") == 0
2185 || strcmp (args, "limit") == 0)
2186 fixed_p = 0;
2187 else
2189 char *end;
2191 size = strtoul (args, &end, 0);
2192 if (args == end)
2193 error (_("Invalid %s (bad syntax)."), config->name);
2195 /* Instead of explicitly capping the size of a packet to or
2196 disallowing it, the user is allowed to set the size to
2197 something arbitrarily large. */
2200 /* Extra checks? */
2201 if (fixed_p && !config->fixed_p)
2203 /* So that the query shows the correct value. */
2204 long query_size = (size <= 0
2205 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2206 : size);
2208 if (target_connected
2209 && !query (_("The target may not be able to correctly handle a %s\n"
2210 "of %ld bytes. Change the packet size? "),
2211 config->name, query_size))
2212 error (_("Packet size not changed."));
2213 else if (!target_connected
2214 && !query (_("Future remote targets may not be able to "
2215 "correctly handle a %s\nof %ld bytes. Change the "
2216 "packet size for future remote targets? "),
2217 config->name, query_size))
2218 error (_("Packet size not changed."));
2220 /* Update the config. */
2221 config->fixed_p = fixed_p;
2222 config->size = size;
2224 const char *target_type = get_target_type_name (target_connected);
2225 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2226 args);
2230 /* Show the memory-read or write-packet size configuration CONFIG of the
2231 target REMOTE. If REMOTE is nullptr, the default configuration for future
2232 remote targets should be passed in CONFIG. */
2234 static void
2235 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2237 const char *target_type = get_target_type_name (remote != nullptr);
2239 if (config->size == 0)
2240 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2241 else
2242 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2243 config->size);
2245 if (config->fixed_p)
2246 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2247 get_fixed_memory_packet_size (config));
2248 else
2250 if (remote != nullptr)
2251 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2252 remote->get_memory_packet_size (config));
2253 else
2254 gdb_puts ("The actual limit will be further reduced "
2255 "dependent on the target.\n");
2259 /* Configure the memory-write-packet size of the currently selected target. If
2260 no target is available, the default configuration for future remote targets
2261 is configured. */
2263 static void
2264 set_memory_write_packet_size (const char *args, int from_tty)
2266 remote_target *remote = get_current_remote_target ();
2267 if (remote != nullptr)
2269 set_memory_packet_size
2270 (args, &remote->m_features.m_memory_write_packet_config, true);
2272 else
2274 memory_packet_config* config = &memory_write_packet_config;
2275 set_memory_packet_size (args, config, false);
2279 /* Display the memory-write-packet size of the currently selected target. If
2280 no target is available, the default configuration for future remote targets
2281 is shown. */
2283 static void
2284 show_memory_write_packet_size (const char *args, int from_tty)
2286 remote_target *remote = get_current_remote_target ();
2287 if (remote != nullptr)
2288 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2289 remote);
2290 else
2291 show_memory_packet_size (&memory_write_packet_config, nullptr);
2294 /* Show the number of hardware watchpoints that can be used. */
2296 static void
2297 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2298 struct cmd_list_element *c,
2299 const char *value)
2301 gdb_printf (file, _("The maximum number of target hardware "
2302 "watchpoints is %s.\n"), value);
2305 /* Show the length limit (in bytes) for hardware watchpoints. */
2307 static void
2308 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2309 struct cmd_list_element *c,
2310 const char *value)
2312 gdb_printf (file, _("The maximum length (in bytes) of a target "
2313 "hardware watchpoint is %s.\n"), value);
2316 /* Show the number of hardware breakpoints that can be used. */
2318 static void
2319 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2320 struct cmd_list_element *c,
2321 const char *value)
2323 gdb_printf (file, _("The maximum number of target hardware "
2324 "breakpoints is %s.\n"), value);
2327 /* Controls the maximum number of characters to display in the debug output
2328 for each remote packet. The remaining characters are omitted. */
2330 static int remote_packet_max_chars = 512;
2332 /* Show the maximum number of characters to display for each remote packet
2333 when remote debugging is enabled. */
2335 static void
2336 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2337 struct cmd_list_element *c,
2338 const char *value)
2340 gdb_printf (file, _("Number of remote packet characters to "
2341 "display is %s.\n"), value);
2344 long
2345 remote_target::get_memory_write_packet_size ()
2347 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2350 /* Configure the memory-read-packet size of the currently selected target. If
2351 no target is available, the default configuration for future remote targets
2352 is adapted. */
2354 static void
2355 set_memory_read_packet_size (const char *args, int from_tty)
2357 remote_target *remote = get_current_remote_target ();
2358 if (remote != nullptr)
2359 set_memory_packet_size
2360 (args, &remote->m_features.m_memory_read_packet_config, true);
2361 else
2363 memory_packet_config* config = &memory_read_packet_config;
2364 set_memory_packet_size (args, config, false);
2369 /* Display the memory-read-packet size of the currently selected target. If
2370 no target is available, the default configuration for future remote targets
2371 is shown. */
2373 static void
2374 show_memory_read_packet_size (const char *args, int from_tty)
2376 remote_target *remote = get_current_remote_target ();
2377 if (remote != nullptr)
2378 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2379 remote);
2380 else
2381 show_memory_packet_size (&memory_read_packet_config, nullptr);
2384 long
2385 remote_target::get_memory_read_packet_size ()
2387 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2389 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2390 extra buffer size argument before the memory read size can be
2391 increased beyond this. */
2392 if (size > get_remote_packet_size ())
2393 size = get_remote_packet_size ();
2394 return size;
2397 static enum packet_support packet_config_support (const packet_config *config);
2400 static void
2401 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2402 cmd_list_element *c)
2404 remote_target *remote = get_current_remote_target ();
2405 gdb_assert (c->var.has_value ());
2407 auto *default_config = static_cast<packet_config *> (c->context ());
2408 const int packet_idx = std::distance (remote_protocol_packets,
2409 default_config);
2411 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2413 const char *name = packets_descriptions[packet_idx].name;
2414 const auto_boolean value = c->var->get<auto_boolean> ();
2415 const char *support = get_packet_support_name (value);
2416 const char *target_type = get_target_type_name (remote != nullptr);
2418 if (remote != nullptr)
2419 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2420 else
2421 remote_protocol_packets[packet_idx].detect = value;
2423 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2424 target_type, support);
2425 return;
2428 internal_error (_("Could not find config for %s"), c->name);
2431 static void
2432 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2433 remote_target *remote)
2435 const char *support = "internal-error";
2436 const char *target_type = get_target_type_name (remote != nullptr);
2438 packet_config *config;
2439 if (remote != nullptr)
2440 config = &remote->m_features.m_protocol_packets[which_packet];
2441 else
2442 config = &remote_protocol_packets[which_packet];
2444 switch (packet_config_support (config))
2446 case PACKET_ENABLE:
2447 support = "enabled";
2448 break;
2449 case PACKET_DISABLE:
2450 support = "disabled";
2451 break;
2452 case PACKET_SUPPORT_UNKNOWN:
2453 support = "unknown";
2454 break;
2456 switch (config->detect)
2458 case AUTO_BOOLEAN_AUTO:
2459 gdb_printf (file,
2460 _("Support for the '%s' packet %s is \"auto\", "
2461 "currently %s.\n"),
2462 packets_descriptions[which_packet].name, target_type,
2463 support);
2464 break;
2465 case AUTO_BOOLEAN_TRUE:
2466 case AUTO_BOOLEAN_FALSE:
2467 gdb_printf (file,
2468 _("Support for the '%s' packet %s is \"%s\".\n"),
2469 packets_descriptions[which_packet].name, target_type,
2470 get_packet_support_name (config->detect));
2471 break;
2475 static void
2476 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2477 const char *title, int legacy)
2479 packets_descriptions[which_packet].name = name;
2480 packets_descriptions[which_packet].title = title;
2482 packet_config *config = &remote_protocol_packets[which_packet];
2484 gdb::unique_xmalloc_ptr<char> set_doc
2485 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2486 name, title);
2487 gdb::unique_xmalloc_ptr<char> show_doc
2488 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2489 name, title);
2490 /* set/show TITLE-packet {auto,on,off} */
2491 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2492 set_show_commands cmds
2493 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2494 &config->detect, set_doc.get (),
2495 show_doc.get (), NULL, /* help_doc */
2496 set_remote_protocol_packet_cmd,
2497 show_remote_protocol_packet_cmd,
2498 &remote_set_cmdlist, &remote_show_cmdlist);
2499 cmds.show->set_context (config);
2500 cmds.set->set_context (config);
2502 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2503 if (legacy)
2505 /* It's not clear who should take ownership of the LEGACY_NAME string
2506 created below, so, for now, place the string into a static vector
2507 which ensures the strings is released when GDB exits. */
2508 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2509 gdb::unique_xmalloc_ptr<char> legacy_name
2510 = xstrprintf ("%s-packet", name);
2511 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2512 &remote_set_cmdlist);
2513 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2514 &remote_show_cmdlist);
2515 legacy_names.emplace_back (std::move (legacy_name));
2519 /* Check GDBserver's reply packet. Return packet_result structure
2520 which contains the packet_status enum and an error message for the
2521 PACKET_ERROR case.
2523 An error packet can always take the form Exx (where xx is a hex
2524 code). */
2525 static packet_result
2526 packet_check_result (const char *buf)
2528 if (buf[0] != '\0')
2530 /* The stub recognized the packet request. Check that the
2531 operation succeeded. */
2532 if (buf[0] == 'E'
2533 && isxdigit (buf[1]) && isxdigit (buf[2])
2534 && buf[3] == '\0')
2535 /* "Enn" - definitely an error. */
2536 return packet_result::make_numeric_error (buf + 1);
2538 /* Always treat "E." as an error. This will be used for
2539 more verbose error messages, such as E.memtypes. */
2540 if (buf[0] == 'E' && buf[1] == '.')
2542 if (buf[2] != '\0')
2543 return packet_result::make_textual_error (buf + 2);
2544 else
2545 return packet_result::make_textual_error ("no error provided");
2548 /* The packet may or may not be OK. Just assume it is. */
2549 return packet_result::make_ok ();
2551 else
2553 /* The stub does not support the packet. */
2554 return packet_result::make_unknown ();
2558 static packet_result
2559 packet_check_result (const gdb::char_vector &buf)
2561 return packet_check_result (buf.data ());
2564 packet_result
2565 remote_features::packet_ok (const char *buf, const int which_packet)
2567 packet_config *config = &m_protocol_packets[which_packet];
2568 packet_description *descr = &packets_descriptions[which_packet];
2570 if (config->detect != AUTO_BOOLEAN_TRUE
2571 && config->support == PACKET_DISABLE)
2572 internal_error (_("packet_ok: attempt to use a disabled packet"));
2574 packet_result result = packet_check_result (buf);
2575 switch (result.status ())
2577 case PACKET_OK:
2578 case PACKET_ERROR:
2579 /* The stub recognized the packet request. */
2580 if (config->support == PACKET_SUPPORT_UNKNOWN)
2582 remote_debug_printf ("Packet %s (%s) is supported",
2583 descr->name, descr->title);
2584 config->support = PACKET_ENABLE;
2586 break;
2587 case PACKET_UNKNOWN:
2588 /* The stub does not support the packet. */
2589 if (config->detect == AUTO_BOOLEAN_AUTO
2590 && config->support == PACKET_ENABLE)
2592 /* If the stub previously indicated that the packet was
2593 supported then there is a protocol error. */
2594 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2595 descr->name, descr->title);
2597 else if (config->detect == AUTO_BOOLEAN_TRUE)
2599 /* The user set it wrong. */
2600 error (_("Enabled packet %s (%s) not recognized by stub"),
2601 descr->name, descr->title);
2604 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2605 descr->title);
2606 config->support = PACKET_DISABLE;
2607 break;
2610 return result;
2613 packet_result
2614 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2616 return packet_ok (buf.data (), which_packet);
2619 /* Returns whether a given packet or feature is supported. This takes
2620 into account the state of the corresponding "set remote foo-packet"
2621 command, which may be used to bypass auto-detection. */
2623 static enum packet_support
2624 packet_config_support (const packet_config *config)
2626 switch (config->detect)
2628 case AUTO_BOOLEAN_TRUE:
2629 return PACKET_ENABLE;
2630 case AUTO_BOOLEAN_FALSE:
2631 return PACKET_DISABLE;
2632 case AUTO_BOOLEAN_AUTO:
2633 return config->support;
2634 default:
2635 gdb_assert_not_reached ("bad switch");
2639 packet_support
2640 remote_features::packet_support (int packet) const
2642 const packet_config *config = &m_protocol_packets[packet];
2643 return packet_config_support (config);
2646 static void
2647 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2648 struct cmd_list_element *c,
2649 const char *value)
2651 remote_target *remote = get_current_remote_target ();
2652 gdb_assert (c->var.has_value ());
2654 auto *default_config = static_cast<packet_config *> (c->context ());
2655 const int packet_idx = std::distance (remote_protocol_packets,
2656 default_config);
2658 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2660 show_packet_config_cmd (file, packet_idx, remote);
2661 return;
2663 internal_error (_("Could not find config for %s"), c->name);
2666 /* Should we try one of the 'Z' requests? */
2668 enum Z_packet_type
2670 Z_PACKET_SOFTWARE_BP,
2671 Z_PACKET_HARDWARE_BP,
2672 Z_PACKET_WRITE_WP,
2673 Z_PACKET_READ_WP,
2674 Z_PACKET_ACCESS_WP,
2675 NR_Z_PACKET_TYPES
2678 /* For compatibility with older distributions. Provide a ``set remote
2679 Z-packet ...'' command that updates all the Z packet types. */
2681 static enum auto_boolean remote_Z_packet_detect;
2683 static void
2684 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2685 struct cmd_list_element *c)
2687 remote_target *remote = get_current_remote_target ();
2688 int i;
2690 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2692 if (remote != nullptr)
2693 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2694 = remote_Z_packet_detect;
2695 else
2696 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2699 const char *support = get_packet_support_name (remote_Z_packet_detect);
2700 const char *target_type = get_target_type_name (remote != nullptr);
2701 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2702 support);
2706 static void
2707 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2708 struct cmd_list_element *c,
2709 const char *value)
2711 remote_target *remote = get_current_remote_target ();
2712 int i;
2714 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2715 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2718 /* Insert fork catchpoint target routine. If fork events are enabled
2719 then return success, nothing more to do. */
2722 remote_target::insert_fork_catchpoint (int pid)
2724 return !m_features.remote_fork_event_p ();
2727 /* Remove fork catchpoint target routine. Nothing to do, just
2728 return success. */
2731 remote_target::remove_fork_catchpoint (int pid)
2733 return 0;
2736 /* Insert vfork catchpoint target routine. If vfork events are enabled
2737 then return success, nothing more to do. */
2740 remote_target::insert_vfork_catchpoint (int pid)
2742 return !m_features.remote_vfork_event_p ();
2745 /* Remove vfork catchpoint target routine. Nothing to do, just
2746 return success. */
2749 remote_target::remove_vfork_catchpoint (int pid)
2751 return 0;
2754 /* Insert exec catchpoint target routine. If exec events are
2755 enabled, just return success. */
2758 remote_target::insert_exec_catchpoint (int pid)
2760 return !m_features.remote_exec_event_p ();
2763 /* Remove exec catchpoint target routine. Nothing to do, just
2764 return success. */
2767 remote_target::remove_exec_catchpoint (int pid)
2769 return 0;
2774 /* Take advantage of the fact that the TID field is not used, to tag
2775 special ptids with it set to != 0. */
2776 static const ptid_t magic_null_ptid (42000, -1, 1);
2777 static const ptid_t not_sent_ptid (42000, -2, 1);
2778 static const ptid_t any_thread_ptid (42000, 0, 1);
2780 /* Find out if the stub attached to PID (and hence GDB should offer to
2781 detach instead of killing it when bailing out). */
2784 remote_target::remote_query_attached (int pid)
2786 struct remote_state *rs = get_remote_state ();
2787 size_t size = get_remote_packet_size ();
2789 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2790 return 0;
2792 if (m_features.remote_multi_process_p ())
2793 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2794 else
2795 xsnprintf (rs->buf.data (), size, "qAttached");
2797 putpkt (rs->buf);
2798 getpkt (&rs->buf);
2800 packet_result result = m_features.packet_ok (rs->buf, PACKET_qAttached);
2801 switch (result.status ())
2803 case PACKET_OK:
2804 if (strcmp (rs->buf.data (), "1") == 0)
2805 return 1;
2806 break;
2807 case PACKET_ERROR:
2808 warning (_("Remote failure reply: %s"), result.err_msg ());
2809 break;
2810 case PACKET_UNKNOWN:
2811 break;
2814 return 0;
2817 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2818 has been invented by GDB, instead of reported by the target. Since
2819 we can be connected to a remote system before before knowing about
2820 any inferior, mark the target with execution when we find the first
2821 inferior. If ATTACHED is 1, then we had just attached to this
2822 inferior. If it is 0, then we just created this inferior. If it
2823 is -1, then try querying the remote stub to find out if it had
2824 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2825 attempt to open this inferior's executable as the main executable
2826 if no main executable is open already. */
2828 inferior *
2829 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2830 int try_open_exec)
2832 struct inferior *inf;
2834 /* Check whether this process we're learning about is to be
2835 considered attached, or if is to be considered to have been
2836 spawned by the stub. */
2837 if (attached == -1)
2838 attached = remote_query_attached (pid);
2840 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2842 /* If the target shares code across all inferiors, then every
2843 attach adds a new inferior. */
2844 inf = add_inferior (pid);
2846 /* ... and every inferior is bound to the same program space.
2847 However, each inferior may still have its own address
2848 space. */
2849 inf->aspace = maybe_new_address_space ();
2850 inf->pspace = current_program_space;
2852 else
2854 /* In the traditional debugging scenario, there's a 1-1 match
2855 between program/address spaces. We simply bind the inferior
2856 to the program space's address space. */
2857 inf = current_inferior ();
2859 /* However, if the current inferior is already bound to a
2860 process, find some other empty inferior. */
2861 if (inf->pid != 0)
2863 inf = nullptr;
2864 for (inferior *it : all_inferiors ())
2865 if (it->pid == 0)
2867 inf = it;
2868 break;
2871 if (inf == nullptr)
2873 /* Since all inferiors were already bound to a process, add
2874 a new inferior. */
2875 inf = add_inferior_with_spaces ();
2877 switch_to_inferior_no_thread (inf);
2878 inf->push_target (this);
2879 inferior_appeared (inf, pid);
2882 inf->attach_flag = attached;
2883 inf->fake_pid_p = fake_pid_p;
2885 /* If no main executable is currently open then attempt to
2886 open the file that was executed to create this inferior. */
2887 if (try_open_exec && current_program_space->exec_filename () == nullptr)
2888 exec_file_locate_attach (pid, 0, 1);
2890 /* Check for exec file mismatch, and let the user solve it. */
2891 validate_exec_file (1);
2893 return inf;
2896 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2897 static remote_thread_info *get_remote_thread_info (remote_target *target,
2898 ptid_t ptid);
2900 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2901 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2902 remote_state::starting_up flag) is true then the new thread is added
2903 silently, otherwise the new thread will be announced to the user. */
2905 thread_info *
2906 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2907 bool silent_p)
2909 struct remote_state *rs = get_remote_state ();
2910 struct thread_info *thread;
2912 /* GDB historically didn't pull threads in the initial connection
2913 setup. If the remote target doesn't even have a concept of
2914 threads (e.g., a bare-metal target), even if internally we
2915 consider that a single-threaded target, mentioning a new thread
2916 might be confusing to the user. Be silent then, preserving the
2917 age old behavior. */
2918 if (rs->starting_up || silent_p)
2919 thread = add_thread_silent (this, ptid);
2920 else
2921 thread = add_thread (this, ptid);
2923 if (executing)
2924 get_remote_thread_info (thread)->set_resumed ();
2925 set_executing (this, ptid, executing);
2926 set_running (this, ptid, running);
2928 return thread;
2931 /* Come here when we learn about a thread id from the remote target.
2932 It may be the first time we hear about such thread, so take the
2933 opportunity to add it to GDB's thread list. In case this is the
2934 first time we're noticing its corresponding inferior, add it to
2935 GDB's inferior list as well. EXECUTING indicates whether the
2936 thread is (internally) executing or stopped. */
2938 void
2939 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2941 /* In non-stop mode, we assume new found threads are (externally)
2942 running until proven otherwise with a stop reply. In all-stop,
2943 we can only get here if all threads are stopped. */
2944 bool running = target_is_non_stop_p ();
2946 /* If this is a new thread, add it to GDB's thread list.
2947 If we leave it up to WFI to do this, bad things will happen. */
2949 thread_info *tp = this->find_thread (currthread);
2950 if (tp != NULL && tp->state == THREAD_EXITED)
2952 /* We're seeing an event on a thread id we knew had exited.
2953 This has to be a new thread reusing the old id. Add it. */
2954 remote_add_thread (currthread, running, executing, false);
2955 return;
2958 if (!in_thread_list (this, currthread))
2960 struct inferior *inf = NULL;
2961 int pid = currthread.pid ();
2963 if (inferior_ptid.is_pid ()
2964 && pid == inferior_ptid.pid ())
2966 /* inferior_ptid has no thread member yet. This can happen
2967 with the vAttach -> remote_wait,"TAAthread:" path if the
2968 stub doesn't support qC. This is the first stop reported
2969 after an attach, so this is the main thread. Update the
2970 ptid in the thread list. */
2971 if (in_thread_list (this, ptid_t (pid)))
2972 thread_change_ptid (this, inferior_ptid, currthread);
2973 else
2975 thread_info *thr
2976 = remote_add_thread (currthread, running, executing, false);
2977 switch_to_thread (thr);
2979 return;
2982 if (magic_null_ptid == inferior_ptid)
2984 /* inferior_ptid is not set yet. This can happen with the
2985 vRun -> remote_wait,"TAAthread:" path if the stub
2986 doesn't support qC. This is the first stop reported
2987 after an attach, so this is the main thread. Update the
2988 ptid in the thread list. */
2989 thread_change_ptid (this, inferior_ptid, currthread);
2990 return;
2993 /* When connecting to a target remote, or to a target
2994 extended-remote which already was debugging an inferior, we
2995 may not know about it yet. Add it before adding its child
2996 thread, so notifications are emitted in a sensible order. */
2997 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2999 bool fake_pid_p = !m_features.remote_multi_process_p ();
3001 inf = remote_add_inferior (fake_pid_p,
3002 currthread.pid (), -1, 1);
3005 /* This is really a new thread. Add it. */
3006 thread_info *new_thr
3007 = remote_add_thread (currthread, running, executing, false);
3009 /* If we found a new inferior, let the common code do whatever
3010 it needs to with it (e.g., read shared libraries, insert
3011 breakpoints), unless we're just setting up an all-stop
3012 connection. */
3013 if (inf != NULL)
3015 struct remote_state *rs = get_remote_state ();
3017 if (!rs->starting_up)
3018 notice_new_inferior (new_thr, executing, 0);
3023 /* Return THREAD's private thread data, creating it if necessary. */
3025 static remote_thread_info *
3026 get_remote_thread_info (thread_info *thread)
3028 gdb_assert (thread != NULL);
3030 if (thread->priv == NULL)
3031 thread->priv.reset (new remote_thread_info);
3033 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
3036 /* Return PTID's private thread data, creating it if necessary. */
3038 static remote_thread_info *
3039 get_remote_thread_info (remote_target *target, ptid_t ptid)
3041 thread_info *thr = target->find_thread (ptid);
3042 return get_remote_thread_info (thr);
3045 /* Call this function as a result of
3046 1) A halt indication (T packet) containing a thread id
3047 2) A direct query of currthread
3048 3) Successful execution of set thread */
3050 static void
3051 record_currthread (struct remote_state *rs, ptid_t currthread)
3053 rs->general_thread = currthread;
3056 /* If 'QPassSignals' is supported, tell the remote stub what signals
3057 it can simply pass through to the inferior without reporting. */
3059 void
3060 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
3062 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
3064 char *pass_packet, *p;
3065 int count = 0;
3066 struct remote_state *rs = get_remote_state ();
3068 gdb_assert (pass_signals.size () < 256);
3069 for (size_t i = 0; i < pass_signals.size (); i++)
3071 if (pass_signals[i])
3072 count++;
3074 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
3075 strcpy (pass_packet, "QPassSignals:");
3076 p = pass_packet + strlen (pass_packet);
3077 for (size_t i = 0; i < pass_signals.size (); i++)
3079 if (pass_signals[i])
3081 if (i >= 16)
3082 *p++ = tohex (i >> 4);
3083 *p++ = tohex (i & 15);
3084 if (count)
3085 *p++ = ';';
3086 else
3087 break;
3088 count--;
3091 *p = 0;
3092 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
3094 putpkt (pass_packet);
3095 getpkt (&rs->buf);
3096 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
3097 xfree (rs->last_pass_packet);
3098 rs->last_pass_packet = pass_packet;
3100 else
3101 xfree (pass_packet);
3105 /* If 'QCatchSyscalls' is supported, tell the remote stub
3106 to report syscalls to GDB. */
3109 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3110 gdb::array_view<const int> syscall_counts)
3112 const char *catch_packet;
3113 int n_sysno = 0;
3115 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3117 /* Not supported. */
3118 return 1;
3121 if (needed && any_count == 0)
3123 /* Count how many syscalls are to be caught. */
3124 for (size_t i = 0; i < syscall_counts.size (); i++)
3126 if (syscall_counts[i] != 0)
3127 n_sysno++;
3131 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3132 pid, needed, any_count, n_sysno);
3134 std::string built_packet;
3135 if (needed)
3137 /* Prepare a packet with the sysno list, assuming max 8+1
3138 characters for a sysno. If the resulting packet size is too
3139 big, fallback on the non-selective packet. */
3140 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3141 built_packet.reserve (maxpktsz);
3142 built_packet = "QCatchSyscalls:1";
3143 if (any_count == 0)
3145 /* Add in each syscall to be caught. */
3146 for (size_t i = 0; i < syscall_counts.size (); i++)
3148 if (syscall_counts[i] != 0)
3149 string_appendf (built_packet, ";%zx", i);
3152 if (built_packet.size () > get_remote_packet_size ())
3154 /* catch_packet too big. Fallback to less efficient
3155 non selective mode, with GDB doing the filtering. */
3156 catch_packet = "QCatchSyscalls:1";
3158 else
3159 catch_packet = built_packet.c_str ();
3161 else
3162 catch_packet = "QCatchSyscalls:0";
3164 struct remote_state *rs = get_remote_state ();
3166 putpkt (catch_packet);
3167 getpkt (&rs->buf);
3168 packet_result result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3169 if (result.status () == PACKET_OK)
3170 return 0;
3171 else
3172 return -1;
3175 /* If 'QProgramSignals' is supported, tell the remote stub what
3176 signals it should pass through to the inferior when detaching. */
3178 void
3179 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3181 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3183 char *packet, *p;
3184 int count = 0;
3185 struct remote_state *rs = get_remote_state ();
3187 gdb_assert (signals.size () < 256);
3188 for (size_t i = 0; i < signals.size (); i++)
3190 if (signals[i])
3191 count++;
3193 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3194 strcpy (packet, "QProgramSignals:");
3195 p = packet + strlen (packet);
3196 for (size_t i = 0; i < signals.size (); i++)
3198 if (signal_pass_state (i))
3200 if (i >= 16)
3201 *p++ = tohex (i >> 4);
3202 *p++ = tohex (i & 15);
3203 if (count)
3204 *p++ = ';';
3205 else
3206 break;
3207 count--;
3210 *p = 0;
3211 if (!rs->last_program_signals_packet
3212 || strcmp (rs->last_program_signals_packet, packet) != 0)
3214 putpkt (packet);
3215 getpkt (&rs->buf);
3216 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3217 xfree (rs->last_program_signals_packet);
3218 rs->last_program_signals_packet = packet;
3220 else
3221 xfree (packet);
3225 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3226 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3227 thread. If GEN is set, set the general thread, if not, then set
3228 the step/continue thread. */
3229 void
3230 remote_target::set_thread (ptid_t ptid, int gen)
3232 struct remote_state *rs = get_remote_state ();
3233 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3234 char *buf = rs->buf.data ();
3235 char *endbuf = buf + get_remote_packet_size ();
3237 if (state == ptid)
3238 return;
3240 *buf++ = 'H';
3241 *buf++ = gen ? 'g' : 'c';
3242 if (ptid == magic_null_ptid)
3243 xsnprintf (buf, endbuf - buf, "0");
3244 else if (ptid == any_thread_ptid)
3245 xsnprintf (buf, endbuf - buf, "0");
3246 else if (ptid == minus_one_ptid)
3247 xsnprintf (buf, endbuf - buf, "-1");
3248 else
3249 write_ptid (buf, endbuf, ptid);
3250 putpkt (rs->buf);
3251 getpkt (&rs->buf);
3252 if (gen)
3253 rs->general_thread = ptid;
3254 else
3255 rs->continue_thread = ptid;
3258 void
3259 remote_target::set_general_thread (ptid_t ptid)
3261 set_thread (ptid, 1);
3264 void
3265 remote_target::set_continue_thread (ptid_t ptid)
3267 set_thread (ptid, 0);
3270 /* Change the remote current process. Which thread within the process
3271 ends up selected isn't important, as long as it is the same process
3272 as what INFERIOR_PTID points to.
3274 This comes from that fact that there is no explicit notion of
3275 "selected process" in the protocol. The selected process for
3276 general operations is the process the selected general thread
3277 belongs to. */
3279 void
3280 remote_target::set_general_process ()
3282 /* If the remote can't handle multiple processes, don't bother. */
3283 if (!m_features.remote_multi_process_p ())
3284 return;
3286 remote_state *rs = get_remote_state ();
3288 /* We only need to change the remote current thread if it's pointing
3289 at some other process. */
3290 if (rs->general_thread.pid () != inferior_ptid.pid ())
3291 set_general_thread (inferior_ptid);
3295 /* Return nonzero if this is the main thread that we made up ourselves
3296 to model non-threaded targets as single-threaded. */
3298 static int
3299 remote_thread_always_alive (ptid_t ptid)
3301 if (ptid == magic_null_ptid)
3302 /* The main thread is always alive. */
3303 return 1;
3305 if (ptid.pid () != 0 && ptid.lwp () == 0)
3306 /* The main thread is always alive. This can happen after a
3307 vAttach, if the remote side doesn't support
3308 multi-threading. */
3309 return 1;
3311 return 0;
3314 /* Return nonzero if the thread PTID is still alive on the remote
3315 system. */
3317 bool
3318 remote_target::thread_alive (ptid_t ptid)
3320 struct remote_state *rs = get_remote_state ();
3321 char *p, *endp;
3323 /* Check if this is a thread that we made up ourselves to model
3324 non-threaded targets as single-threaded. */
3325 if (remote_thread_always_alive (ptid))
3326 return 1;
3328 p = rs->buf.data ();
3329 endp = p + get_remote_packet_size ();
3331 *p++ = 'T';
3332 write_ptid (p, endp, ptid);
3334 putpkt (rs->buf);
3335 getpkt (&rs->buf);
3336 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3339 /* Return a pointer to a thread name if we know it and NULL otherwise.
3340 The thread_info object owns the memory for the name. */
3342 const char *
3343 remote_target::thread_name (struct thread_info *info)
3345 if (info->priv != NULL)
3347 const std::string &name = get_remote_thread_info (info)->name;
3348 return !name.empty () ? name.c_str () : NULL;
3351 return NULL;
3354 /* About these extended threadlist and threadinfo packets. They are
3355 variable length packets but, the fields within them are often fixed
3356 length. They are redundant enough to send over UDP as is the
3357 remote protocol in general. There is a matching unit test module
3358 in libstub. */
3360 /* WARNING: This threadref data structure comes from the remote O.S.,
3361 libstub protocol encoding, and remote.c. It is not particularly
3362 changeable. */
3364 /* Right now, the internal structure is int. We want it to be bigger.
3365 Plan to fix this. */
3367 typedef int gdb_threadref; /* Internal GDB thread reference. */
3369 /* gdb_ext_thread_info is an internal GDB data structure which is
3370 equivalent to the reply of the remote threadinfo packet. */
3372 struct gdb_ext_thread_info
3374 threadref threadid; /* External form of thread reference. */
3375 int active; /* Has state interesting to GDB?
3376 regs, stack. */
3377 char display[256]; /* Brief state display, name,
3378 blocked/suspended. */
3379 char shortname[32]; /* To be used to name threads. */
3380 char more_display[256]; /* Long info, statistics, queue depth,
3381 whatever. */
3384 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3386 static const char *unpack_nibble (const char *buf, int *val);
3388 static const char *unpack_byte (const char *buf, int *value);
3390 static char *pack_int (char *buf, int value);
3392 static const char *unpack_int (const char *buf, int *value);
3394 static const char *unpack_string (const char *src, char *dest, int length);
3396 static char *pack_threadid (char *pkt, threadref *id);
3398 static const char *unpack_threadid (const char *inbuf, threadref *id);
3400 void int_to_threadref (threadref *id, int value);
3402 static int threadref_to_int (threadref *ref);
3404 static void copy_threadref (threadref *dest, threadref *src);
3406 static int threadmatch (threadref *dest, threadref *src);
3408 static char *pack_threadinfo_request (char *pkt, int mode,
3409 threadref *id);
3411 static char *pack_threadlist_request (char *pkt, int startflag,
3412 int threadcount,
3413 threadref *nextthread);
3415 static int remote_newthread_step (threadref *ref, void *context);
3418 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3419 buffer we're allowed to write to. Returns
3420 BUF+CHARACTERS_WRITTEN. */
3422 char *
3423 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3425 int pid, tid;
3427 if (m_features.remote_multi_process_p ())
3429 pid = ptid.pid ();
3430 if (pid < 0)
3431 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3432 else
3433 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3435 tid = ptid.lwp ();
3436 if (tid < 0)
3437 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3438 else
3439 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3441 return buf;
3444 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3445 last parsed char. Returns null_ptid if no thread id is found, and
3446 throws an error if the thread id has an invalid format. */
3448 static ptid_t
3449 read_ptid (const char *buf, const char **obuf)
3451 const char *p = buf;
3452 const char *pp;
3453 ULONGEST pid = 0, tid = 0;
3455 if (*p == 'p')
3457 /* Multi-process ptid. */
3458 pp = unpack_varlen_hex (p + 1, &pid);
3459 if (*pp != '.')
3460 error (_("invalid remote ptid: %s"), p);
3462 p = pp;
3463 pp = unpack_varlen_hex (p + 1, &tid);
3464 if (obuf)
3465 *obuf = pp;
3466 return ptid_t (pid, tid);
3469 /* No multi-process. Just a tid. */
3470 pp = unpack_varlen_hex (p, &tid);
3472 /* Return null_ptid when no thread id is found. */
3473 if (p == pp)
3475 if (obuf)
3476 *obuf = pp;
3477 return null_ptid;
3480 /* Since the stub is not sending a process id, default to what's
3481 current_inferior, unless it doesn't have a PID yet. If so,
3482 then since there's no way to know the pid of the reported
3483 threads, use the magic number. */
3484 inferior *inf = current_inferior ();
3485 if (inf->pid == 0)
3486 pid = magic_null_ptid.pid ();
3487 else
3488 pid = inf->pid;
3490 if (obuf)
3491 *obuf = pp;
3492 return ptid_t (pid, tid);
3495 static int
3496 stubhex (int ch)
3498 if (ch >= 'a' && ch <= 'f')
3499 return ch - 'a' + 10;
3500 if (ch >= '0' && ch <= '9')
3501 return ch - '0';
3502 if (ch >= 'A' && ch <= 'F')
3503 return ch - 'A' + 10;
3504 return -1;
3507 static int
3508 stub_unpack_int (const char *buff, int fieldlength)
3510 int nibble;
3511 int retval = 0;
3513 while (fieldlength)
3515 nibble = stubhex (*buff++);
3516 retval |= nibble;
3517 fieldlength--;
3518 if (fieldlength)
3519 retval = retval << 4;
3521 return retval;
3524 static const char *
3525 unpack_nibble (const char *buf, int *val)
3527 *val = fromhex (*buf++);
3528 return buf;
3531 static const char *
3532 unpack_byte (const char *buf, int *value)
3534 *value = stub_unpack_int (buf, 2);
3535 return buf + 2;
3538 static char *
3539 pack_int (char *buf, int value)
3541 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3542 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3543 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3544 buf = pack_hex_byte (buf, (value & 0xff));
3545 return buf;
3548 static const char *
3549 unpack_int (const char *buf, int *value)
3551 *value = stub_unpack_int (buf, 8);
3552 return buf + 8;
3555 #if 0 /* Currently unused, uncomment when needed. */
3556 static char *pack_string (char *pkt, char *string);
3558 static char *
3559 pack_string (char *pkt, char *string)
3561 char ch;
3562 int len;
3564 len = strlen (string);
3565 if (len > 200)
3566 len = 200; /* Bigger than most GDB packets, junk??? */
3567 pkt = pack_hex_byte (pkt, len);
3568 while (len-- > 0)
3570 ch = *string++;
3571 if ((ch == '\0') || (ch == '#'))
3572 ch = '*'; /* Protect encapsulation. */
3573 *pkt++ = ch;
3575 return pkt;
3577 #endif /* 0 (unused) */
3579 static const char *
3580 unpack_string (const char *src, char *dest, int length)
3582 while (length--)
3583 *dest++ = *src++;
3584 *dest = '\0';
3585 return src;
3588 static char *
3589 pack_threadid (char *pkt, threadref *id)
3591 char *limit;
3592 unsigned char *altid;
3594 altid = (unsigned char *) id;
3595 limit = pkt + BUF_THREAD_ID_SIZE;
3596 while (pkt < limit)
3597 pkt = pack_hex_byte (pkt, *altid++);
3598 return pkt;
3602 static const char *
3603 unpack_threadid (const char *inbuf, threadref *id)
3605 char *altref;
3606 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3607 int x, y;
3609 altref = (char *) id;
3611 while (inbuf < limit)
3613 x = stubhex (*inbuf++);
3614 y = stubhex (*inbuf++);
3615 *altref++ = (x << 4) | y;
3617 return inbuf;
3620 /* Externally, threadrefs are 64 bits but internally, they are still
3621 ints. This is due to a mismatch of specifications. We would like
3622 to use 64bit thread references internally. This is an adapter
3623 function. */
3625 void
3626 int_to_threadref (threadref *id, int value)
3628 unsigned char *scan;
3630 scan = (unsigned char *) id;
3632 int i = 4;
3633 while (i--)
3634 *scan++ = 0;
3636 *scan++ = (value >> 24) & 0xff;
3637 *scan++ = (value >> 16) & 0xff;
3638 *scan++ = (value >> 8) & 0xff;
3639 *scan++ = (value & 0xff);
3642 static int
3643 threadref_to_int (threadref *ref)
3645 int i, value = 0;
3646 unsigned char *scan;
3648 scan = *ref;
3649 scan += 4;
3650 i = 4;
3651 while (i-- > 0)
3652 value = (value << 8) | ((*scan++) & 0xff);
3653 return value;
3656 static void
3657 copy_threadref (threadref *dest, threadref *src)
3659 int i;
3660 unsigned char *csrc, *cdest;
3662 csrc = (unsigned char *) src;
3663 cdest = (unsigned char *) dest;
3664 i = 8;
3665 while (i--)
3666 *cdest++ = *csrc++;
3669 static int
3670 threadmatch (threadref *dest, threadref *src)
3672 /* Things are broken right now, so just assume we got a match. */
3673 #if 0
3674 unsigned char *srcp, *destp;
3675 int i, result;
3676 srcp = (char *) src;
3677 destp = (char *) dest;
3679 result = 1;
3680 while (i-- > 0)
3681 result &= (*srcp++ == *destp++) ? 1 : 0;
3682 return result;
3683 #endif
3684 return 1;
3688 threadid:1, # always request threadid
3689 context_exists:2,
3690 display:4,
3691 unique_name:8,
3692 more_display:16
3695 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3697 static char *
3698 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3700 *pkt++ = 'q'; /* Info Query */
3701 *pkt++ = 'P'; /* process or thread info */
3702 pkt = pack_int (pkt, mode); /* mode */
3703 pkt = pack_threadid (pkt, id); /* threadid */
3704 *pkt = '\0'; /* terminate */
3705 return pkt;
3708 /* These values tag the fields in a thread info response packet. */
3709 /* Tagging the fields allows us to request specific fields and to
3710 add more fields as time goes by. */
3712 #define TAG_THREADID 1 /* Echo the thread identifier. */
3713 #define TAG_EXISTS 2 /* Is this process defined enough to
3714 fetch registers and its stack? */
3715 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3716 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3717 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3718 the process. */
3721 remote_target::remote_unpack_thread_info_response (const char *pkt,
3722 threadref *expectedref,
3723 gdb_ext_thread_info *info)
3725 struct remote_state *rs = get_remote_state ();
3726 int mask, length;
3727 int tag;
3728 threadref ref;
3729 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3730 int retval = 1;
3732 /* info->threadid = 0; FIXME: implement zero_threadref. */
3733 info->active = 0;
3734 info->display[0] = '\0';
3735 info->shortname[0] = '\0';
3736 info->more_display[0] = '\0';
3738 /* Assume the characters indicating the packet type have been
3739 stripped. */
3740 pkt = unpack_int (pkt, &mask); /* arg mask */
3741 pkt = unpack_threadid (pkt, &ref);
3743 if (mask == 0)
3744 warning (_("Incomplete response to threadinfo request."));
3745 if (!threadmatch (&ref, expectedref))
3746 { /* This is an answer to a different request. */
3747 warning (_("ERROR RMT Thread info mismatch."));
3748 return 0;
3750 copy_threadref (&info->threadid, &ref);
3752 /* Loop on tagged fields , try to bail if something goes wrong. */
3754 /* Packets are terminated with nulls. */
3755 while ((pkt < limit) && mask && *pkt)
3757 pkt = unpack_int (pkt, &tag); /* tag */
3758 pkt = unpack_byte (pkt, &length); /* length */
3759 if (!(tag & mask)) /* Tags out of synch with mask. */
3761 warning (_("ERROR RMT: threadinfo tag mismatch."));
3762 retval = 0;
3763 break;
3765 if (tag == TAG_THREADID)
3767 if (length != 16)
3769 warning (_("ERROR RMT: length of threadid is not 16."));
3770 retval = 0;
3771 break;
3773 pkt = unpack_threadid (pkt, &ref);
3774 mask = mask & ~TAG_THREADID;
3775 continue;
3777 if (tag == TAG_EXISTS)
3779 info->active = stub_unpack_int (pkt, length);
3780 pkt += length;
3781 mask = mask & ~(TAG_EXISTS);
3782 if (length > 8)
3784 warning (_("ERROR RMT: 'exists' length too long."));
3785 retval = 0;
3786 break;
3788 continue;
3790 if (tag == TAG_THREADNAME)
3792 pkt = unpack_string (pkt, &info->shortname[0], length);
3793 mask = mask & ~TAG_THREADNAME;
3794 continue;
3796 if (tag == TAG_DISPLAY)
3798 pkt = unpack_string (pkt, &info->display[0], length);
3799 mask = mask & ~TAG_DISPLAY;
3800 continue;
3802 if (tag == TAG_MOREDISPLAY)
3804 pkt = unpack_string (pkt, &info->more_display[0], length);
3805 mask = mask & ~TAG_MOREDISPLAY;
3806 continue;
3808 warning (_("ERROR RMT: unknown thread info tag."));
3809 break; /* Not a tag we know about. */
3811 return retval;
3815 remote_target::remote_get_threadinfo (threadref *threadid,
3816 int fieldset,
3817 gdb_ext_thread_info *info)
3819 struct remote_state *rs = get_remote_state ();
3820 int result;
3822 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3823 putpkt (rs->buf);
3824 getpkt (&rs->buf);
3826 if (rs->buf[0] == '\0')
3827 return 0;
3829 result = remote_unpack_thread_info_response (&rs->buf[2],
3830 threadid, info);
3831 return result;
3834 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3836 static char *
3837 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3838 threadref *nextthread)
3840 *pkt++ = 'q'; /* info query packet */
3841 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3842 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3843 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3844 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3845 *pkt = '\0';
3846 return pkt;
3849 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3852 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3853 threadref *original_echo,
3854 threadref *resultlist,
3855 int *doneflag)
3857 struct remote_state *rs = get_remote_state ();
3858 int count, resultcount, done;
3860 resultcount = 0;
3861 /* Assume the 'q' and 'M chars have been stripped. */
3862 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3863 /* done parse past here */
3864 pkt = unpack_byte (pkt, &count); /* count field */
3865 pkt = unpack_nibble (pkt, &done);
3866 /* The first threadid is the argument threadid. */
3867 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3868 while ((count-- > 0) && (pkt < limit))
3870 pkt = unpack_threadid (pkt, resultlist++);
3871 if (resultcount++ >= result_limit)
3872 break;
3874 if (doneflag)
3875 *doneflag = done;
3876 return resultcount;
3879 /* Fetch the next batch of threads from the remote. Returns -1 if the
3880 qL packet is not supported, 0 on error and 1 on success. */
3883 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3884 int result_limit, int *done, int *result_count,
3885 threadref *threadlist)
3887 struct remote_state *rs = get_remote_state ();
3888 int result = 1;
3890 /* Truncate result limit to be smaller than the packet size. */
3891 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3892 >= get_remote_packet_size ())
3893 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3895 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3896 nextthread);
3897 putpkt (rs->buf);
3898 getpkt (&rs->buf);
3899 if (rs->buf[0] == '\0')
3901 /* Packet not supported. */
3902 return -1;
3905 *result_count =
3906 parse_threadlist_response (&rs->buf[2], result_limit,
3907 &rs->echo_nextthread, threadlist, done);
3909 if (!threadmatch (&rs->echo_nextthread, nextthread))
3911 /* FIXME: This is a good reason to drop the packet. */
3912 /* Possibly, there is a duplicate response. */
3913 /* Possibilities :
3914 retransmit immediatly - race conditions
3915 retransmit after timeout - yes
3916 exit
3917 wait for packet, then exit
3919 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3920 return 0; /* I choose simply exiting. */
3922 if (*result_count <= 0)
3924 if (*done != 1)
3926 warning (_("RMT ERROR : failed to get remote thread list."));
3927 result = 0;
3929 return result; /* break; */
3931 if (*result_count > result_limit)
3933 *result_count = 0;
3934 warning (_("RMT ERROR: threadlist response longer than requested."));
3935 return 0;
3937 return result;
3940 /* Fetch the list of remote threads, with the qL packet, and call
3941 STEPFUNCTION for each thread found. Stops iterating and returns 1
3942 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3943 STEPFUNCTION returns false. If the packet is not supported,
3944 returns -1. */
3947 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3948 void *context, int looplimit)
3950 struct remote_state *rs = get_remote_state ();
3951 int done, i, result_count;
3952 int startflag = 1;
3953 int result = 1;
3954 int loopcount = 0;
3956 done = 0;
3957 while (!done)
3959 if (loopcount++ > looplimit)
3961 result = 0;
3962 warning (_("Remote fetch threadlist -infinite loop-."));
3963 break;
3965 result = remote_get_threadlist (startflag, &rs->nextthread,
3966 MAXTHREADLISTRESULTS,
3967 &done, &result_count,
3968 rs->resultthreadlist);
3969 if (result <= 0)
3970 break;
3971 /* Clear for later iterations. */
3972 startflag = 0;
3973 /* Setup to resume next batch of thread references, set nextthread. */
3974 if (result_count >= 1)
3975 copy_threadref (&rs->nextthread,
3976 &rs->resultthreadlist[result_count - 1]);
3977 i = 0;
3978 while (result_count--)
3980 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3982 result = 0;
3983 break;
3987 return result;
3990 /* A thread found on the remote target. */
3992 struct thread_item
3994 explicit thread_item (ptid_t ptid_)
3995 : ptid (ptid_)
3998 thread_item (thread_item &&other) = default;
3999 thread_item &operator= (thread_item &&other) = default;
4001 DISABLE_COPY_AND_ASSIGN (thread_item);
4003 /* The thread's PTID. */
4004 ptid_t ptid;
4006 /* The thread's extra info. */
4007 std::string extra;
4009 /* The thread's name. */
4010 std::string name;
4012 /* The core the thread was running on. -1 if not known. */
4013 int core = -1;
4015 /* The thread handle associated with the thread. */
4016 gdb::byte_vector thread_handle;
4019 /* Context passed around to the various methods listing remote
4020 threads. As new threads are found, they're added to the ITEMS
4021 vector. */
4023 struct threads_listing_context
4025 /* Return true if this object contains an entry for a thread with ptid
4026 PTID. */
4028 bool contains_thread (ptid_t ptid) const
4030 auto match_ptid = [&] (const thread_item &item)
4032 return item.ptid == ptid;
4035 auto it = std::find_if (this->items.begin (),
4036 this->items.end (),
4037 match_ptid);
4039 return it != this->items.end ();
4042 /* Remove the thread with ptid PTID. */
4044 void remove_thread (ptid_t ptid)
4046 auto match_ptid = [&] (const thread_item &item)
4048 return item.ptid == ptid;
4051 auto it = std::remove_if (this->items.begin (),
4052 this->items.end (),
4053 match_ptid);
4055 if (it != this->items.end ())
4056 this->items.erase (it);
4059 /* The threads found on the remote target. */
4060 std::vector<thread_item> items;
4063 static int
4064 remote_newthread_step (threadref *ref, void *data)
4066 struct threads_listing_context *context
4067 = (struct threads_listing_context *) data;
4068 int pid = inferior_ptid.pid ();
4069 int lwp = threadref_to_int (ref);
4070 ptid_t ptid (pid, lwp);
4072 context->items.emplace_back (ptid);
4074 return 1; /* continue iterator */
4077 #define CRAZY_MAX_THREADS 1000
4079 ptid_t
4080 remote_target::remote_current_thread (ptid_t oldpid)
4082 struct remote_state *rs = get_remote_state ();
4084 putpkt ("qC");
4085 getpkt (&rs->buf);
4086 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
4088 const char *obuf;
4089 ptid_t result;
4091 result = read_ptid (&rs->buf[2], &obuf);
4092 if (*obuf != '\0')
4093 remote_debug_printf ("warning: garbage in qC reply");
4095 return result;
4097 else
4098 return oldpid;
4101 /* List remote threads using the deprecated qL packet. */
4104 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4106 if (remote_threadlist_iterator (remote_newthread_step, context,
4107 CRAZY_MAX_THREADS) >= 0)
4108 return 1;
4110 return 0;
4113 #if defined(HAVE_LIBEXPAT)
4115 static void
4116 start_thread (struct gdb_xml_parser *parser,
4117 const struct gdb_xml_element *element,
4118 void *user_data,
4119 std::vector<gdb_xml_value> &attributes)
4121 struct threads_listing_context *data
4122 = (struct threads_listing_context *) user_data;
4123 struct gdb_xml_value *attr;
4125 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4126 ptid_t ptid = read_ptid (id, NULL);
4128 thread_item &item = data->items.emplace_back (ptid);
4130 attr = xml_find_attribute (attributes, "core");
4131 if (attr != NULL)
4132 item.core = *(ULONGEST *) attr->value.get ();
4134 attr = xml_find_attribute (attributes, "name");
4135 if (attr != NULL)
4136 item.name = (const char *) attr->value.get ();
4138 attr = xml_find_attribute (attributes, "handle");
4139 if (attr != NULL)
4140 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4143 static void
4144 end_thread (struct gdb_xml_parser *parser,
4145 const struct gdb_xml_element *element,
4146 void *user_data, const char *body_text)
4148 struct threads_listing_context *data
4149 = (struct threads_listing_context *) user_data;
4151 if (body_text != NULL && *body_text != '\0')
4152 data->items.back ().extra = body_text;
4155 const struct gdb_xml_attribute thread_attributes[] = {
4156 { "id", GDB_XML_AF_NONE, NULL, NULL },
4157 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4158 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4159 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4160 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4163 const struct gdb_xml_element thread_children[] = {
4164 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4167 const struct gdb_xml_element threads_children[] = {
4168 { "thread", thread_attributes, thread_children,
4169 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4170 start_thread, end_thread },
4171 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4174 const struct gdb_xml_element threads_elements[] = {
4175 { "threads", NULL, threads_children,
4176 GDB_XML_EF_NONE, NULL, NULL },
4177 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4180 #endif
4182 /* List remote threads using qXfer:threads:read. */
4185 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4187 #if defined(HAVE_LIBEXPAT)
4188 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4190 std::optional<gdb::char_vector> xml
4191 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4193 if (xml && (*xml)[0] != '\0')
4195 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4196 threads_elements, xml->data (), context);
4199 return 1;
4201 #endif
4203 return 0;
4206 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4209 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4211 struct remote_state *rs = get_remote_state ();
4213 if (rs->use_threadinfo_query)
4215 const char *bufp;
4217 putpkt ("qfThreadInfo");
4218 getpkt (&rs->buf);
4219 bufp = rs->buf.data ();
4220 if (bufp[0] != '\0') /* q packet recognized */
4222 while (*bufp++ == 'm') /* reply contains one or more TID */
4226 ptid_t ptid = read_ptid (bufp, &bufp);
4227 context->items.emplace_back (ptid);
4229 while (*bufp++ == ','); /* comma-separated list */
4230 putpkt ("qsThreadInfo");
4231 getpkt (&rs->buf);
4232 bufp = rs->buf.data ();
4234 return 1;
4236 else
4238 /* Packet not recognized. */
4239 rs->use_threadinfo_query = 0;
4243 return 0;
4246 /* Return true if INF only has one non-exited thread. */
4248 static bool
4249 has_single_non_exited_thread (inferior *inf)
4251 int count = 0;
4252 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4253 if (++count > 1)
4254 break;
4255 return count == 1;
4258 /* Implement the to_update_thread_list function for the remote
4259 targets. */
4261 void
4262 remote_target::update_thread_list ()
4264 struct threads_listing_context context;
4265 int got_list = 0;
4267 /* We have a few different mechanisms to fetch the thread list. Try
4268 them all, starting with the most preferred one first, falling
4269 back to older methods. */
4270 if (remote_get_threads_with_qxfer (&context)
4271 || remote_get_threads_with_qthreadinfo (&context)
4272 || remote_get_threads_with_ql (&context))
4274 got_list = 1;
4276 if (context.items.empty ()
4277 && remote_thread_always_alive (inferior_ptid))
4279 /* Some targets don't really support threads, but still
4280 reply an (empty) thread list in response to the thread
4281 listing packets, instead of replying "packet not
4282 supported". Exit early so we don't delete the main
4283 thread. */
4284 return;
4287 /* CONTEXT now holds the current thread list on the remote
4288 target end. Delete GDB-side threads no longer found on the
4289 target. */
4290 for (thread_info *tp : all_threads_safe ())
4292 if (tp->inf->process_target () != this)
4293 continue;
4295 if (!context.contains_thread (tp->ptid))
4297 /* Do not remove the thread if it is the last thread in
4298 the inferior. This situation happens when we have a
4299 pending exit process status to process. Otherwise we
4300 may end up with a seemingly live inferior (i.e. pid
4301 != 0) that has no threads. */
4302 if (has_single_non_exited_thread (tp->inf))
4303 continue;
4305 /* Do not remove the thread if we've requested to be
4306 notified of its exit. For example, the thread may be
4307 displaced stepping, infrun will need to handle the
4308 exit event, and displaced stepping info is recorded
4309 in the thread object. If we deleted the thread now,
4310 we'd lose that info. */
4311 if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
4312 continue;
4314 /* Not found. */
4315 delete_thread (tp);
4319 /* Remove any unreported fork/vfork/clone child threads from
4320 CONTEXT so that we don't interfere with follow
4321 fork/vfork/clone, which is where creation of such threads is
4322 handled. */
4323 remove_new_children (&context);
4325 /* And now add threads we don't know about yet to our list. */
4326 for (thread_item &item : context.items)
4328 if (item.ptid != null_ptid)
4330 /* In non-stop mode, we assume new found threads are
4331 executing until proven otherwise with a stop reply.
4332 In all-stop, we can only get here if all threads are
4333 stopped. */
4334 bool executing = target_is_non_stop_p ();
4336 remote_notice_new_inferior (item.ptid, executing);
4338 thread_info *tp = this->find_thread (item.ptid);
4339 remote_thread_info *info = get_remote_thread_info (tp);
4340 info->core = item.core;
4341 info->extra = std::move (item.extra);
4342 info->name = std::move (item.name);
4343 info->thread_handle = std::move (item.thread_handle);
4348 if (!got_list)
4350 /* If no thread listing method is supported, then query whether
4351 each known thread is alive, one by one, with the T packet.
4352 If the target doesn't support threads at all, then this is a
4353 no-op. See remote_thread_alive. */
4354 prune_threads ();
4359 * Collect a descriptive string about the given thread.
4360 * The target may say anything it wants to about the thread
4361 * (typically info about its blocked / runnable state, name, etc.).
4362 * This string will appear in the info threads display.
4364 * Optional: targets are not required to implement this function.
4367 const char *
4368 remote_target::extra_thread_info (thread_info *tp)
4370 struct remote_state *rs = get_remote_state ();
4371 int set;
4372 threadref id;
4373 struct gdb_ext_thread_info threadinfo;
4375 if (rs->remote_desc == 0) /* paranoia */
4376 internal_error (_("remote_threads_extra_info"));
4378 if (tp->ptid == magic_null_ptid
4379 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4380 /* This is the main thread which was added by GDB. The remote
4381 server doesn't know about it. */
4382 return NULL;
4384 std::string &extra = get_remote_thread_info (tp)->extra;
4386 /* If already have cached info, use it. */
4387 if (!extra.empty ())
4388 return extra.c_str ();
4390 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4392 /* If we're using qXfer:threads:read, then the extra info is
4393 included in the XML. So if we didn't have anything cached,
4394 it's because there's really no extra info. */
4395 return NULL;
4398 if (rs->use_threadextra_query)
4400 char *b = rs->buf.data ();
4401 char *endb = b + get_remote_packet_size ();
4403 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4404 b += strlen (b);
4405 write_ptid (b, endb, tp->ptid);
4407 putpkt (rs->buf);
4408 getpkt (&rs->buf);
4409 if (rs->buf[0] != 0)
4411 extra.resize (strlen (rs->buf.data ()) / 2);
4412 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4413 return extra.c_str ();
4417 /* If the above query fails, fall back to the old method. */
4418 rs->use_threadextra_query = 0;
4419 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4420 | TAG_MOREDISPLAY | TAG_DISPLAY;
4421 int_to_threadref (&id, tp->ptid.lwp ());
4422 if (remote_get_threadinfo (&id, set, &threadinfo))
4423 if (threadinfo.active)
4425 if (*threadinfo.shortname)
4426 string_appendf (extra, " Name: %s", threadinfo.shortname);
4427 if (*threadinfo.display)
4429 if (!extra.empty ())
4430 extra += ',';
4431 string_appendf (extra, " State: %s", threadinfo.display);
4433 if (*threadinfo.more_display)
4435 if (!extra.empty ())
4436 extra += ',';
4437 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4439 return extra.c_str ();
4441 return NULL;
4445 bool
4446 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4447 struct static_tracepoint_marker *marker)
4449 struct remote_state *rs = get_remote_state ();
4450 char *p = rs->buf.data ();
4452 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4453 p += strlen (p);
4454 p += hexnumstr (p, addr);
4455 putpkt (rs->buf);
4456 getpkt (&rs->buf);
4457 p = rs->buf.data ();
4459 if (*p == 'E')
4460 error (_("Remote failure reply: %s"), p);
4462 if (*p++ == 'm')
4464 parse_static_tracepoint_marker_definition (p, NULL, marker);
4465 return true;
4468 return false;
4471 std::vector<static_tracepoint_marker>
4472 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4474 struct remote_state *rs = get_remote_state ();
4475 std::vector<static_tracepoint_marker> markers;
4476 const char *p;
4477 static_tracepoint_marker marker;
4479 /* Ask for a first packet of static tracepoint marker
4480 definition. */
4481 putpkt ("qTfSTM");
4482 getpkt (&rs->buf);
4483 p = rs->buf.data ();
4484 if (*p == 'E')
4485 error (_("Remote failure reply: %s"), p);
4487 while (*p++ == 'm')
4491 parse_static_tracepoint_marker_definition (p, &p, &marker);
4493 if (strid == NULL || marker.str_id == strid)
4494 markers.push_back (std::move (marker));
4496 while (*p++ == ','); /* comma-separated list */
4497 /* Ask for another packet of static tracepoint definition. */
4498 putpkt ("qTsSTM");
4499 getpkt (&rs->buf);
4500 p = rs->buf.data ();
4503 return markers;
4507 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4509 ptid_t
4510 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4512 return ptid_t (inferior_ptid.pid (), lwp);
4516 /* Restart the remote side; this is an extended protocol operation. */
4518 void
4519 remote_target::extended_remote_restart ()
4521 struct remote_state *rs = get_remote_state ();
4523 /* Send the restart command; for reasons I don't understand the
4524 remote side really expects a number after the "R". */
4525 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4526 putpkt (rs->buf);
4528 remote_fileio_reset ();
4531 /* Clean up connection to a remote debugger. */
4533 void
4534 remote_target::close ()
4536 /* Make sure we leave stdin registered in the event loop. */
4537 terminal_ours ();
4539 trace_reset_local_state ();
4541 delete this;
4544 remote_target::~remote_target ()
4546 struct remote_state *rs = get_remote_state ();
4548 /* Check for NULL because we may get here with a partially
4549 constructed target/connection. */
4550 if (rs->remote_desc == nullptr)
4551 return;
4553 serial_close (rs->remote_desc);
4555 /* We are destroying the remote target, so we should discard
4556 everything of this target. */
4557 discard_pending_stop_replies_in_queue ();
4559 rs->delete_async_event_handler ();
4561 delete rs->notif_state;
4564 /* Query the remote side for the text, data and bss offsets. */
4566 void
4567 remote_target::get_offsets ()
4569 struct remote_state *rs = get_remote_state ();
4570 char *buf;
4571 char *ptr;
4572 int lose, num_segments = 0, do_sections, do_segments;
4573 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4575 if (current_program_space->symfile_object_file == NULL)
4576 return;
4578 putpkt ("qOffsets");
4579 getpkt (&rs->buf);
4580 buf = rs->buf.data ();
4582 if (buf[0] == '\000')
4583 return; /* Return silently. Stub doesn't support
4584 this command. */
4585 if (buf[0] == 'E')
4587 warning (_("Remote failure reply: %s"), buf);
4588 return;
4591 /* Pick up each field in turn. This used to be done with scanf, but
4592 scanf will make trouble if CORE_ADDR size doesn't match
4593 conversion directives correctly. The following code will work
4594 with any size of CORE_ADDR. */
4595 text_addr = data_addr = bss_addr = 0;
4596 ptr = buf;
4597 lose = 0;
4599 if (startswith (ptr, "Text="))
4601 ptr += 5;
4602 /* Don't use strtol, could lose on big values. */
4603 while (*ptr && *ptr != ';')
4604 text_addr = (text_addr << 4) + fromhex (*ptr++);
4606 if (startswith (ptr, ";Data="))
4608 ptr += 6;
4609 while (*ptr && *ptr != ';')
4610 data_addr = (data_addr << 4) + fromhex (*ptr++);
4612 else
4613 lose = 1;
4615 if (!lose && startswith (ptr, ";Bss="))
4617 ptr += 5;
4618 while (*ptr && *ptr != ';')
4619 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4621 if (bss_addr != data_addr)
4622 warning (_("Target reported unsupported offsets: %s"), buf);
4624 else
4625 lose = 1;
4627 else if (startswith (ptr, "TextSeg="))
4629 ptr += 8;
4630 /* Don't use strtol, could lose on big values. */
4631 while (*ptr && *ptr != ';')
4632 text_addr = (text_addr << 4) + fromhex (*ptr++);
4633 num_segments = 1;
4635 if (startswith (ptr, ";DataSeg="))
4637 ptr += 9;
4638 while (*ptr && *ptr != ';')
4639 data_addr = (data_addr << 4) + fromhex (*ptr++);
4640 num_segments++;
4643 else
4644 lose = 1;
4646 if (lose)
4647 error (_("Malformed response to offset query, %s"), buf);
4648 else if (*ptr != '\0')
4649 warning (_("Target reported unsupported offsets: %s"), buf);
4651 objfile *objf = current_program_space->symfile_object_file;
4652 section_offsets offs = objf->section_offsets;
4654 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4655 do_segments = (data != NULL);
4656 do_sections = num_segments == 0;
4658 if (num_segments > 0)
4660 segments[0] = text_addr;
4661 segments[1] = data_addr;
4663 /* If we have two segments, we can still try to relocate everything
4664 by assuming that the .text and .data offsets apply to the whole
4665 text and data segments. Convert the offsets given in the packet
4666 to base addresses for symfile_map_offsets_to_segments. */
4667 else if (data != nullptr && data->segments.size () == 2)
4669 segments[0] = data->segments[0].base + text_addr;
4670 segments[1] = data->segments[1].base + data_addr;
4671 num_segments = 2;
4673 /* If the object file has only one segment, assume that it is text
4674 rather than data; main programs with no writable data are rare,
4675 but programs with no code are useless. Of course the code might
4676 have ended up in the data segment... to detect that we would need
4677 the permissions here. */
4678 else if (data && data->segments.size () == 1)
4680 segments[0] = data->segments[0].base + text_addr;
4681 num_segments = 1;
4683 /* There's no way to relocate by segment. */
4684 else
4685 do_segments = 0;
4687 if (do_segments)
4689 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4690 data.get (), offs,
4691 num_segments, segments);
4693 if (ret == 0 && !do_sections)
4694 error (_("Can not handle qOffsets TextSeg "
4695 "response with this symbol file"));
4697 if (ret > 0)
4698 do_sections = 0;
4701 if (do_sections)
4703 offs[SECT_OFF_TEXT (objf)] = text_addr;
4705 /* This is a temporary kludge to force data and bss to use the
4706 same offsets because that's what nlmconv does now. The real
4707 solution requires changes to the stub and remote.c that I
4708 don't have time to do right now. */
4710 offs[SECT_OFF_DATA (objf)] = data_addr;
4711 offs[SECT_OFF_BSS (objf)] = data_addr;
4714 objfile_relocate (objf, offs);
4717 /* Send interrupt_sequence to remote target. */
4719 void
4720 remote_target::send_interrupt_sequence ()
4722 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4723 remote_serial_write ("\x03", 1);
4724 else if (interrupt_sequence_mode == interrupt_sequence_break)
4725 remote_serial_send_break ();
4726 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4728 remote_serial_send_break ();
4729 remote_serial_write ("g", 1);
4731 else
4732 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4733 interrupt_sequence_mode);
4736 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4737 and extract the PTID. Returns NULL_PTID if not found. */
4739 static ptid_t
4740 stop_reply_extract_thread (const char *stop_reply)
4742 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4744 const char *p;
4746 /* Txx r:val ; r:val (...) */
4747 p = &stop_reply[3];
4749 /* Look for "register" named "thread". */
4750 while (*p != '\0')
4752 const char *p1;
4754 p1 = strchr (p, ':');
4755 if (p1 == NULL)
4756 return null_ptid;
4758 if (strncmp (p, "thread", p1 - p) == 0)
4759 return read_ptid (++p1, &p);
4761 p1 = strchr (p, ';');
4762 if (p1 == NULL)
4763 return null_ptid;
4764 p1++;
4766 p = p1;
4770 return null_ptid;
4773 /* Determine the remote side's current thread. If we have a stop
4774 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4775 "thread" register we can extract the current thread from. If not,
4776 ask the remote which is the current thread with qC. The former
4777 method avoids a roundtrip. */
4779 ptid_t
4780 remote_target::get_current_thread (const char *wait_status)
4782 ptid_t ptid = null_ptid;
4784 /* Note we don't use remote_parse_stop_reply as that makes use of
4785 the target architecture, which we haven't yet fully determined at
4786 this point. */
4787 if (wait_status != NULL)
4788 ptid = stop_reply_extract_thread (wait_status);
4789 if (ptid == null_ptid)
4790 ptid = remote_current_thread (inferior_ptid);
4792 return ptid;
4795 /* Query the remote target for which is the current thread/process,
4796 add it to our tables, and update INFERIOR_PTID. The caller is
4797 responsible for setting the state such that the remote end is ready
4798 to return the current thread.
4800 This function is called after handling the '?' or 'vRun' packets,
4801 whose response is a stop reply from which we can also try
4802 extracting the thread. If the target doesn't support the explicit
4803 qC query, we infer the current thread from that stop reply, passed
4804 in in WAIT_STATUS, which may be NULL.
4806 The function returns pointer to the main thread of the inferior. */
4808 thread_info *
4809 remote_target::add_current_inferior_and_thread (const char *wait_status)
4811 bool fake_pid_p = false;
4813 switch_to_no_thread ();
4815 /* Now, if we have thread information, update the current thread's
4816 ptid. */
4817 ptid_t curr_ptid = get_current_thread (wait_status);
4819 if (curr_ptid != null_ptid)
4821 if (!m_features.remote_multi_process_p ())
4822 fake_pid_p = true;
4824 else
4826 /* Without this, some commands which require an active target
4827 (such as kill) won't work. This variable serves (at least)
4828 double duty as both the pid of the target process (if it has
4829 such), and as a flag indicating that a target is active. */
4830 curr_ptid = magic_null_ptid;
4831 fake_pid_p = true;
4834 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4836 /* Add the main thread and switch to it. Don't try reading
4837 registers yet, since we haven't fetched the target description
4838 yet. */
4839 thread_info *tp = add_thread_silent (this, curr_ptid);
4840 switch_to_thread_no_regs (tp);
4842 return tp;
4845 /* Print info about a thread that was found already stopped on
4846 connection. */
4848 void
4849 remote_target::print_one_stopped_thread (thread_info *thread)
4851 target_waitstatus ws;
4853 /* If there is a pending waitstatus, use it. If there isn't it's because
4854 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4855 and process_initial_stop_replies decided it wasn't interesting to save
4856 and report to the core. */
4857 if (thread->has_pending_waitstatus ())
4859 ws = thread->pending_waitstatus ();
4860 thread->clear_pending_waitstatus ();
4862 else
4864 ws.set_stopped (GDB_SIGNAL_0);
4867 switch_to_thread (thread);
4868 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4869 set_current_sal_from_frame (get_current_frame ());
4871 /* For "info program". */
4872 set_last_target_status (this, thread->ptid, ws);
4874 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4876 enum gdb_signal sig = ws.sig ();
4878 if (signal_print_state (sig))
4879 notify_signal_received (sig);
4882 notify_normal_stop (nullptr, 1);
4885 /* Process all initial stop replies the remote side sent in response
4886 to the ? packet. These indicate threads that were already stopped
4887 on initial connection. We mark these threads as stopped and print
4888 their current frame before giving the user the prompt. */
4890 void
4891 remote_target::process_initial_stop_replies (int from_tty)
4893 int pending_stop_replies = stop_reply_queue_length ();
4894 struct thread_info *selected = NULL;
4895 struct thread_info *lowest_stopped = NULL;
4896 struct thread_info *first = NULL;
4898 /* This is only used when the target is non-stop. */
4899 gdb_assert (target_is_non_stop_p ());
4901 /* Consume the initial pending events. */
4902 while (pending_stop_replies-- > 0)
4904 ptid_t waiton_ptid = minus_one_ptid;
4905 ptid_t event_ptid;
4906 struct target_waitstatus ws;
4907 int ignore_event = 0;
4909 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4910 if (remote_debug)
4911 print_target_wait_results (waiton_ptid, event_ptid, ws);
4913 switch (ws.kind ())
4915 case TARGET_WAITKIND_IGNORE:
4916 case TARGET_WAITKIND_NO_RESUMED:
4917 case TARGET_WAITKIND_SIGNALLED:
4918 case TARGET_WAITKIND_EXITED:
4919 /* We shouldn't see these, but if we do, just ignore. */
4920 remote_debug_printf ("event ignored");
4921 ignore_event = 1;
4922 break;
4924 default:
4925 break;
4928 if (ignore_event)
4929 continue;
4931 thread_info *evthread = this->find_thread (event_ptid);
4933 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4935 enum gdb_signal sig = ws.sig ();
4937 /* Stubs traditionally report SIGTRAP as initial signal,
4938 instead of signal 0. Suppress it. */
4939 if (sig == GDB_SIGNAL_TRAP)
4940 sig = GDB_SIGNAL_0;
4941 evthread->set_stop_signal (sig);
4942 ws.set_stopped (sig);
4945 if (ws.kind () != TARGET_WAITKIND_STOPPED
4946 || ws.sig () != GDB_SIGNAL_0)
4947 evthread->set_pending_waitstatus (ws);
4949 set_executing (this, event_ptid, false);
4950 set_running (this, event_ptid, false);
4951 get_remote_thread_info (evthread)->set_not_resumed ();
4954 /* "Notice" the new inferiors before anything related to
4955 registers/memory. */
4956 for (inferior *inf : all_non_exited_inferiors (this))
4958 inf->needs_setup = true;
4960 if (non_stop)
4962 thread_info *thread = any_live_thread_of_inferior (inf);
4963 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4964 from_tty);
4968 /* If all-stop on top of non-stop, pause all threads. Note this
4969 records the threads' stop pc, so must be done after "noticing"
4970 the inferiors. */
4971 if (!non_stop)
4974 /* At this point, the remote target is not async. It needs to be for
4975 the poll in stop_all_threads to consider events from it, so enable
4976 it temporarily. */
4977 gdb_assert (!this->is_async_p ());
4978 SCOPE_EXIT { target_async (false); };
4979 target_async (true);
4980 stop_all_threads ("remote connect in all-stop");
4983 /* If all threads of an inferior were already stopped, we
4984 haven't setup the inferior yet. */
4985 for (inferior *inf : all_non_exited_inferiors (this))
4987 if (inf->needs_setup)
4989 thread_info *thread = any_live_thread_of_inferior (inf);
4990 switch_to_thread_no_regs (thread);
4991 setup_inferior (0);
4996 /* Now go over all threads that are stopped, and print their current
4997 frame. If all-stop, then if there's a signalled thread, pick
4998 that as current. */
4999 for (thread_info *thread : all_non_exited_threads (this))
5001 if (first == NULL)
5002 first = thread;
5004 if (!non_stop)
5005 thread->set_running (false);
5006 else if (thread->state != THREAD_STOPPED)
5007 continue;
5009 if (selected == nullptr && thread->has_pending_waitstatus ())
5010 selected = thread;
5012 if (lowest_stopped == NULL
5013 || thread->inf->num < lowest_stopped->inf->num
5014 || thread->per_inf_num < lowest_stopped->per_inf_num)
5015 lowest_stopped = thread;
5017 if (non_stop)
5018 print_one_stopped_thread (thread);
5021 /* In all-stop, we only print the status of one thread, and leave
5022 others with their status pending. */
5023 if (!non_stop)
5025 thread_info *thread = selected;
5026 if (thread == NULL)
5027 thread = lowest_stopped;
5028 if (thread == NULL)
5029 thread = first;
5031 print_one_stopped_thread (thread);
5035 /* Mark a remote_target as starting (by setting the starting_up flag within
5036 its remote_state) for the lifetime of this object. The reference count
5037 on the remote target is temporarily incremented, to prevent the target
5038 being deleted under our feet. */
5040 struct scoped_mark_target_starting
5042 /* Constructor, TARGET is the target to be marked as starting, its
5043 reference count will be incremented. */
5044 scoped_mark_target_starting (remote_target *target)
5045 : m_remote_target (remote_target_ref::new_reference (target)),
5046 m_restore_starting_up (set_starting_up_flag (target))
5047 { /* Nothing. */ }
5049 private:
5051 /* Helper function, set the starting_up flag on TARGET and return an
5052 object which, when it goes out of scope, will restore the previous
5053 value of the starting_up flag. */
5054 static scoped_restore_tmpl<bool>
5055 set_starting_up_flag (remote_target *target)
5057 remote_state *rs = target->get_remote_state ();
5058 gdb_assert (!rs->starting_up);
5059 return make_scoped_restore (&rs->starting_up, true);
5062 /* A gdb::ref_ptr pointer to a remote_target. */
5063 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
5065 /* A reference to the target on which we are operating. */
5066 remote_target_ref m_remote_target;
5068 /* An object which restores the previous value of the starting_up flag
5069 when it goes out of scope. */
5070 scoped_restore_tmpl<bool> m_restore_starting_up;
5073 /* Transfer ownership of the stop_reply owned by EVENT to a
5074 stop_reply_up object. */
5076 static stop_reply_up
5077 as_stop_reply_up (notif_event_up event)
5079 auto *stop_reply = static_cast<struct stop_reply *> (event.release ());
5080 return stop_reply_up (stop_reply);
5083 /* Helper for remote_target::start_remote, start the remote connection and
5084 sync state. Return true if everything goes OK, otherwise, return false.
5085 This function exists so that the scoped_restore created within it will
5086 expire before we return to remote_target::start_remote. */
5088 bool
5089 remote_target::start_remote_1 (int from_tty, int extended_p)
5091 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
5093 struct remote_state *rs = get_remote_state ();
5095 /* Signal other parts that we're going through the initial setup,
5096 and so things may not be stable yet. E.g., we don't try to
5097 install tracepoints until we've relocated symbols. Also, a
5098 Ctrl-C before we're connected and synced up can't interrupt the
5099 target. Instead, it offers to drop the (potentially wedged)
5100 connection. */
5101 scoped_mark_target_starting target_is_starting (this);
5103 QUIT;
5105 if (interrupt_on_connect)
5106 send_interrupt_sequence ();
5108 /* Ack any packet which the remote side has already sent. */
5109 remote_serial_write ("+", 1);
5111 /* The first packet we send to the target is the optional "supported
5112 packets" request. If the target can answer this, it will tell us
5113 which later probes to skip. */
5114 remote_query_supported ();
5116 /* Check vCont support and set the remote state's vCont_action_support
5117 attribute. */
5118 remote_vcont_probe ();
5120 /* If the stub wants to get a QAllow, compose one and send it. */
5121 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5122 set_permissions ();
5124 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5125 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5126 as a reply to known packet. For packet "vFile:setfs:" it is an
5127 invalid reply and GDB would return error in
5128 remote_hostio_set_filesystem, making remote files access impossible.
5129 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5130 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5132 const char v_mustreplyempty[] = "vMustReplyEmpty";
5134 putpkt (v_mustreplyempty);
5135 getpkt (&rs->buf);
5136 if (strcmp (rs->buf.data (), "OK") == 0)
5138 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5139 = PACKET_DISABLE;
5141 else if (strcmp (rs->buf.data (), "") != 0)
5142 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5143 rs->buf.data ());
5146 /* Next, we possibly activate noack mode.
5148 If the QStartNoAckMode packet configuration is set to AUTO,
5149 enable noack mode if the stub reported a wish for it with
5150 qSupported.
5152 If set to TRUE, then enable noack mode even if the stub didn't
5153 report it in qSupported. If the stub doesn't reply OK, the
5154 session ends with an error.
5156 If FALSE, then don't activate noack mode, regardless of what the
5157 stub claimed should be the default with qSupported. */
5159 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5161 putpkt ("QStartNoAckMode");
5162 getpkt (&rs->buf);
5163 if ((m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode)).status ()
5164 == PACKET_OK)
5165 rs->noack_mode = 1;
5168 if (extended_p)
5170 /* Tell the remote that we are using the extended protocol. */
5171 putpkt ("!");
5172 getpkt (&rs->buf);
5175 /* Let the target know which signals it is allowed to pass down to
5176 the program. */
5177 update_signals_program_target ();
5179 /* Next, if the target can specify a description, read it. We do
5180 this before anything involving memory or registers. */
5181 target_find_description ();
5183 /* Next, now that we know something about the target, update the
5184 address spaces in the program spaces. */
5185 update_address_spaces ();
5187 /* On OSs where the list of libraries is global to all
5188 processes, we fetch them early. */
5189 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5190 solib_add (NULL, from_tty, auto_solib_add);
5192 if (target_is_non_stop_p ())
5194 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5195 error (_("Non-stop mode requested, but remote "
5196 "does not support non-stop"));
5198 putpkt ("QNonStop:1");
5199 getpkt (&rs->buf);
5201 if (strcmp (rs->buf.data (), "OK") != 0)
5202 error (_("Remote refused setting non-stop mode with: %s"),
5203 rs->buf.data ());
5205 /* Find about threads and processes the stub is already
5206 controlling. We default to adding them in the running state.
5207 The '?' query below will then tell us about which threads are
5208 stopped. */
5209 this->update_thread_list ();
5211 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5213 /* Don't assume that the stub can operate in all-stop mode.
5214 Request it explicitly. */
5215 putpkt ("QNonStop:0");
5216 getpkt (&rs->buf);
5218 if (strcmp (rs->buf.data (), "OK") != 0)
5219 error (_("Remote refused setting all-stop mode with: %s"),
5220 rs->buf.data ());
5223 /* Upload TSVs regardless of whether the target is running or not. The
5224 remote stub, such as GDBserver, may have some predefined or builtin
5225 TSVs, even if the target is not running. */
5226 if (get_trace_status (current_trace_status ()) != -1)
5228 struct uploaded_tsv *uploaded_tsvs = NULL;
5230 upload_trace_state_variables (&uploaded_tsvs);
5231 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5234 /* Check whether the target is running now. */
5235 putpkt ("?");
5236 getpkt (&rs->buf);
5238 if (!target_is_non_stop_p ())
5240 char *wait_status = NULL;
5242 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5244 if (!extended_p)
5245 error (_("The target is not running (try extended-remote?)"));
5246 return false;
5248 else
5250 /* Save the reply for later. */
5251 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5252 strcpy (wait_status, rs->buf.data ());
5255 /* Fetch thread list. */
5256 target_update_thread_list ();
5258 /* Let the stub know that we want it to return the thread. */
5259 set_continue_thread (minus_one_ptid);
5261 if (thread_count (this) == 0)
5263 /* Target has no concept of threads at all. GDB treats
5264 non-threaded target as single-threaded; add a main
5265 thread. */
5266 thread_info *tp = add_current_inferior_and_thread (wait_status);
5267 get_remote_thread_info (tp)->set_resumed ();
5269 else
5271 /* We have thread information; select the thread the target
5272 says should be current. If we're reconnecting to a
5273 multi-threaded program, this will ideally be the thread
5274 that last reported an event before GDB disconnected. */
5275 ptid_t curr_thread = get_current_thread (wait_status);
5276 if (curr_thread == null_ptid)
5278 /* Odd... The target was able to list threads, but not
5279 tell us which thread was current (no "thread"
5280 register in T stop reply?). Just pick the first
5281 thread in the thread list then. */
5283 remote_debug_printf ("warning: couldn't determine remote "
5284 "current thread; picking first in list.");
5286 for (thread_info *tp : all_non_exited_threads (this,
5287 minus_one_ptid))
5289 switch_to_thread (tp);
5290 break;
5293 else
5294 switch_to_thread (this->find_thread (curr_thread));
5296 get_remote_thread_info (inferior_thread ())->set_resumed ();
5299 /* init_wait_for_inferior should be called before get_offsets in order
5300 to manage `inserted' flag in bp loc in a correct state.
5301 breakpoint_init_inferior, called from init_wait_for_inferior, set
5302 `inserted' flag to 0, while before breakpoint_re_set, called from
5303 start_remote, set `inserted' flag to 1. In the initialization of
5304 inferior, breakpoint_init_inferior should be called first, and then
5305 breakpoint_re_set can be called. If this order is broken, state of
5306 `inserted' flag is wrong, and cause some problems on breakpoint
5307 manipulation. */
5308 init_wait_for_inferior ();
5310 get_offsets (); /* Get text, data & bss offsets. */
5312 /* If we could not find a description using qXfer, and we know
5313 how to do it some other way, try again. This is not
5314 supported for non-stop; it could be, but it is tricky if
5315 there are no stopped threads when we connect. */
5316 if (remote_read_description_p (this)
5317 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5319 target_clear_description ();
5320 target_find_description ();
5323 /* Use the previously fetched status. */
5324 gdb_assert (wait_status != NULL);
5325 notif_event_up reply
5326 = remote_notif_parse (this, &notif_client_stop, wait_status);
5327 push_stop_reply (as_stop_reply_up (std::move (reply)));
5329 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5331 else
5333 /* Clear WFI global state. Do this before finding about new
5334 threads and inferiors, and setting the current inferior.
5335 Otherwise we would clear the proceed status of the current
5336 inferior when we want its stop_soon state to be preserved
5337 (see notice_new_inferior). */
5338 init_wait_for_inferior ();
5340 /* In non-stop, we will either get an "OK", meaning that there
5341 are no stopped threads at this time; or, a regular stop
5342 reply. In the latter case, there may be more than one thread
5343 stopped --- we pull them all out using the vStopped
5344 mechanism. */
5345 if (strcmp (rs->buf.data (), "OK") != 0)
5347 const notif_client *notif = &notif_client_stop;
5349 /* remote_notif_get_pending_replies acks this one, and gets
5350 the rest out. */
5351 rs->notif_state->pending_event[notif_client_stop.id]
5352 = remote_notif_parse (this, notif, rs->buf.data ());
5353 remote_notif_get_pending_events (notif);
5356 if (thread_count (this) == 0)
5358 if (!extended_p)
5359 error (_("The target is not running (try extended-remote?)"));
5360 return false;
5363 /* Report all signals during attach/startup. */
5364 pass_signals ({});
5366 /* If there are already stopped threads, mark them stopped and
5367 report their stops before giving the prompt to the user. */
5368 process_initial_stop_replies (from_tty);
5370 if (target_can_async_p ())
5371 target_async (true);
5374 /* Give the target a chance to look up symbols. */
5375 for (inferior *inf : all_inferiors (this))
5377 /* The inferiors that exist at this point were created from what
5378 was found already running on the remote side, so we know they
5379 have execution. */
5380 gdb_assert (this->has_execution (inf));
5382 /* No use without a symbol-file. */
5383 if (inf->pspace->symfile_object_file == nullptr)
5384 continue;
5386 /* Need to switch to a specific thread, because remote_check_symbols
5387 uses INFERIOR_PTID to set the general thread. */
5388 scoped_restore_current_thread restore_thread;
5389 thread_info *thread = any_thread_of_inferior (inf);
5390 switch_to_thread (thread);
5391 this->remote_check_symbols ();
5394 /* Possibly the target has been engaged in a trace run started
5395 previously; find out where things are at. */
5396 if (get_trace_status (current_trace_status ()) != -1)
5398 struct uploaded_tp *uploaded_tps = NULL;
5400 if (current_trace_status ()->running)
5401 gdb_printf (_("Trace is already running on the target.\n"));
5403 upload_tracepoints (&uploaded_tps);
5405 merge_uploaded_tracepoints (&uploaded_tps);
5408 /* Possibly the target has been engaged in a btrace record started
5409 previously; find out where things are at. */
5410 remote_btrace_maybe_reopen ();
5412 return true;
5415 /* Start the remote connection and sync state. */
5417 void
5418 remote_target::start_remote (int from_tty, int extended_p)
5420 if (start_remote_1 (from_tty, extended_p)
5421 && breakpoints_should_be_inserted_now ())
5422 insert_breakpoints ();
5425 const char *
5426 remote_target::connection_string ()
5428 remote_state *rs = get_remote_state ();
5430 if (rs->remote_desc->name != NULL)
5431 return rs->remote_desc->name;
5432 else
5433 return NULL;
5436 /* Open a connection to a remote debugger.
5437 NAME is the filename used for communication. */
5439 void
5440 remote_target::open (const char *name, int from_tty)
5442 open_1 (name, from_tty, 0);
5445 /* Open a connection to a remote debugger using the extended
5446 remote gdb protocol. NAME is the filename used for communication. */
5448 void
5449 extended_remote_target::open (const char *name, int from_tty)
5451 open_1 (name, from_tty, 1 /*extended_p */);
5454 void
5455 remote_features::reset_all_packet_configs_support ()
5457 int i;
5459 for (i = 0; i < PACKET_MAX; i++)
5460 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5463 /* Initialize all packet configs. */
5465 static void
5466 init_all_packet_configs (void)
5468 int i;
5470 for (i = 0; i < PACKET_MAX; i++)
5472 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5473 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5477 /* Symbol look-up. */
5479 void
5480 remote_target::remote_check_symbols ()
5482 char *tmp;
5483 int end;
5485 /* It doesn't make sense to send a qSymbol packet for an inferior that
5486 doesn't have execution, because the remote side doesn't know about
5487 inferiors without execution. */
5488 gdb_assert (target_has_execution ());
5490 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5491 return;
5493 /* Make sure the remote is pointing at the right process. Note
5494 there's no way to select "no process". */
5495 set_general_process ();
5497 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5498 because we need both at the same time. */
5499 gdb::char_vector msg (get_remote_packet_size ());
5500 gdb::char_vector reply (get_remote_packet_size ());
5502 /* Invite target to request symbol lookups. */
5504 putpkt ("qSymbol::");
5505 getpkt (&reply);
5506 m_features.packet_ok (reply, PACKET_qSymbol);
5508 while (startswith (reply.data (), "qSymbol:"))
5510 tmp = &reply[8];
5511 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5512 strlen (tmp) / 2);
5513 msg[end] = '\0';
5514 bound_minimal_symbol sym
5515 = lookup_minimal_symbol (current_program_space, msg.data ());
5516 if (sym.minsym == NULL)
5517 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5518 &reply[8]);
5519 else
5521 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5522 CORE_ADDR sym_addr = sym.value_address ();
5524 /* If this is a function address, return the start of code
5525 instead of any data function descriptor. */
5526 sym_addr = gdbarch_convert_from_func_ptr_addr
5527 (current_inferior ()->arch (), sym_addr,
5528 current_inferior ()->top_target ());
5530 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5531 phex_nz (sym_addr, addr_size), &reply[8]);
5534 putpkt (msg.data ());
5535 getpkt (&reply);
5539 static struct serial *
5540 remote_serial_open (const char *name)
5542 static int udp_warning = 0;
5544 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5545 of in ser-tcp.c, because it is the remote protocol assuming that the
5546 serial connection is reliable and not the serial connection promising
5547 to be. */
5548 if (!udp_warning && startswith (name, "udp:"))
5550 warning (_("The remote protocol may be unreliable over UDP.\n"
5551 "Some events may be lost, rendering further debugging "
5552 "impossible."));
5553 udp_warning = 1;
5556 return serial_open (name);
5559 /* Inform the target of our permission settings. The permission flags
5560 work without this, but if the target knows the settings, it can do
5561 a couple things. First, it can add its own check, to catch cases
5562 that somehow manage to get by the permissions checks in target
5563 methods. Second, if the target is wired to disallow particular
5564 settings (for instance, a system in the field that is not set up to
5565 be able to stop at a breakpoint), it can object to any unavailable
5566 permissions. */
5568 void
5569 remote_target::set_permissions ()
5571 struct remote_state *rs = get_remote_state ();
5573 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5574 "WriteReg:%x;WriteMem:%x;"
5575 "InsertBreak:%x;InsertTrace:%x;"
5576 "InsertFastTrace:%x;Stop:%x",
5577 may_write_registers, may_write_memory,
5578 may_insert_breakpoints, may_insert_tracepoints,
5579 may_insert_fast_tracepoints, may_stop);
5580 putpkt (rs->buf);
5581 getpkt (&rs->buf);
5583 /* If the target didn't like the packet, warn the user. Do not try
5584 to undo the user's settings, that would just be maddening. */
5585 if (strcmp (rs->buf.data (), "OK") != 0)
5586 warning (_("Remote refused setting permissions with: %s"),
5587 rs->buf.data ());
5590 /* This type describes each known response to the qSupported
5591 packet. */
5592 struct protocol_feature
5594 /* The name of this protocol feature. */
5595 const char *name;
5597 /* The default for this protocol feature. */
5598 enum packet_support default_support;
5600 /* The function to call when this feature is reported, or after
5601 qSupported processing if the feature is not supported.
5602 The first argument points to this structure. The second
5603 argument indicates whether the packet requested support be
5604 enabled, disabled, or probed (or the default, if this function
5605 is being called at the end of processing and this feature was
5606 not reported). The third argument may be NULL; if not NULL, it
5607 is a NUL-terminated string taken from the packet following
5608 this feature's name and an equals sign. */
5609 void (*func) (remote_target *remote, const struct protocol_feature *,
5610 enum packet_support, const char *);
5612 /* The corresponding packet for this feature. Only used if
5613 FUNC is remote_supported_packet. */
5614 int packet;
5617 static void
5618 remote_supported_packet (remote_target *remote,
5619 const struct protocol_feature *feature,
5620 enum packet_support support,
5621 const char *argument)
5623 if (argument)
5625 warning (_("Remote qSupported response supplied an unexpected value for"
5626 " \"%s\"."), feature->name);
5627 return;
5630 remote->m_features.m_protocol_packets[feature->packet].support = support;
5633 void
5634 remote_target::remote_packet_size (const protocol_feature *feature,
5635 enum packet_support support,
5636 const char *value)
5638 struct remote_state *rs = get_remote_state ();
5640 int packet_size;
5641 char *value_end;
5643 if (support != PACKET_ENABLE)
5644 return;
5646 if (value == NULL || *value == '\0')
5648 warning (_("Remote target reported \"%s\" without a size."),
5649 feature->name);
5650 return;
5653 errno = 0;
5654 packet_size = strtol (value, &value_end, 16);
5655 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5657 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5658 feature->name, value);
5659 return;
5662 /* Record the new maximum packet size. */
5663 rs->explicit_packet_size = packet_size;
5666 static void
5667 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5668 enum packet_support support, const char *value)
5670 remote->remote_packet_size (feature, support, value);
5673 void
5674 remote_target::remote_supported_thread_options (const protocol_feature *feature,
5675 enum packet_support support,
5676 const char *value)
5678 struct remote_state *rs = get_remote_state ();
5680 m_features.m_protocol_packets[feature->packet].support = support;
5682 if (support != PACKET_ENABLE)
5683 return;
5685 if (value == nullptr || *value == '\0')
5687 warning (_("Remote target reported \"%s\" without supported options."),
5688 feature->name);
5689 return;
5692 ULONGEST options = 0;
5693 const char *p = unpack_varlen_hex (value, &options);
5695 if (*p != '\0')
5697 warning (_("Remote target reported \"%s\" with "
5698 "bad thread options: \"%s\"."),
5699 feature->name, value);
5700 return;
5703 /* Record the set of supported options. */
5704 rs->supported_thread_options = (gdb_thread_option) options;
5707 static void
5708 remote_supported_thread_options (remote_target *remote,
5709 const protocol_feature *feature,
5710 enum packet_support support,
5711 const char *value)
5713 remote->remote_supported_thread_options (feature, support, value);
5716 static const struct protocol_feature remote_protocol_features[] = {
5717 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5718 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5719 PACKET_qXfer_auxv },
5720 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5721 PACKET_qXfer_exec_file },
5722 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5723 PACKET_qXfer_features },
5724 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5725 PACKET_qXfer_libraries },
5726 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5727 PACKET_qXfer_libraries_svr4 },
5728 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5729 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5730 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5731 PACKET_qXfer_memory_map },
5732 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5733 PACKET_qXfer_osdata },
5734 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5735 PACKET_qXfer_threads },
5736 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5737 PACKET_qXfer_traceframe_info },
5738 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5739 PACKET_QPassSignals },
5740 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5741 PACKET_QCatchSyscalls },
5742 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5743 PACKET_QProgramSignals },
5744 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5745 PACKET_QSetWorkingDir },
5746 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5747 PACKET_QStartupWithShell },
5748 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5749 PACKET_QEnvironmentHexEncoded },
5750 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5751 PACKET_QEnvironmentReset },
5752 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5753 PACKET_QEnvironmentUnset },
5754 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5755 PACKET_QStartNoAckMode },
5756 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5757 PACKET_multiprocess_feature },
5758 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5759 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5760 PACKET_qXfer_siginfo_read },
5761 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5762 PACKET_qXfer_siginfo_write },
5763 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5764 PACKET_ConditionalTracepoints },
5765 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5766 PACKET_ConditionalBreakpoints },
5767 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5768 PACKET_BreakpointCommands },
5769 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5770 PACKET_FastTracepoints },
5771 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5772 PACKET_StaticTracepoints },
5773 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5774 PACKET_InstallInTrace},
5775 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5776 PACKET_DisconnectedTracing_feature },
5777 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5778 PACKET_bc },
5779 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5780 PACKET_bs },
5781 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5782 PACKET_TracepointSource },
5783 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5784 PACKET_QAllow },
5785 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5786 PACKET_EnableDisableTracepoints_feature },
5787 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5788 PACKET_qXfer_fdpic },
5789 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5790 PACKET_qXfer_uib },
5791 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5792 PACKET_QDisableRandomization },
5793 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5794 { "QTBuffer:size", PACKET_DISABLE,
5795 remote_supported_packet, PACKET_QTBuffer_size},
5796 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5797 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5798 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5799 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5800 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5801 PACKET_qXfer_btrace },
5802 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5803 PACKET_qXfer_btrace_conf },
5804 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5805 PACKET_Qbtrace_conf_bts_size },
5806 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5807 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5808 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5809 PACKET_fork_event_feature },
5810 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5811 PACKET_vfork_event_feature },
5812 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5813 PACKET_exec_event_feature },
5814 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5815 PACKET_Qbtrace_conf_pt_size },
5816 { "Qbtrace-conf:pt:ptwrite", PACKET_DISABLE, remote_supported_packet,
5817 PACKET_Qbtrace_conf_pt_ptwrite },
5818 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5819 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5820 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5821 PACKET_QThreadOptions },
5822 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5823 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5824 PACKET_memory_tagging_feature },
5825 { "error-message", PACKET_ENABLE, remote_supported_packet,
5826 PACKET_accept_error_message },
5829 static char *remote_support_xml;
5831 /* Register string appended to "xmlRegisters=" in qSupported query. */
5833 void
5834 register_remote_support_xml (const char *xml)
5836 #if defined(HAVE_LIBEXPAT)
5837 if (remote_support_xml == NULL)
5838 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5839 else
5841 char *copy = xstrdup (remote_support_xml + 13);
5842 char *saveptr;
5843 char *p = strtok_r (copy, ",", &saveptr);
5847 if (strcmp (p, xml) == 0)
5849 /* already there */
5850 xfree (copy);
5851 return;
5854 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5855 xfree (copy);
5857 remote_support_xml = reconcat (remote_support_xml,
5858 remote_support_xml, ",", xml,
5859 (char *) NULL);
5861 #endif
5864 static void
5865 remote_query_supported_append (std::string *msg, const char *append)
5867 if (!msg->empty ())
5868 msg->append (";");
5869 msg->append (append);
5872 void
5873 remote_target::remote_query_supported ()
5875 struct remote_state *rs = get_remote_state ();
5876 char *next;
5877 int i;
5878 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5880 /* The packet support flags are handled differently for this packet
5881 than for most others. We treat an error, a disabled packet, and
5882 an empty response identically: any features which must be reported
5883 to be used will be automatically disabled. An empty buffer
5884 accomplishes this, since that is also the representation for a list
5885 containing no features. */
5887 rs->buf[0] = 0;
5888 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5890 std::string q;
5892 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5893 != AUTO_BOOLEAN_FALSE)
5894 remote_query_supported_append (&q, "multiprocess+");
5896 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5897 != AUTO_BOOLEAN_FALSE)
5898 remote_query_supported_append (&q, "swbreak+");
5900 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5901 != AUTO_BOOLEAN_FALSE)
5902 remote_query_supported_append (&q, "hwbreak+");
5904 remote_query_supported_append (&q, "qRelocInsn+");
5906 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5907 != AUTO_BOOLEAN_FALSE)
5908 remote_query_supported_append (&q, "fork-events+");
5910 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5911 != AUTO_BOOLEAN_FALSE)
5912 remote_query_supported_append (&q, "vfork-events+");
5914 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5915 != AUTO_BOOLEAN_FALSE)
5916 remote_query_supported_append (&q, "exec-events+");
5918 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5919 != AUTO_BOOLEAN_FALSE)
5920 remote_query_supported_append (&q, "vContSupported+");
5922 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5923 != AUTO_BOOLEAN_FALSE)
5924 remote_query_supported_append (&q, "QThreadEvents+");
5926 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5927 != AUTO_BOOLEAN_FALSE)
5928 remote_query_supported_append (&q, "QThreadOptions+");
5930 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5931 != AUTO_BOOLEAN_FALSE)
5932 remote_query_supported_append (&q, "no-resumed+");
5934 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5935 != AUTO_BOOLEAN_FALSE)
5936 remote_query_supported_append (&q, "memory-tagging+");
5938 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5939 the qSupported:xmlRegisters=i386 handling. */
5940 if (remote_support_xml != NULL
5941 && (m_features.packet_support (PACKET_qXfer_features)
5942 != PACKET_DISABLE))
5943 remote_query_supported_append (&q, remote_support_xml);
5945 if (m_features.packet_set_cmd_state (PACKET_accept_error_message)
5946 != AUTO_BOOLEAN_FALSE)
5947 remote_query_supported_append (&q, "error-message+");
5949 q = "qSupported:" + q;
5950 putpkt (q.c_str ());
5952 getpkt (&rs->buf);
5954 /* If an error occurred, warn, but do not return - just reset the
5955 buffer to empty and go on to disable features. */
5956 packet_result result = m_features.packet_ok (rs->buf, PACKET_qSupported);
5957 if (result.status () == PACKET_ERROR)
5959 warning (_("Remote failure reply: %s"), result.err_msg ());
5960 rs->buf[0] = 0;
5964 memset (seen, 0, sizeof (seen));
5966 next = rs->buf.data ();
5967 while (*next)
5969 enum packet_support is_supported;
5970 char *p, *end, *name_end, *value;
5972 /* First separate out this item from the rest of the packet. If
5973 there's another item after this, we overwrite the separator
5974 (terminated strings are much easier to work with). */
5975 p = next;
5976 end = strchr (p, ';');
5977 if (end == NULL)
5979 end = p + strlen (p);
5980 next = end;
5982 else
5984 *end = '\0';
5985 next = end + 1;
5987 if (end == p)
5989 warning (_("empty item in \"qSupported\" response"));
5990 continue;
5994 name_end = strchr (p, '=');
5995 if (name_end)
5997 /* This is a name=value entry. */
5998 is_supported = PACKET_ENABLE;
5999 value = name_end + 1;
6000 *name_end = '\0';
6002 else
6004 value = NULL;
6005 switch (end[-1])
6007 case '+':
6008 is_supported = PACKET_ENABLE;
6009 break;
6011 case '-':
6012 is_supported = PACKET_DISABLE;
6013 break;
6015 case '?':
6016 is_supported = PACKET_SUPPORT_UNKNOWN;
6017 break;
6019 default:
6020 warning (_("unrecognized item \"%s\" "
6021 "in \"qSupported\" response"), p);
6022 continue;
6024 end[-1] = '\0';
6027 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6028 if (strcmp (remote_protocol_features[i].name, p) == 0)
6030 const struct protocol_feature *feature;
6032 seen[i] = 1;
6033 feature = &remote_protocol_features[i];
6034 feature->func (this, feature, is_supported, value);
6035 break;
6039 /* If we increased the packet size, make sure to increase the global
6040 buffer size also. We delay this until after parsing the entire
6041 qSupported packet, because this is the same buffer we were
6042 parsing. */
6043 if (rs->buf.size () < rs->explicit_packet_size)
6044 rs->buf.resize (rs->explicit_packet_size);
6046 /* Handle the defaults for unmentioned features. */
6047 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6048 if (!seen[i])
6050 const struct protocol_feature *feature;
6052 feature = &remote_protocol_features[i];
6053 feature->func (this, feature, feature->default_support, NULL);
6057 /* Serial QUIT handler for the remote serial descriptor.
6059 Defers handling a Ctrl-C until we're done with the current
6060 command/response packet sequence, unless:
6062 - We're setting up the connection. Don't send a remote interrupt
6063 request, as we're not fully synced yet. Quit immediately
6064 instead.
6066 - The target has been resumed in the foreground
6067 (target_terminal::is_ours is false) with a synchronous resume
6068 packet, and we're blocked waiting for the stop reply, thus a
6069 Ctrl-C should be immediately sent to the target.
6071 - We get a second Ctrl-C while still within the same serial read or
6072 write. In that case the serial is seemingly wedged --- offer to
6073 quit/disconnect.
6075 - We see a second Ctrl-C without target response, after having
6076 previously interrupted the target. In that case the target/stub
6077 is probably wedged --- offer to quit/disconnect.
6080 void
6081 remote_target::remote_serial_quit_handler ()
6083 struct remote_state *rs = get_remote_state ();
6085 if (check_quit_flag ())
6087 /* If we're starting up, we're not fully synced yet. Quit
6088 immediately. */
6089 if (rs->starting_up)
6090 quit ();
6091 else if (rs->got_ctrlc_during_io)
6093 if (query (_("The target is not responding to GDB commands.\n"
6094 "Stop debugging it? ")))
6095 remote_unpush_and_throw (this);
6097 /* If ^C has already been sent once, offer to disconnect. */
6098 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
6099 interrupt_query ();
6100 /* All-stop protocol, and blocked waiting for stop reply. Send
6101 an interrupt request. */
6102 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
6103 target_interrupt ();
6104 else
6105 rs->got_ctrlc_during_io = 1;
6109 /* The remote_target that is current while the quit handler is
6110 overridden with remote_serial_quit_handler. */
6111 static remote_target *curr_quit_handler_target;
6113 static void
6114 remote_serial_quit_handler ()
6116 curr_quit_handler_target->remote_serial_quit_handler ();
6119 /* Remove the remote target from the target stack of each inferior
6120 that is using it. Upper targets depend on it so remove them
6121 first. */
6123 static void
6124 remote_unpush_target (remote_target *target)
6126 /* We have to unpush the target from all inferiors, even those that
6127 aren't running. */
6128 scoped_restore_current_inferior restore_current_inferior;
6130 for (inferior *inf : all_inferiors (target))
6132 switch_to_inferior_no_thread (inf);
6133 inf->pop_all_targets_at_and_above (process_stratum);
6134 generic_mourn_inferior ();
6137 /* Don't rely on target_close doing this when the target is popped
6138 from the last remote inferior above, because something may be
6139 holding a reference to the target higher up on the stack, meaning
6140 target_close won't be called yet. We lost the connection to the
6141 target, so clear these now, otherwise we may later throw
6142 TARGET_CLOSE_ERROR while trying to tell the remote target to
6143 close the file. */
6144 fileio_handles_invalidate_target (target);
6147 [[noreturn]] static void
6148 remote_unpush_and_throw (remote_target *target)
6150 remote_unpush_target (target);
6151 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6154 void
6155 remote_target::open_1 (const char *name, int from_tty, int extended_p)
6157 remote_target *curr_remote = get_current_remote_target ();
6159 if (name == 0)
6160 error (_("To open a remote debug connection, you need to specify what\n"
6161 "serial device is attached to the remote system\n"
6162 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6164 /* If we're connected to a running target, target_preopen will kill it.
6165 Ask this question first, before target_preopen has a chance to kill
6166 anything. */
6167 if (curr_remote != NULL && !target_has_execution ())
6169 if (from_tty
6170 && !query (_("Already connected to a remote target. Disconnect? ")))
6171 error (_("Still connected."));
6174 /* Here the possibly existing remote target gets unpushed. */
6175 target_preopen (from_tty);
6177 remote_fileio_reset ();
6178 reopen_exec_file ();
6179 reread_symbols (from_tty);
6181 remote_target *remote
6182 = (extended_p ? new extended_remote_target () : new remote_target ());
6183 target_ops_up target_holder (remote);
6185 remote_state *rs = remote->get_remote_state ();
6187 /* See FIXME above. */
6188 if (!target_async_permitted)
6189 rs->wait_forever_enabled_p = true;
6191 rs->remote_desc = remote_serial_open (name);
6193 if (baud_rate != -1)
6197 serial_setbaudrate (rs->remote_desc, baud_rate);
6199 catch (const gdb_exception_error &)
6201 /* The requested speed could not be set. Error out to
6202 top level after closing remote_desc. Take care to
6203 set remote_desc to NULL to avoid closing remote_desc
6204 more than once. */
6205 serial_close (rs->remote_desc);
6206 rs->remote_desc = NULL;
6207 throw;
6211 serial_setparity (rs->remote_desc, serial_parity);
6212 serial_raw (rs->remote_desc);
6214 /* If there is something sitting in the buffer we might take it as a
6215 response to a command, which would be bad. */
6216 serial_flush_input (rs->remote_desc);
6218 if (from_tty)
6220 gdb_puts ("Remote debugging using ");
6221 gdb_puts (name);
6222 gdb_puts ("\n");
6225 /* Switch to using the remote target now. */
6226 current_inferior ()->push_target (std::move (target_holder));
6228 /* Register extra event sources in the event loop. */
6229 rs->create_async_event_handler ();
6231 rs->notif_state = remote_notif_state_allocate (remote);
6233 /* Reset the target state; these things will be queried either by
6234 remote_query_supported or as they are needed. */
6235 remote->m_features.reset_all_packet_configs_support ();
6236 rs->explicit_packet_size = 0;
6237 rs->noack_mode = 0;
6238 rs->extended = extended_p;
6239 rs->waiting_for_stop_reply = 0;
6240 rs->ctrlc_pending_p = 0;
6241 rs->got_ctrlc_during_io = 0;
6243 rs->general_thread = not_sent_ptid;
6244 rs->continue_thread = not_sent_ptid;
6245 rs->remote_traceframe_number = -1;
6247 rs->last_resume_exec_dir = EXEC_FORWARD;
6249 /* Probe for ability to use "ThreadInfo" query, as required. */
6250 rs->use_threadinfo_query = 1;
6251 rs->use_threadextra_query = 1;
6253 rs->readahead_cache.invalidate ();
6255 if (target_async_permitted)
6257 /* FIXME: cagney/1999-09-23: During the initial connection it is
6258 assumed that the target is already ready and able to respond to
6259 requests. Unfortunately remote_start_remote() eventually calls
6260 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6261 around this. Eventually a mechanism that allows
6262 wait_for_inferior() to expect/get timeouts will be
6263 implemented. */
6264 rs->wait_forever_enabled_p = false;
6267 /* First delete any symbols previously loaded from shared libraries. */
6268 no_shared_libraries (current_program_space);
6270 /* Start the remote connection. If error() or QUIT, discard this
6271 target (we'd otherwise be in an inconsistent state) and then
6272 propogate the error on up the exception chain. This ensures that
6273 the caller doesn't stumble along blindly assuming that the
6274 function succeeded. The CLI doesn't have this problem but other
6275 UI's, such as MI do.
6277 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6278 this function should return an error indication letting the
6279 caller restore the previous state. Unfortunately the command
6280 ``target remote'' is directly wired to this function making that
6281 impossible. On a positive note, the CLI side of this problem has
6282 been fixed - the function set_cmd_context() makes it possible for
6283 all the ``target ....'' commands to share a common callback
6284 function. See cli-dump.c. */
6289 remote->start_remote (from_tty, extended_p);
6291 catch (const gdb_exception &ex)
6293 /* Pop the partially set up target - unless something else did
6294 already before throwing the exception. */
6295 if (ex.error != TARGET_CLOSE_ERROR)
6296 remote_unpush_target (remote);
6297 throw;
6301 remote_btrace_reset (rs);
6303 if (target_async_permitted)
6304 rs->wait_forever_enabled_p = true;
6307 /* Determine if WS represents a fork status. */
6309 static bool
6310 is_fork_status (target_waitkind kind)
6312 return (kind == TARGET_WAITKIND_FORKED
6313 || kind == TARGET_WAITKIND_VFORKED);
6316 /* Return a reference to the field where a pending child status, if
6317 there's one, is recorded. If there's no child event pending, the
6318 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6320 static const target_waitstatus &
6321 thread_pending_status (struct thread_info *thread)
6323 return (thread->has_pending_waitstatus ()
6324 ? thread->pending_waitstatus ()
6325 : thread->pending_follow);
6328 /* Return THREAD's pending status if it is a pending fork/vfork (but
6329 not clone) parent, else return nullptr. */
6331 static const target_waitstatus *
6332 thread_pending_fork_status (struct thread_info *thread)
6334 const target_waitstatus &ws = thread_pending_status (thread);
6336 if (!is_fork_status (ws.kind ()))
6337 return nullptr;
6339 return &ws;
6342 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6343 event, else return nullptr. */
6345 static const target_waitstatus *
6346 thread_pending_child_status (thread_info *thread)
6348 const target_waitstatus &ws = thread_pending_status (thread);
6350 if (!is_new_child_status (ws.kind ()))
6351 return nullptr;
6353 return &ws;
6356 /* Detach the specified process. */
6358 void
6359 remote_target::remote_detach_pid (int pid)
6361 struct remote_state *rs = get_remote_state ();
6363 /* This should not be necessary, but the handling for D;PID in
6364 GDBserver versions prior to 8.2 incorrectly assumes that the
6365 selected process points to the same process we're detaching,
6366 leading to misbehavior (and possibly GDBserver crashing) when it
6367 does not. Since it's easy and cheap, work around it by forcing
6368 GDBserver to select GDB's current process. */
6369 set_general_process ();
6371 if (m_features.remote_multi_process_p ())
6372 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6373 else
6374 strcpy (rs->buf.data (), "D");
6376 putpkt (rs->buf);
6377 getpkt (&rs->buf);
6379 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6381 else if (rs->buf[0] == '\0')
6382 error (_("Remote doesn't know how to detach"));
6383 else
6385 /* It is possible that we have an unprocessed exit event for this
6386 pid. If this is the case then we can ignore the failure to detach
6387 and just pretend that the detach worked, as far as the user is
6388 concerned, the process exited immediately after the detach. */
6389 bool process_has_already_exited = false;
6390 remote_notif_get_pending_events (&notif_client_stop);
6391 for (stop_reply_up &reply : rs->stop_reply_queue)
6393 if (reply->ptid.pid () != pid)
6394 continue;
6396 enum target_waitkind kind = reply->ws.kind ();
6397 if (kind == TARGET_WAITKIND_EXITED
6398 || kind == TARGET_WAITKIND_SIGNALLED)
6400 process_has_already_exited = true;
6401 remote_debug_printf
6402 ("detach failed, but process already exited");
6403 break;
6407 if (!process_has_already_exited)
6408 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6412 /* This detaches a program to which we previously attached, using
6413 inferior_ptid to identify the process. After this is done, GDB
6414 can be used to debug some other program. We better not have left
6415 any breakpoints in the target program or it'll die when it hits
6416 one. */
6418 void
6419 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6421 int pid = inferior_ptid.pid ();
6422 struct remote_state *rs = get_remote_state ();
6423 int is_fork_parent;
6425 if (!target_has_execution ())
6426 error (_("No process to detach from."));
6428 target_announce_detach (from_tty);
6430 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6432 /* If we're in breakpoints-always-inserted mode, or the inferior
6433 is running, we have to remove breakpoints before detaching.
6434 We don't do this in common code instead because not all
6435 targets support removing breakpoints while the target is
6436 running. The remote target / gdbserver does, though. */
6437 remove_breakpoints_inf (current_inferior ());
6440 /* Tell the remote target to detach. */
6441 remote_detach_pid (pid);
6443 /* Exit only if this is the only active inferior. */
6444 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6445 gdb_puts (_("Ending remote debugging.\n"));
6447 /* See if any thread of the inferior we are detaching has a pending fork
6448 status. In that case, we must detach from the child resulting from
6449 that fork. */
6450 for (thread_info *thread : inf->non_exited_threads ())
6452 const target_waitstatus *ws = thread_pending_fork_status (thread);
6454 if (ws == nullptr)
6455 continue;
6457 remote_detach_pid (ws->child_ptid ().pid ());
6460 /* Check also for any pending fork events in the stop reply queue. */
6461 remote_notif_get_pending_events (&notif_client_stop);
6462 for (stop_reply_up &reply : rs->stop_reply_queue)
6464 if (reply->ptid.pid () != pid)
6465 continue;
6467 if (!is_fork_status (reply->ws.kind ()))
6468 continue;
6470 remote_detach_pid (reply->ws.child_ptid ().pid ());
6473 thread_info *tp = this->find_thread (inferior_ptid);
6475 /* Check to see if we are detaching a fork parent. Note that if we
6476 are detaching a fork child, tp == NULL. */
6477 is_fork_parent = (tp != NULL
6478 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6480 /* If doing detach-on-fork, we don't mourn, because that will delete
6481 breakpoints that should be available for the followed inferior. */
6482 if (!is_fork_parent)
6484 /* Save the pid as a string before mourning, since that will
6485 unpush the remote target, and we need the string after. */
6486 std::string infpid = target_pid_to_str (ptid_t (pid));
6488 target_mourn_inferior (inferior_ptid);
6489 if (print_inferior_events)
6490 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6491 inf->num, infpid.c_str ());
6493 else
6495 switch_to_no_thread ();
6496 detach_inferior (current_inferior ());
6500 void
6501 remote_target::detach (inferior *inf, int from_tty)
6503 remote_detach_1 (inf, from_tty);
6506 void
6507 extended_remote_target::detach (inferior *inf, int from_tty)
6509 remote_detach_1 (inf, from_tty);
6512 /* Target follow-fork function for remote targets. On entry, and
6513 at return, the current inferior is the fork parent.
6515 Note that although this is currently only used for extended-remote,
6516 it is named remote_follow_fork in anticipation of using it for the
6517 remote target as well. */
6519 void
6520 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6521 target_waitkind fork_kind, bool follow_child,
6522 bool detach_fork)
6524 process_stratum_target::follow_fork (child_inf, child_ptid,
6525 fork_kind, follow_child, detach_fork);
6527 if ((fork_kind == TARGET_WAITKIND_FORKED
6528 && m_features.remote_fork_event_p ())
6529 || (fork_kind == TARGET_WAITKIND_VFORKED
6530 && m_features.remote_vfork_event_p ()))
6532 /* When following the parent and detaching the child, we detach
6533 the child here. For the case of following the child and
6534 detaching the parent, the detach is done in the target-
6535 independent follow fork code in infrun.c. We can't use
6536 target_detach when detaching an unfollowed child because
6537 the client side doesn't know anything about the child. */
6538 if (detach_fork && !follow_child)
6540 /* Detach the fork child. */
6541 remote_detach_pid (child_ptid.pid ());
6546 void
6547 remote_target::follow_clone (ptid_t child_ptid)
6549 remote_add_thread (child_ptid, false, false, false);
6552 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6553 in the program space of the new inferior. */
6555 void
6556 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6557 const char *execd_pathname)
6559 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6561 /* We know that this is a target file name, so if it has the "target:"
6562 prefix we strip it off before saving it in the program space. */
6563 if (is_target_filename (execd_pathname))
6564 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6566 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6569 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6571 void
6572 remote_target::disconnect (const char *args, int from_tty)
6574 if (args)
6575 error (_("Argument given to \"disconnect\" when remotely debugging."));
6577 /* Make sure we unpush even the extended remote targets. Calling
6578 target_mourn_inferior won't unpush, and
6579 remote_target::mourn_inferior won't unpush if there is more than
6580 one inferior left. */
6581 remote_unpush_target (this);
6583 if (from_tty)
6584 gdb_puts ("Ending remote debugging.\n");
6587 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6588 be chatty about it. */
6590 void
6591 extended_remote_target::attach (const char *args, int from_tty)
6593 struct remote_state *rs = get_remote_state ();
6594 int pid;
6595 char *wait_status = NULL;
6597 pid = parse_pid_to_attach (args);
6599 /* Remote PID can be freely equal to getpid, do not check it here the same
6600 way as in other targets. */
6602 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6603 error (_("This target does not support attaching to a process"));
6605 target_announce_attach (from_tty, pid);
6607 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6608 putpkt (rs->buf);
6609 getpkt (&rs->buf);
6611 packet_result result = m_features.packet_ok (rs->buf, PACKET_vAttach);
6612 switch (result.status ())
6614 case PACKET_OK:
6615 if (!target_is_non_stop_p ())
6617 /* Save the reply for later. */
6618 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6619 strcpy (wait_status, rs->buf.data ());
6621 else if (strcmp (rs->buf.data (), "OK") != 0)
6622 error (_("Attaching to %s failed with: %s"),
6623 target_pid_to_str (ptid_t (pid)).c_str (),
6624 rs->buf.data ());
6625 break;
6626 case PACKET_UNKNOWN:
6627 error (_("This target does not support attaching to a process"));
6628 case PACKET_ERROR:
6629 error (_("Attaching to %s failed: %s"),
6630 target_pid_to_str (ptid_t (pid)).c_str (), result.err_msg ());
6633 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6635 inferior_ptid = ptid_t (pid);
6637 if (target_is_non_stop_p ())
6639 /* Get list of threads. */
6640 update_thread_list ();
6642 thread_info *thread = first_thread_of_inferior (current_inferior ());
6643 if (thread != nullptr)
6644 switch_to_thread (thread);
6646 /* Invalidate our notion of the remote current thread. */
6647 record_currthread (rs, minus_one_ptid);
6649 else
6651 /* Now, if we have thread information, update the main thread's
6652 ptid. */
6653 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6655 /* Add the main thread to the thread list. We add the thread
6656 silently in this case (the final true parameter). */
6657 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6659 switch_to_thread (thr);
6662 /* Next, if the target can specify a description, read it. We do
6663 this before anything involving memory or registers. */
6664 target_find_description ();
6666 if (!target_is_non_stop_p ())
6668 /* Use the previously fetched status. */
6669 gdb_assert (wait_status != NULL);
6671 notif_event_up reply
6672 = remote_notif_parse (this, &notif_client_stop, wait_status);
6673 push_stop_reply (as_stop_reply_up (std::move (reply)));
6675 else
6677 gdb_assert (wait_status == NULL);
6679 gdb_assert (target_can_async_p ());
6683 /* Implementation of the to_post_attach method. */
6685 void
6686 extended_remote_target::post_attach (int pid)
6688 /* Get text, data & bss offsets. */
6689 get_offsets ();
6691 /* In certain cases GDB might not have had the chance to start
6692 symbol lookup up until now. This could happen if the debugged
6693 binary is not using shared libraries, the vsyscall page is not
6694 present (on Linux) and the binary itself hadn't changed since the
6695 debugging process was started. */
6696 if (current_program_space->symfile_object_file != NULL)
6697 remote_check_symbols();
6701 /* Check for the availability of vCont. This function should also check
6702 the response. */
6704 void
6705 remote_target::remote_vcont_probe ()
6707 remote_state *rs = get_remote_state ();
6708 char *buf;
6710 strcpy (rs->buf.data (), "vCont?");
6711 putpkt (rs->buf);
6712 getpkt (&rs->buf);
6713 buf = rs->buf.data ();
6715 /* Make sure that the features we assume are supported. */
6716 if (startswith (buf, "vCont"))
6718 char *p = &buf[5];
6719 int support_c, support_C;
6721 rs->supports_vCont.s = 0;
6722 rs->supports_vCont.S = 0;
6723 support_c = 0;
6724 support_C = 0;
6725 rs->supports_vCont.t = 0;
6726 rs->supports_vCont.r = 0;
6727 while (p && *p == ';')
6729 p++;
6730 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6731 rs->supports_vCont.s = 1;
6732 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6733 rs->supports_vCont.S = 1;
6734 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6735 support_c = 1;
6736 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6737 support_C = 1;
6738 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6739 rs->supports_vCont.t = 1;
6740 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6741 rs->supports_vCont.r = 1;
6743 p = strchr (p, ';');
6746 /* If c, and C are not all supported, we can't use vCont. Clearing
6747 BUF will make packet_ok disable the packet. */
6748 if (!support_c || !support_C)
6749 buf[0] = 0;
6752 m_features.packet_ok (rs->buf, PACKET_vCont);
6755 /* Helper function for building "vCont" resumptions. Write a
6756 resumption to P. ENDP points to one-passed-the-end of the buffer
6757 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6758 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6759 resumed thread should be single-stepped and/or signalled. If PTID
6760 equals minus_one_ptid, then all threads are resumed; if PTID
6761 represents a process, then all threads of the process are
6762 resumed. */
6764 char *
6765 remote_target::append_resumption (char *p, char *endp,
6766 ptid_t ptid, int step, gdb_signal siggnal)
6768 struct remote_state *rs = get_remote_state ();
6770 if (step && siggnal != GDB_SIGNAL_0)
6771 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6772 else if (step
6773 /* GDB is willing to range step. */
6774 && use_range_stepping
6775 /* Target supports range stepping. */
6776 && rs->supports_vCont.r
6777 /* We don't currently support range stepping multiple
6778 threads with a wildcard (though the protocol allows it,
6779 so stubs shouldn't make an active effort to forbid
6780 it). */
6781 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6783 struct thread_info *tp;
6785 if (ptid == minus_one_ptid)
6787 /* If we don't know about the target thread's tid, then
6788 we're resuming magic_null_ptid (see caller). */
6789 tp = this->find_thread (magic_null_ptid);
6791 else
6792 tp = this->find_thread (ptid);
6793 gdb_assert (tp != NULL);
6795 if (tp->control.may_range_step)
6797 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6799 p += xsnprintf (p, endp - p, ";r%s,%s",
6800 phex_nz (tp->control.step_range_start,
6801 addr_size),
6802 phex_nz (tp->control.step_range_end,
6803 addr_size));
6805 else
6806 p += xsnprintf (p, endp - p, ";s");
6808 else if (step)
6809 p += xsnprintf (p, endp - p, ";s");
6810 else if (siggnal != GDB_SIGNAL_0)
6811 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6812 else
6813 p += xsnprintf (p, endp - p, ";c");
6815 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6817 ptid_t nptid;
6819 /* All (-1) threads of process. */
6820 nptid = ptid_t (ptid.pid (), -1);
6822 p += xsnprintf (p, endp - p, ":");
6823 p = write_ptid (p, endp, nptid);
6825 else if (ptid != minus_one_ptid)
6827 p += xsnprintf (p, endp - p, ":");
6828 p = write_ptid (p, endp, ptid);
6831 return p;
6834 /* Clear the thread's private info on resume. */
6836 static void
6837 resume_clear_thread_private_info (struct thread_info *thread)
6839 if (thread->priv != NULL)
6841 remote_thread_info *priv = get_remote_thread_info (thread);
6843 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6844 priv->watch_data_address = 0;
6848 /* Append a vCont continue-with-signal action for threads that have a
6849 non-zero stop signal. */
6851 char *
6852 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6853 ptid_t ptid)
6855 for (thread_info *thread : all_non_exited_threads (this, ptid))
6856 if (inferior_ptid != thread->ptid
6857 && thread->stop_signal () != GDB_SIGNAL_0)
6859 p = append_resumption (p, endp, thread->ptid,
6860 0, thread->stop_signal ());
6861 thread->set_stop_signal (GDB_SIGNAL_0);
6862 resume_clear_thread_private_info (thread);
6865 return p;
6868 /* Set the target running, using the packets that use Hc
6869 (c/s/C/S). */
6871 void
6872 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6873 gdb_signal siggnal)
6875 struct remote_state *rs = get_remote_state ();
6876 char *buf;
6878 rs->last_sent_signal = siggnal;
6879 rs->last_sent_step = step;
6881 /* The c/s/C/S resume packets use Hc, so set the continue
6882 thread. */
6883 if (ptid == minus_one_ptid)
6884 set_continue_thread (any_thread_ptid);
6885 else
6886 set_continue_thread (ptid);
6888 for (thread_info *thread : all_non_exited_threads (this))
6889 resume_clear_thread_private_info (thread);
6891 buf = rs->buf.data ();
6892 if (::execution_direction == EXEC_REVERSE)
6894 /* We don't pass signals to the target in reverse exec mode. */
6895 if (info_verbose && siggnal != GDB_SIGNAL_0)
6896 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6897 siggnal);
6899 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6900 error (_("Remote reverse-step not supported."));
6901 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6902 error (_("Remote reverse-continue not supported."));
6904 strcpy (buf, step ? "bs" : "bc");
6906 else if (siggnal != GDB_SIGNAL_0)
6908 buf[0] = step ? 'S' : 'C';
6909 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6910 buf[2] = tohex (((int) siggnal) & 0xf);
6911 buf[3] = '\0';
6913 else
6914 strcpy (buf, step ? "s" : "c");
6916 putpkt (buf);
6919 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6920 STEP, and SIGGNAL have the same meaning as in target_resume. This
6921 function returns non-zero iff it resumes the inferior.
6923 This function issues a strict subset of all possible vCont commands
6924 at the moment. */
6927 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6928 enum gdb_signal siggnal)
6930 struct remote_state *rs = get_remote_state ();
6931 char *p;
6932 char *endp;
6934 /* No reverse execution actions defined for vCont. */
6935 if (::execution_direction == EXEC_REVERSE)
6936 return 0;
6938 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6939 return 0;
6941 p = rs->buf.data ();
6942 endp = p + get_remote_packet_size ();
6944 /* If we could generate a wider range of packets, we'd have to worry
6945 about overflowing BUF. Should there be a generic
6946 "multi-part-packet" packet? */
6948 p += xsnprintf (p, endp - p, "vCont");
6950 if (scope_ptid == magic_null_ptid)
6952 /* MAGIC_NULL_PTID means that we don't have any active threads,
6953 so we don't have any TID numbers the inferior will
6954 understand. Make sure to only send forms that do not specify
6955 a TID. */
6956 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6958 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6960 /* Resume all threads (of all processes, or of a single
6961 process), with preference for INFERIOR_PTID. This assumes
6962 inferior_ptid belongs to the set of all threads we are about
6963 to resume. */
6964 if (step || siggnal != GDB_SIGNAL_0)
6966 /* Step inferior_ptid, with or without signal. */
6967 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6970 /* Also pass down any pending signaled resumption for other
6971 threads not the current. */
6972 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6974 /* And continue others without a signal. */
6975 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6977 else
6979 /* Scheduler locking; resume only SCOPE_PTID. */
6980 append_resumption (p, endp, scope_ptid, step, siggnal);
6983 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6984 putpkt (rs->buf);
6986 if (target_is_non_stop_p ())
6988 /* In non-stop, the stub replies to vCont with "OK". The stop
6989 reply will be reported asynchronously by means of a `%Stop'
6990 notification. */
6991 getpkt (&rs->buf);
6992 if (strcmp (rs->buf.data (), "OK") != 0)
6993 error (_("Unexpected vCont reply in non-stop mode: %s"),
6994 rs->buf.data ());
6997 return 1;
7000 /* Tell the remote machine to resume. */
7002 void
7003 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
7005 struct remote_state *rs = get_remote_state ();
7007 /* When connected in non-stop mode, the core resumes threads
7008 individually. Resuming remote threads directly in target_resume
7009 would thus result in sending one packet per thread. Instead, to
7010 minimize roundtrip latency, here we just store the resume
7011 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
7012 resumption will be done in remote_target::commit_resume, where we'll be
7013 able to do vCont action coalescing. */
7014 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
7016 remote_thread_info *remote_thr
7017 = get_remote_thread_info (inferior_thread ());
7019 /* We don't expect the core to ask to resume an already resumed (from
7020 its point of view) thread. */
7021 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
7023 remote_thr->set_resumed_pending_vcont (step, siggnal);
7025 /* There's actually nothing that says that the core can't
7026 request a wildcard resume in non-stop mode, though. It's
7027 just that we know it doesn't currently, so we don't bother
7028 with it. */
7029 gdb_assert (scope_ptid == inferior_ptid);
7030 return;
7033 commit_requested_thread_options ();
7035 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
7036 (explained in remote-notif.c:handle_notification) so
7037 remote_notif_process is not called. We need find a place where
7038 it is safe to start a 'vNotif' sequence. It is good to do it
7039 before resuming inferior, because inferior was stopped and no RSP
7040 traffic at that moment. */
7041 if (!target_is_non_stop_p ())
7042 remote_notif_process (rs->notif_state, &notif_client_stop);
7044 rs->last_resume_exec_dir = ::execution_direction;
7046 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
7047 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
7048 remote_resume_with_hc (scope_ptid, step, siggnal);
7050 /* Update resumed state tracked by the remote target. */
7051 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
7052 get_remote_thread_info (tp)->set_resumed ();
7054 /* We've just told the target to resume. The remote server will
7055 wait for the inferior to stop, and then send a stop reply. In
7056 the mean time, we can't start another command/query ourselves
7057 because the stub wouldn't be ready to process it. This applies
7058 only to the base all-stop protocol, however. In non-stop (which
7059 only supports vCont), the stub replies with an "OK", and is
7060 immediate able to process further serial input. */
7061 if (!target_is_non_stop_p ())
7062 rs->waiting_for_stop_reply = 1;
7065 /* Private per-inferior info for target remote processes. */
7067 struct remote_inferior : public private_inferior
7069 /* Whether we can send a wildcard vCont for this process. */
7070 bool may_wildcard_vcont = true;
7073 /* Get the remote private inferior data associated to INF. */
7075 static remote_inferior *
7076 get_remote_inferior (inferior *inf)
7078 if (inf->priv == NULL)
7079 inf->priv.reset (new remote_inferior);
7081 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
7084 /* Class used to track the construction of a vCont packet in the
7085 outgoing packet buffer. This is used to send multiple vCont
7086 packets if we have more actions than would fit a single packet. */
7088 class vcont_builder
7090 public:
7091 explicit vcont_builder (remote_target *remote)
7092 : m_remote (remote)
7094 restart ();
7097 void flush ();
7098 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
7100 private:
7101 void restart ();
7103 /* The remote target. */
7104 remote_target *m_remote;
7106 /* Pointer to the first action. P points here if no action has been
7107 appended yet. */
7108 char *m_first_action;
7110 /* Where the next action will be appended. */
7111 char *m_p;
7113 /* The end of the buffer. Must never write past this. */
7114 char *m_endp;
7117 /* Prepare the outgoing buffer for a new vCont packet. */
7119 void
7120 vcont_builder::restart ()
7122 struct remote_state *rs = m_remote->get_remote_state ();
7124 m_p = rs->buf.data ();
7125 m_endp = m_p + m_remote->get_remote_packet_size ();
7126 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7127 m_first_action = m_p;
7130 /* If the vCont packet being built has any action, send it to the
7131 remote end. */
7133 void
7134 vcont_builder::flush ()
7136 struct remote_state *rs;
7138 if (m_p == m_first_action)
7139 return;
7141 rs = m_remote->get_remote_state ();
7142 m_remote->putpkt (rs->buf);
7143 m_remote->getpkt (&rs->buf);
7144 if (strcmp (rs->buf.data (), "OK") != 0)
7145 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7148 /* The largest action is range-stepping, with its two addresses. This
7149 is more than sufficient. If a new, bigger action is created, it'll
7150 quickly trigger a failed assertion in append_resumption (and we'll
7151 just bump this). */
7152 #define MAX_ACTION_SIZE 200
7154 /* Append a new vCont action in the outgoing packet being built. If
7155 the action doesn't fit the packet along with previous actions, push
7156 what we've got so far to the remote end and start over a new vCont
7157 packet (with the new action). */
7159 void
7160 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7162 char buf[MAX_ACTION_SIZE + 1];
7164 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7165 ptid, step, siggnal);
7167 /* Check whether this new action would fit in the vCont packet along
7168 with previous actions. If not, send what we've got so far and
7169 start a new vCont packet. */
7170 size_t rsize = endp - buf;
7171 if (rsize > m_endp - m_p)
7173 flush ();
7174 restart ();
7176 /* Should now fit. */
7177 gdb_assert (rsize <= m_endp - m_p);
7180 memcpy (m_p, buf, rsize);
7181 m_p += rsize;
7182 *m_p = '\0';
7185 /* to_commit_resume implementation. */
7187 void
7188 remote_target::commit_resumed ()
7190 /* If connected in all-stop mode, we'd send the remote resume
7191 request directly from remote_resume. Likewise if
7192 reverse-debugging, as there are no defined vCont actions for
7193 reverse execution. */
7194 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7195 return;
7197 commit_requested_thread_options ();
7199 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7200 instead of resuming all threads of each process individually.
7201 However, if any thread of a process must remain halted, we can't
7202 send wildcard resumes and must send one action per thread.
7204 Care must be taken to not resume threads/processes the server
7205 side already told us are stopped, but the core doesn't know about
7206 yet, because the events are still in the vStopped notification
7207 queue. For example:
7209 #1 => vCont s:p1.1;c
7210 #2 <= OK
7211 #3 <= %Stopped T05 p1.1
7212 #4 => vStopped
7213 #5 <= T05 p1.2
7214 #6 => vStopped
7215 #7 <= OK
7216 #8 (infrun handles the stop for p1.1 and continues stepping)
7217 #9 => vCont s:p1.1;c
7219 The last vCont above would resume thread p1.2 by mistake, because
7220 the server has no idea that the event for p1.2 had not been
7221 handled yet.
7223 The server side must similarly ignore resume actions for the
7224 thread that has a pending %Stopped notification (and any other
7225 threads with events pending), until GDB acks the notification
7226 with vStopped. Otherwise, e.g., the following case is
7227 mishandled:
7229 #1 => g (or any other packet)
7230 #2 <= [registers]
7231 #3 <= %Stopped T05 p1.2
7232 #4 => vCont s:p1.1;c
7233 #5 <= OK
7235 Above, the server must not resume thread p1.2. GDB can't know
7236 that p1.2 stopped until it acks the %Stopped notification, and
7237 since from GDB's perspective all threads should be running, it
7238 sends a "c" action.
7240 Finally, special care must also be given to handling fork/vfork
7241 events. A (v)fork event actually tells us that two processes
7242 stopped -- the parent and the child. Until we follow the fork,
7243 we must not resume the child. Therefore, if we have a pending
7244 fork follow, we must not send a global wildcard resume action
7245 (vCont;c). We can still send process-wide wildcards though. */
7247 /* Start by assuming a global wildcard (vCont;c) is possible. */
7248 bool may_global_wildcard_vcont = true;
7250 /* And assume every process is individually wildcard-able too. */
7251 for (inferior *inf : all_non_exited_inferiors (this))
7253 remote_inferior *priv = get_remote_inferior (inf);
7255 priv->may_wildcard_vcont = true;
7258 /* Check for any pending events (not reported or processed yet) and
7259 disable process and global wildcard resumes appropriately. */
7260 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7262 bool any_pending_vcont_resume = false;
7264 for (thread_info *tp : all_non_exited_threads (this))
7266 remote_thread_info *priv = get_remote_thread_info (tp);
7268 /* If a thread of a process is not meant to be resumed, then we
7269 can't wildcard that process. */
7270 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7272 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7274 /* And if we can't wildcard a process, we can't wildcard
7275 everything either. */
7276 may_global_wildcard_vcont = false;
7277 continue;
7280 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7281 any_pending_vcont_resume = true;
7283 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7284 then we can't do a global wildcard, as that would resume the
7285 pending child. */
7286 if (thread_pending_child_status (tp) != nullptr)
7287 may_global_wildcard_vcont = false;
7290 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7291 do. */
7292 if (!any_pending_vcont_resume)
7293 return;
7295 /* Now let's build the vCont packet(s). Actions must be appended
7296 from narrower to wider scopes (thread -> process -> global). If
7297 we end up with too many actions for a single packet vcont_builder
7298 flushes the current vCont packet to the remote side and starts a
7299 new one. */
7300 struct vcont_builder vcont_builder (this);
7302 /* Threads first. */
7303 for (thread_info *tp : all_non_exited_threads (this))
7305 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7307 /* If the thread was previously vCont-resumed, no need to send a specific
7308 action for it. If we didn't receive a resume request for it, don't
7309 send an action for it either. */
7310 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7311 continue;
7313 gdb_assert (!thread_is_in_step_over_chain (tp));
7315 /* We should never be commit-resuming a thread that has a stop reply.
7316 Otherwise, we would end up reporting a stop event for a thread while
7317 it is running on the remote target. */
7318 remote_state *rs = get_remote_state ();
7319 for (const auto &stop_reply : rs->stop_reply_queue)
7320 gdb_assert (stop_reply->ptid != tp->ptid);
7322 const resumed_pending_vcont_info &info
7323 = remote_thr->resumed_pending_vcont_info ();
7325 /* Check if we need to send a specific action for this thread. If not,
7326 it will be included in a wildcard resume instead. */
7327 if (info.step || info.sig != GDB_SIGNAL_0
7328 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7329 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7331 remote_thr->set_resumed ();
7334 /* Now check whether we can send any process-wide wildcard. This is
7335 to avoid sending a global wildcard in the case nothing is
7336 supposed to be resumed. */
7337 bool any_process_wildcard = false;
7339 for (inferior *inf : all_non_exited_inferiors (this))
7341 if (get_remote_inferior (inf)->may_wildcard_vcont)
7343 any_process_wildcard = true;
7344 break;
7348 if (any_process_wildcard)
7350 /* If all processes are wildcard-able, then send a single "c"
7351 action, otherwise, send an "all (-1) threads of process"
7352 continue action for each running process, if any. */
7353 if (may_global_wildcard_vcont)
7355 vcont_builder.push_action (minus_one_ptid,
7356 false, GDB_SIGNAL_0);
7358 else
7360 for (inferior *inf : all_non_exited_inferiors (this))
7362 if (get_remote_inferior (inf)->may_wildcard_vcont)
7364 vcont_builder.push_action (ptid_t (inf->pid),
7365 false, GDB_SIGNAL_0);
7371 vcont_builder.flush ();
7374 /* Implementation of target_has_pending_events. */
7376 bool
7377 remote_target::has_pending_events ()
7379 if (target_can_async_p ())
7381 remote_state *rs = get_remote_state ();
7383 if (rs->async_event_handler_marked ())
7384 return true;
7386 /* Note that BUFCNT can be negative, indicating sticky
7387 error. */
7388 if (rs->remote_desc->bufcnt != 0)
7389 return true;
7391 return false;
7396 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7397 thread, all threads of a remote process, or all threads of all
7398 processes. */
7400 void
7401 remote_target::remote_stop_ns (ptid_t ptid)
7403 struct remote_state *rs = get_remote_state ();
7404 char *p = rs->buf.data ();
7405 char *endp = p + get_remote_packet_size ();
7407 /* If any thread that needs to stop was resumed but pending a vCont
7408 resume, generate a phony stop_reply. However, first check
7409 whether the thread wasn't resumed with a signal. Generating a
7410 phony stop in that case would result in losing the signal. */
7411 bool needs_commit = false;
7412 for (thread_info *tp : all_non_exited_threads (this, ptid))
7414 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7416 if (remote_thr->get_resume_state ()
7417 == resume_state::RESUMED_PENDING_VCONT)
7419 const resumed_pending_vcont_info &info
7420 = remote_thr->resumed_pending_vcont_info ();
7421 if (info.sig != GDB_SIGNAL_0)
7423 /* This signal must be forwarded to the inferior. We
7424 could commit-resume just this thread, but its simpler
7425 to just commit-resume everything. */
7426 needs_commit = true;
7427 break;
7432 if (needs_commit)
7433 commit_resumed ();
7434 else
7435 for (thread_info *tp : all_non_exited_threads (this, ptid))
7437 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7439 if (remote_thr->get_resume_state ()
7440 == resume_state::RESUMED_PENDING_VCONT)
7442 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7443 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7444 tp->ptid.lwp (),
7445 pulongest (tp->ptid.tid ()));
7447 /* Check that the thread wasn't resumed with a signal.
7448 Generating a phony stop would result in losing the
7449 signal. */
7450 const resumed_pending_vcont_info &info
7451 = remote_thr->resumed_pending_vcont_info ();
7452 gdb_assert (info.sig == GDB_SIGNAL_0);
7454 stop_reply_up sr = std::make_unique<stop_reply> ();
7455 sr->ptid = tp->ptid;
7456 sr->rs = rs;
7457 sr->ws.set_stopped (GDB_SIGNAL_0);
7458 sr->arch = tp->inf->arch ();
7459 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7460 sr->watch_data_address = 0;
7461 sr->core = 0;
7462 this->push_stop_reply (std::move (sr));
7464 /* Pretend that this thread was actually resumed on the
7465 remote target, then stopped. If we leave it in the
7466 RESUMED_PENDING_VCONT state and the commit_resumed
7467 method is called while the stop reply is still in the
7468 queue, we'll end up reporting a stop event to the core
7469 for that thread while it is running on the remote
7470 target... that would be bad. */
7471 remote_thr->set_resumed ();
7475 if (!rs->supports_vCont.t)
7476 error (_("Remote server does not support stopping threads"));
7478 if (ptid == minus_one_ptid
7479 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7480 p += xsnprintf (p, endp - p, "vCont;t");
7481 else
7483 ptid_t nptid;
7485 p += xsnprintf (p, endp - p, "vCont;t:");
7487 if (ptid.is_pid ())
7488 /* All (-1) threads of process. */
7489 nptid = ptid_t (ptid.pid (), -1);
7490 else
7492 /* Small optimization: if we already have a stop reply for
7493 this thread, no use in telling the stub we want this
7494 stopped. */
7495 if (peek_stop_reply (ptid))
7496 return;
7498 nptid = ptid;
7501 write_ptid (p, endp, nptid);
7504 /* In non-stop, we get an immediate OK reply. The stop reply will
7505 come in asynchronously by notification. */
7506 putpkt (rs->buf);
7507 getpkt (&rs->buf);
7508 if (strcmp (rs->buf.data (), "OK") != 0)
7509 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7510 rs->buf.data ());
7513 /* All-stop version of target_interrupt. Sends a break or a ^C to
7514 interrupt the remote target. It is undefined which thread of which
7515 process reports the interrupt. */
7517 void
7518 remote_target::remote_interrupt_as ()
7520 struct remote_state *rs = get_remote_state ();
7522 rs->ctrlc_pending_p = 1;
7524 /* If the inferior is stopped already, but the core didn't know
7525 about it yet, just ignore the request. The pending stop events
7526 will be collected in remote_wait. */
7527 if (stop_reply_queue_length () > 0)
7528 return;
7530 /* Send interrupt_sequence to remote target. */
7531 send_interrupt_sequence ();
7534 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7535 the remote target. It is undefined which thread of which process
7536 reports the interrupt. Throws an error if the packet is not
7537 supported by the server. */
7539 void
7540 remote_target::remote_interrupt_ns ()
7542 struct remote_state *rs = get_remote_state ();
7543 char *p = rs->buf.data ();
7544 char *endp = p + get_remote_packet_size ();
7546 xsnprintf (p, endp - p, "vCtrlC");
7548 /* In non-stop, we get an immediate OK reply. The stop reply will
7549 come in asynchronously by notification. */
7550 putpkt (rs->buf);
7551 getpkt (&rs->buf);
7553 packet_result result = m_features.packet_ok (rs->buf, PACKET_vCtrlC);
7554 switch (result.status ())
7556 case PACKET_OK:
7557 break;
7558 case PACKET_UNKNOWN:
7559 error (_("No support for interrupting the remote target."));
7560 case PACKET_ERROR:
7561 error (_("Interrupting target failed: %s"), result.err_msg ());
7565 /* Implement the to_stop function for the remote targets. */
7567 void
7568 remote_target::stop (ptid_t ptid)
7570 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7572 if (target_is_non_stop_p ())
7573 remote_stop_ns (ptid);
7574 else
7576 /* We don't currently have a way to transparently pause the
7577 remote target in all-stop mode. Interrupt it instead. */
7578 remote_interrupt_as ();
7582 /* Implement the to_interrupt function for the remote targets. */
7584 void
7585 remote_target::interrupt ()
7587 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7589 if (target_is_non_stop_p ())
7590 remote_interrupt_ns ();
7591 else
7592 remote_interrupt_as ();
7595 /* Implement the to_pass_ctrlc function for the remote targets. */
7597 void
7598 remote_target::pass_ctrlc ()
7600 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7602 struct remote_state *rs = get_remote_state ();
7604 /* If we're starting up, we're not fully synced yet. Quit
7605 immediately. */
7606 if (rs->starting_up)
7607 quit ();
7608 /* If ^C has already been sent once, offer to disconnect. */
7609 else if (rs->ctrlc_pending_p)
7610 interrupt_query ();
7611 else
7612 target_interrupt ();
7615 /* Ask the user what to do when an interrupt is received. */
7617 void
7618 remote_target::interrupt_query ()
7620 struct remote_state *rs = get_remote_state ();
7622 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7624 if (query (_("The target is not responding to interrupt requests.\n"
7625 "Stop debugging it? ")))
7627 remote_unpush_target (this);
7628 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7631 else
7633 if (query (_("Interrupted while waiting for the program.\n"
7634 "Give up waiting? ")))
7635 quit ();
7639 /* Enable/disable target terminal ownership. Most targets can use
7640 terminal groups to control terminal ownership. Remote targets are
7641 different in that explicit transfer of ownership to/from GDB/target
7642 is required. */
7644 void
7645 remote_target::terminal_inferior ()
7647 /* NOTE: At this point we could also register our selves as the
7648 recipient of all input. Any characters typed could then be
7649 passed on down to the target. */
7652 void
7653 remote_target::terminal_ours ()
7657 static void
7658 remote_console_output (const char *msg, ui_file *stream)
7660 const char *p;
7662 for (p = msg; p[0] && p[1]; p += 2)
7664 char tb[2];
7665 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7667 tb[0] = c;
7668 tb[1] = 0;
7669 stream->puts (tb);
7671 stream->flush ();
7674 /* Return the length of the stop reply queue. */
7677 remote_target::stop_reply_queue_length ()
7679 remote_state *rs = get_remote_state ();
7680 return rs->stop_reply_queue.size ();
7683 static void
7684 remote_notif_stop_parse (remote_target *remote,
7685 const notif_client *self, const char *buf,
7686 struct notif_event *event)
7688 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7691 static void
7692 remote_notif_stop_ack (remote_target *remote,
7693 const notif_client *self, const char *buf,
7694 notif_event_up event)
7696 stop_reply_up stop_reply = as_stop_reply_up (std::move (event));
7698 /* acknowledge */
7699 putpkt (remote, self->ack_command);
7701 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7702 the notification. It was left in the queue because we need to
7703 acknowledge it and pull the rest of the notifications out. */
7704 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7705 remote->push_stop_reply (std::move (stop_reply));
7708 static int
7709 remote_notif_stop_can_get_pending_events (remote_target *remote,
7710 const notif_client *self)
7712 /* We can't get pending events in remote_notif_process for
7713 notification stop, and we have to do this in remote_wait_ns
7714 instead. If we fetch all queued events from stub, remote stub
7715 may exit and we have no chance to process them back in
7716 remote_wait_ns. */
7717 remote_state *rs = remote->get_remote_state ();
7718 rs->mark_async_event_handler ();
7719 return 0;
7722 static notif_event_up
7723 remote_notif_stop_alloc_reply ()
7725 return notif_event_up (new struct stop_reply ());
7728 /* A client of notification Stop. */
7730 const notif_client notif_client_stop =
7732 "Stop",
7733 "vStopped",
7734 remote_notif_stop_parse,
7735 remote_notif_stop_ack,
7736 remote_notif_stop_can_get_pending_events,
7737 remote_notif_stop_alloc_reply,
7738 REMOTE_NOTIF_STOP,
7741 /* If CONTEXT contains any fork/vfork/clone child threads that have
7742 not been reported yet, remove them from the CONTEXT list. If such
7743 a thread exists it is because we are stopped at a fork/vfork/clone
7744 catchpoint and have not yet called follow_fork/follow_clone, which
7745 will set up the host-side data structures for the new child. */
7747 void
7748 remote_target::remove_new_children (threads_listing_context *context)
7750 const notif_client *notif = &notif_client_stop;
7752 /* For any threads stopped at a (v)fork/clone event, remove the
7753 corresponding child threads from the CONTEXT list. */
7754 for (thread_info *thread : all_non_exited_threads (this))
7756 const target_waitstatus *ws = thread_pending_child_status (thread);
7758 if (ws == nullptr)
7759 continue;
7761 context->remove_thread (ws->child_ptid ());
7764 /* Check for any pending (v)fork/clone events (not reported or
7765 processed yet) in process PID and remove those child threads from
7766 the CONTEXT list as well. */
7767 remote_notif_get_pending_events (notif);
7768 for (auto &event : get_remote_state ()->stop_reply_queue)
7769 if (is_new_child_status (event->ws.kind ()))
7770 context->remove_thread (event->ws.child_ptid ());
7771 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7772 context->remove_thread (event->ptid);
7775 /* Check whether any event pending in the vStopped queue would prevent a
7776 global or process wildcard vCont action. Set *may_global_wildcard to
7777 false if we can't do a global wildcard (vCont;c), and clear the event
7778 inferior's may_wildcard_vcont flag if we can't do a process-wide
7779 wildcard resume (vCont;c:pPID.-1). */
7781 void
7782 remote_target::check_pending_events_prevent_wildcard_vcont
7783 (bool *may_global_wildcard)
7785 const notif_client *notif = &notif_client_stop;
7787 remote_notif_get_pending_events (notif);
7788 for (auto &event : get_remote_state ()->stop_reply_queue)
7790 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7791 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7792 continue;
7794 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7795 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7796 *may_global_wildcard = false;
7798 /* This may be the first time we heard about this process.
7799 Regardless, we must not do a global wildcard resume, otherwise
7800 we'd resume this process too. */
7801 *may_global_wildcard = false;
7802 if (event->ptid != null_ptid)
7804 inferior *inf = find_inferior_ptid (this, event->ptid);
7805 if (inf != NULL)
7806 get_remote_inferior (inf)->may_wildcard_vcont = false;
7811 /* Discard all pending stop replies of inferior INF. */
7813 void
7814 remote_target::discard_pending_stop_replies (struct inferior *inf)
7816 struct remote_state *rs = get_remote_state ();
7817 struct remote_notif_state *rns = rs->notif_state;
7819 /* This function can be notified when an inferior exists. When the
7820 target is not remote, the notification state is NULL. */
7821 if (rs->remote_desc == NULL)
7822 return;
7824 struct notif_event *notif_event
7825 = rns->pending_event[notif_client_stop.id].get ();
7826 auto *reply = static_cast<stop_reply *> (notif_event);
7828 /* Discard the in-flight notification. */
7829 if (reply != NULL && reply->ptid.pid () == inf->pid)
7831 /* Leave the notification pending, since the server expects that
7832 we acknowledge it with vStopped. But clear its contents, so
7833 that later on when we acknowledge it, we also discard it. */
7834 remote_debug_printf
7835 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7836 reply->ptid.to_string().c_str(),
7837 reply->ws.to_string ().c_str ());
7838 reply->ws.set_ignore ();
7841 /* Discard the stop replies we have already pulled with
7842 vStopped. */
7843 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7844 rs->stop_reply_queue.end (),
7845 [=] (const stop_reply_up &event)
7847 return event->ptid.pid () == inf->pid;
7849 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7850 remote_debug_printf
7851 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7852 (*it)->ptid.to_string().c_str(),
7853 (*it)->ws.to_string ().c_str ());
7854 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7857 /* Discard the stop replies for RS in stop_reply_queue. */
7859 void
7860 remote_target::discard_pending_stop_replies_in_queue ()
7862 remote_state *rs = get_remote_state ();
7864 /* Discard the stop replies we have already pulled with
7865 vStopped. */
7866 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7867 rs->stop_reply_queue.end (),
7868 [=] (const stop_reply_up &event)
7870 return event->rs == rs;
7872 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7875 /* Remove the first reply in 'stop_reply_queue' which matches
7876 PTID. */
7878 stop_reply_up
7879 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7881 remote_state *rs = get_remote_state ();
7883 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7884 rs->stop_reply_queue.end (),
7885 [=] (const stop_reply_up &event)
7887 return event->ptid.matches (ptid);
7889 stop_reply_up result;
7890 if (iter != rs->stop_reply_queue.end ())
7892 result = std::move (*iter);
7893 rs->stop_reply_queue.erase (iter);
7896 if (notif_debug)
7897 gdb_printf (gdb_stdlog,
7898 "notif: discard queued event: 'Stop' in %s\n",
7899 ptid.to_string ().c_str ());
7901 return result;
7904 /* Look for a queued stop reply belonging to PTID. If one is found,
7905 remove it from the queue, and return it. Returns NULL if none is
7906 found. If there are still queued events left to process, tell the
7907 event loop to get back to target_wait soon. */
7909 stop_reply_up
7910 remote_target::queued_stop_reply (ptid_t ptid)
7912 remote_state *rs = get_remote_state ();
7913 stop_reply_up r = remote_notif_remove_queued_reply (ptid);
7915 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7917 /* There's still at least an event left. */
7918 rs->mark_async_event_handler ();
7921 return r;
7924 /* Push a fully parsed stop reply in the stop reply queue. Since we
7925 know that we now have at least one queued event left to pass to the
7926 core side, tell the event loop to get back to target_wait soon. */
7928 void
7929 remote_target::push_stop_reply (stop_reply_up new_event)
7931 remote_state *rs = get_remote_state ();
7932 rs->stop_reply_queue.push_back (std::move (new_event));
7934 if (notif_debug)
7935 gdb_printf (gdb_stdlog,
7936 "notif: push 'Stop' %s to queue %d\n",
7937 new_event->ptid.to_string ().c_str (),
7938 int (rs->stop_reply_queue.size ()));
7940 /* Mark the pending event queue only if async mode is currently enabled.
7941 If async mode is not currently enabled, then, if it later becomes
7942 enabled, and there are events in this queue, we will mark the event
7943 token at that point, see remote_target::async. */
7944 if (target_is_async_p ())
7945 rs->mark_async_event_handler ();
7948 /* Returns true if we have a stop reply for PTID. */
7951 remote_target::peek_stop_reply (ptid_t ptid)
7953 remote_state *rs = get_remote_state ();
7954 for (auto &event : rs->stop_reply_queue)
7955 if (ptid == event->ptid
7956 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7957 return 1;
7958 return 0;
7961 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7962 starting with P and ending with PEND matches PREFIX. */
7964 static int
7965 strprefix (const char *p, const char *pend, const char *prefix)
7967 for ( ; p < pend; p++, prefix++)
7968 if (*p != *prefix)
7969 return 0;
7970 return *prefix == '\0';
7973 /* Parse the stop reply in BUF. Either the function succeeds, and the
7974 result is stored in EVENT, or throws an error. */
7976 void
7977 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7979 remote_arch_state *rsa = NULL;
7980 ULONGEST addr;
7981 const char *p;
7982 int skipregs = 0;
7984 event->ptid = null_ptid;
7985 event->rs = get_remote_state ();
7986 event->ws.set_ignore ();
7987 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7988 event->regcache.clear ();
7989 event->core = -1;
7991 switch (buf[0])
7993 case 'T': /* Status with PC, SP, FP, ... */
7994 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7995 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7996 ss = signal number
7997 n... = register number
7998 r... = register contents
8001 p = &buf[3]; /* after Txx */
8002 while (*p)
8004 const char *p1;
8005 int fieldsize;
8007 p1 = strchr (p, ':');
8008 if (p1 == NULL)
8009 error (_("Malformed packet(a) (missing colon): %s\n\
8010 Packet: '%s'\n"),
8011 p, buf);
8012 if (p == p1)
8013 error (_("Malformed packet(a) (missing register number): %s\n\
8014 Packet: '%s'\n"),
8015 p, buf);
8017 /* Some "registers" are actually extended stop information.
8018 Note if you're adding a new entry here: GDB 7.9 and
8019 earlier assume that all register "numbers" that start
8020 with an hex digit are real register numbers. Make sure
8021 the server only sends such a packet if it knows the
8022 client understands it. */
8024 if (strprefix (p, p1, "thread"))
8025 event->ptid = read_ptid (++p1, &p);
8026 else if (strprefix (p, p1, "syscall_entry"))
8028 ULONGEST sysno;
8030 p = unpack_varlen_hex (++p1, &sysno);
8031 event->ws.set_syscall_entry ((int) sysno);
8033 else if (strprefix (p, p1, "syscall_return"))
8035 ULONGEST sysno;
8037 p = unpack_varlen_hex (++p1, &sysno);
8038 event->ws.set_syscall_return ((int) sysno);
8040 else if (strprefix (p, p1, "watch")
8041 || strprefix (p, p1, "rwatch")
8042 || strprefix (p, p1, "awatch"))
8044 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
8045 p = unpack_varlen_hex (++p1, &addr);
8046 event->watch_data_address = (CORE_ADDR) addr;
8048 else if (strprefix (p, p1, "swbreak"))
8050 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
8052 /* Make sure the stub doesn't forget to indicate support
8053 with qSupported. */
8054 if (m_features.packet_support (PACKET_swbreak_feature)
8055 != PACKET_ENABLE)
8056 error (_("Unexpected swbreak stop reason"));
8058 /* The value part is documented as "must be empty",
8059 though we ignore it, in case we ever decide to make
8060 use of it in a backward compatible way. */
8061 p = strchrnul (p1 + 1, ';');
8063 else if (strprefix (p, p1, "hwbreak"))
8065 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
8067 /* Make sure the stub doesn't forget to indicate support
8068 with qSupported. */
8069 if (m_features.packet_support (PACKET_hwbreak_feature)
8070 != PACKET_ENABLE)
8071 error (_("Unexpected hwbreak stop reason"));
8073 /* See above. */
8074 p = strchrnul (p1 + 1, ';');
8076 else if (strprefix (p, p1, "library"))
8078 event->ws.set_loaded ();
8079 p = strchrnul (p1 + 1, ';');
8081 else if (strprefix (p, p1, "replaylog"))
8083 event->ws.set_no_history ();
8084 /* p1 will indicate "begin" or "end", but it makes
8085 no difference for now, so ignore it. */
8086 p = strchrnul (p1 + 1, ';');
8088 else if (strprefix (p, p1, "core"))
8090 ULONGEST c;
8092 p = unpack_varlen_hex (++p1, &c);
8093 event->core = c;
8095 else if (strprefix (p, p1, "fork"))
8096 event->ws.set_forked (read_ptid (++p1, &p));
8097 else if (strprefix (p, p1, "vfork"))
8098 event->ws.set_vforked (read_ptid (++p1, &p));
8099 else if (strprefix (p, p1, "clone"))
8100 event->ws.set_thread_cloned (read_ptid (++p1, &p));
8101 else if (strprefix (p, p1, "vforkdone"))
8103 event->ws.set_vfork_done ();
8104 p = strchrnul (p1 + 1, ';');
8106 else if (strprefix (p, p1, "exec"))
8108 ULONGEST ignored;
8109 int pathlen;
8111 /* Determine the length of the execd pathname. */
8112 p = unpack_varlen_hex (++p1, &ignored);
8113 pathlen = (p - p1) / 2;
8115 /* Save the pathname for event reporting and for
8116 the next run command. */
8117 gdb::unique_xmalloc_ptr<char> pathname
8118 ((char *) xmalloc (pathlen + 1));
8119 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8120 pathname.get ()[pathlen] = '\0';
8122 /* This is freed during event handling. */
8123 event->ws.set_execd (std::move (pathname));
8125 /* Skip the registers included in this packet, since
8126 they may be for an architecture different from the
8127 one used by the original program. */
8128 skipregs = 1;
8130 else if (strprefix (p, p1, "create"))
8132 event->ws.set_thread_created ();
8133 p = strchrnul (p1 + 1, ';');
8135 else
8137 ULONGEST pnum;
8138 const char *p_temp;
8140 if (skipregs)
8142 p = strchrnul (p1 + 1, ';');
8143 p++;
8144 continue;
8147 /* Maybe a real ``P'' register number. */
8148 p_temp = unpack_varlen_hex (p, &pnum);
8149 /* If the first invalid character is the colon, we got a
8150 register number. Otherwise, it's an unknown stop
8151 reason. */
8152 if (p_temp == p1)
8154 /* If we haven't parsed the event's thread yet, find
8155 it now, in order to find the architecture of the
8156 reported expedited registers. */
8157 if (event->ptid == null_ptid)
8159 /* If there is no thread-id information then leave
8160 the event->ptid as null_ptid. Later in
8161 process_stop_reply we will pick a suitable
8162 thread. */
8163 const char *thr = strstr (p1 + 1, ";thread:");
8164 if (thr != NULL)
8165 event->ptid = read_ptid (thr + strlen (";thread:"),
8166 NULL);
8169 if (rsa == NULL)
8171 inferior *inf
8172 = (event->ptid == null_ptid
8173 ? NULL
8174 : find_inferior_ptid (this, event->ptid));
8175 /* If this is the first time we learn anything
8176 about this process, skip the registers
8177 included in this packet, since we don't yet
8178 know which architecture to use to parse them.
8179 We'll determine the architecture later when
8180 we process the stop reply and retrieve the
8181 target description, via
8182 remote_notice_new_inferior ->
8183 post_create_inferior. */
8184 if (inf == NULL)
8186 p = strchrnul (p1 + 1, ';');
8187 p++;
8188 continue;
8191 event->arch = inf->arch ();
8192 rsa = event->rs->get_remote_arch_state (event->arch);
8195 packet_reg *reg
8196 = packet_reg_from_pnum (event->arch, rsa, pnum);
8197 cached_reg_t cached_reg;
8199 if (reg == NULL)
8200 error (_("Remote sent bad register number %s: %s\n\
8201 Packet: '%s'\n"),
8202 hex_string (pnum), p, buf);
8204 cached_reg.num = reg->regnum;
8205 cached_reg.data.reset ((gdb_byte *)
8206 xmalloc (register_size (event->arch,
8207 reg->regnum)));
8209 p = p1 + 1;
8210 fieldsize = hex2bin (p, cached_reg.data.get (),
8211 register_size (event->arch, reg->regnum));
8212 p += 2 * fieldsize;
8213 if (fieldsize < register_size (event->arch, reg->regnum))
8214 warning (_("Remote reply is too short: %s"), buf);
8216 event->regcache.push_back (std::move (cached_reg));
8218 else
8220 /* Not a number. Silently skip unknown optional
8221 info. */
8222 p = strchrnul (p1 + 1, ';');
8226 if (*p != ';')
8227 error (_("Remote register badly formatted: %s\nhere: %s"),
8228 buf, p);
8229 ++p;
8232 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8233 break;
8235 [[fallthrough]];
8236 case 'S': /* Old style status, just signal only. */
8238 int sig;
8240 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8241 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8242 event->ws.set_stopped ((enum gdb_signal) sig);
8243 else
8244 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8246 break;
8247 case 'w': /* Thread exited. */
8249 ULONGEST value;
8251 p = unpack_varlen_hex (&buf[1], &value);
8252 event->ws.set_thread_exited (value);
8253 if (*p != ';')
8254 error (_("stop reply packet badly formatted: %s"), buf);
8255 event->ptid = read_ptid (++p, NULL);
8256 break;
8258 case 'W': /* Target exited. */
8259 case 'X':
8261 ULONGEST value;
8263 /* GDB used to accept only 2 hex chars here. Stubs should
8264 only send more if they detect GDB supports multi-process
8265 support. */
8266 p = unpack_varlen_hex (&buf[1], &value);
8268 if (buf[0] == 'W')
8270 /* The remote process exited. */
8271 event->ws.set_exited (value);
8273 else
8275 /* The remote process exited with a signal. */
8276 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8277 event->ws.set_signalled ((enum gdb_signal) value);
8278 else
8279 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8282 /* If no process is specified, return null_ptid, and let the
8283 caller figure out the right process to use. */
8284 int pid = 0;
8285 if (*p == '\0')
8287 else if (*p == ';')
8289 p++;
8291 if (*p == '\0')
8293 else if (startswith (p, "process:"))
8295 ULONGEST upid;
8297 p += sizeof ("process:") - 1;
8298 unpack_varlen_hex (p, &upid);
8299 pid = upid;
8301 else
8302 error (_("unknown stop reply packet: %s"), buf);
8304 else
8305 error (_("unknown stop reply packet: %s"), buf);
8306 event->ptid = ptid_t (pid);
8308 break;
8309 case 'N':
8310 event->ws.set_no_resumed ();
8311 event->ptid = minus_one_ptid;
8312 break;
8316 /* When the stub wants to tell GDB about a new notification reply, it
8317 sends a notification (%Stop, for example). Those can come it at
8318 any time, hence, we have to make sure that any pending
8319 putpkt/getpkt sequence we're making is finished, before querying
8320 the stub for more events with the corresponding ack command
8321 (vStopped, for example). E.g., if we started a vStopped sequence
8322 immediately upon receiving the notification, something like this
8323 could happen:
8325 1.1) --> Hg 1
8326 1.2) <-- OK
8327 1.3) --> g
8328 1.4) <-- %Stop
8329 1.5) --> vStopped
8330 1.6) <-- (registers reply to step #1.3)
8332 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8333 query.
8335 To solve this, whenever we parse a %Stop notification successfully,
8336 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8337 doing whatever we were doing:
8339 2.1) --> Hg 1
8340 2.2) <-- OK
8341 2.3) --> g
8342 2.4) <-- %Stop
8343 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8344 2.5) <-- (registers reply to step #2.3)
8346 Eventually after step #2.5, we return to the event loop, which
8347 notices there's an event on the
8348 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8349 associated callback --- the function below. At this point, we're
8350 always safe to start a vStopped sequence. :
8352 2.6) --> vStopped
8353 2.7) <-- T05 thread:2
8354 2.8) --> vStopped
8355 2.9) --> OK
8358 void
8359 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8361 struct remote_state *rs = get_remote_state ();
8363 if (rs->notif_state->pending_event[nc->id] != NULL)
8365 if (notif_debug)
8366 gdb_printf (gdb_stdlog,
8367 "notif: process: '%s' ack pending event\n",
8368 nc->name);
8370 /* acknowledge */
8371 nc->ack (this, nc, rs->buf.data (),
8372 std::move (rs->notif_state->pending_event[nc->id]));
8374 while (1)
8376 getpkt (&rs->buf);
8377 if (strcmp (rs->buf.data (), "OK") == 0)
8378 break;
8379 else
8380 remote_notif_ack (this, nc, rs->buf.data ());
8383 else
8385 if (notif_debug)
8386 gdb_printf (gdb_stdlog,
8387 "notif: process: '%s' no pending reply\n",
8388 nc->name);
8392 /* Wrapper around remote_target::remote_notif_get_pending_events to
8393 avoid having to export the whole remote_target class. */
8395 void
8396 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8398 remote->remote_notif_get_pending_events (nc);
8401 /* Called from process_stop_reply when the stop packet we are responding
8402 to didn't include a process-id or thread-id. STATUS is the stop event
8403 we are responding to.
8405 It is the task of this function to select a suitable thread (or process)
8406 and return its ptid, this is the thread (or process) we will assume the
8407 stop event came from.
8409 In some cases there isn't really any choice about which thread (or
8410 process) is selected, a basic remote with a single process containing a
8411 single thread might choose not to send any process-id or thread-id in
8412 its stop packets, this function will select and return the one and only
8413 thread.
8415 However, if a target supports multiple threads (or processes) and still
8416 doesn't include a thread-id (or process-id) in its stop packet then
8417 first, this is a badly behaving target, and second, we're going to have
8418 to select a thread (or process) at random and use that. This function
8419 will print a warning to the user if it detects that there is the
8420 possibility that GDB is guessing which thread (or process) to
8421 report.
8423 Note that this is called before GDB fetches the updated thread list from the
8424 target. So it's possible for the stop reply to be ambiguous and for GDB to
8425 not realize it. For example, if there's initially one thread, the target
8426 spawns a second thread, and then sends a stop reply without an id that
8427 concerns the first thread. GDB will assume the stop reply is about the
8428 first thread - the only thread it knows about - without printing a warning.
8429 Anyway, if the remote meant for the stop reply to be about the second thread,
8430 then it would be really broken, because GDB doesn't know about that thread
8431 yet. */
8433 ptid_t
8434 remote_target::select_thread_for_ambiguous_stop_reply
8435 (const target_waitstatus &status)
8437 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8439 /* Some stop events apply to all threads in an inferior, while others
8440 only apply to a single thread. */
8441 bool process_wide_stop
8442 = (status.kind () == TARGET_WAITKIND_EXITED
8443 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8445 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8447 thread_info *first_resumed_thread = nullptr;
8448 bool ambiguous = false;
8450 /* Consider all non-exited threads of the target, find the first resumed
8451 one. */
8452 for (thread_info *thr : all_non_exited_threads (this))
8454 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8456 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8457 continue;
8459 if (first_resumed_thread == nullptr)
8460 first_resumed_thread = thr;
8461 else if (!process_wide_stop
8462 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8463 ambiguous = true;
8466 gdb_assert (first_resumed_thread != nullptr);
8468 remote_debug_printf ("first resumed thread is %s",
8469 pid_to_str (first_resumed_thread->ptid).c_str ());
8470 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8472 /* Warn if the remote target is sending ambiguous stop replies. */
8473 if (ambiguous)
8475 static bool warned = false;
8477 if (!warned)
8479 /* If you are seeing this warning then the remote target has
8480 stopped without specifying a thread-id, but the target
8481 does have multiple threads (or inferiors), and so GDB is
8482 having to guess which thread stopped.
8484 Examples of what might cause this are the target sending
8485 and 'S' stop packet, or a 'T' stop packet and not
8486 including a thread-id.
8488 Additionally, the target might send a 'W' or 'X packet
8489 without including a process-id, when the target has
8490 multiple running inferiors. */
8491 if (process_wide_stop)
8492 warning (_("multi-inferior target stopped without "
8493 "sending a process-id, using first "
8494 "non-exited inferior"));
8495 else
8496 warning (_("multi-threaded target stopped without "
8497 "sending a thread-id, using first "
8498 "non-exited thread"));
8499 warned = true;
8503 /* If this is a stop for all threads then don't use a particular threads
8504 ptid, instead create a new ptid where only the pid field is set. */
8505 if (process_wide_stop)
8506 return ptid_t (first_resumed_thread->ptid.pid ());
8507 else
8508 return first_resumed_thread->ptid;
8511 /* Called when it is decided that STOP_REPLY holds the info of the
8512 event that is to be returned to the core. This function always
8513 destroys STOP_REPLY. */
8515 ptid_t
8516 remote_target::process_stop_reply (stop_reply_up stop_reply,
8517 struct target_waitstatus *status)
8519 *status = stop_reply->ws;
8520 ptid_t ptid = stop_reply->ptid;
8522 /* If no thread/process was reported by the stub then select a suitable
8523 thread/process. */
8524 if (ptid == null_ptid)
8525 ptid = select_thread_for_ambiguous_stop_reply (*status);
8526 gdb_assert (ptid != null_ptid);
8528 if (status->kind () != TARGET_WAITKIND_EXITED
8529 && status->kind () != TARGET_WAITKIND_SIGNALLED
8530 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8532 remote_notice_new_inferior (ptid, false);
8534 /* Expedited registers. */
8535 if (!stop_reply->regcache.empty ())
8537 /* 'w' stop replies don't cary expedited registers (which
8538 wouldn't make any sense for a thread that is gone
8539 already). */
8540 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8542 regcache *regcache
8543 = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
8544 stop_reply->arch);
8546 for (cached_reg_t &reg : stop_reply->regcache)
8547 regcache->raw_supply (reg.num, reg.data.get ());
8550 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8551 remote_thr->core = stop_reply->core;
8552 remote_thr->stop_reason = stop_reply->stop_reason;
8553 remote_thr->watch_data_address = stop_reply->watch_data_address;
8555 if (target_is_non_stop_p ())
8557 /* If the target works in non-stop mode, a stop-reply indicates that
8558 only this thread stopped. */
8559 remote_thr->set_not_resumed ();
8561 else
8563 /* If the target works in all-stop mode, a stop-reply indicates that
8564 all the target's threads stopped. */
8565 for (thread_info *tp : all_non_exited_threads (this))
8566 get_remote_thread_info (tp)->set_not_resumed ();
8570 return ptid;
8573 /* The non-stop mode version of target_wait. */
8575 ptid_t
8576 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8577 target_wait_flags options)
8579 struct remote_state *rs = get_remote_state ();
8580 int ret;
8581 bool is_notif = false;
8583 /* If in non-stop mode, get out of getpkt even if a
8584 notification is received. */
8586 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8587 while (1)
8589 if (ret != -1 && !is_notif)
8590 switch (rs->buf[0])
8592 case 'E': /* Error of some sort. */
8593 /* We're out of sync with the target now. Did it continue
8594 or not? We can't tell which thread it was in non-stop,
8595 so just ignore this. */
8596 warning (_("Remote failure reply: %s"), rs->buf.data ());
8597 break;
8598 case 'O': /* Console output. */
8599 remote_console_output (&rs->buf[1], gdb_stdtarg);
8600 break;
8601 default:
8602 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8603 break;
8606 /* Acknowledge a pending stop reply that may have arrived in the
8607 mean time. */
8608 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8609 remote_notif_get_pending_events (&notif_client_stop);
8611 /* If indeed we noticed a stop reply, we're done. */
8612 stop_reply_up stop_reply = queued_stop_reply (ptid);
8613 if (stop_reply != NULL)
8614 return process_stop_reply (std::move (stop_reply), status);
8616 /* Still no event. If we're just polling for an event, then
8617 return to the event loop. */
8618 if (options & TARGET_WNOHANG)
8620 status->set_ignore ();
8621 return minus_one_ptid;
8624 /* Otherwise do a blocking wait. */
8625 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8629 /* Return the first resumed thread. */
8631 static ptid_t
8632 first_remote_resumed_thread (remote_target *target)
8634 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8635 if (tp->resumed ())
8636 return tp->ptid;
8637 return null_ptid;
8640 /* Wait until the remote machine stops, then return, storing status in
8641 STATUS just as `wait' would. */
8643 ptid_t
8644 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8645 target_wait_flags options)
8647 struct remote_state *rs = get_remote_state ();
8648 ptid_t event_ptid = null_ptid;
8649 char *buf;
8650 stop_reply_up stop_reply;
8652 again:
8654 status->set_ignore ();
8656 stop_reply = queued_stop_reply (ptid);
8657 if (stop_reply != NULL)
8659 /* None of the paths that push a stop reply onto the queue should
8660 have set the waiting_for_stop_reply flag. */
8661 gdb_assert (!rs->waiting_for_stop_reply);
8662 event_ptid = process_stop_reply (std::move (stop_reply), status);
8664 else
8666 bool forever = ((options & TARGET_WNOHANG) == 0
8667 && rs->wait_forever_enabled_p);
8669 if (!rs->waiting_for_stop_reply)
8671 status->set_no_resumed ();
8672 return minus_one_ptid;
8675 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8676 _never_ wait for ever -> test on target_is_async_p().
8677 However, before we do that we need to ensure that the caller
8678 knows how to take the target into/out of async mode. */
8679 bool is_notif;
8680 int ret = getpkt (&rs->buf, forever, &is_notif);
8682 /* GDB gets a notification. Return to core as this event is
8683 not interesting. */
8684 if (ret != -1 && is_notif)
8685 return minus_one_ptid;
8687 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8688 return minus_one_ptid;
8690 buf = rs->buf.data ();
8692 /* Assume that the target has acknowledged Ctrl-C unless we receive
8693 an 'F' or 'O' packet. */
8694 if (buf[0] != 'F' && buf[0] != 'O')
8695 rs->ctrlc_pending_p = 0;
8697 switch (buf[0])
8699 case 'E': /* Error of some sort. */
8700 /* We're out of sync with the target now. Did it continue or
8701 not? Not is more likely, so report a stop. */
8702 rs->waiting_for_stop_reply = 0;
8704 warning (_("Remote failure reply: %s"), buf);
8705 status->set_stopped (GDB_SIGNAL_0);
8706 break;
8707 case 'F': /* File-I/O request. */
8708 /* GDB may access the inferior memory while handling the File-I/O
8709 request, but we don't want GDB accessing memory while waiting
8710 for a stop reply. See the comments in putpkt_binary. Set
8711 waiting_for_stop_reply to 0 temporarily. */
8712 rs->waiting_for_stop_reply = 0;
8713 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8714 rs->ctrlc_pending_p = 0;
8715 /* GDB handled the File-I/O request, and the target is running
8716 again. Keep waiting for events. */
8717 rs->waiting_for_stop_reply = 1;
8718 break;
8719 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8721 /* There is a stop reply to handle. */
8722 rs->waiting_for_stop_reply = 0;
8724 stop_reply
8725 = as_stop_reply_up (remote_notif_parse (this,
8726 &notif_client_stop,
8727 rs->buf.data ()));
8729 event_ptid = process_stop_reply (std::move (stop_reply), status);
8730 break;
8732 case 'O': /* Console output. */
8733 remote_console_output (buf + 1, gdb_stdtarg);
8734 break;
8735 case '\0':
8736 if (rs->last_sent_signal != GDB_SIGNAL_0)
8738 /* Zero length reply means that we tried 'S' or 'C' and the
8739 remote system doesn't support it. */
8740 target_terminal::ours_for_output ();
8741 gdb_printf
8742 ("Can't send signals to this remote system. %s not sent.\n",
8743 gdb_signal_to_name (rs->last_sent_signal));
8744 rs->last_sent_signal = GDB_SIGNAL_0;
8745 target_terminal::inferior ();
8747 strcpy (buf, rs->last_sent_step ? "s" : "c");
8748 putpkt (buf);
8749 break;
8751 [[fallthrough]];
8752 default:
8753 warning (_("Invalid remote reply: %s"), buf);
8754 break;
8758 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8759 return minus_one_ptid;
8760 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8762 /* Nothing interesting happened. If we're doing a non-blocking
8763 poll, we're done. Otherwise, go back to waiting. */
8764 if (options & TARGET_WNOHANG)
8765 return minus_one_ptid;
8766 else
8767 goto again;
8769 else if (status->kind () != TARGET_WAITKIND_EXITED
8770 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8772 if (event_ptid != null_ptid)
8773 record_currthread (rs, event_ptid);
8774 else
8775 event_ptid = first_remote_resumed_thread (this);
8777 else
8779 /* A process exit. Invalidate our notion of current thread. */
8780 record_currthread (rs, minus_one_ptid);
8781 /* It's possible that the packet did not include a pid. */
8782 if (event_ptid == null_ptid)
8783 event_ptid = first_remote_resumed_thread (this);
8784 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8785 if (event_ptid == null_ptid)
8786 event_ptid = magic_null_ptid;
8789 return event_ptid;
8792 /* Wait until the remote machine stops, then return, storing status in
8793 STATUS just as `wait' would. */
8795 ptid_t
8796 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8797 target_wait_flags options)
8799 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8801 remote_state *rs = get_remote_state ();
8803 /* Start by clearing the flag that asks for our wait method to be called,
8804 we'll mark it again at the end if needed. If the target is not in
8805 async mode then the async token should not be marked. */
8806 if (target_is_async_p ())
8807 rs->clear_async_event_handler ();
8808 else
8809 gdb_assert (!rs->async_event_handler_marked ());
8811 ptid_t event_ptid;
8813 if (target_is_non_stop_p ())
8814 event_ptid = wait_ns (ptid, status, options);
8815 else
8816 event_ptid = wait_as (ptid, status, options);
8818 if (target_is_async_p ())
8820 /* If there are events left in the queue, or unacknowledged
8821 notifications, then tell the event loop to call us again. */
8822 if (!rs->stop_reply_queue.empty ()
8823 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8824 rs->mark_async_event_handler ();
8827 return event_ptid;
8830 /* Fetch a single register using a 'p' packet. */
8833 remote_target::fetch_register_using_p (struct regcache *regcache,
8834 packet_reg *reg)
8836 struct gdbarch *gdbarch = regcache->arch ();
8837 struct remote_state *rs = get_remote_state ();
8838 char *buf, *p;
8839 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8840 int i;
8842 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8843 return 0;
8845 if (reg->pnum == -1)
8846 return 0;
8848 p = rs->buf.data ();
8849 *p++ = 'p';
8850 p += hexnumstr (p, reg->pnum);
8851 *p++ = '\0';
8852 putpkt (rs->buf);
8853 getpkt (&rs->buf);
8855 buf = rs->buf.data ();
8857 packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
8858 switch (result.status ())
8860 case PACKET_OK:
8861 break;
8862 case PACKET_UNKNOWN:
8863 return 0;
8864 case PACKET_ERROR:
8865 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8866 gdbarch_register_name (regcache->arch (), reg->regnum),
8867 result.err_msg ());
8870 /* If this register is unfetchable, tell the regcache. */
8871 if (buf[0] == 'x')
8873 regcache->raw_supply (reg->regnum, NULL);
8874 return 1;
8877 /* Otherwise, parse and supply the value. */
8878 p = buf;
8879 i = 0;
8880 while (p[0] != 0)
8882 if (p[1] == 0)
8883 error (_("fetch_register_using_p: early buf termination"));
8885 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8886 p += 2;
8888 regcache->raw_supply (reg->regnum, regp);
8889 return 1;
8892 /* Fetch the registers included in the target's 'g' packet. */
8895 remote_target::send_g_packet ()
8897 struct remote_state *rs = get_remote_state ();
8898 int buf_len;
8900 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8901 putpkt (rs->buf);
8902 getpkt (&rs->buf);
8903 packet_result result = packet_check_result (rs->buf);
8904 if (result.status () == PACKET_ERROR)
8905 error (_("Could not read registers; remote failure reply '%s'"),
8906 result.err_msg ());
8908 /* We can get out of synch in various cases. If the first character
8909 in the buffer is not a hex character, assume that has happened
8910 and try to fetch another packet to read. */
8911 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8912 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8913 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8914 && rs->buf[0] != 'x') /* New: unavailable register value. */
8916 remote_debug_printf ("Bad register packet; fetching a new packet");
8917 getpkt (&rs->buf);
8920 buf_len = strlen (rs->buf.data ());
8922 /* Sanity check the received packet. */
8923 if (buf_len % 2 != 0)
8924 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8926 return buf_len / 2;
8929 void
8930 remote_target::process_g_packet (struct regcache *regcache)
8932 struct gdbarch *gdbarch = regcache->arch ();
8933 struct remote_state *rs = get_remote_state ();
8934 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8935 int i, buf_len;
8936 char *p;
8937 char *regs;
8939 buf_len = strlen (rs->buf.data ());
8941 /* Further sanity checks, with knowledge of the architecture. */
8942 if (buf_len > 2 * rsa->sizeof_g_packet)
8943 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8944 "bytes): %s"),
8945 rsa->sizeof_g_packet, buf_len / 2,
8946 rs->buf.data ());
8948 /* Save the size of the packet sent to us by the target. It is used
8949 as a heuristic when determining the max size of packets that the
8950 target can safely receive. */
8951 if (rsa->actual_register_packet_size == 0)
8952 rsa->actual_register_packet_size = buf_len;
8954 /* If this is smaller than we guessed the 'g' packet would be,
8955 update our records. A 'g' reply that doesn't include a register's
8956 value implies either that the register is not available, or that
8957 the 'p' packet must be used. */
8958 if (buf_len < 2 * rsa->sizeof_g_packet)
8960 long sizeof_g_packet = buf_len / 2;
8962 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8964 long offset = rsa->regs[i].offset;
8965 long reg_size = register_size (gdbarch, i);
8967 if (rsa->regs[i].pnum == -1)
8968 continue;
8970 if (offset >= sizeof_g_packet)
8971 rsa->regs[i].in_g_packet = 0;
8972 else if (offset + reg_size > sizeof_g_packet)
8973 error (_("Truncated register %d in remote 'g' packet"), i);
8974 else
8975 rsa->regs[i].in_g_packet = 1;
8978 /* Looks valid enough, we can assume this is the correct length
8979 for a 'g' packet. It's important not to adjust
8980 rsa->sizeof_g_packet if we have truncated registers otherwise
8981 this "if" won't be run the next time the method is called
8982 with a packet of the same size and one of the internal errors
8983 below will trigger instead. */
8984 rsa->sizeof_g_packet = sizeof_g_packet;
8987 regs = (char *) alloca (rsa->sizeof_g_packet);
8989 /* Unimplemented registers read as all bits zero. */
8990 memset (regs, 0, rsa->sizeof_g_packet);
8992 /* Reply describes registers byte by byte, each byte encoded as two
8993 hex characters. Suck them all up, then supply them to the
8994 register cacheing/storage mechanism. */
8996 p = rs->buf.data ();
8997 for (i = 0; i < rsa->sizeof_g_packet; i++)
8999 if (p[0] == 0 || p[1] == 0)
9000 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
9001 internal_error (_("unexpected end of 'g' packet reply"));
9003 if (p[0] == 'x' && p[1] == 'x')
9004 regs[i] = 0; /* 'x' */
9005 else
9006 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
9007 p += 2;
9010 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9012 struct packet_reg *r = &rsa->regs[i];
9013 long reg_size = register_size (gdbarch, i);
9015 if (r->in_g_packet)
9017 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
9018 /* This shouldn't happen - we adjusted in_g_packet above. */
9019 internal_error (_("unexpected end of 'g' packet reply"));
9020 else if (rs->buf[r->offset * 2] == 'x')
9022 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
9023 /* The register isn't available, mark it as such (at
9024 the same time setting the value to zero). */
9025 regcache->raw_supply (r->regnum, NULL);
9027 else
9028 regcache->raw_supply (r->regnum, regs + r->offset);
9033 void
9034 remote_target::fetch_registers_using_g (struct regcache *regcache)
9036 send_g_packet ();
9037 process_g_packet (regcache);
9040 /* Make the remote selected traceframe match GDB's selected
9041 traceframe. */
9043 void
9044 remote_target::set_remote_traceframe ()
9046 int newnum;
9047 struct remote_state *rs = get_remote_state ();
9049 if (rs->remote_traceframe_number == get_traceframe_number ())
9050 return;
9052 /* Avoid recursion, remote_trace_find calls us again. */
9053 rs->remote_traceframe_number = get_traceframe_number ();
9055 newnum = target_trace_find (tfind_number,
9056 get_traceframe_number (), 0, 0, NULL);
9058 /* Should not happen. If it does, all bets are off. */
9059 if (newnum != get_traceframe_number ())
9060 warning (_("could not set remote traceframe"));
9063 void
9064 remote_target::fetch_registers (struct regcache *regcache, int regnum)
9066 struct gdbarch *gdbarch = regcache->arch ();
9067 struct remote_state *rs = get_remote_state ();
9068 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9069 int i;
9071 set_remote_traceframe ();
9072 set_general_thread (regcache->ptid ());
9074 if (regnum >= 0)
9076 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9078 gdb_assert (reg != NULL);
9080 /* If this register might be in the 'g' packet, try that first -
9081 we are likely to read more than one register. If this is the
9082 first 'g' packet, we might be overly optimistic about its
9083 contents, so fall back to 'p'. */
9084 if (reg->in_g_packet)
9086 fetch_registers_using_g (regcache);
9087 if (reg->in_g_packet)
9088 return;
9091 if (fetch_register_using_p (regcache, reg))
9092 return;
9094 /* This register is not available. */
9095 regcache->raw_supply (reg->regnum, NULL);
9097 return;
9100 fetch_registers_using_g (regcache);
9102 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9103 if (!rsa->regs[i].in_g_packet)
9104 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
9106 /* This register is not available. */
9107 regcache->raw_supply (i, NULL);
9111 /* Prepare to store registers. Since we may send them all (using a
9112 'G' request), we have to read out the ones we don't want to change
9113 first. */
9115 void
9116 remote_target::prepare_to_store (struct regcache *regcache)
9118 struct remote_state *rs = get_remote_state ();
9119 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9120 int i;
9122 /* Make sure the entire registers array is valid. */
9123 switch (m_features.packet_support (PACKET_P))
9125 case PACKET_DISABLE:
9126 case PACKET_SUPPORT_UNKNOWN:
9127 /* Make sure all the necessary registers are cached. */
9128 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9129 if (rsa->regs[i].in_g_packet)
9130 regcache->raw_update (rsa->regs[i].regnum);
9131 break;
9132 case PACKET_ENABLE:
9133 break;
9137 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9138 packet was not recognized. */
9141 remote_target::store_register_using_P (const struct regcache *regcache,
9142 packet_reg *reg)
9144 struct gdbarch *gdbarch = regcache->arch ();
9145 struct remote_state *rs = get_remote_state ();
9146 /* Try storing a single register. */
9147 char *buf = rs->buf.data ();
9148 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9149 char *p;
9151 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9152 return 0;
9154 if (reg->pnum == -1)
9155 return 0;
9157 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9158 p = buf + strlen (buf);
9159 regcache->raw_collect (reg->regnum, regp);
9160 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9161 putpkt (rs->buf);
9162 getpkt (&rs->buf);
9164 packet_result result = m_features.packet_ok (rs->buf, PACKET_P);
9165 switch (result.status ())
9167 case PACKET_OK:
9168 return 1;
9169 case PACKET_ERROR:
9170 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9171 gdbarch_register_name (gdbarch, reg->regnum), result.err_msg ());
9172 case PACKET_UNKNOWN:
9173 return 0;
9174 default:
9175 internal_error (_("Bad result from packet_ok"));
9179 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9180 contents of the register cache buffer. FIXME: ignores errors. */
9182 void
9183 remote_target::store_registers_using_G (const struct regcache *regcache)
9185 struct remote_state *rs = get_remote_state ();
9186 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9187 gdb_byte *regs;
9188 char *p;
9190 /* Extract all the registers in the regcache copying them into a
9191 local buffer. */
9193 int i;
9195 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9196 memset (regs, 0, rsa->sizeof_g_packet);
9197 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9199 struct packet_reg *r = &rsa->regs[i];
9201 if (r->in_g_packet)
9202 regcache->raw_collect (r->regnum, regs + r->offset);
9206 /* Command describes registers byte by byte,
9207 each byte encoded as two hex characters. */
9208 p = rs->buf.data ();
9209 *p++ = 'G';
9210 bin2hex (regs, p, rsa->sizeof_g_packet);
9211 putpkt (rs->buf);
9212 getpkt (&rs->buf);
9213 packet_result pkt_status = packet_check_result (rs->buf);
9214 if (pkt_status.status () == PACKET_ERROR)
9215 error (_("Could not write registers; remote failure reply '%s'"),
9216 pkt_status.err_msg ());
9219 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9220 of the register cache buffer. FIXME: ignores errors. */
9222 void
9223 remote_target::store_registers (struct regcache *regcache, int regnum)
9225 struct gdbarch *gdbarch = regcache->arch ();
9226 struct remote_state *rs = get_remote_state ();
9227 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9228 int i;
9230 set_remote_traceframe ();
9231 set_general_thread (regcache->ptid ());
9233 if (regnum >= 0)
9235 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9237 gdb_assert (reg != NULL);
9239 /* Always prefer to store registers using the 'P' packet if
9240 possible; we often change only a small number of registers.
9241 Sometimes we change a larger number; we'd need help from a
9242 higher layer to know to use 'G'. */
9243 if (store_register_using_P (regcache, reg))
9244 return;
9246 /* For now, don't complain if we have no way to write the
9247 register. GDB loses track of unavailable registers too
9248 easily. Some day, this may be an error. We don't have
9249 any way to read the register, either... */
9250 if (!reg->in_g_packet)
9251 return;
9253 store_registers_using_G (regcache);
9254 return;
9257 store_registers_using_G (regcache);
9259 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9260 if (!rsa->regs[i].in_g_packet)
9261 if (!store_register_using_P (regcache, &rsa->regs[i]))
9262 /* See above for why we do not issue an error here. */
9263 continue;
9267 /* Return the number of hex digits in num. */
9269 static int
9270 hexnumlen (ULONGEST num)
9272 int i;
9274 for (i = 0; num != 0; i++)
9275 num >>= 4;
9277 return std::max (i, 1);
9280 /* Set BUF to the minimum number of hex digits representing NUM. */
9282 static int
9283 hexnumstr (char *buf, ULONGEST num)
9285 int len = hexnumlen (num);
9287 return hexnumnstr (buf, num, len);
9291 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9293 static int
9294 hexnumnstr (char *buf, ULONGEST num, int width)
9296 int i;
9298 buf[width] = '\0';
9300 for (i = width - 1; i >= 0; i--)
9302 buf[i] = "0123456789abcdef"[(num & 0xf)];
9303 num >>= 4;
9306 return width;
9309 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9311 static CORE_ADDR
9312 remote_address_masked (CORE_ADDR addr)
9314 unsigned int address_size = remote_address_size;
9316 /* If "remoteaddresssize" was not set, default to target address size. */
9317 if (!address_size)
9318 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9320 if (address_size > 0
9321 && address_size < (sizeof (ULONGEST) * 8))
9323 /* Only create a mask when that mask can safely be constructed
9324 in a ULONGEST variable. */
9325 ULONGEST mask = 1;
9327 mask = (mask << address_size) - 1;
9328 addr &= mask;
9330 return addr;
9333 /* Determine whether the remote target supports binary downloading.
9334 This is accomplished by sending a no-op memory write of zero length
9335 to the target at the specified address. It does not suffice to send
9336 the whole packet, since many stubs strip the eighth bit and
9337 subsequently compute a wrong checksum, which causes real havoc with
9338 remote_write_bytes.
9340 NOTE: This can still lose if the serial line is not eight-bit
9341 clean. In cases like this, the user should clear "remote
9342 X-packet". */
9344 void
9345 remote_target::check_binary_download (CORE_ADDR addr)
9347 struct remote_state *rs = get_remote_state ();
9349 switch (m_features.packet_support (PACKET_X))
9351 case PACKET_DISABLE:
9352 break;
9353 case PACKET_ENABLE:
9354 break;
9355 case PACKET_SUPPORT_UNKNOWN:
9357 char *p;
9359 p = rs->buf.data ();
9360 *p++ = 'X';
9361 p += hexnumstr (p, (ULONGEST) addr);
9362 *p++ = ',';
9363 p += hexnumstr (p, (ULONGEST) 0);
9364 *p++ = ':';
9365 *p = '\0';
9367 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9368 getpkt (&rs->buf);
9370 if (rs->buf[0] == '\0')
9372 remote_debug_printf ("binary downloading NOT supported by target");
9373 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9375 else
9377 remote_debug_printf ("binary downloading supported by target");
9378 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9380 break;
9385 /* Helper function to resize the payload in order to try to get a good
9386 alignment. We try to write an amount of data such that the next write will
9387 start on an address aligned on REMOTE_ALIGN_WRITES. */
9389 static int
9390 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9392 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9395 /* Write memory data directly to the remote machine.
9396 This does not inform the data cache; the data cache uses this.
9397 HEADER is the starting part of the packet.
9398 MEMADDR is the address in the remote memory space.
9399 MYADDR is the address of the buffer in our space.
9400 LEN_UNITS is the number of addressable units to write.
9401 UNIT_SIZE is the length in bytes of an addressable unit.
9402 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9403 should send data as binary ('X'), or hex-encoded ('M').
9405 The function creates packet of the form
9406 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9408 where encoding of <DATA> is terminated by PACKET_FORMAT.
9410 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9411 are omitted.
9413 Return the transferred status, error or OK (an
9414 'enum target_xfer_status' value). Save the number of addressable units
9415 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9417 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9418 exchange between gdb and the stub could look like (?? in place of the
9419 checksum):
9421 -> $m1000,4#??
9422 <- aaaabbbbccccdddd
9424 -> $M1000,3:eeeeffffeeee#??
9425 <- OK
9427 -> $m1000,4#??
9428 <- eeeeffffeeeedddd */
9430 target_xfer_status
9431 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9432 const gdb_byte *myaddr,
9433 ULONGEST len_units,
9434 int unit_size,
9435 ULONGEST *xfered_len_units,
9436 char packet_format, int use_length)
9438 struct remote_state *rs = get_remote_state ();
9439 char *p;
9440 char *plen = NULL;
9441 int plenlen = 0;
9442 int todo_units;
9443 int units_written;
9444 int payload_capacity_bytes;
9445 int payload_length_bytes;
9447 if (packet_format != 'X' && packet_format != 'M')
9448 internal_error (_("remote_write_bytes_aux: bad packet format"));
9450 if (len_units == 0)
9451 return TARGET_XFER_EOF;
9453 payload_capacity_bytes = get_memory_write_packet_size ();
9455 /* The packet buffer will be large enough for the payload;
9456 get_memory_packet_size ensures this. */
9457 rs->buf[0] = '\0';
9459 /* Compute the size of the actual payload by subtracting out the
9460 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9462 payload_capacity_bytes -= strlen ("$,:#NN");
9463 if (!use_length)
9464 /* The comma won't be used. */
9465 payload_capacity_bytes += 1;
9466 payload_capacity_bytes -= strlen (header);
9467 payload_capacity_bytes -= hexnumlen (memaddr);
9469 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9471 strcat (rs->buf.data (), header);
9472 p = rs->buf.data () + strlen (header);
9474 /* Compute a best guess of the number of bytes actually transfered. */
9475 if (packet_format == 'X')
9477 /* Best guess at number of bytes that will fit. */
9478 todo_units = std::min (len_units,
9479 (ULONGEST) payload_capacity_bytes / unit_size);
9480 if (use_length)
9481 payload_capacity_bytes -= hexnumlen (todo_units);
9482 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9484 else
9486 /* Number of bytes that will fit. */
9487 todo_units
9488 = std::min (len_units,
9489 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9490 if (use_length)
9491 payload_capacity_bytes -= hexnumlen (todo_units);
9492 todo_units = std::min (todo_units,
9493 (payload_capacity_bytes / unit_size) / 2);
9496 if (todo_units <= 0)
9497 internal_error (_("minimum packet size too small to write data"));
9499 /* If we already need another packet, then try to align the end
9500 of this packet to a useful boundary. */
9501 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9502 todo_units = align_for_efficient_write (todo_units, memaddr);
9504 /* Append "<memaddr>". */
9505 memaddr = remote_address_masked (memaddr);
9506 p += hexnumstr (p, (ULONGEST) memaddr);
9508 if (use_length)
9510 /* Append ",". */
9511 *p++ = ',';
9513 /* Append the length and retain its location and size. It may need to be
9514 adjusted once the packet body has been created. */
9515 plen = p;
9516 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9517 p += plenlen;
9520 /* Append ":". */
9521 *p++ = ':';
9522 *p = '\0';
9524 /* Append the packet body. */
9525 if (packet_format == 'X')
9527 /* Binary mode. Send target system values byte by byte, in
9528 increasing byte addresses. Only escape certain critical
9529 characters. */
9530 payload_length_bytes =
9531 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9532 &units_written, payload_capacity_bytes);
9534 /* If not all TODO units fit, then we'll need another packet. Make
9535 a second try to keep the end of the packet aligned. Don't do
9536 this if the packet is tiny. */
9537 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9539 int new_todo_units;
9541 new_todo_units = align_for_efficient_write (units_written, memaddr);
9543 if (new_todo_units != units_written)
9544 payload_length_bytes =
9545 remote_escape_output (myaddr, new_todo_units, unit_size,
9546 (gdb_byte *) p, &units_written,
9547 payload_capacity_bytes);
9550 p += payload_length_bytes;
9551 if (use_length && units_written < todo_units)
9553 /* Escape chars have filled up the buffer prematurely,
9554 and we have actually sent fewer units than planned.
9555 Fix-up the length field of the packet. Use the same
9556 number of characters as before. */
9557 plen += hexnumnstr (plen, (ULONGEST) units_written,
9558 plenlen);
9559 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9562 else
9564 /* Normal mode: Send target system values byte by byte, in
9565 increasing byte addresses. Each byte is encoded as a two hex
9566 value. */
9567 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9568 units_written = todo_units;
9571 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9572 getpkt (&rs->buf);
9574 if (rs->buf[0] == 'E')
9575 return TARGET_XFER_E_IO;
9577 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9578 send fewer units than we'd planned. */
9579 *xfered_len_units = (ULONGEST) units_written;
9580 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9583 /* Write memory data directly to the remote machine.
9584 This does not inform the data cache; the data cache uses this.
9585 MEMADDR is the address in the remote memory space.
9586 MYADDR is the address of the buffer in our space.
9587 LEN is the number of bytes.
9589 Return the transferred status, error or OK (an
9590 'enum target_xfer_status' value). Save the number of bytes
9591 transferred in *XFERED_LEN. Only transfer a single packet. */
9593 target_xfer_status
9594 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9595 ULONGEST len, int unit_size,
9596 ULONGEST *xfered_len)
9598 const char *packet_format = NULL;
9600 /* Check whether the target supports binary download. */
9601 check_binary_download (memaddr);
9603 switch (m_features.packet_support (PACKET_X))
9605 case PACKET_ENABLE:
9606 packet_format = "X";
9607 break;
9608 case PACKET_DISABLE:
9609 packet_format = "M";
9610 break;
9611 case PACKET_SUPPORT_UNKNOWN:
9612 internal_error (_("remote_write_bytes: bad internal state"));
9613 default:
9614 internal_error (_("bad switch"));
9617 return remote_write_bytes_aux (packet_format,
9618 memaddr, myaddr, len, unit_size, xfered_len,
9619 packet_format[0], 1);
9622 /* Read memory data directly from the remote machine.
9623 This does not use the data cache; the data cache uses this.
9624 MEMADDR is the address in the remote memory space.
9625 MYADDR is the address of the buffer in our space.
9626 LEN_UNITS is the number of addressable memory units to read..
9627 UNIT_SIZE is the length in bytes of an addressable unit.
9629 Return the transferred status, error or OK (an
9630 'enum target_xfer_status' value). Save the number of bytes
9631 transferred in *XFERED_LEN_UNITS.
9633 See the comment of remote_write_bytes_aux for an example of
9634 memory read/write exchange between gdb and the stub. */
9636 target_xfer_status
9637 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9638 ULONGEST len_units,
9639 int unit_size, ULONGEST *xfered_len_units)
9641 struct remote_state *rs = get_remote_state ();
9642 int buf_size_bytes; /* Max size of packet output buffer. */
9643 char *p;
9644 int todo_units;
9645 int decoded_bytes;
9647 buf_size_bytes = get_memory_read_packet_size ();
9648 /* The packet buffer will be large enough for the payload;
9649 get_memory_packet_size ensures this. */
9651 /* Number of units that will fit. */
9652 todo_units = std::min (len_units,
9653 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9655 /* Construct "m"<memaddr>","<len>". */
9656 memaddr = remote_address_masked (memaddr);
9657 p = rs->buf.data ();
9658 *p++ = 'm';
9659 p += hexnumstr (p, (ULONGEST) memaddr);
9660 *p++ = ',';
9661 p += hexnumstr (p, (ULONGEST) todo_units);
9662 *p = '\0';
9663 putpkt (rs->buf);
9664 getpkt (&rs->buf);
9665 packet_result result = packet_check_result (rs->buf);
9666 if (result.status () == PACKET_ERROR)
9667 return TARGET_XFER_E_IO;
9668 /* Reply describes memory byte by byte, each byte encoded as two hex
9669 characters. */
9670 p = rs->buf.data ();
9671 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9672 /* Return what we have. Let higher layers handle partial reads. */
9673 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9674 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9677 /* Using the set of read-only target sections of remote, read live
9678 read-only memory.
9680 For interface/parameters/return description see target.h,
9681 to_xfer_partial. */
9683 target_xfer_status
9684 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9685 ULONGEST memaddr,
9686 ULONGEST len,
9687 int unit_size,
9688 ULONGEST *xfered_len)
9690 const struct target_section *secp;
9692 secp = target_section_by_addr (this, memaddr);
9693 if (secp != NULL
9694 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9696 ULONGEST memend = memaddr + len;
9698 const std::vector<target_section> *table
9699 = target_get_section_table (this);
9700 for (const target_section &p : *table)
9702 if (memaddr >= p.addr)
9704 if (memend <= p.endaddr)
9706 /* Entire transfer is within this section. */
9707 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9708 xfered_len);
9710 else if (memaddr >= p.endaddr)
9712 /* This section ends before the transfer starts. */
9713 continue;
9715 else
9717 /* This section overlaps the transfer. Just do half. */
9718 len = p.endaddr - memaddr;
9719 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9720 xfered_len);
9726 return TARGET_XFER_EOF;
9729 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9730 first if the requested memory is unavailable in traceframe.
9731 Otherwise, fall back to remote_read_bytes_1. */
9733 target_xfer_status
9734 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9735 gdb_byte *myaddr, ULONGEST len, int unit_size,
9736 ULONGEST *xfered_len)
9738 if (len == 0)
9739 return TARGET_XFER_EOF;
9741 if (get_traceframe_number () != -1)
9743 std::vector<mem_range> available;
9745 /* If we fail to get the set of available memory, then the
9746 target does not support querying traceframe info, and so we
9747 attempt reading from the traceframe anyway (assuming the
9748 target implements the old QTro packet then). */
9749 if (traceframe_available_memory (&available, memaddr, len))
9751 if (available.empty () || available[0].start != memaddr)
9753 enum target_xfer_status res;
9755 /* Don't read into the traceframe's available
9756 memory. */
9757 if (!available.empty ())
9759 LONGEST oldlen = len;
9761 len = available[0].start - memaddr;
9762 gdb_assert (len <= oldlen);
9765 /* This goes through the topmost target again. */
9766 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9767 len, unit_size, xfered_len);
9768 if (res == TARGET_XFER_OK)
9769 return TARGET_XFER_OK;
9770 else
9772 /* No use trying further, we know some memory starting
9773 at MEMADDR isn't available. */
9774 *xfered_len = len;
9775 return (*xfered_len != 0) ?
9776 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9780 /* Don't try to read more than how much is available, in
9781 case the target implements the deprecated QTro packet to
9782 cater for older GDBs (the target's knowledge of read-only
9783 sections may be outdated by now). */
9784 len = available[0].length;
9788 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9793 /* Sends a packet with content determined by the printf format string
9794 FORMAT and the remaining arguments, then gets the reply. Returns
9795 whether the packet was a success, a failure, or unknown. */
9797 packet_status
9798 remote_target::remote_send_printf (const char *format, ...)
9800 struct remote_state *rs = get_remote_state ();
9801 int max_size = get_remote_packet_size ();
9802 va_list ap;
9804 va_start (ap, format);
9806 rs->buf[0] = '\0';
9807 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9809 va_end (ap);
9811 if (size >= max_size)
9812 internal_error (_("Too long remote packet."));
9814 if (putpkt (rs->buf) < 0)
9815 error (_("Communication problem with target."));
9817 rs->buf[0] = '\0';
9818 getpkt (&rs->buf);
9820 return packet_check_result (rs->buf).status ();
9823 /* Flash writing can take quite some time. We'll set
9824 effectively infinite timeout for flash operations.
9825 In future, we'll need to decide on a better approach. */
9826 static const int remote_flash_timeout = 1000;
9828 void
9829 remote_target::flash_erase (ULONGEST address, LONGEST length)
9831 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9832 enum packet_status ret;
9833 scoped_restore restore_timeout
9834 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9836 ret = remote_send_printf ("vFlashErase:%s,%s",
9837 phex (address, addr_size),
9838 phex (length, 4));
9839 switch (ret)
9841 case PACKET_UNKNOWN:
9842 error (_("Remote target does not support flash erase"));
9843 case PACKET_ERROR:
9844 error (_("Error erasing flash with vFlashErase packet"));
9845 default:
9846 break;
9850 target_xfer_status
9851 remote_target::remote_flash_write (ULONGEST address,
9852 ULONGEST length, ULONGEST *xfered_len,
9853 const gdb_byte *data)
9855 scoped_restore restore_timeout
9856 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9857 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9858 xfered_len,'X', 0);
9861 void
9862 remote_target::flash_done ()
9864 int ret;
9866 scoped_restore restore_timeout
9867 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9869 ret = remote_send_printf ("vFlashDone");
9871 switch (ret)
9873 case PACKET_UNKNOWN:
9874 error (_("Remote target does not support vFlashDone"));
9875 case PACKET_ERROR:
9876 error (_("Error finishing flash operation"));
9877 default:
9878 break;
9883 /* Stuff for dealing with the packets which are part of this protocol.
9884 See comment at top of file for details. */
9886 /* Read a single character from the remote end. The current quit
9887 handler is overridden to avoid quitting in the middle of packet
9888 sequence, as that would break communication with the remote server.
9889 See remote_serial_quit_handler for more detail. */
9892 remote_target::readchar (int timeout)
9894 int ch;
9895 struct remote_state *rs = get_remote_state ();
9899 scoped_restore restore_quit_target
9900 = make_scoped_restore (&curr_quit_handler_target, this);
9901 scoped_restore restore_quit
9902 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9904 rs->got_ctrlc_during_io = 0;
9906 ch = serial_readchar (rs->remote_desc, timeout);
9908 if (rs->got_ctrlc_during_io)
9909 set_quit_flag ();
9911 catch (const gdb_exception_error &ex)
9913 remote_unpush_target (this);
9914 throw_error (TARGET_CLOSE_ERROR,
9915 _("Remote communication error. "
9916 "Target disconnected: %s"),
9917 ex.what ());
9920 if (ch >= 0)
9921 return ch;
9923 if (ch == SERIAL_EOF)
9925 remote_unpush_target (this);
9926 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9929 return ch;
9932 /* Wrapper for serial_write that closes the target and throws if
9933 writing fails. The current quit handler is overridden to avoid
9934 quitting in the middle of packet sequence, as that would break
9935 communication with the remote server. See
9936 remote_serial_quit_handler for more detail. */
9938 void
9939 remote_target::remote_serial_write (const char *str, int len)
9941 struct remote_state *rs = get_remote_state ();
9943 scoped_restore restore_quit_target
9944 = make_scoped_restore (&curr_quit_handler_target, this);
9945 scoped_restore restore_quit
9946 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9948 rs->got_ctrlc_during_io = 0;
9952 serial_write (rs->remote_desc, str, len);
9954 catch (const gdb_exception_error &ex)
9956 remote_unpush_target (this);
9957 throw_error (TARGET_CLOSE_ERROR,
9958 _("Remote communication error. "
9959 "Target disconnected: %s"),
9960 ex.what ());
9963 if (rs->got_ctrlc_during_io)
9964 set_quit_flag ();
9967 void
9968 remote_target::remote_serial_send_break ()
9970 struct remote_state *rs = get_remote_state ();
9974 serial_send_break (rs->remote_desc);
9976 catch (const gdb_exception_error &ex)
9978 remote_unpush_target (this);
9979 throw_error (TARGET_CLOSE_ERROR,
9980 _("Remote communication error. "
9981 "Target disconnected: %s"),
9982 ex.what ());
9986 /* Return a string representing an escaped version of BUF, of len N.
9987 E.g. \n is converted to \\n, \t to \\t, etc. */
9989 static std::string
9990 escape_buffer (const char *buf, int n)
9992 string_file stb;
9994 stb.putstrn (buf, n, '\\');
9995 return stb.release ();
9999 remote_target::putpkt (const char *buf)
10001 return putpkt_binary (buf, strlen (buf));
10004 /* Wrapper around remote_target::putpkt to avoid exporting
10005 remote_target. */
10008 putpkt (remote_target *remote, const char *buf)
10010 return remote->putpkt (buf);
10013 /* Send a packet to the remote machine, with error checking. The data
10014 of the packet is in BUF. The string in BUF can be at most
10015 get_remote_packet_size () - 5 to account for the $, # and checksum,
10016 and for a possible /0 if we are debugging (remote_debug) and want
10017 to print the sent packet as a string. */
10020 remote_target::putpkt_binary (const char *buf, int cnt)
10022 struct remote_state *rs = get_remote_state ();
10023 int i;
10024 unsigned char csum = 0;
10025 gdb::def_vector<char> data (cnt + 6);
10026 char *buf2 = data.data ();
10028 int ch;
10029 int tcount = 0;
10030 char *p;
10032 /* Catch cases like trying to read memory or listing threads while
10033 we're waiting for a stop reply. The remote server wouldn't be
10034 ready to handle this request, so we'd hang and timeout. We don't
10035 have to worry about this in synchronous mode, because in that
10036 case it's not possible to issue a command while the target is
10037 running. This is not a problem in non-stop mode, because in that
10038 case, the stub is always ready to process serial input. */
10039 if (!target_is_non_stop_p ()
10040 && target_is_async_p ()
10041 && rs->waiting_for_stop_reply)
10043 error (_("Cannot execute this command while the target is running.\n"
10044 "Use the \"interrupt\" command to stop the target\n"
10045 "and then try again."));
10048 /* Copy the packet into buffer BUF2, encapsulating it
10049 and giving it a checksum. */
10051 p = buf2;
10052 *p++ = '$';
10054 for (i = 0; i < cnt; i++)
10056 csum += buf[i];
10057 *p++ = buf[i];
10059 *p++ = '#';
10060 *p++ = tohex ((csum >> 4) & 0xf);
10061 *p++ = tohex (csum & 0xf);
10063 /* Send it over and over until we get a positive ack. */
10065 while (1)
10067 if (remote_debug)
10069 *p = '\0';
10071 int len = (int) (p - buf2);
10072 int max_chars;
10074 if (remote_packet_max_chars < 0)
10075 max_chars = len;
10076 else
10077 max_chars = remote_packet_max_chars;
10079 std::string str
10080 = escape_buffer (buf2, std::min (len, max_chars));
10082 if (len > max_chars)
10083 remote_debug_printf_nofunc
10084 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
10085 len - max_chars);
10086 else
10087 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
10089 remote_serial_write (buf2, p - buf2);
10091 /* If this is a no acks version of the remote protocol, send the
10092 packet and move on. */
10093 if (rs->noack_mode)
10094 break;
10096 /* Read until either a timeout occurs (-2) or '+' is read.
10097 Handle any notification that arrives in the mean time. */
10098 while (1)
10100 ch = readchar (remote_timeout);
10102 switch (ch)
10104 case '+':
10105 remote_debug_printf_nofunc ("Received Ack");
10106 return 1;
10107 case '-':
10108 remote_debug_printf_nofunc ("Received Nak");
10109 [[fallthrough]];
10110 case SERIAL_TIMEOUT:
10111 tcount++;
10112 if (tcount > 3)
10113 return 0;
10114 break; /* Retransmit buffer. */
10115 case '$':
10117 remote_debug_printf ("Packet instead of Ack, ignoring it");
10118 /* It's probably an old response sent because an ACK
10119 was lost. Gobble up the packet and ack it so it
10120 doesn't get retransmitted when we resend this
10121 packet. */
10122 skip_frame ();
10123 remote_serial_write ("+", 1);
10124 continue; /* Now, go look for +. */
10127 case '%':
10129 int val;
10131 /* If we got a notification, handle it, and go back to looking
10132 for an ack. */
10133 /* We've found the start of a notification. Now
10134 collect the data. */
10135 val = read_frame (&rs->buf);
10136 if (val >= 0)
10138 remote_debug_printf_nofunc
10139 (" Notification received: %s",
10140 escape_buffer (rs->buf.data (), val).c_str ());
10142 handle_notification (rs->notif_state, rs->buf.data ());
10143 /* We're in sync now, rewait for the ack. */
10144 tcount = 0;
10146 else
10147 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10148 rs->buf.data ());
10149 continue;
10151 default:
10152 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10153 rs->buf.data ());
10154 continue;
10156 break; /* Here to retransmit. */
10159 #if 0
10160 /* This is wrong. If doing a long backtrace, the user should be
10161 able to get out next time we call QUIT, without anything as
10162 violent as interrupt_query. If we want to provide a way out of
10163 here without getting to the next QUIT, it should be based on
10164 hitting ^C twice as in remote_wait. */
10165 if (quit_flag)
10167 quit_flag = 0;
10168 interrupt_query ();
10170 #endif
10173 return 0;
10176 /* Come here after finding the start of a frame when we expected an
10177 ack. Do our best to discard the rest of this packet. */
10179 void
10180 remote_target::skip_frame ()
10182 int c;
10184 while (1)
10186 c = readchar (remote_timeout);
10187 switch (c)
10189 case SERIAL_TIMEOUT:
10190 /* Nothing we can do. */
10191 return;
10192 case '#':
10193 /* Discard the two bytes of checksum and stop. */
10194 c = readchar (remote_timeout);
10195 if (c >= 0)
10196 c = readchar (remote_timeout);
10198 return;
10199 case '*': /* Run length encoding. */
10200 /* Discard the repeat count. */
10201 c = readchar (remote_timeout);
10202 if (c < 0)
10203 return;
10204 break;
10205 default:
10206 /* A regular character. */
10207 break;
10212 /* Come here after finding the start of the frame. Collect the rest
10213 into *BUF, verifying the checksum, length, and handling run-length
10214 compression. NUL terminate the buffer. If there is not enough room,
10215 expand *BUF.
10217 Returns -1 on error, number of characters in buffer (ignoring the
10218 trailing NULL) on success. (could be extended to return one of the
10219 SERIAL status indications). */
10221 long
10222 remote_target::read_frame (gdb::char_vector *buf_p)
10224 unsigned char csum;
10225 long bc;
10226 int c;
10227 char *buf = buf_p->data ();
10228 struct remote_state *rs = get_remote_state ();
10230 csum = 0;
10231 bc = 0;
10233 while (1)
10235 c = readchar (remote_timeout);
10236 switch (c)
10238 case SERIAL_TIMEOUT:
10239 remote_debug_printf ("Timeout in mid-packet, retrying");
10240 return -1;
10242 case '$':
10243 remote_debug_printf ("Saw new packet start in middle of old one");
10244 return -1; /* Start a new packet, count retries. */
10246 case '#':
10248 unsigned char pktcsum;
10249 int check_0 = 0;
10250 int check_1 = 0;
10252 buf[bc] = '\0';
10254 check_0 = readchar (remote_timeout);
10255 if (check_0 >= 0)
10256 check_1 = readchar (remote_timeout);
10258 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10260 remote_debug_printf ("Timeout in checksum, retrying");
10261 return -1;
10263 else if (check_0 < 0 || check_1 < 0)
10265 remote_debug_printf ("Communication error in checksum");
10266 return -1;
10269 /* Don't recompute the checksum; with no ack packets we
10270 don't have any way to indicate a packet retransmission
10271 is necessary. */
10272 if (rs->noack_mode)
10273 return bc;
10275 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10276 if (csum == pktcsum)
10277 return bc;
10279 remote_debug_printf
10280 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10281 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10283 /* Number of characters in buffer ignoring trailing
10284 NULL. */
10285 return -1;
10287 case '*': /* Run length encoding. */
10289 int repeat;
10291 csum += c;
10292 c = readchar (remote_timeout);
10293 csum += c;
10294 repeat = c - ' ' + 3; /* Compute repeat count. */
10296 /* The character before ``*'' is repeated. */
10298 if (repeat > 0 && repeat <= 255 && bc > 0)
10300 if (bc + repeat - 1 >= buf_p->size () - 1)
10302 /* Make some more room in the buffer. */
10303 buf_p->resize (buf_p->size () + repeat);
10304 buf = buf_p->data ();
10307 memset (&buf[bc], buf[bc - 1], repeat);
10308 bc += repeat;
10309 continue;
10312 buf[bc] = '\0';
10313 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10314 return -1;
10316 default:
10317 if (bc >= buf_p->size () - 1)
10319 /* Make some more room in the buffer. */
10320 buf_p->resize (buf_p->size () * 2);
10321 buf = buf_p->data ();
10324 buf[bc++] = c;
10325 csum += c;
10326 continue;
10331 /* Set this to the maximum number of seconds to wait instead of waiting forever
10332 in target_wait(). If this timer times out, then it generates an error and
10333 the command is aborted. This replaces most of the need for timeouts in the
10334 GDB test suite, and makes it possible to distinguish between a hung target
10335 and one with slow communications. */
10337 static int watchdog = 0;
10338 static void
10339 show_watchdog (struct ui_file *file, int from_tty,
10340 struct cmd_list_element *c, const char *value)
10342 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10345 /* Read a packet from the remote machine, with error checking, and
10346 store it in *BUF. Resize *BUF if necessary to hold the result. If
10347 FOREVER, wait forever rather than timing out; this is used (in
10348 synchronous mode) to wait for a target that is is executing user
10349 code to stop. If FOREVER == false, this function is allowed to time
10350 out gracefully and return an indication of this to the caller.
10351 Otherwise return the number of bytes read. If IS_NOTIF is not
10352 NULL, then consider receiving a notification enough reason to
10353 return to the caller. In this case, *IS_NOTIF is an output boolean
10354 that indicates whether *BUF holds a notification or not (a regular
10355 packet). */
10358 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10360 struct remote_state *rs = get_remote_state ();
10361 int c;
10362 int tries;
10363 int timeout;
10364 int val = -1;
10366 strcpy (buf->data (), "timeout");
10368 if (forever)
10369 timeout = watchdog > 0 ? watchdog : -1;
10370 else if (is_notif != nullptr)
10371 timeout = 0; /* There should already be a char in the buffer. If
10372 not, bail out. */
10373 else
10374 timeout = remote_timeout;
10376 #define MAX_TRIES 3
10378 /* Process any number of notifications, and then return when
10379 we get a packet. */
10380 for (;;)
10382 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10383 times. */
10384 for (tries = 1; tries <= MAX_TRIES; tries++)
10386 /* This can loop forever if the remote side sends us
10387 characters continuously, but if it pauses, we'll get
10388 SERIAL_TIMEOUT from readchar because of timeout. Then
10389 we'll count that as a retry.
10391 Note that even when forever is set, we will only wait
10392 forever prior to the start of a packet. After that, we
10393 expect characters to arrive at a brisk pace. They should
10394 show up within remote_timeout intervals. */
10396 c = readchar (timeout);
10397 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10399 if (c == SERIAL_TIMEOUT)
10401 if (is_notif != nullptr)
10402 return -1; /* Don't complain, it's normal to not get
10403 anything in this case. */
10405 if (forever) /* Watchdog went off? Kill the target. */
10407 remote_unpush_target (this);
10408 throw_error (TARGET_CLOSE_ERROR,
10409 _("Watchdog timeout has expired. "
10410 "Target detached."));
10413 remote_debug_printf ("Timed out.");
10415 else
10417 /* We've found the start of a packet or notification.
10418 Now collect the data. */
10419 val = read_frame (buf);
10420 if (val >= 0)
10421 break;
10424 remote_serial_write ("-", 1);
10427 if (tries > MAX_TRIES)
10429 /* We have tried hard enough, and just can't receive the
10430 packet/notification. Give up. */
10431 gdb_printf (_("Ignoring packet error, continuing...\n"));
10433 /* Skip the ack char if we're in no-ack mode. */
10434 if (!rs->noack_mode)
10435 remote_serial_write ("+", 1);
10436 return -1;
10439 /* If we got an ordinary packet, return that to our caller. */
10440 if (c == '$')
10442 if (remote_debug)
10444 int max_chars;
10446 if (remote_packet_max_chars < 0)
10447 max_chars = val;
10448 else
10449 max_chars = remote_packet_max_chars;
10451 std::string str
10452 = escape_buffer (buf->data (),
10453 std::min (val, max_chars));
10455 if (val > max_chars)
10456 remote_debug_printf_nofunc
10457 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10458 val - max_chars);
10459 else
10460 remote_debug_printf_nofunc ("Packet received: %s",
10461 str.c_str ());
10464 /* Skip the ack char if we're in no-ack mode. */
10465 if (!rs->noack_mode)
10466 remote_serial_write ("+", 1);
10467 if (is_notif != NULL)
10468 *is_notif = false;
10469 return val;
10472 /* If we got a notification, handle it, and go back to looking
10473 for a packet. */
10474 else
10476 gdb_assert (c == '%');
10478 remote_debug_printf_nofunc
10479 (" Notification received: %s",
10480 escape_buffer (buf->data (), val).c_str ());
10482 if (is_notif != NULL)
10483 *is_notif = true;
10485 handle_notification (rs->notif_state, buf->data ());
10487 /* Notifications require no acknowledgement. */
10489 if (is_notif != nullptr)
10490 return val;
10495 /* Kill any new fork children of inferior INF that haven't been
10496 processed by follow_fork. */
10498 void
10499 remote_target::kill_new_fork_children (inferior *inf)
10501 remote_state *rs = get_remote_state ();
10502 const notif_client *notif = &notif_client_stop;
10504 /* Kill the fork child threads of any threads in inferior INF that are stopped
10505 at a fork event. */
10506 for (thread_info *thread : inf->non_exited_threads ())
10508 const target_waitstatus *ws = thread_pending_fork_status (thread);
10510 if (ws == nullptr)
10511 continue;
10513 int child_pid = ws->child_ptid ().pid ();
10514 int res = remote_vkill (child_pid);
10516 if (res != 0)
10517 error (_("Can't kill fork child process %d"), child_pid);
10520 /* Check for any pending fork events (not reported or processed yet)
10521 in inferior INF and kill those fork child threads as well. */
10522 remote_notif_get_pending_events (notif);
10523 for (auto &event : rs->stop_reply_queue)
10525 if (event->ptid.pid () != inf->pid)
10526 continue;
10528 if (!is_fork_status (event->ws.kind ()))
10529 continue;
10531 int child_pid = event->ws.child_ptid ().pid ();
10532 int res = remote_vkill (child_pid);
10534 if (res != 0)
10535 error (_("Can't kill fork child process %d"), child_pid);
10540 /* Target hook to kill the current inferior. */
10542 void
10543 remote_target::kill ()
10545 int res = -1;
10546 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10548 gdb_assert (inf != nullptr);
10550 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10552 /* If we're stopped while forking and we haven't followed yet,
10553 kill the child task. We need to do this before killing the
10554 parent task because if this is a vfork then the parent will
10555 be sleeping. */
10556 kill_new_fork_children (inf);
10558 res = remote_vkill (inf->pid);
10559 if (res == 0)
10561 target_mourn_inferior (inferior_ptid);
10562 return;
10566 /* If we are in 'target remote' mode and we are killing the only
10567 inferior, then we will tell gdbserver to exit and unpush the
10568 target. */
10569 if (res == -1 && !m_features.remote_multi_process_p ()
10570 && number_of_live_inferiors (this) == 1)
10572 remote_kill_k ();
10574 /* We've killed the remote end, we get to mourn it. If we are
10575 not in extended mode, mourning the inferior also unpushes
10576 remote_ops from the target stack, which closes the remote
10577 connection. */
10578 target_mourn_inferior (inferior_ptid);
10580 return;
10583 error (_("Can't kill process"));
10586 /* Send a kill request to the target using the 'vKill' packet. */
10589 remote_target::remote_vkill (int pid)
10591 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10592 return -1;
10594 remote_state *rs = get_remote_state ();
10596 /* Tell the remote target to detach. */
10597 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10598 putpkt (rs->buf);
10599 getpkt (&rs->buf);
10601 switch ((m_features.packet_ok (rs->buf, PACKET_vKill)).status ())
10603 case PACKET_OK:
10604 return 0;
10605 case PACKET_ERROR:
10606 return 1;
10607 case PACKET_UNKNOWN:
10608 return -1;
10609 default:
10610 internal_error (_("Bad result from packet_ok"));
10614 /* Send a kill request to the target using the 'k' packet. */
10616 void
10617 remote_target::remote_kill_k ()
10619 /* Catch errors so the user can quit from gdb even when we
10620 aren't on speaking terms with the remote system. */
10623 putpkt ("k");
10625 catch (const gdb_exception_error &ex)
10627 if (ex.error == TARGET_CLOSE_ERROR)
10629 /* If we got an (EOF) error that caused the target
10630 to go away, then we're done, that's what we wanted.
10631 "k" is susceptible to cause a premature EOF, given
10632 that the remote server isn't actually required to
10633 reply to "k", and it can happen that it doesn't
10634 even get to reply ACK to the "k". */
10635 return;
10638 /* Otherwise, something went wrong. We didn't actually kill
10639 the target. Just propagate the exception, and let the
10640 user or higher layers decide what to do. */
10641 throw;
10645 void
10646 remote_target::mourn_inferior ()
10648 struct remote_state *rs = get_remote_state ();
10650 /* We're no longer interested in notification events of an inferior
10651 that exited or was killed/detached. */
10652 discard_pending_stop_replies (current_inferior ());
10654 /* In 'target remote' mode with one inferior, we close the connection. */
10655 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10657 remote_unpush_target (this);
10658 return;
10661 /* In case we got here due to an error, but we're going to stay
10662 connected. */
10663 rs->waiting_for_stop_reply = 0;
10665 /* If the current general thread belonged to the process we just
10666 detached from or has exited, the remote side current general
10667 thread becomes undefined. Considering a case like this:
10669 - We just got here due to a detach.
10670 - The process that we're detaching from happens to immediately
10671 report a global breakpoint being hit in non-stop mode, in the
10672 same thread we had selected before.
10673 - GDB attaches to this process again.
10674 - This event happens to be the next event we handle.
10676 GDB would consider that the current general thread didn't need to
10677 be set on the stub side (with Hg), since for all it knew,
10678 GENERAL_THREAD hadn't changed.
10680 Notice that although in all-stop mode, the remote server always
10681 sets the current thread to the thread reporting the stop event,
10682 that doesn't happen in non-stop mode; in non-stop, the stub *must
10683 not* change the current thread when reporting a breakpoint hit,
10684 due to the decoupling of event reporting and event handling.
10686 To keep things simple, we always invalidate our notion of the
10687 current thread. */
10688 record_currthread (rs, minus_one_ptid);
10690 /* Call common code to mark the inferior as not running. */
10691 generic_mourn_inferior ();
10694 bool
10695 extended_remote_target::supports_disable_randomization ()
10697 return (m_features.packet_support (PACKET_QDisableRandomization)
10698 == PACKET_ENABLE);
10701 void
10702 remote_target::extended_remote_disable_randomization (int val)
10704 struct remote_state *rs = get_remote_state ();
10705 char *reply;
10707 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10708 "QDisableRandomization:%x", val);
10709 putpkt (rs->buf);
10710 reply = remote_get_noisy_reply ();
10711 if (*reply == '\0')
10712 error (_("Target does not support QDisableRandomization."));
10713 if (strcmp (reply, "OK") != 0)
10714 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10718 remote_target::extended_remote_run (const std::string &args)
10720 struct remote_state *rs = get_remote_state ();
10721 int len;
10722 const char *remote_exec_file = get_remote_exec_file ();
10724 /* If the user has disabled vRun support, or we have detected that
10725 support is not available, do not try it. */
10726 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10727 return -1;
10729 strcpy (rs->buf.data (), "vRun;");
10730 len = strlen (rs->buf.data ());
10732 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10733 error (_("Remote file name too long for run packet"));
10734 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10735 strlen (remote_exec_file));
10737 if (!args.empty ())
10739 int i;
10741 gdb_argv argv (args.c_str ());
10742 for (i = 0; argv[i] != NULL; i++)
10744 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10745 error (_("Argument list too long for run packet"));
10746 rs->buf[len++] = ';';
10747 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10748 strlen (argv[i]));
10752 rs->buf[len++] = '\0';
10754 putpkt (rs->buf);
10755 getpkt (&rs->buf);
10757 packet_result result = m_features.packet_ok (rs->buf, PACKET_vRun);
10758 switch (result.status ())
10760 case PACKET_OK:
10761 /* We have a wait response. All is well. */
10762 return 0;
10763 case PACKET_UNKNOWN:
10764 return -1;
10765 case PACKET_ERROR:
10766 /* If we have a textual error message, print just that. This
10767 makes remote debugging output the same as native output, when
10768 possible. */
10769 if (result.textual_err_msg ())
10770 error (("%s"), result.err_msg ());
10771 if (remote_exec_file[0] == '\0')
10772 error (_("Running the default executable on the remote target failed; "
10773 "try \"set remote exec-file\"?"));
10774 else
10775 error (_("Running \"%s\" on the remote target failed"),
10776 remote_exec_file);
10777 default:
10778 gdb_assert_not_reached ("bad switch");
10782 /* Helper function to send set/unset environment packets. ACTION is
10783 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10784 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10785 sent. */
10787 void
10788 remote_target::send_environment_packet (const char *action,
10789 const char *packet,
10790 const char *value)
10792 remote_state *rs = get_remote_state ();
10794 /* Convert the environment variable to an hex string, which
10795 is the best format to be transmitted over the wire. */
10796 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10797 strlen (value));
10799 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10800 "%s:%s", packet, encoded_value.c_str ());
10802 putpkt (rs->buf);
10803 getpkt (&rs->buf);
10804 if (strcmp (rs->buf.data (), "OK") != 0)
10805 warning (_("Unable to %s environment variable '%s' on remote."),
10806 action, value);
10809 /* Helper function to handle the QEnvironment* packets. */
10811 void
10812 remote_target::extended_remote_environment_support ()
10814 remote_state *rs = get_remote_state ();
10816 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10818 putpkt ("QEnvironmentReset");
10819 getpkt (&rs->buf);
10820 if (strcmp (rs->buf.data (), "OK") != 0)
10821 warning (_("Unable to reset environment on remote."));
10824 gdb_environ *e = &current_inferior ()->environment;
10826 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10827 != PACKET_DISABLE)
10829 for (const std::string &el : e->user_set_env ())
10830 send_environment_packet ("set", "QEnvironmentHexEncoded",
10831 el.c_str ());
10835 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10836 for (const std::string &el : e->user_unset_env ())
10837 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10840 /* Helper function to set the current working directory for the
10841 inferior in the remote target. */
10843 void
10844 remote_target::extended_remote_set_inferior_cwd ()
10846 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10848 const std::string &inferior_cwd = current_inferior ()->cwd ();
10849 remote_state *rs = get_remote_state ();
10851 if (!inferior_cwd.empty ())
10853 std::string hexpath
10854 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10855 inferior_cwd.size ());
10857 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10858 "QSetWorkingDir:%s", hexpath.c_str ());
10860 else
10862 /* An empty inferior_cwd means that the user wants us to
10863 reset the remote server's inferior's cwd. */
10864 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10865 "QSetWorkingDir:");
10868 putpkt (rs->buf);
10869 getpkt (&rs->buf);
10870 packet_result result = m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir);
10871 if (result.status () == PACKET_ERROR)
10872 error (_("\
10873 Remote replied unexpectedly while setting the inferior's working\n\
10874 directory: %s"),
10875 result.err_msg ());
10876 if (result.status () == PACKET_UNKNOWN)
10877 error (_("Remote target failed to process setting the inferior's working directory"));
10882 /* In the extended protocol we want to be able to do things like
10883 "run" and have them basically work as expected. So we need
10884 a special create_inferior function. We support changing the
10885 executable file and the command line arguments, but not the
10886 environment. */
10888 void
10889 extended_remote_target::create_inferior (const char *exec_file,
10890 const std::string &args,
10891 char **env, int from_tty)
10893 int run_worked;
10894 char *stop_reply;
10895 struct remote_state *rs = get_remote_state ();
10896 const char *remote_exec_file = get_remote_exec_file ();
10898 /* If running asynchronously, register the target file descriptor
10899 with the event loop. */
10900 if (target_can_async_p ())
10901 target_async (true);
10903 /* Disable address space randomization if requested (and supported). */
10904 if (supports_disable_randomization ())
10905 extended_remote_disable_randomization (disable_randomization);
10907 /* If startup-with-shell is on, we inform gdbserver to start the
10908 remote inferior using a shell. */
10909 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10911 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10912 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10913 putpkt (rs->buf);
10914 getpkt (&rs->buf);
10915 if (strcmp (rs->buf.data (), "OK") != 0)
10916 error (_("\
10917 Remote replied unexpectedly while setting startup-with-shell: %s"),
10918 rs->buf.data ());
10921 extended_remote_environment_support ();
10923 extended_remote_set_inferior_cwd ();
10925 /* Now restart the remote server. */
10926 run_worked = extended_remote_run (args) != -1;
10927 if (!run_worked)
10929 /* vRun was not supported. Fail if we need it to do what the
10930 user requested. */
10931 if (remote_exec_file[0])
10932 error (_("Remote target does not support \"set remote exec-file\""));
10933 if (!args.empty ())
10934 error (_("Remote target does not support \"set args\" or run ARGS"));
10936 /* Fall back to "R". */
10937 extended_remote_restart ();
10940 /* vRun's success return is a stop reply. */
10941 stop_reply = run_worked ? rs->buf.data () : NULL;
10942 add_current_inferior_and_thread (stop_reply);
10944 /* Get updated offsets, if the stub uses qOffsets. */
10945 get_offsets ();
10949 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10950 the list of conditions (in agent expression bytecode format), if any, the
10951 target needs to evaluate. The output is placed into the packet buffer
10952 started from BUF and ended at BUF_END. */
10954 static int
10955 remote_add_target_side_condition (struct gdbarch *gdbarch,
10956 struct bp_target_info *bp_tgt, char *buf,
10957 char *buf_end)
10959 if (bp_tgt->conditions.empty ())
10960 return 0;
10962 buf += strlen (buf);
10963 xsnprintf (buf, buf_end - buf, "%s", ";");
10964 buf++;
10966 /* Send conditions to the target. */
10967 for (agent_expr *aexpr : bp_tgt->conditions)
10969 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10970 buf += strlen (buf);
10971 for (int i = 0; i < aexpr->buf.size (); ++i)
10972 buf = pack_hex_byte (buf, aexpr->buf[i]);
10973 *buf = '\0';
10975 return 0;
10978 static void
10979 remote_add_target_side_commands (struct gdbarch *gdbarch,
10980 struct bp_target_info *bp_tgt, char *buf)
10982 if (bp_tgt->tcommands.empty ())
10983 return;
10985 buf += strlen (buf);
10987 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10988 buf += strlen (buf);
10990 /* Concatenate all the agent expressions that are commands into the
10991 cmds parameter. */
10992 for (agent_expr *aexpr : bp_tgt->tcommands)
10994 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10995 buf += strlen (buf);
10996 for (int i = 0; i < aexpr->buf.size (); ++i)
10997 buf = pack_hex_byte (buf, aexpr->buf[i]);
10998 *buf = '\0';
11002 /* Insert a breakpoint. On targets that have software breakpoint
11003 support, we ask the remote target to do the work; on targets
11004 which don't, we insert a traditional memory breakpoint. */
11007 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
11008 struct bp_target_info *bp_tgt)
11010 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
11011 If it succeeds, then set the support to PACKET_ENABLE. If it
11012 fails, and the user has explicitly requested the Z support then
11013 report an error, otherwise, mark it disabled and go on. */
11015 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11017 CORE_ADDR addr = bp_tgt->reqstd_address;
11018 struct remote_state *rs;
11019 char *p, *endbuf;
11021 /* Make sure the remote is pointing at the right process, if
11022 necessary. */
11023 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11024 set_general_process ();
11026 rs = get_remote_state ();
11027 p = rs->buf.data ();
11028 endbuf = p + get_remote_packet_size ();
11030 *(p++) = 'Z';
11031 *(p++) = '0';
11032 *(p++) = ',';
11033 addr = (ULONGEST) remote_address_masked (addr);
11034 p += hexnumstr (p, addr);
11035 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11037 if (supports_evaluation_of_breakpoint_conditions ())
11038 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11040 if (can_run_breakpoint_commands ())
11041 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11043 putpkt (rs->buf);
11044 getpkt (&rs->buf);
11046 switch ((m_features.packet_ok (rs->buf, PACKET_Z0)).status ())
11048 case PACKET_ERROR:
11049 return -1;
11050 case PACKET_OK:
11051 return 0;
11052 case PACKET_UNKNOWN:
11053 break;
11057 /* If this breakpoint has target-side commands but this stub doesn't
11058 support Z0 packets, throw error. */
11059 if (!bp_tgt->tcommands.empty ())
11060 throw_error (NOT_SUPPORTED_ERROR, _("\
11061 Target doesn't support breakpoints that have target side commands."));
11063 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
11067 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
11068 struct bp_target_info *bp_tgt,
11069 enum remove_bp_reason reason)
11071 CORE_ADDR addr = bp_tgt->placed_address;
11072 struct remote_state *rs = get_remote_state ();
11074 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11076 char *p = rs->buf.data ();
11077 char *endbuf = p + get_remote_packet_size ();
11079 /* Make sure the remote is pointing at the right process, if
11080 necessary. */
11081 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11082 set_general_process ();
11084 *(p++) = 'z';
11085 *(p++) = '0';
11086 *(p++) = ',';
11088 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
11089 p += hexnumstr (p, addr);
11090 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11092 putpkt (rs->buf);
11093 getpkt (&rs->buf);
11095 return (rs->buf[0] == 'E');
11098 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
11101 static enum Z_packet_type
11102 watchpoint_to_Z_packet (int type)
11104 switch (type)
11106 case hw_write:
11107 return Z_PACKET_WRITE_WP;
11108 break;
11109 case hw_read:
11110 return Z_PACKET_READ_WP;
11111 break;
11112 case hw_access:
11113 return Z_PACKET_ACCESS_WP;
11114 break;
11115 default:
11116 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
11121 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
11122 enum target_hw_bp_type type, struct expression *cond)
11124 struct remote_state *rs = get_remote_state ();
11125 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11126 char *p;
11127 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11129 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11130 + to_underlying (packet))) == PACKET_DISABLE)
11131 return 1;
11133 /* Make sure the remote is pointing at the right process, if
11134 necessary. */
11135 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11136 set_general_process ();
11138 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11139 p = strchr (rs->buf.data (), '\0');
11140 addr = remote_address_masked (addr);
11141 p += hexnumstr (p, (ULONGEST) addr);
11142 xsnprintf (p, endbuf - p, ",%x", len);
11144 putpkt (rs->buf);
11145 getpkt (&rs->buf);
11147 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11148 + to_underlying (packet)))).status ())
11150 case PACKET_ERROR:
11151 return -1;
11152 case PACKET_UNKNOWN:
11153 return 1;
11154 case PACKET_OK:
11155 return 0;
11157 internal_error (_("remote_insert_watchpoint: reached end of function"));
11160 bool
11161 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11162 CORE_ADDR start, int length)
11164 CORE_ADDR diff = remote_address_masked (addr - start);
11166 return diff < length;
11171 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11172 enum target_hw_bp_type type, struct expression *cond)
11174 struct remote_state *rs = get_remote_state ();
11175 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11176 char *p;
11177 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11179 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11180 + to_underlying (packet))) == PACKET_DISABLE)
11181 return -1;
11183 /* Make sure the remote is pointing at the right process, if
11184 necessary. */
11185 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11186 set_general_process ();
11188 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11189 p = strchr (rs->buf.data (), '\0');
11190 addr = remote_address_masked (addr);
11191 p += hexnumstr (p, (ULONGEST) addr);
11192 xsnprintf (p, endbuf - p, ",%x", len);
11193 putpkt (rs->buf);
11194 getpkt (&rs->buf);
11196 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11197 + to_underlying (packet)))).status ())
11199 case PACKET_ERROR:
11200 case PACKET_UNKNOWN:
11201 return -1;
11202 case PACKET_OK:
11203 return 0;
11205 internal_error (_("remote_remove_watchpoint: reached end of function"));
11209 static int remote_hw_watchpoint_limit = -1;
11210 static int remote_hw_watchpoint_length_limit = -1;
11211 static int remote_hw_breakpoint_limit = -1;
11214 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11216 if (remote_hw_watchpoint_length_limit == 0)
11217 return 0;
11218 else if (remote_hw_watchpoint_length_limit < 0)
11219 return 1;
11220 else if (len <= remote_hw_watchpoint_length_limit)
11221 return 1;
11222 else
11223 return 0;
11227 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11229 if (type == bp_hardware_breakpoint)
11231 if (remote_hw_breakpoint_limit == 0)
11232 return 0;
11233 else if (remote_hw_breakpoint_limit < 0)
11234 return 1;
11235 else if (cnt <= remote_hw_breakpoint_limit)
11236 return 1;
11238 else
11240 if (remote_hw_watchpoint_limit == 0)
11241 return 0;
11242 else if (remote_hw_watchpoint_limit < 0)
11243 return 1;
11244 else if (ot)
11245 return -1;
11246 else if (cnt <= remote_hw_watchpoint_limit)
11247 return 1;
11249 return -1;
11252 /* The to_stopped_by_sw_breakpoint method of target remote. */
11254 bool
11255 remote_target::stopped_by_sw_breakpoint ()
11257 struct thread_info *thread = inferior_thread ();
11259 return (thread->priv != NULL
11260 && (get_remote_thread_info (thread)->stop_reason
11261 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11264 /* The to_supports_stopped_by_sw_breakpoint method of target
11265 remote. */
11267 bool
11268 remote_target::supports_stopped_by_sw_breakpoint ()
11270 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11273 /* The to_stopped_by_hw_breakpoint method of target remote. */
11275 bool
11276 remote_target::stopped_by_hw_breakpoint ()
11278 struct thread_info *thread = inferior_thread ();
11280 return (thread->priv != NULL
11281 && (get_remote_thread_info (thread)->stop_reason
11282 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11285 /* The to_supports_stopped_by_hw_breakpoint method of target
11286 remote. */
11288 bool
11289 remote_target::supports_stopped_by_hw_breakpoint ()
11291 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11294 bool
11295 remote_target::stopped_by_watchpoint ()
11297 struct thread_info *thread = inferior_thread ();
11299 return (thread->priv != NULL
11300 && (get_remote_thread_info (thread)->stop_reason
11301 == TARGET_STOPPED_BY_WATCHPOINT));
11304 bool
11305 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11307 struct thread_info *thread = inferior_thread ();
11309 if (thread->priv != NULL
11310 && (get_remote_thread_info (thread)->stop_reason
11311 == TARGET_STOPPED_BY_WATCHPOINT))
11313 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11314 return true;
11317 return false;
11322 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11323 struct bp_target_info *bp_tgt)
11325 CORE_ADDR addr = bp_tgt->reqstd_address;
11326 struct remote_state *rs;
11327 char *p, *endbuf;
11329 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11330 return -1;
11332 /* Make sure the remote is pointing at the right process, if
11333 necessary. */
11334 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11335 set_general_process ();
11337 rs = get_remote_state ();
11338 p = rs->buf.data ();
11339 endbuf = p + get_remote_packet_size ();
11341 *(p++) = 'Z';
11342 *(p++) = '1';
11343 *(p++) = ',';
11345 addr = remote_address_masked (addr);
11346 p += hexnumstr (p, (ULONGEST) addr);
11347 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11349 if (supports_evaluation_of_breakpoint_conditions ())
11350 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11352 if (can_run_breakpoint_commands ())
11353 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11355 putpkt (rs->buf);
11356 getpkt (&rs->buf);
11358 packet_result result = m_features.packet_ok (rs->buf, PACKET_Z1);
11359 switch (result.status ())
11361 case PACKET_ERROR:
11362 error (_("Remote failure reply: %s"), result.err_msg ());
11363 case PACKET_UNKNOWN:
11364 return -1;
11365 case PACKET_OK:
11366 return 0;
11368 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11373 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11374 struct bp_target_info *bp_tgt)
11376 CORE_ADDR addr;
11377 struct remote_state *rs = get_remote_state ();
11378 char *p = rs->buf.data ();
11379 char *endbuf = p + get_remote_packet_size ();
11381 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11382 return -1;
11384 /* Make sure the remote is pointing at the right process, if
11385 necessary. */
11386 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11387 set_general_process ();
11389 *(p++) = 'z';
11390 *(p++) = '1';
11391 *(p++) = ',';
11393 addr = remote_address_masked (bp_tgt->placed_address);
11394 p += hexnumstr (p, (ULONGEST) addr);
11395 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11397 putpkt (rs->buf);
11398 getpkt (&rs->buf);
11400 switch ((m_features.packet_ok (rs->buf, PACKET_Z1)).status ())
11402 case PACKET_ERROR:
11403 case PACKET_UNKNOWN:
11404 return -1;
11405 case PACKET_OK:
11406 return 0;
11408 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11411 /* Verify memory using the "qCRC:" request. */
11414 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11416 struct remote_state *rs = get_remote_state ();
11417 unsigned long host_crc, target_crc;
11418 char *tmp;
11420 /* It doesn't make sense to use qCRC if the remote target is
11421 connected but not running. */
11422 if (target_has_execution ()
11423 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11425 enum packet_status status;
11427 /* Make sure the remote is pointing at the right process. */
11428 set_general_process ();
11430 /* FIXME: assumes lma can fit into long. */
11431 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11432 (long) lma, (long) size);
11433 putpkt (rs->buf);
11435 /* Be clever; compute the host_crc before waiting for target
11436 reply. */
11437 host_crc = xcrc32 (data, size, 0xffffffff);
11439 getpkt (&rs->buf);
11441 status = (m_features.packet_ok (rs->buf, PACKET_qCRC)).status ();
11442 if (status == PACKET_ERROR)
11443 return -1;
11444 else if (status == PACKET_OK)
11446 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11447 target_crc = target_crc * 16 + fromhex (*tmp);
11449 return (host_crc == target_crc);
11453 return simple_verify_memory (this, data, lma, size);
11456 /* compare-sections command
11458 With no arguments, compares each loadable section in the exec bfd
11459 with the same memory range on the target, and reports mismatches.
11460 Useful for verifying the image on the target against the exec file. */
11462 static void
11463 compare_sections_command (const char *args, int from_tty)
11465 asection *s;
11466 const char *sectname;
11467 bfd_size_type size;
11468 bfd_vma lma;
11469 int matched = 0;
11470 int mismatched = 0;
11471 int res;
11472 int read_only = 0;
11474 if (!current_program_space->exec_bfd ())
11475 error (_("command cannot be used without an exec file"));
11477 if (args != NULL && strcmp (args, "-r") == 0)
11479 read_only = 1;
11480 args = NULL;
11483 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11485 if (!(s->flags & SEC_LOAD))
11486 continue; /* Skip non-loadable section. */
11488 if (read_only && (s->flags & SEC_READONLY) == 0)
11489 continue; /* Skip writeable sections */
11491 size = bfd_section_size (s);
11492 if (size == 0)
11493 continue; /* Skip zero-length section. */
11495 sectname = bfd_section_name (s);
11496 if (args && strcmp (args, sectname) != 0)
11497 continue; /* Not the section selected by user. */
11499 matched = 1; /* Do this section. */
11500 lma = s->lma;
11502 gdb::byte_vector sectdata (size);
11503 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11504 sectdata.data (), 0, size);
11506 res = target_verify_memory (sectdata.data (), lma, size);
11508 if (res == -1)
11509 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11510 paddress (current_inferior ()->arch (), lma),
11511 paddress (current_inferior ()->arch (), lma + size));
11513 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11514 paddress (current_inferior ()->arch (), lma),
11515 paddress (current_inferior ()->arch (), lma + size));
11516 if (res)
11517 gdb_printf ("matched.\n");
11518 else
11520 gdb_printf ("MIS-MATCHED!\n");
11521 mismatched++;
11524 if (mismatched > 0)
11525 warning (_("One or more sections of the target image does "
11526 "not match the loaded file"));
11527 if (args && !matched)
11528 gdb_printf (_("No loaded section named '%s'.\n"), args);
11531 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11532 into remote target. The number of bytes written to the remote
11533 target is returned, or -1 for error. */
11535 target_xfer_status
11536 remote_target::remote_write_qxfer (const char *object_name,
11537 const char *annex, const gdb_byte *writebuf,
11538 ULONGEST offset, LONGEST len,
11539 ULONGEST *xfered_len,
11540 const unsigned int which_packet)
11542 int i, buf_len;
11543 ULONGEST n;
11544 struct remote_state *rs = get_remote_state ();
11545 int max_size = get_memory_write_packet_size ();
11547 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11548 return TARGET_XFER_E_IO;
11550 /* Insert header. */
11551 i = snprintf (rs->buf.data (), max_size,
11552 "qXfer:%s:write:%s:%s:",
11553 object_name, annex ? annex : "",
11554 phex_nz (offset, sizeof offset));
11555 max_size -= (i + 1);
11557 /* Escape as much data as fits into rs->buf. */
11558 buf_len = remote_escape_output
11559 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11561 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11562 || getpkt (&rs->buf) < 0
11563 || (m_features.packet_ok (rs->buf, which_packet)).status () != PACKET_OK)
11564 return TARGET_XFER_E_IO;
11566 unpack_varlen_hex (rs->buf.data (), &n);
11568 *xfered_len = n;
11569 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11572 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11573 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11574 number of bytes read is returned, or 0 for EOF, or -1 for error.
11575 The number of bytes read may be less than LEN without indicating an
11576 EOF. PACKET is checked and updated to indicate whether the remote
11577 target supports this object. */
11579 target_xfer_status
11580 remote_target::remote_read_qxfer (const char *object_name,
11581 const char *annex,
11582 gdb_byte *readbuf, ULONGEST offset,
11583 LONGEST len,
11584 ULONGEST *xfered_len,
11585 const unsigned int which_packet)
11587 struct remote_state *rs = get_remote_state ();
11588 LONGEST i, n, packet_len;
11590 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11591 return TARGET_XFER_E_IO;
11593 /* Check whether we've cached an end-of-object packet that matches
11594 this request. */
11595 if (rs->finished_object)
11597 if (strcmp (object_name, rs->finished_object) == 0
11598 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11599 && offset == rs->finished_offset)
11600 return TARGET_XFER_EOF;
11603 /* Otherwise, we're now reading something different. Discard
11604 the cache. */
11605 xfree (rs->finished_object);
11606 xfree (rs->finished_annex);
11607 rs->finished_object = NULL;
11608 rs->finished_annex = NULL;
11611 /* Request only enough to fit in a single packet. The actual data
11612 may not, since we don't know how much of it will need to be escaped;
11613 the target is free to respond with slightly less data. We subtract
11614 five to account for the response type and the protocol frame. */
11615 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11616 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11617 "qXfer:%s:read:%s:%s,%s",
11618 object_name, annex ? annex : "",
11619 phex_nz (offset, sizeof offset),
11620 phex_nz (n, sizeof n));
11621 i = putpkt (rs->buf);
11622 if (i < 0)
11623 return TARGET_XFER_E_IO;
11625 rs->buf[0] = '\0';
11626 packet_len = getpkt (&rs->buf);
11627 if (packet_len < 0
11628 || m_features.packet_ok (rs->buf, which_packet).status () != PACKET_OK)
11629 return TARGET_XFER_E_IO;
11631 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11632 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11634 /* 'm' means there is (or at least might be) more data after this
11635 batch. That does not make sense unless there's at least one byte
11636 of data in this reply. */
11637 if (rs->buf[0] == 'm' && packet_len == 1)
11638 error (_("Remote qXfer reply contained no data."));
11640 /* Got some data. */
11641 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11642 packet_len - 1, readbuf, n);
11644 /* 'l' is an EOF marker, possibly including a final block of data,
11645 or possibly empty. If we have the final block of a non-empty
11646 object, record this fact to bypass a subsequent partial read. */
11647 if (rs->buf[0] == 'l' && offset + i > 0)
11649 rs->finished_object = xstrdup (object_name);
11650 rs->finished_annex = xstrdup (annex ? annex : "");
11651 rs->finished_offset = offset + i;
11654 if (i == 0)
11655 return TARGET_XFER_EOF;
11656 else
11658 *xfered_len = i;
11659 return TARGET_XFER_OK;
11663 enum target_xfer_status
11664 remote_target::xfer_partial (enum target_object object,
11665 const char *annex, gdb_byte *readbuf,
11666 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11667 ULONGEST *xfered_len)
11669 struct remote_state *rs;
11670 int i;
11671 char *p2;
11672 char query_type;
11673 int unit_size
11674 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11676 set_remote_traceframe ();
11677 set_general_thread (inferior_ptid);
11679 rs = get_remote_state ();
11681 /* Handle memory using the standard memory routines. */
11682 if (object == TARGET_OBJECT_MEMORY)
11684 /* If the remote target is connected but not running, we should
11685 pass this request down to a lower stratum (e.g. the executable
11686 file). */
11687 if (!target_has_execution ())
11688 return TARGET_XFER_EOF;
11690 if (writebuf != NULL)
11691 return remote_write_bytes (offset, writebuf, len, unit_size,
11692 xfered_len);
11693 else
11694 return remote_read_bytes (offset, readbuf, len, unit_size,
11695 xfered_len);
11698 /* Handle extra signal info using qxfer packets. */
11699 if (object == TARGET_OBJECT_SIGNAL_INFO)
11701 if (readbuf)
11702 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11703 xfered_len, PACKET_qXfer_siginfo_read);
11704 else
11705 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11706 xfered_len, PACKET_qXfer_siginfo_write);
11709 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11711 if (readbuf)
11712 return remote_read_qxfer ("statictrace", annex,
11713 readbuf, offset, len, xfered_len,
11714 PACKET_qXfer_statictrace_read);
11715 else
11716 return TARGET_XFER_E_IO;
11719 /* Only handle flash writes. */
11720 if (writebuf != NULL)
11722 switch (object)
11724 case TARGET_OBJECT_FLASH:
11725 return remote_flash_write (offset, len, xfered_len,
11726 writebuf);
11728 default:
11729 return TARGET_XFER_E_IO;
11733 /* Map pre-existing objects onto letters. DO NOT do this for new
11734 objects!!! Instead specify new query packets. */
11735 switch (object)
11737 case TARGET_OBJECT_AVR:
11738 query_type = 'R';
11739 break;
11741 case TARGET_OBJECT_AUXV:
11742 gdb_assert (annex == NULL);
11743 return remote_read_qxfer
11744 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11746 case TARGET_OBJECT_AVAILABLE_FEATURES:
11747 return remote_read_qxfer
11748 ("features", annex, readbuf, offset, len, xfered_len,
11749 PACKET_qXfer_features);
11751 case TARGET_OBJECT_LIBRARIES:
11752 return remote_read_qxfer
11753 ("libraries", annex, readbuf, offset, len, xfered_len,
11754 PACKET_qXfer_libraries);
11756 case TARGET_OBJECT_LIBRARIES_SVR4:
11757 return remote_read_qxfer
11758 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11759 PACKET_qXfer_libraries_svr4);
11761 case TARGET_OBJECT_MEMORY_MAP:
11762 gdb_assert (annex == NULL);
11763 return remote_read_qxfer
11764 ("memory-map", annex, readbuf, offset, len, xfered_len,
11765 PACKET_qXfer_memory_map);
11767 case TARGET_OBJECT_OSDATA:
11768 /* Should only get here if we're connected. */
11769 gdb_assert (rs->remote_desc);
11770 return remote_read_qxfer
11771 ("osdata", annex, readbuf, offset, len, xfered_len,
11772 PACKET_qXfer_osdata);
11774 case TARGET_OBJECT_THREADS:
11775 gdb_assert (annex == NULL);
11776 return remote_read_qxfer
11777 ("threads", annex, readbuf, offset, len, xfered_len,
11778 PACKET_qXfer_threads);
11780 case TARGET_OBJECT_TRACEFRAME_INFO:
11781 gdb_assert (annex == NULL);
11782 return remote_read_qxfer
11783 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11784 PACKET_qXfer_traceframe_info);
11786 case TARGET_OBJECT_FDPIC:
11787 return remote_read_qxfer
11788 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11790 case TARGET_OBJECT_OPENVMS_UIB:
11791 return remote_read_qxfer
11792 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11794 case TARGET_OBJECT_BTRACE:
11795 return remote_read_qxfer
11796 ("btrace", annex, readbuf, offset, len, xfered_len,
11797 PACKET_qXfer_btrace);
11799 case TARGET_OBJECT_BTRACE_CONF:
11800 return remote_read_qxfer
11801 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11802 PACKET_qXfer_btrace_conf);
11804 case TARGET_OBJECT_EXEC_FILE:
11805 return remote_read_qxfer
11806 ("exec-file", annex, readbuf, offset, len, xfered_len,
11807 PACKET_qXfer_exec_file);
11809 default:
11810 return TARGET_XFER_E_IO;
11813 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11814 large enough let the caller deal with it. */
11815 if (len < get_remote_packet_size ())
11816 return TARGET_XFER_E_IO;
11817 len = get_remote_packet_size ();
11819 /* Except for querying the minimum buffer size, target must be open. */
11820 if (!rs->remote_desc)
11821 error (_("remote query is only available after target open"));
11823 gdb_assert (annex != NULL);
11824 gdb_assert (readbuf != NULL);
11826 p2 = rs->buf.data ();
11827 *p2++ = 'q';
11828 *p2++ = query_type;
11830 /* We used one buffer char for the remote protocol q command and
11831 another for the query type. As the remote protocol encapsulation
11832 uses 4 chars plus one extra in case we are debugging
11833 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11834 string. */
11835 i = 0;
11836 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11838 /* Bad caller may have sent forbidden characters. */
11839 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11840 *p2++ = annex[i];
11841 i++;
11843 *p2 = '\0';
11844 gdb_assert (annex[i] == '\0');
11846 i = putpkt (rs->buf);
11847 if (i < 0)
11848 return TARGET_XFER_E_IO;
11850 getpkt (&rs->buf);
11851 strcpy ((char *) readbuf, rs->buf.data ());
11853 *xfered_len = strlen ((char *) readbuf);
11854 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11857 /* Implementation of to_get_memory_xfer_limit. */
11859 ULONGEST
11860 remote_target::get_memory_xfer_limit ()
11862 return get_memory_write_packet_size ();
11866 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11867 const gdb_byte *pattern, ULONGEST pattern_len,
11868 CORE_ADDR *found_addrp)
11870 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11871 struct remote_state *rs = get_remote_state ();
11872 int max_size = get_memory_write_packet_size ();
11874 /* Number of packet bytes used to encode the pattern;
11875 this could be more than PATTERN_LEN due to escape characters. */
11876 int escaped_pattern_len;
11877 /* Amount of pattern that was encodable in the packet. */
11878 int used_pattern_len;
11879 int i;
11880 int found;
11881 ULONGEST found_addr;
11883 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11885 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11886 == len);
11889 /* Don't go to the target if we don't have to. This is done before
11890 checking packet_support to avoid the possibility that a success for this
11891 edge case means the facility works in general. */
11892 if (pattern_len > search_space_len)
11893 return 0;
11894 if (pattern_len == 0)
11896 *found_addrp = start_addr;
11897 return 1;
11900 /* If we already know the packet isn't supported, fall back to the simple
11901 way of searching memory. */
11903 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11905 /* Target doesn't provided special support, fall back and use the
11906 standard support (copy memory and do the search here). */
11907 return simple_search_memory (read_memory, start_addr, search_space_len,
11908 pattern, pattern_len, found_addrp);
11911 /* Make sure the remote is pointing at the right process. */
11912 set_general_process ();
11914 /* Insert header. */
11915 i = snprintf (rs->buf.data (), max_size,
11916 "qSearch:memory:%s;%s;",
11917 phex_nz (start_addr, addr_size),
11918 phex_nz (search_space_len, sizeof (search_space_len)));
11919 max_size -= (i + 1);
11921 /* Escape as much data as fits into rs->buf. */
11922 escaped_pattern_len =
11923 remote_escape_output (pattern, pattern_len, 1,
11924 (gdb_byte *) rs->buf.data () + i,
11925 &used_pattern_len, max_size);
11927 /* Bail if the pattern is too large. */
11928 if (used_pattern_len != pattern_len)
11929 error (_("Pattern is too large to transmit to remote target."));
11931 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11932 || getpkt (&rs->buf) < 0
11933 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory).status ()
11934 != PACKET_OK)
11936 /* The request may not have worked because the command is not
11937 supported. If so, fall back to the simple way. */
11938 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11940 return simple_search_memory (read_memory, start_addr, search_space_len,
11941 pattern, pattern_len, found_addrp);
11943 return -1;
11946 if (rs->buf[0] == '0')
11947 found = 0;
11948 else if (rs->buf[0] == '1')
11950 found = 1;
11951 if (rs->buf[1] != ',')
11952 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11953 unpack_varlen_hex (&rs->buf[2], &found_addr);
11954 *found_addrp = found_addr;
11956 else
11957 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11959 return found;
11962 void
11963 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11965 struct remote_state *rs = get_remote_state ();
11966 char *p = rs->buf.data ();
11968 if (!rs->remote_desc)
11969 error (_("remote rcmd is only available after target open"));
11971 /* Send a NULL command across as an empty command. */
11972 if (command == NULL)
11973 command = "";
11975 /* The query prefix. */
11976 strcpy (rs->buf.data (), "qRcmd,");
11977 p = strchr (rs->buf.data (), '\0');
11979 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11980 > get_remote_packet_size ())
11981 error (_("\"monitor\" command ``%s'' is too long."), command);
11983 /* Encode the actual command. */
11984 bin2hex ((const gdb_byte *) command, p, strlen (command));
11986 if (putpkt (rs->buf) < 0)
11987 error (_("Communication problem with target."));
11989 /* get/display the response */
11990 while (1)
11992 char *buf;
11994 /* XXX - see also remote_get_noisy_reply(). */
11995 QUIT; /* Allow user to bail out with ^C. */
11996 rs->buf[0] = '\0';
11997 if (getpkt (&rs->buf) == -1)
11999 /* Timeout. Continue to (try to) read responses.
12000 This is better than stopping with an error, assuming the stub
12001 is still executing the (long) monitor command.
12002 If needed, the user can interrupt gdb using C-c, obtaining
12003 an effect similar to stop on timeout. */
12004 continue;
12006 buf = rs->buf.data ();
12007 if (buf[0] == 'O' && buf[1] != 'K')
12009 /* 'O' message from stub. */
12010 remote_console_output (buf + 1, outbuf);
12011 continue;
12013 packet_result result = packet_check_result (buf);
12014 switch (result.status ())
12016 case PACKET_UNKNOWN:
12017 error (_("Target does not support this command."));
12018 case PACKET_ERROR:
12019 error (_("Protocol error with Rcmd: %s."), result.err_msg ());
12020 case PACKET_OK:
12021 break;
12024 if (strcmp (buf, "OK") != 0)
12026 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
12028 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
12029 gdb_putc (c, outbuf);
12032 break;
12036 std::vector<mem_region>
12037 remote_target::memory_map ()
12039 std::vector<mem_region> result;
12040 std::optional<gdb::char_vector> text
12041 = target_read_stralloc (current_inferior ()->top_target (),
12042 TARGET_OBJECT_MEMORY_MAP, NULL);
12044 if (text)
12045 result = parse_memory_map (text->data ());
12047 return result;
12050 /* Set of callbacks used to implement the 'maint packet' command. */
12052 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
12054 /* Called before the packet is sent. BUF is the packet content before
12055 the protocol specific prefix, suffix, and escaping is added. */
12057 void sending (gdb::array_view<const char> &buf) override
12059 gdb_puts ("sending: ");
12060 print_packet (buf);
12061 gdb_puts ("\n");
12064 /* Called with BUF, the reply from the remote target. */
12066 void received (gdb::array_view<const char> &buf) override
12068 gdb_puts ("received: \"");
12069 print_packet (buf);
12070 gdb_puts ("\"\n");
12073 private:
12075 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
12076 '\x??' with '??' replaced by the hexadecimal value of the byte. */
12078 static void
12079 print_packet (gdb::array_view<const char> &buf)
12081 string_file stb;
12083 for (int i = 0; i < buf.size (); ++i)
12085 gdb_byte c = buf[i];
12086 if (isprint (c))
12087 gdb_putc (c, &stb);
12088 else
12089 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
12092 gdb_puts (stb.string ().c_str ());
12096 /* See remote.h. */
12098 void
12099 send_remote_packet (gdb::array_view<const char> &buf,
12100 send_remote_packet_callbacks *callbacks)
12102 if (buf.size () == 0 || buf.data ()[0] == '\0')
12103 error (_("a remote packet must not be empty"));
12105 remote_target *remote = get_current_remote_target ();
12106 if (remote == nullptr)
12107 error (_("packets can only be sent to a remote target"));
12109 callbacks->sending (buf);
12111 remote->putpkt_binary (buf.data (), buf.size ());
12112 remote_state *rs = remote->get_remote_state ();
12113 int bytes = remote->getpkt (&rs->buf);
12115 if (bytes < 0)
12116 error (_("error while fetching packet from remote target"));
12118 gdb::array_view<const char> view (&rs->buf[0], bytes);
12119 callbacks->received (view);
12122 /* Entry point for the 'maint packet' command. */
12124 static void
12125 cli_packet_command (const char *args, int from_tty)
12127 cli_packet_command_callbacks cb;
12128 gdb::array_view<const char> view
12129 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
12130 send_remote_packet (view, &cb);
12133 #if 0
12134 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12136 static void display_thread_info (struct gdb_ext_thread_info *info);
12138 static void threadset_test_cmd (char *cmd, int tty);
12140 static void threadalive_test (char *cmd, int tty);
12142 static void threadlist_test_cmd (char *cmd, int tty);
12144 int get_and_display_threadinfo (threadref *ref);
12146 static void threadinfo_test_cmd (char *cmd, int tty);
12148 static int thread_display_step (threadref *ref, void *context);
12150 static void threadlist_update_test_cmd (char *cmd, int tty);
12152 static void init_remote_threadtests (void);
12154 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12156 static void
12157 threadset_test_cmd (const char *cmd, int tty)
12159 int sample_thread = SAMPLE_THREAD;
12161 gdb_printf (_("Remote threadset test\n"));
12162 set_general_thread (sample_thread);
12166 static void
12167 threadalive_test (const char *cmd, int tty)
12169 int sample_thread = SAMPLE_THREAD;
12170 int pid = inferior_ptid.pid ();
12171 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12173 if (remote_thread_alive (ptid))
12174 gdb_printf ("PASS: Thread alive test\n");
12175 else
12176 gdb_printf ("FAIL: Thread alive test\n");
12179 void output_threadid (char *title, threadref *ref);
12181 void
12182 output_threadid (char *title, threadref *ref)
12184 char hexid[20];
12186 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12187 hexid[16] = 0;
12188 gdb_printf ("%s %s\n", title, (&hexid[0]));
12191 static void
12192 threadlist_test_cmd (const char *cmd, int tty)
12194 int startflag = 1;
12195 threadref nextthread;
12196 int done, result_count;
12197 threadref threadlist[3];
12199 gdb_printf ("Remote Threadlist test\n");
12200 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12201 &result_count, &threadlist[0]))
12202 gdb_printf ("FAIL: threadlist test\n");
12203 else
12205 threadref *scan = threadlist;
12206 threadref *limit = scan + result_count;
12208 while (scan < limit)
12209 output_threadid (" thread ", scan++);
12213 void
12214 display_thread_info (struct gdb_ext_thread_info *info)
12216 output_threadid ("Threadid: ", &info->threadid);
12217 gdb_printf ("Name: %s\n ", info->shortname);
12218 gdb_printf ("State: %s\n", info->display);
12219 gdb_printf ("other: %s\n\n", info->more_display);
12223 get_and_display_threadinfo (threadref *ref)
12225 int result;
12226 int set;
12227 struct gdb_ext_thread_info threadinfo;
12229 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12230 | TAG_MOREDISPLAY | TAG_DISPLAY;
12231 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12232 display_thread_info (&threadinfo);
12233 return result;
12236 static void
12237 threadinfo_test_cmd (const char *cmd, int tty)
12239 int athread = SAMPLE_THREAD;
12240 threadref thread;
12241 int set;
12243 int_to_threadref (&thread, athread);
12244 gdb_printf ("Remote Threadinfo test\n");
12245 if (!get_and_display_threadinfo (&thread))
12246 gdb_printf ("FAIL cannot get thread info\n");
12249 static int
12250 thread_display_step (threadref *ref, void *context)
12252 /* output_threadid(" threadstep ",ref); *//* simple test */
12253 return get_and_display_threadinfo (ref);
12256 static void
12257 threadlist_update_test_cmd (const char *cmd, int tty)
12259 gdb_printf ("Remote Threadlist update test\n");
12260 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12263 static void
12264 init_remote_threadtests (void)
12266 add_com ("tlist", class_obscure, threadlist_test_cmd,
12267 _("Fetch and print the remote list of "
12268 "thread identifiers, one pkt only."));
12269 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12270 _("Fetch and display info about one thread."));
12271 add_com ("tset", class_obscure, threadset_test_cmd,
12272 _("Test setting to a different thread."));
12273 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12274 _("Iterate through updating all remote thread info."));
12275 add_com ("talive", class_obscure, threadalive_test,
12276 _("Remote thread alive test."));
12279 #endif /* 0 */
12281 /* Convert a thread ID to a string. */
12283 std::string
12284 remote_target::pid_to_str (ptid_t ptid)
12286 if (ptid == null_ptid)
12287 return normal_pid_to_str (ptid);
12288 else if (ptid.is_pid ())
12290 /* Printing an inferior target id. */
12292 /* When multi-process extensions are off, there's no way in the
12293 remote protocol to know the remote process id, if there's any
12294 at all. There's one exception --- when we're connected with
12295 target extended-remote, and we manually attached to a process
12296 with "attach PID". We don't record anywhere a flag that
12297 allows us to distinguish that case from the case of
12298 connecting with extended-remote and the stub already being
12299 attached to a process, and reporting yes to qAttached, hence
12300 no smart special casing here. */
12301 if (!m_features.remote_multi_process_p ())
12302 return "Remote target";
12304 return normal_pid_to_str (ptid);
12306 else
12308 if (magic_null_ptid == ptid)
12309 return "Thread <main>";
12310 else if (m_features.remote_multi_process_p ())
12311 if (ptid.lwp () == 0)
12312 return normal_pid_to_str (ptid);
12313 else
12314 return string_printf ("Thread %d.%ld",
12315 ptid.pid (), ptid.lwp ());
12316 else
12317 return string_printf ("Thread %ld", ptid.lwp ());
12321 /* Get the address of the thread local variable in OBJFILE which is
12322 stored at OFFSET within the thread local storage for thread PTID. */
12324 CORE_ADDR
12325 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12326 CORE_ADDR offset)
12328 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12330 struct remote_state *rs = get_remote_state ();
12331 char *p = rs->buf.data ();
12332 char *endp = p + get_remote_packet_size ();
12334 strcpy (p, "qGetTLSAddr:");
12335 p += strlen (p);
12336 p = write_ptid (p, endp, ptid);
12337 *p++ = ',';
12338 p += hexnumstr (p, offset);
12339 *p++ = ',';
12340 p += hexnumstr (p, lm);
12341 *p++ = '\0';
12343 putpkt (rs->buf);
12344 getpkt (&rs->buf);
12345 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12346 if (result.status () == PACKET_OK)
12348 ULONGEST addr;
12350 unpack_varlen_hex (rs->buf.data (), &addr);
12351 return addr;
12353 else if (result.status () == PACKET_UNKNOWN)
12354 throw_error (TLS_GENERIC_ERROR,
12355 _("Remote target doesn't support qGetTLSAddr packet"));
12356 else
12357 throw_error (TLS_GENERIC_ERROR,
12358 _("Remote target failed to process qGetTLSAddr request"));
12360 else
12361 throw_error (TLS_GENERIC_ERROR,
12362 _("TLS not supported or disabled on this target"));
12363 /* Not reached. */
12364 return 0;
12367 /* Provide thread local base, i.e. Thread Information Block address.
12368 Returns 1 if ptid is found and thread_local_base is non zero. */
12370 bool
12371 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12373 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12375 struct remote_state *rs = get_remote_state ();
12376 char *p = rs->buf.data ();
12377 char *endp = p + get_remote_packet_size ();
12379 strcpy (p, "qGetTIBAddr:");
12380 p += strlen (p);
12381 p = write_ptid (p, endp, ptid);
12382 *p++ = '\0';
12384 putpkt (rs->buf);
12385 getpkt (&rs->buf);
12386 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12387 if (result.status () == PACKET_OK)
12389 ULONGEST val;
12390 unpack_varlen_hex (rs->buf.data (), &val);
12391 if (addr)
12392 *addr = (CORE_ADDR) val;
12393 return true;
12395 else if (result.status () == PACKET_UNKNOWN)
12396 error (_("Remote target doesn't support qGetTIBAddr packet"));
12397 else
12398 error (_("Remote target failed to process qGetTIBAddr request, %s"),
12399 result.err_msg ());
12401 else
12402 error (_("qGetTIBAddr not supported or disabled on this target"));
12403 /* Not reached. */
12404 return false;
12407 /* Support for inferring a target description based on the current
12408 architecture and the size of a 'g' packet. While the 'g' packet
12409 can have any size (since optional registers can be left off the
12410 end), some sizes are easily recognizable given knowledge of the
12411 approximate architecture. */
12413 struct remote_g_packet_guess
12415 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12416 : bytes (bytes_),
12417 tdesc (tdesc_)
12421 int bytes;
12422 const struct target_desc *tdesc;
12425 struct remote_g_packet_data
12427 std::vector<remote_g_packet_guess> guesses;
12430 static const registry<gdbarch>::key<struct remote_g_packet_data>
12431 remote_g_packet_data_handle;
12433 static struct remote_g_packet_data *
12434 get_g_packet_data (struct gdbarch *gdbarch)
12436 struct remote_g_packet_data *data
12437 = remote_g_packet_data_handle.get (gdbarch);
12438 if (data == nullptr)
12439 data = remote_g_packet_data_handle.emplace (gdbarch);
12440 return data;
12443 void
12444 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12445 const struct target_desc *tdesc)
12447 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12449 gdb_assert (tdesc != NULL);
12451 for (const remote_g_packet_guess &guess : data->guesses)
12452 if (guess.bytes == bytes)
12453 internal_error (_("Duplicate g packet description added for size %d"),
12454 bytes);
12456 data->guesses.emplace_back (bytes, tdesc);
12459 /* Return true if remote_read_description would do anything on this target
12460 and architecture, false otherwise. */
12462 static bool
12463 remote_read_description_p (struct target_ops *target)
12465 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12467 return !data->guesses.empty ();
12470 const struct target_desc *
12471 remote_target::read_description ()
12473 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12475 /* Do not try this during initial connection, when we do not know
12476 whether there is a running but stopped thread. */
12477 if (!target_has_execution () || inferior_ptid == null_ptid)
12478 return beneath ()->read_description ();
12480 if (!data->guesses.empty ())
12482 int bytes = send_g_packet ();
12484 for (const remote_g_packet_guess &guess : data->guesses)
12485 if (guess.bytes == bytes)
12486 return guess.tdesc;
12488 /* We discard the g packet. A minor optimization would be to
12489 hold on to it, and fill the register cache once we have selected
12490 an architecture, but it's too tricky to do safely. */
12493 return beneath ()->read_description ();
12496 /* Remote file transfer support. This is host-initiated I/O, not
12497 target-initiated; for target-initiated, see remote-fileio.c. */
12499 /* If *LEFT is at least the length of STRING, copy STRING to
12500 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12501 decrease *LEFT. Otherwise raise an error. */
12503 static void
12504 remote_buffer_add_string (char **buffer, int *left, const char *string)
12506 int len = strlen (string);
12508 if (len > *left)
12509 error (_("Packet too long for target."));
12511 memcpy (*buffer, string, len);
12512 *buffer += len;
12513 *left -= len;
12515 /* NUL-terminate the buffer as a convenience, if there is
12516 room. */
12517 if (*left)
12518 **buffer = '\0';
12521 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12522 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12523 decrease *LEFT. Otherwise raise an error. */
12525 static void
12526 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12527 int len)
12529 if (2 * len > *left)
12530 error (_("Packet too long for target."));
12532 bin2hex (bytes, *buffer, len);
12533 *buffer += 2 * len;
12534 *left -= 2 * len;
12536 /* NUL-terminate the buffer as a convenience, if there is
12537 room. */
12538 if (*left)
12539 **buffer = '\0';
12542 /* If *LEFT is large enough, convert VALUE to hex and add it to
12543 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12544 decrease *LEFT. Otherwise raise an error. */
12546 static void
12547 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12549 int len = hexnumlen (value);
12551 if (len > *left)
12552 error (_("Packet too long for target."));
12554 hexnumstr (*buffer, value);
12555 *buffer += len;
12556 *left -= len;
12558 /* NUL-terminate the buffer as a convenience, if there is
12559 room. */
12560 if (*left)
12561 **buffer = '\0';
12564 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12565 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12566 was included, and *ATTACHMENT to point to the start of the annex
12567 if any. The length of the packet isn't needed here; there may
12568 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12570 Return 0 if the packet could be parsed, -1 if it could not. If
12571 -1 is returned, the other variables may not be initialized. */
12573 static int
12574 remote_hostio_parse_result (const char *buffer, int *retcode,
12575 fileio_error *remote_errno, const char **attachment)
12577 char *p, *p2;
12579 *remote_errno = FILEIO_SUCCESS;
12580 *attachment = NULL;
12582 if (buffer[0] != 'F')
12583 return -1;
12585 errno = 0;
12586 *retcode = strtol (&buffer[1], &p, 16);
12587 if (errno != 0 || p == &buffer[1])
12588 return -1;
12590 /* Check for ",errno". */
12591 if (*p == ',')
12593 errno = 0;
12594 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12595 if (errno != 0 || p + 1 == p2)
12596 return -1;
12597 p = p2;
12600 /* Check for ";attachment". If there is no attachment, the
12601 packet should end here. */
12602 if (*p == ';')
12604 *attachment = p + 1;
12605 return 0;
12607 else if (*p == '\0')
12608 return 0;
12609 else
12610 return -1;
12613 /* Send a prepared I/O packet to the target and read its response.
12614 The prepared packet is in the global RS->BUF before this function
12615 is called, and the answer is there when we return.
12617 COMMAND_BYTES is the length of the request to send, which may include
12618 binary data. WHICH_PACKET is the packet configuration to check
12619 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12620 is set to the error number and -1 is returned. Otherwise the value
12621 returned by the function is returned.
12623 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12624 attachment is expected; an error will be reported if there's a
12625 mismatch. If one is found, *ATTACHMENT will be set to point into
12626 the packet buffer and *ATTACHMENT_LEN will be set to the
12627 attachment's length. */
12630 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12631 fileio_error *remote_errno, const char **attachment,
12632 int *attachment_len)
12634 struct remote_state *rs = get_remote_state ();
12635 int ret, bytes_read;
12636 const char *attachment_tmp;
12638 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12640 *remote_errno = FILEIO_ENOSYS;
12641 return -1;
12644 putpkt_binary (rs->buf.data (), command_bytes);
12645 bytes_read = getpkt (&rs->buf);
12647 /* If it timed out, something is wrong. Don't try to parse the
12648 buffer. */
12649 if (bytes_read < 0)
12651 *remote_errno = FILEIO_EINVAL;
12652 return -1;
12655 switch (m_features.packet_ok (rs->buf, which_packet).status ())
12657 case PACKET_ERROR:
12658 *remote_errno = FILEIO_EINVAL;
12659 return -1;
12660 case PACKET_UNKNOWN:
12661 *remote_errno = FILEIO_ENOSYS;
12662 return -1;
12663 case PACKET_OK:
12664 break;
12667 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12668 &attachment_tmp))
12670 *remote_errno = FILEIO_EINVAL;
12671 return -1;
12674 if (*remote_errno != FILEIO_SUCCESS)
12675 return -1;
12677 /* Make sure we saw an attachment if and only if we expected one. */
12678 if ((attachment_tmp == NULL && attachment != NULL)
12679 || (attachment_tmp != NULL && attachment == NULL))
12681 *remote_errno = FILEIO_EINVAL;
12682 return -1;
12685 /* If an attachment was found, it must point into the packet buffer;
12686 work out how many bytes there were. */
12687 if (attachment_tmp != NULL)
12689 *attachment = attachment_tmp;
12690 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12693 return ret;
12696 /* See declaration.h. */
12698 void
12699 readahead_cache::invalidate ()
12701 this->fd = -1;
12704 /* See declaration.h. */
12706 void
12707 readahead_cache::invalidate_fd (int fd)
12709 if (this->fd == fd)
12710 this->fd = -1;
12713 /* Set the filesystem remote_hostio functions that take FILENAME
12714 arguments will use. Return 0 on success, or -1 if an error
12715 occurs (and set *REMOTE_ERRNO). */
12718 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12719 fileio_error *remote_errno)
12721 struct remote_state *rs = get_remote_state ();
12722 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12723 char *p = rs->buf.data ();
12724 int left = get_remote_packet_size () - 1;
12725 char arg[9];
12726 int ret;
12728 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12729 return 0;
12731 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12732 return 0;
12734 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12736 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12737 remote_buffer_add_string (&p, &left, arg);
12739 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12740 remote_errno, NULL, NULL);
12742 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12743 return 0;
12745 if (ret == 0)
12746 rs->fs_pid = required_pid;
12748 return ret;
12751 /* Implementation of to_fileio_open. */
12754 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12755 int flags, int mode, int warn_if_slow,
12756 fileio_error *remote_errno)
12758 struct remote_state *rs = get_remote_state ();
12759 char *p = rs->buf.data ();
12760 int left = get_remote_packet_size () - 1;
12762 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12763 return -1;
12765 remote_buffer_add_string (&p, &left, "vFile:open:");
12767 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12768 strlen (filename));
12769 remote_buffer_add_string (&p, &left, ",");
12771 remote_buffer_add_int (&p, &left, flags);
12772 remote_buffer_add_string (&p, &left, ",");
12774 remote_buffer_add_int (&p, &left, mode);
12776 int res = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12777 remote_errno, nullptr, nullptr);
12779 if (warn_if_slow && res != -1)
12781 static int warning_issued = 0;
12783 gdb_printf (_("Reading %ps from remote target...\n"),
12784 styled_string (file_name_style.style (), filename));
12786 if (!warning_issued)
12788 warning (_("File transfers from remote targets can be slow."
12789 " Use \"set sysroot\" to access files locally"
12790 " instead."));
12791 warning_issued = 1;
12795 return res;
12799 remote_target::fileio_open (struct inferior *inf, const char *filename,
12800 int flags, int mode, int warn_if_slow,
12801 fileio_error *remote_errno)
12803 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12804 remote_errno);
12807 /* Implementation of to_fileio_pwrite. */
12810 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12811 ULONGEST offset, fileio_error *remote_errno)
12813 struct remote_state *rs = get_remote_state ();
12814 char *p = rs->buf.data ();
12815 int left = get_remote_packet_size ();
12816 int out_len;
12818 rs->readahead_cache.invalidate_fd (fd);
12820 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12822 remote_buffer_add_int (&p, &left, fd);
12823 remote_buffer_add_string (&p, &left, ",");
12825 remote_buffer_add_int (&p, &left, offset);
12826 remote_buffer_add_string (&p, &left, ",");
12828 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12829 (get_remote_packet_size ()
12830 - (p - rs->buf.data ())));
12832 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12833 remote_errno, NULL, NULL);
12837 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12838 ULONGEST offset, fileio_error *remote_errno)
12840 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12843 /* Helper for the implementation of to_fileio_pread. Read the file
12844 from the remote side with vFile:pread. */
12847 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12848 ULONGEST offset, fileio_error *remote_errno)
12850 struct remote_state *rs = get_remote_state ();
12851 char *p = rs->buf.data ();
12852 const char *attachment;
12853 int left = get_remote_packet_size ();
12854 int ret, attachment_len;
12855 int read_len;
12857 remote_buffer_add_string (&p, &left, "vFile:pread:");
12859 remote_buffer_add_int (&p, &left, fd);
12860 remote_buffer_add_string (&p, &left, ",");
12862 remote_buffer_add_int (&p, &left, len);
12863 remote_buffer_add_string (&p, &left, ",");
12865 remote_buffer_add_int (&p, &left, offset);
12867 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12868 remote_errno, &attachment,
12869 &attachment_len);
12871 if (ret < 0)
12872 return ret;
12874 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12875 read_buf, len);
12876 if (read_len != ret)
12877 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12879 return ret;
12882 /* See declaration.h. */
12885 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12886 ULONGEST offset)
12888 if (this->fd == fd
12889 && this->offset <= offset
12890 && offset < this->offset + this->buf.size ())
12892 ULONGEST max = this->offset + this->buf.size ();
12894 if (offset + len > max)
12895 len = max - offset;
12897 memcpy (read_buf, &this->buf[offset - this->offset], len);
12898 return len;
12901 return 0;
12904 /* Implementation of to_fileio_pread. */
12907 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12908 ULONGEST offset, fileio_error *remote_errno)
12910 int ret;
12911 struct remote_state *rs = get_remote_state ();
12912 readahead_cache *cache = &rs->readahead_cache;
12914 ret = cache->pread (fd, read_buf, len, offset);
12915 if (ret > 0)
12917 cache->hit_count++;
12919 remote_debug_printf ("readahead cache hit %s",
12920 pulongest (cache->hit_count));
12921 return ret;
12924 cache->miss_count++;
12926 remote_debug_printf ("readahead cache miss %s",
12927 pulongest (cache->miss_count));
12929 cache->fd = fd;
12930 cache->offset = offset;
12931 cache->buf.resize (get_remote_packet_size ());
12933 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12934 cache->buf.size (),
12935 cache->offset, remote_errno);
12936 if (ret <= 0)
12938 cache->invalidate_fd (fd);
12939 return ret;
12942 cache->buf.resize (ret);
12943 return cache->pread (fd, read_buf, len, offset);
12947 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12948 ULONGEST offset, fileio_error *remote_errno)
12950 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12953 /* Implementation of to_fileio_close. */
12956 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12958 struct remote_state *rs = get_remote_state ();
12959 char *p = rs->buf.data ();
12960 int left = get_remote_packet_size () - 1;
12962 rs->readahead_cache.invalidate_fd (fd);
12964 remote_buffer_add_string (&p, &left, "vFile:close:");
12966 remote_buffer_add_int (&p, &left, fd);
12968 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12969 remote_errno, NULL, NULL);
12973 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12975 return remote_hostio_close (fd, remote_errno);
12978 /* Implementation of to_fileio_unlink. */
12981 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12982 fileio_error *remote_errno)
12984 struct remote_state *rs = get_remote_state ();
12985 char *p = rs->buf.data ();
12986 int left = get_remote_packet_size () - 1;
12988 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12989 return -1;
12991 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12993 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12994 strlen (filename));
12996 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12997 remote_errno, NULL, NULL);
13001 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
13002 fileio_error *remote_errno)
13004 return remote_hostio_unlink (inf, filename, remote_errno);
13007 /* Implementation of to_fileio_readlink. */
13009 std::optional<std::string>
13010 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
13011 fileio_error *remote_errno)
13013 struct remote_state *rs = get_remote_state ();
13014 char *p = rs->buf.data ();
13015 const char *attachment;
13016 int left = get_remote_packet_size ();
13017 int len, attachment_len;
13018 int read_len;
13020 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13021 return {};
13023 remote_buffer_add_string (&p, &left, "vFile:readlink:");
13025 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13026 strlen (filename));
13028 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
13029 remote_errno, &attachment,
13030 &attachment_len);
13032 if (len < 0)
13033 return {};
13035 std::string ret (len, '\0');
13037 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13038 (gdb_byte *) &ret[0], len);
13039 if (read_len != len)
13040 error (_("Readlink returned %d, but %d bytes."), len, read_len);
13042 return ret;
13045 /* Helper function to handle ::fileio_fstat and ::fileio_stat result
13046 processing. When this function is called the remote syscall has been
13047 performed and we know we didn't get an error back.
13049 ATTACHMENT and ATTACHMENT_LEN are the attachment data extracted from the
13050 remote syscall reply. EXPECTED_LEN is the length returned from the
13051 fstat or stat call, this the length of the returned data (in ATTACHMENT)
13052 once it has been decoded. The fstat/stat result (from the ATTACHMENT
13053 data) is to be placed in ST. */
13055 static int
13056 fileio_process_fstat_and_stat_reply (const char *attachment,
13057 int attachment_len,
13058 int expected_len,
13059 struct stat *st)
13061 struct fio_stat fst;
13063 int read_len
13064 = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13065 (gdb_byte *) &fst, sizeof (fst));
13067 if (read_len != expected_len)
13068 error (_("vFile:fstat returned %d, but %d bytes."),
13069 expected_len, read_len);
13071 if (read_len != sizeof (fst))
13072 error (_("vFile:fstat returned %d bytes, but expecting %d."),
13073 read_len, (int) sizeof (fst));
13075 remote_fileio_to_host_stat (&fst, st);
13077 return 0;
13080 /* Implementation of to_fileio_fstat. */
13083 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
13085 struct remote_state *rs = get_remote_state ();
13086 char *p = rs->buf.data ();
13087 int left = get_remote_packet_size ();
13088 int attachment_len, ret;
13089 const char *attachment;
13091 remote_buffer_add_string (&p, &left, "vFile:fstat:");
13093 remote_buffer_add_int (&p, &left, fd);
13095 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
13096 remote_errno, &attachment,
13097 &attachment_len);
13098 if (ret < 0)
13100 if (*remote_errno != FILEIO_ENOSYS)
13101 return ret;
13103 /* Strictly we should return -1, ENOSYS here, but when
13104 "set sysroot remote:" was implemented in August 2008
13105 BFD's need for a stat function was sidestepped with
13106 this hack. This was not remedied until March 2015
13107 so we retain the previous behavior to avoid breaking
13108 compatibility.
13110 Note that the memset is a March 2015 addition; older
13111 GDBs set st_size *and nothing else* so the structure
13112 would have garbage in all other fields. This might
13113 break something but retaining the previous behavior
13114 here would be just too wrong. */
13116 memset (st, 0, sizeof (struct stat));
13117 st->st_size = INT_MAX;
13118 return 0;
13121 return fileio_process_fstat_and_stat_reply (attachment, attachment_len,
13122 ret, st);
13125 /* Implementation of to_fileio_stat. */
13128 remote_target::fileio_stat (struct inferior *inf, const char *filename,
13129 struct stat *st, fileio_error *remote_errno)
13131 struct remote_state *rs = get_remote_state ();
13132 char *p = rs->buf.data ();
13133 int left = get_remote_packet_size () - 1;
13135 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13136 return {};
13138 remote_buffer_add_string (&p, &left, "vFile:stat:");
13140 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13141 strlen (filename));
13143 int attachment_len;
13144 const char *attachment;
13145 int ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_stat,
13146 remote_errno, &attachment,
13147 &attachment_len);
13149 /* Unlike ::fileio_fstat, the stat fileio call was added later on, and
13150 has none of the legacy bfd issues, so we can just return the error. */
13151 if (ret < 0)
13152 return ret;
13154 return fileio_process_fstat_and_stat_reply (attachment, attachment_len,
13155 ret, st);
13158 /* Implementation of to_filesystem_is_local. */
13160 bool
13161 remote_target::filesystem_is_local ()
13163 /* Valgrind GDB presents itself as a remote target but works
13164 on the local filesystem: it does not implement remote get
13165 and users are not expected to set a sysroot. To handle
13166 this case we treat the remote filesystem as local if the
13167 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
13168 does not support vFile:open. */
13169 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
13171 packet_support ps = m_features.packet_support (PACKET_vFile_open);
13173 if (ps == PACKET_SUPPORT_UNKNOWN)
13175 int fd;
13176 fileio_error remote_errno;
13178 /* Try opening a file to probe support. The supplied
13179 filename is irrelevant, we only care about whether
13180 the stub recognizes the packet or not. */
13181 fd = remote_hostio_open (NULL, "just probing",
13182 FILEIO_O_RDONLY, 0700, 0,
13183 &remote_errno);
13185 if (fd >= 0)
13186 remote_hostio_close (fd, &remote_errno);
13188 ps = m_features.packet_support (PACKET_vFile_open);
13191 if (ps == PACKET_DISABLE)
13193 static int warning_issued = 0;
13195 if (!warning_issued)
13197 warning (_("remote target does not support file"
13198 " transfer, attempting to access files"
13199 " from local filesystem."));
13200 warning_issued = 1;
13203 return true;
13207 return false;
13210 static char *
13211 remote_hostio_error (fileio_error errnum)
13213 int host_error = fileio_error_to_host (errnum);
13215 if (host_error == -1)
13216 error (_("Unknown remote I/O error %d"), errnum);
13217 else
13218 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13221 /* A RAII wrapper around a remote file descriptor. */
13223 class scoped_remote_fd
13225 public:
13226 scoped_remote_fd (remote_target *remote, int fd)
13227 : m_remote (remote), m_fd (fd)
13231 ~scoped_remote_fd ()
13233 if (m_fd != -1)
13237 fileio_error remote_errno;
13238 m_remote->remote_hostio_close (m_fd, &remote_errno);
13240 catch (...)
13242 /* Swallow exception before it escapes the dtor. If
13243 something goes wrong, likely the connection is gone,
13244 and there's nothing else that can be done. */
13249 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13251 /* Release ownership of the file descriptor, and return it. */
13252 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13254 int fd = m_fd;
13255 m_fd = -1;
13256 return fd;
13259 /* Return the owned file descriptor. */
13260 int get () const noexcept
13262 return m_fd;
13265 private:
13266 /* The remote target. */
13267 remote_target *m_remote;
13269 /* The owned remote I/O file descriptor. */
13270 int m_fd;
13273 void
13274 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13276 remote_target *remote = get_current_remote_target ();
13278 if (remote == nullptr)
13279 error (_("command can only be used with remote target"));
13281 remote->remote_file_put (local_file, remote_file, from_tty);
13284 void
13285 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13286 int from_tty)
13288 int retcode, bytes, io_size;
13289 fileio_error remote_errno;
13290 int bytes_in_buffer;
13291 int saw_eof;
13292 ULONGEST offset;
13294 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13295 if (file == NULL)
13296 perror_with_name (local_file);
13298 scoped_remote_fd fd
13299 (this, remote_hostio_open (NULL,
13300 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13301 | FILEIO_O_TRUNC),
13302 0700, 0, &remote_errno));
13303 if (fd.get () == -1)
13304 remote_hostio_error (remote_errno);
13306 /* Send up to this many bytes at once. They won't all fit in the
13307 remote packet limit, so we'll transfer slightly fewer. */
13308 io_size = get_remote_packet_size ();
13309 gdb::byte_vector buffer (io_size);
13311 bytes_in_buffer = 0;
13312 saw_eof = 0;
13313 offset = 0;
13314 while (bytes_in_buffer || !saw_eof)
13316 if (!saw_eof)
13318 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13319 io_size - bytes_in_buffer,
13320 file.get ());
13321 if (bytes == 0)
13323 if (ferror (file.get ()))
13324 error (_("Error reading %s."), local_file);
13325 else
13327 /* EOF. Unless there is something still in the
13328 buffer from the last iteration, we are done. */
13329 saw_eof = 1;
13330 if (bytes_in_buffer == 0)
13331 break;
13335 else
13336 bytes = 0;
13338 bytes += bytes_in_buffer;
13339 bytes_in_buffer = 0;
13341 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13342 offset, &remote_errno);
13344 if (retcode < 0)
13345 remote_hostio_error (remote_errno);
13346 else if (retcode == 0)
13347 error (_("Remote write of %d bytes returned 0!"), bytes);
13348 else if (retcode < bytes)
13350 /* Short write. Save the rest of the read data for the next
13351 write. */
13352 bytes_in_buffer = bytes - retcode;
13353 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13356 offset += retcode;
13359 if (remote_hostio_close (fd.release (), &remote_errno))
13360 remote_hostio_error (remote_errno);
13362 if (from_tty)
13363 gdb_printf (_("Successfully sent file \"%ps\".\n"),
13364 styled_string (file_name_style.style (), local_file));
13367 void
13368 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13370 remote_target *remote = get_current_remote_target ();
13372 if (remote == nullptr)
13373 error (_("command can only be used with remote target"));
13375 remote->remote_file_get (remote_file, local_file, from_tty);
13378 void
13379 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13380 int from_tty)
13382 fileio_error remote_errno;
13383 int bytes, io_size;
13384 ULONGEST offset;
13386 scoped_remote_fd fd
13387 (this, remote_hostio_open (NULL,
13388 remote_file, FILEIO_O_RDONLY, 0, 0,
13389 &remote_errno));
13390 if (fd.get () == -1)
13391 remote_hostio_error (remote_errno);
13393 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13394 if (file == NULL)
13395 perror_with_name (local_file);
13397 /* Send up to this many bytes at once. They won't all fit in the
13398 remote packet limit, so we'll transfer slightly fewer. */
13399 io_size = get_remote_packet_size ();
13400 gdb::byte_vector buffer (io_size);
13402 offset = 0;
13403 while (1)
13405 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13406 &remote_errno);
13407 if (bytes == 0)
13408 /* Success, but no bytes, means end-of-file. */
13409 break;
13410 if (bytes == -1)
13411 remote_hostio_error (remote_errno);
13413 offset += bytes;
13415 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13416 if (bytes == 0)
13417 perror_with_name (local_file);
13420 if (remote_hostio_close (fd.release (), &remote_errno))
13421 remote_hostio_error (remote_errno);
13423 if (from_tty)
13424 gdb_printf (_("Successfully fetched file \"%ps\".\n"),
13425 styled_string (file_name_style.style (), remote_file));
13428 void
13429 remote_file_delete (const char *remote_file, int from_tty)
13431 remote_target *remote = get_current_remote_target ();
13433 if (remote == nullptr)
13434 error (_("command can only be used with remote target"));
13436 remote->remote_file_delete (remote_file, from_tty);
13439 void
13440 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13442 int retcode;
13443 fileio_error remote_errno;
13445 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13446 if (retcode == -1)
13447 remote_hostio_error (remote_errno);
13449 if (from_tty)
13450 gdb_printf (_("Successfully deleted file \"%ps\".\n"),
13451 styled_string (file_name_style.style (), remote_file));
13454 static void
13455 remote_put_command (const char *args, int from_tty)
13457 if (args == NULL)
13458 error_no_arg (_("file to put"));
13460 gdb_argv argv (args);
13461 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13462 error (_("Invalid parameters to remote put"));
13464 remote_file_put (argv[0], argv[1], from_tty);
13467 static void
13468 remote_get_command (const char *args, int from_tty)
13470 if (args == NULL)
13471 error_no_arg (_("file to get"));
13473 gdb_argv argv (args);
13474 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13475 error (_("Invalid parameters to remote get"));
13477 remote_file_get (argv[0], argv[1], from_tty);
13480 static void
13481 remote_delete_command (const char *args, int from_tty)
13483 if (args == NULL)
13484 error_no_arg (_("file to delete"));
13486 gdb_argv argv (args);
13487 if (argv[0] == NULL || argv[1] != NULL)
13488 error (_("Invalid parameters to remote delete"));
13490 remote_file_delete (argv[0], from_tty);
13493 bool
13494 remote_target::can_execute_reverse ()
13496 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13497 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13498 return true;
13499 else
13500 return false;
13503 bool
13504 remote_target::supports_non_stop ()
13506 return true;
13509 bool
13510 remote_target::supports_disable_randomization ()
13512 /* Only supported in extended mode. */
13513 return false;
13516 bool
13517 remote_target::supports_multi_process ()
13519 return m_features.remote_multi_process_p ();
13523 remote_target::remote_supports_cond_tracepoints ()
13525 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13526 == PACKET_ENABLE);
13529 bool
13530 remote_target::supports_evaluation_of_breakpoint_conditions ()
13532 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13533 == PACKET_ENABLE);
13537 remote_target::remote_supports_fast_tracepoints ()
13539 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13543 remote_target::remote_supports_static_tracepoints ()
13545 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13549 remote_target::remote_supports_install_in_trace ()
13551 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13554 bool
13555 remote_target::supports_enable_disable_tracepoint ()
13557 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13558 == PACKET_ENABLE);
13561 bool
13562 remote_target::supports_string_tracing ()
13564 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13567 bool
13568 remote_target::can_run_breakpoint_commands ()
13570 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13573 void
13574 remote_target::trace_init ()
13576 struct remote_state *rs = get_remote_state ();
13578 putpkt ("QTinit");
13579 remote_get_noisy_reply ();
13580 if (strcmp (rs->buf.data (), "OK") != 0)
13581 error (_("Target does not support this command."));
13584 /* Recursive routine to walk through command list including loops, and
13585 download packets for each command. */
13587 void
13588 remote_target::remote_download_command_source (int num, ULONGEST addr,
13589 struct command_line *cmds)
13591 struct remote_state *rs = get_remote_state ();
13592 struct command_line *cmd;
13594 for (cmd = cmds; cmd; cmd = cmd->next)
13596 QUIT; /* Allow user to bail out with ^C. */
13597 strcpy (rs->buf.data (), "QTDPsrc:");
13598 encode_source_string (num, addr, "cmd", cmd->line,
13599 rs->buf.data () + strlen (rs->buf.data ()),
13600 rs->buf.size () - strlen (rs->buf.data ()));
13601 putpkt (rs->buf);
13602 remote_get_noisy_reply ();
13603 if (strcmp (rs->buf.data (), "OK"))
13604 warning (_("Target does not support source download."));
13606 if (cmd->control_type == while_control
13607 || cmd->control_type == while_stepping_control)
13609 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13611 QUIT; /* Allow user to bail out with ^C. */
13612 strcpy (rs->buf.data (), "QTDPsrc:");
13613 encode_source_string (num, addr, "cmd", "end",
13614 rs->buf.data () + strlen (rs->buf.data ()),
13615 rs->buf.size () - strlen (rs->buf.data ()));
13616 putpkt (rs->buf);
13617 remote_get_noisy_reply ();
13618 if (strcmp (rs->buf.data (), "OK"))
13619 warning (_("Target does not support source download."));
13624 void
13625 remote_target::download_tracepoint (struct bp_location *loc)
13627 CORE_ADDR tpaddr;
13628 char addrbuf[40];
13629 std::vector<std::string> tdp_actions;
13630 std::vector<std::string> stepping_actions;
13631 char *pkt;
13632 struct breakpoint *b = loc->owner;
13633 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13634 struct remote_state *rs = get_remote_state ();
13635 int ret;
13636 const char *err_msg = _("Tracepoint packet too large for target.");
13637 size_t size_left;
13639 /* We use a buffer other than rs->buf because we'll build strings
13640 across multiple statements, and other statements in between could
13641 modify rs->buf. */
13642 gdb::char_vector buf (get_remote_packet_size ());
13644 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13646 tpaddr = loc->address;
13647 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13648 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13649 b->number, addrbuf, /* address */
13650 (b->enable_state == bp_enabled ? 'E' : 'D'),
13651 t->step_count, t->pass_count);
13653 if (ret < 0 || ret >= buf.size ())
13654 error ("%s", err_msg);
13656 /* Fast tracepoints are mostly handled by the target, but we can
13657 tell the target how big of an instruction block should be moved
13658 around. */
13659 if (b->type == bp_fast_tracepoint)
13661 /* Only test for support at download time; we may not know
13662 target capabilities at definition time. */
13663 if (remote_supports_fast_tracepoints ())
13665 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13666 NULL))
13668 size_left = buf.size () - strlen (buf.data ());
13669 ret = snprintf (buf.data () + strlen (buf.data ()),
13670 size_left, ":F%x",
13671 gdb_insn_length (loc->gdbarch, tpaddr));
13673 if (ret < 0 || ret >= size_left)
13674 error ("%s", err_msg);
13676 else
13677 /* If it passed validation at definition but fails now,
13678 something is very wrong. */
13679 internal_error (_("Fast tracepoint not valid during download"));
13681 else
13682 /* Fast tracepoints are functionally identical to regular
13683 tracepoints, so don't take lack of support as a reason to
13684 give up on the trace run. */
13685 warning (_("Target does not support fast tracepoints, "
13686 "downloading %d as regular tracepoint"), b->number);
13688 else if (b->type == bp_static_tracepoint
13689 || b->type == bp_static_marker_tracepoint)
13691 /* Only test for support at download time; we may not know
13692 target capabilities at definition time. */
13693 if (remote_supports_static_tracepoints ())
13695 struct static_tracepoint_marker marker;
13697 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13699 size_left = buf.size () - strlen (buf.data ());
13700 ret = snprintf (buf.data () + strlen (buf.data ()),
13701 size_left, ":S");
13703 if (ret < 0 || ret >= size_left)
13704 error ("%s", err_msg);
13706 else
13707 error (_("Static tracepoint not valid during download"));
13709 else
13710 /* Fast tracepoints are functionally identical to regular
13711 tracepoints, so don't take lack of support as a reason
13712 to give up on the trace run. */
13713 error (_("Target does not support static tracepoints"));
13715 /* If the tracepoint has a conditional, make it into an agent
13716 expression and append to the definition. */
13717 if (loc->cond)
13719 /* Only test support at download time, we may not know target
13720 capabilities at definition time. */
13721 if (remote_supports_cond_tracepoints ())
13723 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13724 loc->cond.get ());
13726 size_left = buf.size () - strlen (buf.data ());
13728 ret = snprintf (buf.data () + strlen (buf.data ()),
13729 size_left, ":X%x,", (int) aexpr->buf.size ());
13731 if (ret < 0 || ret >= size_left)
13732 error ("%s", err_msg);
13734 size_left = buf.size () - strlen (buf.data ());
13736 /* Two bytes to encode each aexpr byte, plus the terminating
13737 null byte. */
13738 if (aexpr->buf.size () * 2 + 1 > size_left)
13739 error ("%s", err_msg);
13741 pkt = buf.data () + strlen (buf.data ());
13743 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13744 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13745 *pkt = '\0';
13747 else
13748 warning (_("Target does not support conditional tracepoints, "
13749 "ignoring tp %d cond"), b->number);
13752 if (b->commands || !default_collect.empty ())
13754 size_left = buf.size () - strlen (buf.data ());
13756 ret = snprintf (buf.data () + strlen (buf.data ()),
13757 size_left, "-");
13759 if (ret < 0 || ret >= size_left)
13760 error ("%s", err_msg);
13763 putpkt (buf.data ());
13764 remote_get_noisy_reply ();
13765 if (strcmp (rs->buf.data (), "OK"))
13766 error (_("Target does not support tracepoints."));
13768 /* do_single_steps (t); */
13769 for (auto action_it = tdp_actions.begin ();
13770 action_it != tdp_actions.end (); action_it++)
13772 QUIT; /* Allow user to bail out with ^C. */
13774 bool has_more = ((action_it + 1) != tdp_actions.end ()
13775 || !stepping_actions.empty ());
13777 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13778 b->number, addrbuf, /* address */
13779 action_it->c_str (),
13780 has_more ? '-' : 0);
13782 if (ret < 0 || ret >= buf.size ())
13783 error ("%s", err_msg);
13785 putpkt (buf.data ());
13786 remote_get_noisy_reply ();
13787 if (strcmp (rs->buf.data (), "OK"))
13788 error (_("Error on target while setting tracepoints."));
13791 for (auto action_it = stepping_actions.begin ();
13792 action_it != stepping_actions.end (); action_it++)
13794 QUIT; /* Allow user to bail out with ^C. */
13796 bool is_first = action_it == stepping_actions.begin ();
13797 bool has_more = (action_it + 1) != stepping_actions.end ();
13799 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13800 b->number, addrbuf, /* address */
13801 is_first ? "S" : "",
13802 action_it->c_str (),
13803 has_more ? "-" : "");
13805 if (ret < 0 || ret >= buf.size ())
13806 error ("%s", err_msg);
13808 putpkt (buf.data ());
13809 remote_get_noisy_reply ();
13810 if (strcmp (rs->buf.data (), "OK"))
13811 error (_("Error on target while setting tracepoints."));
13814 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13816 if (b->locspec != nullptr)
13818 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13820 if (ret < 0 || ret >= buf.size ())
13821 error ("%s", err_msg);
13823 const char *str = b->locspec->to_string ();
13824 encode_source_string (b->number, loc->address, "at", str,
13825 buf.data () + strlen (buf.data ()),
13826 buf.size () - strlen (buf.data ()));
13827 putpkt (buf.data ());
13828 remote_get_noisy_reply ();
13829 if (strcmp (rs->buf.data (), "OK"))
13830 warning (_("Target does not support source download."));
13832 if (b->cond_string)
13834 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13836 if (ret < 0 || ret >= buf.size ())
13837 error ("%s", err_msg);
13839 encode_source_string (b->number, loc->address,
13840 "cond", b->cond_string.get (),
13841 buf.data () + strlen (buf.data ()),
13842 buf.size () - strlen (buf.data ()));
13843 putpkt (buf.data ());
13844 remote_get_noisy_reply ();
13845 if (strcmp (rs->buf.data (), "OK"))
13846 warning (_("Target does not support source download."));
13848 remote_download_command_source (b->number, loc->address,
13849 breakpoint_commands (b));
13853 bool
13854 remote_target::can_download_tracepoint ()
13856 struct remote_state *rs = get_remote_state ();
13857 struct trace_status *ts;
13858 int status;
13860 /* Don't try to install tracepoints until we've relocated our
13861 symbols, and fetched and merged the target's tracepoint list with
13862 ours. */
13863 if (rs->starting_up)
13864 return false;
13866 ts = current_trace_status ();
13867 status = get_trace_status (ts);
13869 if (status == -1 || !ts->running_known || !ts->running)
13870 return false;
13872 /* If we are in a tracing experiment, but remote stub doesn't support
13873 installing tracepoint in trace, we have to return. */
13874 if (!remote_supports_install_in_trace ())
13875 return false;
13877 return true;
13881 void
13882 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13884 struct remote_state *rs = get_remote_state ();
13885 char *p;
13887 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13888 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13889 tsv.builtin);
13890 p = rs->buf.data () + strlen (rs->buf.data ());
13891 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13892 >= get_remote_packet_size ())
13893 error (_("Trace state variable name too long for tsv definition packet"));
13894 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13895 *p++ = '\0';
13896 putpkt (rs->buf);
13897 remote_get_noisy_reply ();
13898 if (rs->buf[0] == '\0')
13899 error (_("Target does not support this command."));
13900 if (strcmp (rs->buf.data (), "OK") != 0)
13901 error (_("Error on target while downloading trace state variable."));
13904 void
13905 remote_target::enable_tracepoint (struct bp_location *location)
13907 struct remote_state *rs = get_remote_state ();
13909 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13910 location->owner->number,
13911 phex (location->address, sizeof (CORE_ADDR)));
13912 putpkt (rs->buf);
13913 remote_get_noisy_reply ();
13914 if (rs->buf[0] == '\0')
13915 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13916 if (strcmp (rs->buf.data (), "OK") != 0)
13917 error (_("Error on target while enabling tracepoint."));
13920 void
13921 remote_target::disable_tracepoint (struct bp_location *location)
13923 struct remote_state *rs = get_remote_state ();
13925 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13926 location->owner->number,
13927 phex (location->address, sizeof (CORE_ADDR)));
13928 putpkt (rs->buf);
13929 remote_get_noisy_reply ();
13930 if (rs->buf[0] == '\0')
13931 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13932 if (strcmp (rs->buf.data (), "OK") != 0)
13933 error (_("Error on target while disabling tracepoint."));
13936 void
13937 remote_target::trace_set_readonly_regions ()
13939 asection *s;
13940 bfd_size_type size;
13941 bfd_vma vma;
13942 int anysecs = 0;
13943 int offset = 0;
13944 bfd *abfd = current_program_space->exec_bfd ();
13946 if (!abfd)
13947 return; /* No information to give. */
13949 struct remote_state *rs = get_remote_state ();
13951 strcpy (rs->buf.data (), "QTro");
13952 offset = strlen (rs->buf.data ());
13953 for (s = abfd->sections; s; s = s->next)
13955 char tmp1[40], tmp2[40];
13956 int sec_length;
13958 if ((s->flags & SEC_LOAD) == 0
13959 /* || (s->flags & SEC_CODE) == 0 */
13960 || (s->flags & SEC_READONLY) == 0)
13961 continue;
13963 anysecs = 1;
13964 vma = bfd_section_vma (s);
13965 size = bfd_section_size (s);
13966 bfd_sprintf_vma (abfd, tmp1, vma);
13967 bfd_sprintf_vma (abfd, tmp2, vma + size);
13968 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13969 if (offset + sec_length + 1 > rs->buf.size ())
13971 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13972 != PACKET_ENABLE)
13973 warning (_("\
13974 Too many sections for read-only sections definition packet."));
13975 break;
13977 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13978 tmp1, tmp2);
13979 offset += sec_length;
13981 if (anysecs)
13983 putpkt (rs->buf);
13984 getpkt (&rs->buf);
13988 void
13989 remote_target::trace_start ()
13991 struct remote_state *rs = get_remote_state ();
13993 putpkt ("QTStart");
13994 remote_get_noisy_reply ();
13995 if (rs->buf[0] == '\0')
13996 error (_("Target does not support this command."));
13997 if (strcmp (rs->buf.data (), "OK") != 0)
13998 error (_("Bogus reply from target: %s"), rs->buf.data ());
14002 remote_target::get_trace_status (struct trace_status *ts)
14004 /* Initialize it just to avoid a GCC false warning. */
14005 char *p = NULL;
14006 struct remote_state *rs = get_remote_state ();
14008 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
14009 return -1;
14011 /* FIXME we need to get register block size some other way. */
14012 trace_regblock_size
14013 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
14015 putpkt ("qTStatus");
14019 p = remote_get_noisy_reply ();
14021 catch (const gdb_exception_error &ex)
14023 if (ex.error != TARGET_CLOSE_ERROR)
14025 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
14026 return -1;
14028 throw;
14031 packet_result result = m_features.packet_ok (p, PACKET_qTStatus);
14033 switch (result.status ())
14035 case PACKET_ERROR:
14036 error (_("Remote failure reply: %s"), result.err_msg ());
14037 /* If the remote target doesn't do tracing, flag it. */
14038 case PACKET_UNKNOWN:
14039 return -1;
14042 /* We're working with a live target. */
14043 ts->filename = NULL;
14045 if (*p++ != 'T')
14046 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
14048 /* Function 'parse_trace_status' sets default value of each field of
14049 'ts' at first, so we don't have to do it here. */
14050 parse_trace_status (p, ts);
14052 return ts->running;
14055 void
14056 remote_target::get_tracepoint_status (tracepoint *tp,
14057 struct uploaded_tp *utp)
14059 struct remote_state *rs = get_remote_state ();
14060 char *reply;
14061 size_t size = get_remote_packet_size ();
14063 if (tp)
14065 tp->hit_count = 0;
14066 tp->traceframe_usage = 0;
14067 for (bp_location &loc : tp->locations ())
14069 /* If the tracepoint was never downloaded, don't go asking for
14070 any status. */
14071 if (tp->number_on_target == 0)
14072 continue;
14073 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
14074 phex_nz (loc.address, 0));
14075 putpkt (rs->buf);
14076 reply = remote_get_noisy_reply ();
14077 if (reply && *reply)
14079 if (*reply == 'V')
14080 parse_tracepoint_status (reply + 1, tp, utp);
14084 else if (utp)
14086 utp->hit_count = 0;
14087 utp->traceframe_usage = 0;
14088 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
14089 phex_nz (utp->addr, 0));
14090 putpkt (rs->buf);
14091 reply = remote_get_noisy_reply ();
14092 if (reply && *reply)
14094 if (*reply == 'V')
14095 parse_tracepoint_status (reply + 1, tp, utp);
14100 void
14101 remote_target::trace_stop ()
14103 struct remote_state *rs = get_remote_state ();
14105 putpkt ("QTStop");
14106 remote_get_noisy_reply ();
14107 if (rs->buf[0] == '\0')
14108 error (_("Target does not support this command."));
14109 if (strcmp (rs->buf.data (), "OK") != 0)
14110 error (_("Bogus reply from target: %s"), rs->buf.data ());
14114 remote_target::trace_find (enum trace_find_type type, int num,
14115 CORE_ADDR addr1, CORE_ADDR addr2,
14116 int *tpp)
14118 struct remote_state *rs = get_remote_state ();
14119 char *endbuf = rs->buf.data () + get_remote_packet_size ();
14120 char *p, *reply;
14121 int target_frameno = -1, target_tracept = -1;
14123 /* Lookups other than by absolute frame number depend on the current
14124 trace selected, so make sure it is correct on the remote end
14125 first. */
14126 if (type != tfind_number)
14127 set_remote_traceframe ();
14129 p = rs->buf.data ();
14130 strcpy (p, "QTFrame:");
14131 p = strchr (p, '\0');
14132 switch (type)
14134 case tfind_number:
14135 xsnprintf (p, endbuf - p, "%x", num);
14136 break;
14137 case tfind_pc:
14138 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
14139 break;
14140 case tfind_tp:
14141 xsnprintf (p, endbuf - p, "tdp:%x", num);
14142 break;
14143 case tfind_range:
14144 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
14145 phex_nz (addr2, 0));
14146 break;
14147 case tfind_outside:
14148 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
14149 phex_nz (addr2, 0));
14150 break;
14151 default:
14152 error (_("Unknown trace find type %d"), type);
14155 putpkt (rs->buf);
14156 reply = remote_get_noisy_reply ();
14157 if (*reply == '\0')
14158 error (_("Target does not support this command."));
14160 while (reply && *reply)
14161 switch (*reply)
14163 case 'F':
14164 p = ++reply;
14165 target_frameno = (int) strtol (p, &reply, 16);
14166 if (reply == p)
14167 error (_("Unable to parse trace frame number"));
14168 /* Don't update our remote traceframe number cache on failure
14169 to select a remote traceframe. */
14170 if (target_frameno == -1)
14171 return -1;
14172 break;
14173 case 'T':
14174 p = ++reply;
14175 target_tracept = (int) strtol (p, &reply, 16);
14176 if (reply == p)
14177 error (_("Unable to parse tracepoint number"));
14178 break;
14179 case 'O': /* "OK"? */
14180 if (reply[1] == 'K' && reply[2] == '\0')
14181 reply += 2;
14182 else
14183 error (_("Bogus reply from target: %s"), reply);
14184 break;
14185 default:
14186 error (_("Bogus reply from target: %s"), reply);
14188 if (tpp)
14189 *tpp = target_tracept;
14191 rs->remote_traceframe_number = target_frameno;
14192 return target_frameno;
14195 bool
14196 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
14198 struct remote_state *rs = get_remote_state ();
14199 char *reply;
14200 ULONGEST uval;
14202 set_remote_traceframe ();
14204 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
14205 putpkt (rs->buf);
14206 reply = remote_get_noisy_reply ();
14207 if (reply && *reply)
14209 if (*reply == 'V')
14211 unpack_varlen_hex (reply + 1, &uval);
14212 *val = (LONGEST) uval;
14213 return true;
14216 return false;
14220 remote_target::save_trace_data (const char *filename)
14222 struct remote_state *rs = get_remote_state ();
14223 char *p, *reply;
14225 p = rs->buf.data ();
14226 strcpy (p, "QTSave:");
14227 p += strlen (p);
14228 if ((p - rs->buf.data ()) + strlen (filename) * 2
14229 >= get_remote_packet_size ())
14230 error (_("Remote file name too long for trace save packet"));
14231 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14232 *p++ = '\0';
14233 putpkt (rs->buf);
14234 reply = remote_get_noisy_reply ();
14235 if (*reply == '\0')
14236 error (_("Target does not support this command."));
14237 if (strcmp (reply, "OK") != 0)
14238 error (_("Bogus reply from target: %s"), reply);
14239 return 0;
14242 /* This is basically a memory transfer, but needs to be its own packet
14243 because we don't know how the target actually organizes its trace
14244 memory, plus we want to be able to ask for as much as possible, but
14245 not be unhappy if we don't get as much as we ask for. */
14247 LONGEST
14248 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14250 struct remote_state *rs = get_remote_state ();
14251 char *reply;
14252 char *p;
14253 int rslt;
14255 p = rs->buf.data ();
14256 strcpy (p, "qTBuffer:");
14257 p += strlen (p);
14258 p += hexnumstr (p, offset);
14259 *p++ = ',';
14260 p += hexnumstr (p, len);
14261 *p++ = '\0';
14263 putpkt (rs->buf);
14264 reply = remote_get_noisy_reply ();
14265 if (reply && *reply)
14267 /* 'l' by itself means we're at the end of the buffer and
14268 there is nothing more to get. */
14269 if (*reply == 'l')
14270 return 0;
14272 /* Convert the reply into binary. Limit the number of bytes to
14273 convert according to our passed-in buffer size, rather than
14274 what was returned in the packet; if the target is
14275 unexpectedly generous and gives us a bigger reply than we
14276 asked for, we don't want to crash. */
14277 rslt = hex2bin (reply, buf, len);
14278 return rslt;
14281 /* Something went wrong, flag as an error. */
14282 return -1;
14285 void
14286 remote_target::set_disconnected_tracing (int val)
14288 struct remote_state *rs = get_remote_state ();
14290 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14291 == PACKET_ENABLE)
14293 char *reply;
14295 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14296 "QTDisconnected:%x", val);
14297 putpkt (rs->buf);
14298 reply = remote_get_noisy_reply ();
14299 if (*reply == '\0')
14300 error (_("Target does not support this command."));
14301 if (strcmp (reply, "OK") != 0)
14302 error (_("Bogus reply from target: %s"), reply);
14304 else if (val)
14305 warning (_("Target does not support disconnected tracing."));
14309 remote_target::core_of_thread (ptid_t ptid)
14311 thread_info *info = this->find_thread (ptid);
14313 if (info != NULL && info->priv != NULL)
14314 return get_remote_thread_info (info)->core;
14316 return -1;
14319 void
14320 remote_target::set_circular_trace_buffer (int val)
14322 struct remote_state *rs = get_remote_state ();
14323 char *reply;
14325 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14326 "QTBuffer:circular:%x", val);
14327 putpkt (rs->buf);
14328 reply = remote_get_noisy_reply ();
14329 if (*reply == '\0')
14330 error (_("Target does not support this command."));
14331 if (strcmp (reply, "OK") != 0)
14332 error (_("Bogus reply from target: %s"), reply);
14335 traceframe_info_up
14336 remote_target::traceframe_info ()
14338 std::optional<gdb::char_vector> text
14339 = target_read_stralloc (current_inferior ()->top_target (),
14340 TARGET_OBJECT_TRACEFRAME_INFO,
14341 NULL);
14342 if (text)
14343 return parse_traceframe_info (text->data ());
14345 return NULL;
14348 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14349 instruction on which a fast tracepoint may be placed. Returns -1
14350 if the packet is not supported, and 0 if the minimum instruction
14351 length is unknown. */
14354 remote_target::get_min_fast_tracepoint_insn_len ()
14356 struct remote_state *rs = get_remote_state ();
14357 char *reply;
14359 /* If we're not debugging a process yet, the IPA can't be
14360 loaded. */
14361 if (!target_has_execution ())
14362 return 0;
14364 /* Make sure the remote is pointing at the right process. */
14365 set_general_process ();
14367 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14368 putpkt (rs->buf);
14369 reply = remote_get_noisy_reply ();
14370 if (*reply == '\0')
14371 return -1;
14372 else
14374 ULONGEST min_insn_len;
14376 unpack_varlen_hex (reply, &min_insn_len);
14378 return (int) min_insn_len;
14382 void
14383 remote_target::set_trace_buffer_size (LONGEST val)
14385 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14387 struct remote_state *rs = get_remote_state ();
14388 char *buf = rs->buf.data ();
14389 char *endbuf = buf + get_remote_packet_size ();
14391 gdb_assert (val >= 0 || val == -1);
14392 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14393 /* Send -1 as literal "-1" to avoid host size dependency. */
14394 if (val < 0)
14396 *buf++ = '-';
14397 buf += hexnumstr (buf, (ULONGEST) -val);
14399 else
14400 buf += hexnumstr (buf, (ULONGEST) val);
14402 putpkt (rs->buf);
14403 remote_get_noisy_reply ();
14404 packet_result result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14405 switch (result.status ())
14407 case PACKET_ERROR:
14408 warning (_("Error reply from target: %s"), result.err_msg ());
14409 break;
14410 case PACKET_UNKNOWN:
14411 warning (_("Remote target failed to process the request "));
14416 bool
14417 remote_target::set_trace_notes (const char *user, const char *notes,
14418 const char *stop_notes)
14420 struct remote_state *rs = get_remote_state ();
14421 char *reply;
14422 char *buf = rs->buf.data ();
14423 char *endbuf = buf + get_remote_packet_size ();
14424 int nbytes;
14426 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14427 if (user)
14429 buf += xsnprintf (buf, endbuf - buf, "user:");
14430 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14431 buf += 2 * nbytes;
14432 *buf++ = ';';
14434 if (notes)
14436 buf += xsnprintf (buf, endbuf - buf, "notes:");
14437 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14438 buf += 2 * nbytes;
14439 *buf++ = ';';
14441 if (stop_notes)
14443 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14444 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14445 buf += 2 * nbytes;
14446 *buf++ = ';';
14448 /* Ensure the buffer is terminated. */
14449 *buf = '\0';
14451 putpkt (rs->buf);
14452 reply = remote_get_noisy_reply ();
14453 if (*reply == '\0')
14454 return false;
14456 if (strcmp (reply, "OK") != 0)
14457 error (_("Bogus reply from target: %s"), reply);
14459 return true;
14462 bool
14463 remote_target::use_agent (bool use)
14465 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14467 struct remote_state *rs = get_remote_state ();
14469 /* If the stub supports QAgent. */
14470 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14471 putpkt (rs->buf);
14472 getpkt (&rs->buf);
14474 if (strcmp (rs->buf.data (), "OK") == 0)
14476 ::use_agent = use;
14477 return true;
14481 return false;
14484 bool
14485 remote_target::can_use_agent ()
14487 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14490 #if defined (HAVE_LIBEXPAT)
14492 /* Check the btrace document version. */
14494 static void
14495 check_xml_btrace_version (struct gdb_xml_parser *parser,
14496 const struct gdb_xml_element *element,
14497 void *user_data,
14498 std::vector<gdb_xml_value> &attributes)
14500 const char *version
14501 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14503 if (strcmp (version, "1.0") != 0)
14504 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14507 /* Parse a btrace "block" xml record. */
14509 static void
14510 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14511 const struct gdb_xml_element *element,
14512 void *user_data,
14513 std::vector<gdb_xml_value> &attributes)
14515 struct btrace_data *btrace;
14516 ULONGEST *begin, *end;
14518 btrace = (struct btrace_data *) user_data;
14520 switch (btrace->format)
14522 case BTRACE_FORMAT_BTS:
14523 break;
14525 case BTRACE_FORMAT_NONE:
14526 btrace->format = BTRACE_FORMAT_BTS;
14527 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14528 break;
14530 default:
14531 gdb_xml_error (parser, _("Btrace format error."));
14534 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14535 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14536 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14539 /* Parse a "raw" xml record. */
14541 static void
14542 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14543 gdb_byte **pdata, size_t *psize)
14545 gdb_byte *bin;
14546 size_t len, size;
14548 len = strlen (body_text);
14549 if (len % 2 != 0)
14550 gdb_xml_error (parser, _("Bad raw data size."));
14552 size = len / 2;
14554 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14555 bin = data.get ();
14557 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14558 while (len > 0)
14560 char hi, lo;
14562 hi = *body_text++;
14563 lo = *body_text++;
14565 if (hi == 0 || lo == 0)
14566 gdb_xml_error (parser, _("Bad hex encoding."));
14568 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14569 len -= 2;
14572 *pdata = data.release ();
14573 *psize = size;
14576 /* Parse a btrace pt-config "cpu" xml record. */
14578 static void
14579 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14580 const struct gdb_xml_element *element,
14581 void *user_data,
14582 std::vector<gdb_xml_value> &attributes)
14584 struct btrace_data *btrace;
14585 const char *vendor;
14586 ULONGEST *family, *model, *stepping;
14588 vendor
14589 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14590 family
14591 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14592 model
14593 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14594 stepping
14595 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14597 btrace = (struct btrace_data *) user_data;
14599 if (strcmp (vendor, "GenuineIntel") == 0)
14600 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14602 btrace->variant.pt.config.cpu.family = *family;
14603 btrace->variant.pt.config.cpu.model = *model;
14604 btrace->variant.pt.config.cpu.stepping = *stepping;
14607 /* Parse a btrace pt "raw" xml record. */
14609 static void
14610 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14611 const struct gdb_xml_element *element,
14612 void *user_data, const char *body_text)
14614 struct btrace_data *btrace;
14616 btrace = (struct btrace_data *) user_data;
14617 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14618 &btrace->variant.pt.size);
14621 /* Parse a btrace "pt" xml record. */
14623 static void
14624 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14625 const struct gdb_xml_element *element,
14626 void *user_data,
14627 std::vector<gdb_xml_value> &attributes)
14629 struct btrace_data *btrace;
14631 btrace = (struct btrace_data *) user_data;
14632 btrace->format = BTRACE_FORMAT_PT;
14633 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14634 btrace->variant.pt.data = NULL;
14635 btrace->variant.pt.size = 0;
14638 static const struct gdb_xml_attribute block_attributes[] = {
14639 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14640 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14641 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14644 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14645 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14646 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14647 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14648 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14649 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14652 static const struct gdb_xml_element btrace_pt_config_children[] = {
14653 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14654 parse_xml_btrace_pt_config_cpu, NULL },
14655 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14658 static const struct gdb_xml_element btrace_pt_children[] = {
14659 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14660 NULL },
14661 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14662 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14665 static const struct gdb_xml_attribute btrace_attributes[] = {
14666 { "version", GDB_XML_AF_NONE, NULL, NULL },
14667 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14670 static const struct gdb_xml_element btrace_children[] = {
14671 { "block", block_attributes, NULL,
14672 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14673 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14674 NULL },
14675 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14678 static const struct gdb_xml_element btrace_elements[] = {
14679 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14680 check_xml_btrace_version, NULL },
14681 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14684 #endif /* defined (HAVE_LIBEXPAT) */
14686 /* Parse a branch trace xml document XML into DATA. */
14688 static void
14689 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14691 #if defined (HAVE_LIBEXPAT)
14693 int errcode;
14694 btrace_data result;
14695 result.format = BTRACE_FORMAT_NONE;
14697 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14698 buffer, &result);
14699 if (errcode != 0)
14700 error (_("Error parsing branch trace."));
14702 /* Keep parse results. */
14703 *btrace = std::move (result);
14705 #else /* !defined (HAVE_LIBEXPAT) */
14707 error (_("Cannot process branch trace. XML support was disabled at "
14708 "compile time."));
14710 #endif /* !defined (HAVE_LIBEXPAT) */
14713 #if defined (HAVE_LIBEXPAT)
14715 /* Parse a btrace-conf "bts" xml record. */
14717 static void
14718 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14719 const struct gdb_xml_element *element,
14720 void *user_data,
14721 std::vector<gdb_xml_value> &attributes)
14723 struct btrace_config *conf;
14724 struct gdb_xml_value *size;
14726 conf = (struct btrace_config *) user_data;
14727 conf->format = BTRACE_FORMAT_BTS;
14728 conf->bts.size = 0;
14730 size = xml_find_attribute (attributes, "size");
14731 if (size != NULL)
14732 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14735 /* Parse a btrace-conf "pt" xml record. */
14737 static void
14738 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14739 const struct gdb_xml_element *element,
14740 void *user_data,
14741 std::vector<gdb_xml_value> &attributes)
14743 struct btrace_config *conf;
14744 struct gdb_xml_value *size, *ptwrite;
14746 conf = (struct btrace_config *) user_data;
14747 conf->format = BTRACE_FORMAT_PT;
14748 conf->pt.size = 0;
14750 size = xml_find_attribute (attributes, "size");
14751 if (size != NULL)
14752 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14754 ptwrite = xml_find_attribute (attributes, "ptwrite");
14755 if (ptwrite != nullptr)
14756 conf->pt.ptwrite = (bool) *(ULONGEST *) ptwrite->value.get ();
14759 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14760 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14761 { "ptwrite", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_enum,
14762 gdb_xml_enums_boolean },
14763 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14766 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14767 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14768 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14771 static const struct gdb_xml_element btrace_conf_children[] = {
14772 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14773 parse_xml_btrace_conf_bts, NULL },
14774 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14775 parse_xml_btrace_conf_pt, NULL },
14776 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14779 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14780 { "version", GDB_XML_AF_NONE, NULL, NULL },
14781 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14784 static const struct gdb_xml_element btrace_conf_elements[] = {
14785 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14786 GDB_XML_EF_NONE, NULL, NULL },
14787 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14790 #endif /* defined (HAVE_LIBEXPAT) */
14792 /* Parse a branch trace configuration xml document XML into CONF. */
14794 static void
14795 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14797 #if defined (HAVE_LIBEXPAT)
14799 int errcode;
14800 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14801 btrace_conf_elements, xml, conf);
14802 if (errcode != 0)
14803 error (_("Error parsing branch trace configuration."));
14805 #else /* !defined (HAVE_LIBEXPAT) */
14807 error (_("Cannot process the branch trace configuration. XML support "
14808 "was disabled at compile time."));
14810 #endif /* !defined (HAVE_LIBEXPAT) */
14813 /* Reset our idea of our target's btrace configuration. */
14815 static void
14816 remote_btrace_reset (remote_state *rs)
14818 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14821 /* Synchronize the configuration with the target. */
14823 void
14824 remote_target::btrace_sync_conf (const btrace_config *conf)
14826 struct remote_state *rs;
14827 char *buf, *pos, *endbuf;
14829 rs = get_remote_state ();
14830 buf = rs->buf.data ();
14831 endbuf = buf + get_remote_packet_size ();
14833 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14834 && conf->bts.size != rs->btrace_config.bts.size)
14836 pos = buf;
14837 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14838 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14839 conf->bts.size);
14841 putpkt (buf);
14842 getpkt (&rs->buf);
14844 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size);
14845 if (result.status () == PACKET_ERROR)
14846 error (_("Failed to configure the BTS buffer size: %s"), result.err_msg ());
14848 rs->btrace_config.bts.size = conf->bts.size;
14851 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14852 && conf->pt.size != rs->btrace_config.pt.size)
14854 pos = buf;
14855 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14856 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14857 conf->pt.size);
14859 putpkt (buf);
14860 getpkt (&rs->buf);
14862 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size);
14863 if (result.status () == PACKET_ERROR)
14864 error (_("Failed to configure the trace buffer size: %s"), result.err_msg ());
14866 rs->btrace_config.pt.size = conf->pt.size;
14869 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_ptwrite)
14870 == PACKET_ENABLE)
14871 && conf->pt.ptwrite != rs->btrace_config.pt.ptwrite)
14873 pos = buf;
14874 const char *ptw = conf->pt.ptwrite ? "yes" : "no";
14875 const char *name
14876 = packets_descriptions[PACKET_Qbtrace_conf_pt_ptwrite].name;
14877 pos += xsnprintf (pos, endbuf - pos, "%s=\"%s\"", name, ptw);
14879 putpkt (buf);
14880 getpkt (&rs->buf, 0);
14882 packet_result result
14883 = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_ptwrite);
14884 if (result.status () == PACKET_ERROR)
14886 if (buf[0] == 'E' && buf[1] == '.')
14887 error (_("Failed to sync ptwrite config: %s"), buf + 2);
14888 else
14889 error (_("Failed to sync ptwrite config."));
14892 rs->btrace_config.pt.ptwrite = conf->pt.ptwrite;
14896 /* Read TP's btrace configuration from the target and store it into CONF. */
14898 static void
14899 btrace_read_config (thread_info *tp, btrace_config *conf)
14901 /* target_read_stralloc relies on INFERIOR_PTID. */
14902 scoped_restore_current_thread restore_thread;
14903 switch_to_thread (tp);
14905 std::optional<gdb::char_vector> xml
14906 = target_read_stralloc (current_inferior ()->top_target (),
14907 TARGET_OBJECT_BTRACE_CONF, "");
14908 if (xml)
14909 parse_xml_btrace_conf (conf, xml->data ());
14912 /* Maybe reopen target btrace. */
14914 void
14915 remote_target::remote_btrace_maybe_reopen ()
14917 struct remote_state *rs = get_remote_state ();
14918 int btrace_target_pushed = 0;
14919 #if !defined (HAVE_LIBIPT)
14920 int warned = 0;
14921 #endif
14923 /* Don't bother walking the entirety of the remote thread list when
14924 we know the feature isn't supported by the remote. */
14925 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14926 return;
14928 for (thread_info *tp : all_non_exited_threads (this))
14930 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14931 btrace_read_config (tp, &rs->btrace_config);
14933 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14934 continue;
14936 #if !defined (HAVE_LIBIPT)
14937 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14939 if (!warned)
14941 warned = 1;
14942 warning (_("Target is recording using Intel Processor Trace "
14943 "but support was disabled at compile time."));
14946 continue;
14948 #endif /* !defined (HAVE_LIBIPT) */
14950 /* Push target, once, but before anything else happens. This way our
14951 changes to the threads will be cleaned up by unpushing the target
14952 in case btrace_read_config () throws. */
14953 if (!btrace_target_pushed)
14955 btrace_target_pushed = 1;
14956 record_btrace_push_target ();
14957 gdb_printf (_("Target is recording using %s.\n"),
14958 btrace_format_string (rs->btrace_config.format));
14961 tp->btrace.target
14962 = new btrace_target_info { tp->ptid, rs->btrace_config };
14966 /* Enable branch tracing. */
14968 struct btrace_target_info *
14969 remote_target::enable_btrace (thread_info *tp,
14970 const struct btrace_config *conf)
14972 struct packet_config *packet = NULL;
14973 struct remote_state *rs = get_remote_state ();
14974 char *buf = rs->buf.data ();
14975 char *endbuf = buf + get_remote_packet_size ();
14977 unsigned int which_packet;
14978 switch (conf->format)
14980 case BTRACE_FORMAT_BTS:
14981 which_packet = PACKET_Qbtrace_bts;
14982 break;
14983 case BTRACE_FORMAT_PT:
14984 which_packet = PACKET_Qbtrace_pt;
14985 break;
14986 default:
14987 internal_error (_("Bad branch btrace format: %u."),
14988 (unsigned int) conf->format);
14991 packet = &m_features.m_protocol_packets[which_packet];
14992 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14993 error (_("Target does not support branch tracing."));
14995 btrace_sync_conf (conf);
14997 ptid_t ptid = tp->ptid;
14998 set_general_thread (ptid);
15000 buf += xsnprintf (buf, endbuf - buf, "%s",
15001 packets_descriptions[which_packet].name);
15002 putpkt (rs->buf);
15003 getpkt (&rs->buf);
15005 packet_result result = m_features.packet_ok (rs->buf, which_packet);
15006 if (result.status () == PACKET_ERROR)
15007 error (_("Could not enable branch tracing for %s: %s"),
15008 target_pid_to_str (ptid).c_str (), result.err_msg ());
15010 btrace_target_info *tinfo = new btrace_target_info { ptid };
15012 /* If we fail to read the configuration, we lose some information, but the
15013 tracing itself is not impacted. */
15016 btrace_read_config (tp, &tinfo->conf);
15018 catch (const gdb_exception_error &err)
15020 if (err.message != NULL)
15021 warning ("%s", err.what ());
15024 return tinfo;
15027 /* Disable branch tracing. */
15029 void
15030 remote_target::disable_btrace (struct btrace_target_info *tinfo)
15032 struct remote_state *rs = get_remote_state ();
15033 char *buf = rs->buf.data ();
15034 char *endbuf = buf + get_remote_packet_size ();
15036 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
15037 error (_("Target does not support branch tracing."));
15039 set_general_thread (tinfo->ptid);
15041 buf += xsnprintf (buf, endbuf - buf, "%s",
15042 packets_descriptions[PACKET_Qbtrace_off].name);
15043 putpkt (rs->buf);
15044 getpkt (&rs->buf);
15046 packet_result result = m_features.packet_ok (rs->buf, PACKET_Qbtrace_off);
15047 if (result.status () == PACKET_ERROR)
15048 error (_("Could not disable branch tracing for %s: %s"),
15049 target_pid_to_str (tinfo->ptid).c_str (), result.err_msg ());
15051 delete tinfo;
15054 /* Teardown branch tracing. */
15056 void
15057 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
15059 /* We must not talk to the target during teardown. */
15060 delete tinfo;
15063 /* Read the branch trace. */
15065 enum btrace_error
15066 remote_target::read_btrace (struct btrace_data *btrace,
15067 struct btrace_target_info *tinfo,
15068 enum btrace_read_type type)
15070 const char *annex;
15072 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
15073 error (_("Target does not support branch tracing."));
15075 #if !defined(HAVE_LIBEXPAT)
15076 error (_("Cannot process branch tracing result. XML parsing not supported."));
15077 #endif
15079 switch (type)
15081 case BTRACE_READ_ALL:
15082 annex = "all";
15083 break;
15084 case BTRACE_READ_NEW:
15085 annex = "new";
15086 break;
15087 case BTRACE_READ_DELTA:
15088 annex = "delta";
15089 break;
15090 default:
15091 internal_error (_("Bad branch tracing read type: %u."),
15092 (unsigned int) type);
15095 std::optional<gdb::char_vector> xml
15096 = target_read_stralloc (current_inferior ()->top_target (),
15097 TARGET_OBJECT_BTRACE, annex);
15098 if (!xml)
15099 return BTRACE_ERR_UNKNOWN;
15101 parse_xml_btrace (btrace, xml->data ());
15103 return BTRACE_ERR_NONE;
15106 const struct btrace_config *
15107 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
15109 return &tinfo->conf;
15112 bool
15113 remote_target::augmented_libraries_svr4_read ()
15115 return
15116 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
15117 == PACKET_ENABLE);
15120 /* Implementation of to_load. */
15122 void
15123 remote_target::load (const char *name, int from_tty)
15125 generic_load (name, from_tty);
15128 /* Accepts an integer PID; returns a string representing a file that
15129 can be opened on the remote side to get the symbols for the child
15130 process. Returns NULL if the operation is not supported. */
15132 const char *
15133 remote_target::pid_to_exec_file (int pid)
15135 static std::optional<gdb::char_vector> filename;
15136 char *annex = NULL;
15138 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
15139 return NULL;
15141 inferior *inf = find_inferior_pid (this, pid);
15142 if (inf == NULL)
15143 internal_error (_("not currently attached to process %d"), pid);
15145 if (!inf->fake_pid_p)
15147 const int annex_size = 9;
15149 annex = (char *) alloca (annex_size);
15150 xsnprintf (annex, annex_size, "%x", pid);
15153 filename = target_read_stralloc (current_inferior ()->top_target (),
15154 TARGET_OBJECT_EXEC_FILE, annex);
15156 return filename ? filename->data () : nullptr;
15159 /* Implement the to_can_do_single_step target_ops method. */
15162 remote_target::can_do_single_step ()
15164 /* We can only tell whether target supports single step or not by
15165 supported s and S vCont actions if the stub supports vContSupported
15166 feature. If the stub doesn't support vContSupported feature,
15167 we have conservatively to think target doesn't supports single
15168 step. */
15169 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
15171 struct remote_state *rs = get_remote_state ();
15173 return rs->supports_vCont.s && rs->supports_vCont.S;
15175 else
15176 return 0;
15179 /* Implementation of the to_execution_direction method for the remote
15180 target. */
15182 enum exec_direction_kind
15183 remote_target::execution_direction ()
15185 struct remote_state *rs = get_remote_state ();
15187 return rs->last_resume_exec_dir;
15190 /* Return pointer to the thread_info struct which corresponds to
15191 THREAD_HANDLE (having length HANDLE_LEN). */
15193 thread_info *
15194 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
15195 int handle_len,
15196 inferior *inf)
15198 for (thread_info *tp : all_non_exited_threads (this))
15200 remote_thread_info *priv = get_remote_thread_info (tp);
15202 if (tp->inf == inf && priv != NULL)
15204 if (handle_len != priv->thread_handle.size ())
15205 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15206 handle_len, priv->thread_handle.size ());
15207 if (memcmp (thread_handle, priv->thread_handle.data (),
15208 handle_len) == 0)
15209 return tp;
15213 return NULL;
15216 gdb::array_view<const gdb_byte>
15217 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15219 remote_thread_info *priv = get_remote_thread_info (tp);
15220 return priv->thread_handle;
15223 bool
15224 remote_target::can_async_p ()
15226 /* This flag should be checked in the common target.c code. */
15227 gdb_assert (target_async_permitted);
15229 /* We're async whenever the serial device can. */
15230 return get_remote_state ()->can_async_p ();
15233 bool
15234 remote_target::is_async_p ()
15236 /* We're async whenever the serial device is. */
15237 return get_remote_state ()->is_async_p ();
15240 /* Pass the SERIAL event on and up to the client. One day this code
15241 will be able to delay notifying the client of an event until the
15242 point where an entire packet has been received. */
15244 static serial_event_ftype remote_async_serial_handler;
15246 static void
15247 remote_async_serial_handler (struct serial *scb, void *context)
15249 /* Don't propogate error information up to the client. Instead let
15250 the client find out about the error by querying the target. */
15251 inferior_event_handler (INF_REG_EVENT);
15255 remote_target::async_wait_fd ()
15257 struct remote_state *rs = get_remote_state ();
15258 return rs->remote_desc->fd;
15261 void
15262 remote_target::async (bool enable)
15264 struct remote_state *rs = get_remote_state ();
15266 if (enable)
15268 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15270 /* If there are pending events in the stop reply queue tell the
15271 event loop to process them. */
15272 if (!rs->stop_reply_queue.empty ())
15273 rs->mark_async_event_handler ();
15275 /* For simplicity, below we clear the pending events token
15276 without remembering whether it is marked, so here we always
15277 mark it. If there's actually no pending notification to
15278 process, this ends up being a no-op (other than a spurious
15279 event-loop wakeup). */
15280 if (target_is_non_stop_p ())
15281 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15283 else
15285 serial_async (rs->remote_desc, NULL, NULL);
15286 /* If the core is disabling async, it doesn't want to be
15287 disturbed with target events. Clear all async event sources
15288 too. */
15289 rs->clear_async_event_handler ();
15291 if (target_is_non_stop_p ())
15292 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15296 /* Implementation of the to_thread_events method. */
15298 void
15299 remote_target::thread_events (bool enable)
15301 struct remote_state *rs = get_remote_state ();
15302 size_t size = get_remote_packet_size ();
15304 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15305 return;
15307 if (rs->last_thread_events == enable)
15308 return;
15310 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15311 putpkt (rs->buf);
15312 getpkt (&rs->buf);
15314 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadEvents);
15315 switch (result.status ())
15317 case PACKET_OK:
15318 if (strcmp (rs->buf.data (), "OK") != 0)
15319 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15320 rs->last_thread_events = enable;
15321 break;
15322 case PACKET_ERROR:
15323 warning (_("Remote failure reply: %s"), result.err_msg ());
15324 break;
15325 case PACKET_UNKNOWN:
15326 break;
15330 /* Implementation of the supports_set_thread_options target
15331 method. */
15333 bool
15334 remote_target::supports_set_thread_options (gdb_thread_options options)
15336 remote_state *rs = get_remote_state ();
15337 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15338 && (rs->supported_thread_options & options) == options);
15341 /* For coalescing reasons, actually sending the options to the target
15342 happens at resume time, via this function. See target_resume for
15343 all-stop, and target_commit_resumed for non-stop. */
15345 void
15346 remote_target::commit_requested_thread_options ()
15348 struct remote_state *rs = get_remote_state ();
15350 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15351 return;
15353 char *p = rs->buf.data ();
15354 char *endp = p + get_remote_packet_size ();
15356 /* Clear options for all threads by default. Note that unlike
15357 vCont, the rightmost options that match a thread apply, so we
15358 don't have to worry about whether we can use wildcard ptids. */
15359 strcpy (p, "QThreadOptions;0");
15360 p += strlen (p);
15362 /* Send the QThreadOptions packet stored in P. */
15363 auto flush = [&] ()
15365 *p++ = '\0';
15367 putpkt (rs->buf);
15368 getpkt (&rs->buf, 0);
15370 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadOptions);
15371 switch (result.status ())
15373 case PACKET_OK:
15374 if (strcmp (rs->buf.data (), "OK") != 0)
15375 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15376 break;
15377 case PACKET_ERROR:
15378 error (_("Remote failure reply: %s"), result.err_msg ());
15379 case PACKET_UNKNOWN:
15380 gdb_assert_not_reached ("PACKET_UNKNOWN");
15381 break;
15385 /* Prepare P for another QThreadOptions packet. */
15386 auto restart = [&] ()
15388 p = rs->buf.data ();
15389 strcpy (p, "QThreadOptions");
15390 p += strlen (p);
15393 /* Now set non-zero options for threads that need them. We don't
15394 bother with the case of all threads of a process wanting the same
15395 non-zero options as that's not an expected scenario. */
15396 for (thread_info *tp : all_non_exited_threads (this))
15398 gdb_thread_options options = tp->thread_options ();
15400 if (options == 0)
15401 continue;
15403 /* It might be possible to we have more threads with options
15404 than can fit a single QThreadOptions packet. So build each
15405 options/thread pair in this separate buffer to make sure it
15406 fits. */
15407 constexpr size_t max_options_size = 100;
15408 char obuf[max_options_size];
15409 char *obuf_p = obuf;
15410 char *obuf_endp = obuf + max_options_size;
15412 *obuf_p++ = ';';
15413 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15414 phex_nz (options, sizeof (options)));
15415 if (tp->ptid != magic_null_ptid)
15417 *obuf_p++ = ':';
15418 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15421 size_t osize = obuf_p - obuf;
15422 if (osize > endp - p)
15424 /* This new options/thread pair doesn't fit the packet
15425 buffer. Send what we have already. */
15426 flush ();
15427 restart ();
15429 /* Should now fit. */
15430 gdb_assert (osize <= endp - p);
15433 memcpy (p, obuf, osize);
15434 p += osize;
15437 flush ();
15440 static void
15441 show_remote_cmd (const char *args, int from_tty)
15443 /* We can't just use cmd_show_list here, because we want to skip
15444 the redundant "show remote Z-packet" and the legacy aliases. */
15445 struct cmd_list_element *list = remote_show_cmdlist;
15446 struct ui_out *uiout = current_uiout;
15448 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15449 for (; list != NULL; list = list->next)
15450 if (strcmp (list->name, "Z-packet") == 0)
15451 continue;
15452 else if (list->type == not_set_cmd)
15453 /* Alias commands are exactly like the original, except they
15454 don't have the normal type. */
15455 continue;
15456 else
15458 ui_out_emit_tuple option_emitter (uiout, "option");
15460 uiout->field_string ("name", list->name);
15461 uiout->text (": ");
15462 if (list->type == show_cmd)
15463 do_show_command (NULL, from_tty, list);
15464 else
15465 cmd_func (list, NULL, from_tty);
15469 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15470 offer all inferiors using that program space a change to look up symbols. */
15472 static void
15473 remote_objfile_changed_check_symbols (program_space *pspace)
15475 /* The affected program space is possibly shared by multiple inferiors.
15476 Consider sending a qSymbol packet for each of the inferiors using that
15477 program space. */
15478 for (inferior *inf : all_inferiors ())
15480 if (inf->pspace != pspace)
15481 continue;
15483 /* Check whether the inferior's process target is a remote target. */
15484 remote_target *remote = as_remote_target (inf->process_target ());
15485 if (remote == nullptr)
15486 continue;
15488 /* When we are attaching or handling a fork child and the shared library
15489 subsystem reads the list of loaded libraries, we receive new objfile
15490 events in between each found library. The libraries are read in an
15491 undefined order, so if we gave the remote side a chance to look up
15492 symbols between each objfile, we might give it an inconsistent picture
15493 of the inferior. It could appear that a library A appears loaded but
15494 a library B does not, even though library A requires library B. That
15495 would present a state that couldn't normally exist in the inferior.
15497 So, skip these events, we'll give the remote a chance to look up
15498 symbols once all the loaded libraries and their symbols are known to
15499 GDB. */
15500 if (inf->in_initial_library_scan)
15501 continue;
15503 if (!remote->has_execution (inf))
15504 continue;
15506 /* Need to switch to a specific thread, because remote_check_symbols will
15507 set the general thread using INFERIOR_PTID.
15509 It's possible to have inferiors with no thread here, because we are
15510 called very early in the connection process, while the inferior is
15511 being set up, before threads are added. Just skip it, start_remote_1
15512 also calls remote_check_symbols when it's done setting things up. */
15513 thread_info *thread = any_thread_of_inferior (inf);
15514 if (thread != nullptr)
15516 scoped_restore_current_thread restore_thread;
15517 switch_to_thread (thread);
15518 remote->remote_check_symbols ();
15523 /* Function to be called whenever a new objfile (shlib) is detected. */
15525 static void
15526 remote_new_objfile (struct objfile *objfile)
15528 remote_objfile_changed_check_symbols (objfile->pspace ());
15531 /* Pull all the tracepoints defined on the target and create local
15532 data structures representing them. We don't want to create real
15533 tracepoints yet, we don't want to mess up the user's existing
15534 collection. */
15537 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15539 struct remote_state *rs = get_remote_state ();
15540 char *p;
15542 /* Ask for a first packet of tracepoint definition. */
15543 putpkt ("qTfP");
15544 getpkt (&rs->buf);
15545 p = rs->buf.data ();
15546 while (*p && *p != 'l')
15548 parse_tracepoint_definition (p, utpp);
15549 /* Ask for another packet of tracepoint definition. */
15550 putpkt ("qTsP");
15551 getpkt (&rs->buf);
15552 p = rs->buf.data ();
15554 return 0;
15558 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15560 struct remote_state *rs = get_remote_state ();
15561 char *p;
15563 /* Ask for a first packet of variable definition. */
15564 putpkt ("qTfV");
15565 getpkt (&rs->buf);
15566 p = rs->buf.data ();
15567 while (*p && *p != 'l')
15569 parse_tsv_definition (p, utsvp);
15570 /* Ask for another packet of variable definition. */
15571 putpkt ("qTsV");
15572 getpkt (&rs->buf);
15573 p = rs->buf.data ();
15575 return 0;
15578 /* The "set/show range-stepping" show hook. */
15580 static void
15581 show_range_stepping (struct ui_file *file, int from_tty,
15582 struct cmd_list_element *c,
15583 const char *value)
15585 gdb_printf (file,
15586 _("Debugger's willingness to use range stepping "
15587 "is %s.\n"), value);
15590 /* Return true if the vCont;r action is supported by the remote
15591 stub. */
15593 bool
15594 remote_target::vcont_r_supported ()
15596 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15597 && get_remote_state ()->supports_vCont.r);
15600 /* The "set/show range-stepping" set hook. */
15602 static void
15603 set_range_stepping (const char *ignore_args, int from_tty,
15604 struct cmd_list_element *c)
15606 /* When enabling, check whether range stepping is actually supported
15607 by the target, and warn if not. */
15608 if (use_range_stepping)
15610 remote_target *remote = get_current_remote_target ();
15611 if (remote == NULL
15612 || !remote->vcont_r_supported ())
15613 warning (_("Range stepping is not supported by the current target"));
15617 static void
15618 show_remote_debug (struct ui_file *file, int from_tty,
15619 struct cmd_list_element *c, const char *value)
15621 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15622 value);
15625 static void
15626 show_remote_timeout (struct ui_file *file, int from_tty,
15627 struct cmd_list_element *c, const char *value)
15629 gdb_printf (file,
15630 _("Timeout limit to wait for target to respond is %s.\n"),
15631 value);
15634 /* Implement the "supports_memory_tagging" target_ops method. */
15636 bool
15637 remote_target::supports_memory_tagging ()
15639 return m_features.remote_memory_tagging_p ();
15642 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15644 static void
15645 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15646 size_t len, int type)
15648 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15650 std::string request = string_printf ("qMemTags:%s,%s:%s",
15651 phex_nz (address, addr_size),
15652 phex_nz (len, sizeof (len)),
15653 phex_nz (type, sizeof (type)));
15655 strcpy (packet.data (), request.c_str ());
15658 /* Parse the qMemTags packet reply into TAGS.
15660 Return true if successful, false otherwise. */
15662 static bool
15663 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15664 gdb::byte_vector &tags)
15666 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15667 return false;
15669 /* Copy the tag data. */
15670 tags = hex2bin (reply.data () + 1);
15672 return true;
15675 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15677 static void
15678 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15679 size_t len, int type,
15680 const gdb::byte_vector &tags)
15682 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15684 /* Put together the main packet, address and length. */
15685 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15686 phex_nz (address, addr_size),
15687 phex_nz (len, sizeof (len)),
15688 phex_nz (type, sizeof (type)));
15689 request += bin2hex (tags.data (), tags.size ());
15691 /* Check if we have exceeded the maximum packet size. */
15692 if (packet.size () < request.length ())
15693 error (_("Contents too big for packet QMemTags."));
15695 strcpy (packet.data (), request.c_str ());
15698 static void
15699 create_is_address_tagged_request (gdbarch *gdbarch, gdb::char_vector &packet,
15700 CORE_ADDR address)
15702 int addr_size;
15703 std::string request;
15705 addr_size = gdbarch_addr_bit (gdbarch) / 8;
15706 request = string_printf ("qIsAddressTagged:%s", phex_nz (address, addr_size));
15708 if (packet.size () < request.length () + 1)
15709 error (_("Contents too big for packet qIsAddressTagged."));
15711 strcpy (packet.data (), request.c_str ());
15714 static bool
15715 check_is_address_tagged_reply (remote_target *remote, gdb::char_vector &packet,
15716 bool &tagged)
15718 gdb_assert (remote != nullptr);
15719 /* Check reply and disable qIsAddressTagged usage if it's not supported. */
15720 packet_result result = remote->m_features.packet_ok (packet,
15721 PACKET_qIsAddressTagged);
15723 /* Return false on error (Exx), empty reply (packet not supported), or reply
15724 size doesn't match 2 hex digits. */
15725 if ((result.status () != PACKET_OK) || (strlen (packet.data ()) != 2))
15726 return false;
15728 gdb_byte reply;
15729 /* Convert only 2 hex digits, i.e. 1 byte in hex format. */
15730 hex2bin (packet.data (), &reply, 1);
15732 if (reply == 0x00 || reply == 0x01)
15734 tagged = !!reply;
15735 return true;
15738 /* Invalid reply. */
15739 return false;
15742 /* Implement the "fetch_memtags" target_ops method. */
15744 bool
15745 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15746 gdb::byte_vector &tags, int type)
15748 /* Make sure the qMemTags packet is supported. */
15749 if (!m_features.remote_memory_tagging_p ())
15750 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15752 struct remote_state *rs = get_remote_state ();
15754 create_fetch_memtags_request (rs->buf, address, len, type);
15756 putpkt (rs->buf);
15757 getpkt (&rs->buf);
15759 return parse_fetch_memtags_reply (rs->buf, tags);
15762 /* Implement the "store_memtags" target_ops method. */
15764 bool
15765 remote_target::store_memtags (CORE_ADDR address, size_t len,
15766 const gdb::byte_vector &tags, int type)
15768 /* Make sure the QMemTags packet is supported. */
15769 if (!m_features.remote_memory_tagging_p ())
15770 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15772 struct remote_state *rs = get_remote_state ();
15774 create_store_memtags_request (rs->buf, address, len, type, tags);
15776 putpkt (rs->buf);
15777 getpkt (&rs->buf);
15779 /* Verify if the request was successful. */
15780 return packet_check_result (rs->buf).status () == PACKET_OK;
15783 /* Implement the "is_address_tagged" target_ops method. */
15785 bool
15786 remote_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
15788 /* Firstly, attempt to check the address using the qIsAddressTagged
15789 packet. */
15790 if (m_features.packet_support (PACKET_qIsAddressTagged) != PACKET_DISABLE)
15792 remote_target *remote = get_current_remote_target ();
15793 struct remote_state *rs = get_remote_state ();
15794 bool is_addr_tagged;
15796 create_is_address_tagged_request (gdbarch, rs->buf, address);
15798 putpkt (rs->buf);
15799 getpkt (&rs->buf);
15801 /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
15802 set to PACKET_DISABLE so no further attempt is made to check addresses
15803 using this packet and the fallback mechanism below will be used
15804 instead. Also, if the check fails due to an error (Exx reply) the
15805 fallback is used too. Otherwise, the qIsAddressTagged query succeeded
15806 and is_addr_tagged is valid. */
15807 if (check_is_address_tagged_reply (remote, rs->buf, is_addr_tagged))
15808 return is_addr_tagged;
15811 /* Fallback to arch-specific method of checking whether an address is tagged
15812 in case check via qIsAddressTagged fails. */
15813 return gdbarch_tagged_address_p (gdbarch, address);
15816 /* Return true if remote target T is non-stop. */
15818 bool
15819 remote_target_is_non_stop_p (remote_target *t)
15821 scoped_restore_current_thread restore_thread;
15822 switch_to_target_no_thread (t);
15824 return target_is_non_stop_p ();
15827 #if GDB_SELF_TEST
15829 namespace selftests {
15831 static void
15832 test_memory_tagging_functions ()
15834 remote_target remote;
15836 struct packet_config *config
15837 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15839 scoped_restore restore_memtag_support_
15840 = make_scoped_restore (&config->support);
15842 struct gdbarch *gdbarch = current_inferior ()->arch ();
15844 /* Test memory tagging packet support. */
15845 config->support = PACKET_SUPPORT_UNKNOWN;
15846 SELF_CHECK (remote.supports_memory_tagging () == false);
15847 config->support = PACKET_DISABLE;
15848 SELF_CHECK (remote.supports_memory_tagging () == false);
15849 config->support = PACKET_ENABLE;
15850 SELF_CHECK (remote.supports_memory_tagging () == true);
15852 /* Setup testing. */
15853 gdb::char_vector packet;
15854 gdb::byte_vector tags, bv;
15855 std::string expected, reply;
15856 packet.resize (32000);
15858 /* Test creating a qMemTags request. */
15860 expected = "qMemTags:0,0:0";
15861 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15862 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15864 expected = "qMemTags:deadbeef,10:1";
15865 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15866 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15868 /* Test parsing a qMemTags reply. */
15870 /* Error reply, tags vector unmodified. */
15871 reply = "E00";
15872 strcpy (packet.data (), reply.c_str ());
15873 tags.resize (0);
15874 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15875 SELF_CHECK (tags.size () == 0);
15877 /* Valid reply, tags vector updated. */
15878 tags.resize (0);
15879 bv.resize (0);
15881 for (int i = 0; i < 5; i++)
15882 bv.push_back (i);
15884 reply = "m" + bin2hex (bv.data (), bv.size ());
15885 strcpy (packet.data (), reply.c_str ());
15887 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15888 SELF_CHECK (tags.size () == 5);
15890 for (int i = 0; i < 5; i++)
15891 SELF_CHECK (tags[i] == i);
15893 /* Test creating a QMemTags request. */
15895 /* Empty tag data. */
15896 tags.resize (0);
15897 expected = "QMemTags:0,0:0:";
15898 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15899 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15900 expected.length ()) == 0);
15902 /* Non-empty tag data. */
15903 tags.resize (0);
15904 for (int i = 0; i < 5; i++)
15905 tags.push_back (i);
15906 expected = "QMemTags:deadbeef,ff:1:0001020304";
15907 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15908 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15909 expected.length ()) == 0);
15911 /* Test creating a qIsAddressTagged request. */
15912 expected = "qIsAddressTagged:deadbeef";
15913 create_is_address_tagged_request (gdbarch, packet, 0xdeadbeef);
15914 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15916 /* Test error reply on qIsAddressTagged request. */
15917 reply = "E00";
15918 strcpy (packet.data (), reply.c_str ());
15919 /* is_tagged must not change, hence it's tested too. */
15920 bool 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 'tagged' as reply. */
15926 reply = "01";
15927 strcpy (packet.data (), reply.c_str ());
15928 /* Because the byte is 01, is_tagged should be set to true. */
15929 is_tagged = false;
15930 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15931 true);
15932 SELF_CHECK (is_tagged == true);
15934 /* Test 'not tagged' as reply. */
15935 reply = "00";
15936 strcpy (packet.data (), reply.c_str ());
15937 /* Because the byte is 00, is_tagged should be set to false. */
15938 is_tagged = true;
15939 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15940 true);
15941 SELF_CHECK (is_tagged == false);
15943 /* Test an invalid reply (neither 00 nor 01). */
15944 reply = "04";
15945 strcpy (packet.data (), reply.c_str ());
15946 /* Because the byte is invalid is_tagged must not change. */
15947 is_tagged = false;
15948 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15949 false);
15950 SELF_CHECK (is_tagged == false);
15952 /* Test malformed reply of incorrect length. */
15953 reply = "0104A590001234006";
15954 strcpy (packet.data (), reply.c_str ());
15955 /* Because this is a malformed reply is_tagged must not change. */
15956 is_tagged = false;
15957 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15958 false);
15959 SELF_CHECK (is_tagged == false);
15961 /* Test empty reply. */
15962 reply = "";
15963 strcpy (packet.data (), reply.c_str ());
15964 /* is_tagged must not change, hence it's tested too. */
15965 is_tagged = true;
15966 /* On the previous tests, qIsAddressTagged packet was auto detected and set
15967 as supported. But an empty reply means the packet is unsupported, so for
15968 testing the empty reply the support is reset to unknown state, otherwise
15969 packet_ok will complain. */
15970 remote.m_features.m_protocol_packets[PACKET_qIsAddressTagged].support =
15971 PACKET_SUPPORT_UNKNOWN;
15972 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15973 false);
15974 SELF_CHECK (is_tagged == true);
15977 static void
15978 test_packet_check_result ()
15980 std::string buf = "E.msg";
15981 packet_result result = packet_check_result (buf.data ());
15983 SELF_CHECK (result.status () == PACKET_ERROR);
15984 SELF_CHECK (strcmp(result.err_msg (), "msg") == 0);
15986 result = packet_check_result ("E01");
15987 SELF_CHECK (result.status () == PACKET_ERROR);
15988 SELF_CHECK (strcmp(result.err_msg (), "01") == 0);
15990 SELF_CHECK (packet_check_result ("E1").status () == PACKET_OK);
15992 SELF_CHECK (packet_check_result ("E000").status () == PACKET_OK);
15994 result = packet_check_result ("E.");
15995 SELF_CHECK (result.status () == PACKET_ERROR);
15996 SELF_CHECK (strcmp(result.err_msg (), "no error provided") == 0);
15998 SELF_CHECK (packet_check_result ("some response").status () == PACKET_OK);
16000 SELF_CHECK (packet_check_result ("").status () == PACKET_UNKNOWN);
16002 } // namespace selftests
16003 #endif /* GDB_SELF_TEST */
16005 void _initialize_remote ();
16006 void
16007 _initialize_remote ()
16009 add_target (remote_target_info, remote_target::open);
16010 add_target (extended_remote_target_info, extended_remote_target::open);
16012 /* Hook into new objfile notification. */
16013 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
16014 gdb::observers::all_objfiles_removed.attach
16015 (remote_objfile_changed_check_symbols, "remote");
16017 #if 0
16018 init_remote_threadtests ();
16019 #endif
16021 /* set/show remote ... */
16023 add_basic_prefix_cmd ("remote", class_maintenance, _("\
16024 Remote protocol specific variables.\n\
16025 Configure various remote-protocol specific variables such as\n\
16026 the packets being used."),
16027 &remote_set_cmdlist,
16028 0 /* allow-unknown */, &setlist);
16029 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
16030 Remote protocol specific variables.\n\
16031 Configure various remote-protocol specific variables such as\n\
16032 the packets being used."),
16033 &remote_show_cmdlist,
16034 0 /* allow-unknown */, &showlist);
16036 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
16037 Compare section data on target to the exec file.\n\
16038 Argument is a single section name (default: all loaded sections).\n\
16039 To compare only read-only loaded sections, specify the -r option."),
16040 &cmdlist);
16042 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
16043 Send an arbitrary packet to a remote target.\n\
16044 maintenance packet TEXT\n\
16045 If GDB is talking to an inferior via the GDB serial protocol, then\n\
16046 this command sends the string TEXT to the inferior, and displays the\n\
16047 response packet. GDB supplies the initial `$' character, and the\n\
16048 terminating `#' character and checksum."),
16049 &maintenancelist);
16051 set_show_commands remotebreak_cmds
16052 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
16053 Set whether to send break if interrupted."), _("\
16054 Show whether to send break if interrupted."), _("\
16055 If set, a break, instead of a cntrl-c, is sent to the remote target."),
16056 set_remotebreak, show_remotebreak,
16057 &setlist, &showlist);
16058 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
16059 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
16061 add_setshow_enum_cmd ("interrupt-sequence", class_support,
16062 interrupt_sequence_modes, &interrupt_sequence_mode,
16063 _("\
16064 Set interrupt sequence to remote target."), _("\
16065 Show interrupt sequence to remote target."), _("\
16066 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
16067 NULL, show_interrupt_sequence,
16068 &remote_set_cmdlist,
16069 &remote_show_cmdlist);
16071 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
16072 &interrupt_on_connect, _("\
16073 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16074 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16075 If set, interrupt sequence is sent to remote target."),
16076 NULL, NULL,
16077 &remote_set_cmdlist, &remote_show_cmdlist);
16079 /* Install commands for configuring memory read/write packets. */
16081 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
16082 Set the maximum number of bytes per memory write packet (deprecated)."),
16083 &setlist);
16084 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
16085 Show the maximum number of bytes per memory write packet (deprecated)."),
16086 &showlist);
16087 add_cmd ("memory-write-packet-size", no_class,
16088 set_memory_write_packet_size, _("\
16089 Set the maximum number of bytes per memory-write packet.\n\
16090 Specify the number of bytes in a packet or 0 (zero) for the\n\
16091 default packet size. The actual limit is further reduced\n\
16092 dependent on the target. Specify \"fixed\" to disable the\n\
16093 further restriction and \"limit\" to enable that restriction."),
16094 &remote_set_cmdlist);
16095 add_cmd ("memory-read-packet-size", no_class,
16096 set_memory_read_packet_size, _("\
16097 Set the maximum number of bytes per memory-read packet.\n\
16098 Specify the number of bytes in a packet or 0 (zero) for the\n\
16099 default packet size. The actual limit is further reduced\n\
16100 dependent on the target. Specify \"fixed\" to disable the\n\
16101 further restriction and \"limit\" to enable that restriction."),
16102 &remote_set_cmdlist);
16103 add_cmd ("memory-write-packet-size", no_class,
16104 show_memory_write_packet_size,
16105 _("Show the maximum number of bytes per memory-write packet."),
16106 &remote_show_cmdlist);
16107 add_cmd ("memory-read-packet-size", no_class,
16108 show_memory_read_packet_size,
16109 _("Show the maximum number of bytes per memory-read packet."),
16110 &remote_show_cmdlist);
16112 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
16113 &remote_hw_watchpoint_limit, _("\
16114 Set the maximum number of target hardware watchpoints."), _("\
16115 Show the maximum number of target hardware watchpoints."), _("\
16116 Specify \"unlimited\" for unlimited hardware watchpoints."),
16117 NULL, show_hardware_watchpoint_limit,
16118 &remote_set_cmdlist,
16119 &remote_show_cmdlist);
16120 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
16121 no_class,
16122 &remote_hw_watchpoint_length_limit, _("\
16123 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
16124 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
16125 Specify \"unlimited\" to allow watchpoints of unlimited size."),
16126 NULL, show_hardware_watchpoint_length_limit,
16127 &remote_set_cmdlist, &remote_show_cmdlist);
16128 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
16129 &remote_hw_breakpoint_limit, _("\
16130 Set the maximum number of target hardware breakpoints."), _("\
16131 Show the maximum number of target hardware breakpoints."), _("\
16132 Specify \"unlimited\" for unlimited hardware breakpoints."),
16133 NULL, show_hardware_breakpoint_limit,
16134 &remote_set_cmdlist, &remote_show_cmdlist);
16136 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
16137 &remote_address_size, _("\
16138 Set the maximum size of the address (in bits) in a memory packet."), _("\
16139 Show the maximum size of the address (in bits) in a memory packet."), NULL,
16140 NULL,
16141 NULL, /* FIXME: i18n: */
16142 &setlist, &showlist);
16144 init_all_packet_configs ();
16146 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
16148 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
16150 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
16153 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
16154 "catch-syscalls", 0);
16156 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
16157 "program-signals", 0);
16159 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
16160 "set-working-dir", 0);
16162 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
16163 "startup-with-shell", 0);
16165 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
16166 "environment-hex-encoded", 0);
16168 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
16169 "environment-reset", 0);
16171 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
16172 "environment-unset", 0);
16174 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
16176 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
16178 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
16180 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
16182 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
16184 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
16186 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
16188 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
16190 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
16191 "read-aux-vector", 0);
16193 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
16194 "pid-to-exec-file", 0);
16196 add_packet_config_cmd (PACKET_qXfer_features,
16197 "qXfer:features:read", "target-features", 0);
16199 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
16200 "library-info", 0);
16202 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
16203 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
16205 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
16206 "memory-map", 0);
16208 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
16210 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
16213 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
16214 "read-siginfo-object", 0);
16216 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
16217 "write-siginfo-object", 0);
16219 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
16220 "qXfer:traceframe-info:read", "traceframe-info", 0);
16222 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
16223 "unwind-info-block", 0);
16225 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
16226 "get-thread-local-storage-address", 0);
16228 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
16229 "get-thread-information-block-address", 0);
16231 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
16233 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
16235 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
16238 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
16239 "search-memory", 0);
16241 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
16243 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
16245 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
16247 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
16249 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
16252 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
16254 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
16257 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
16258 "hostio-readlink", 0);
16260 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
16262 add_packet_config_cmd (PACKET_vFile_stat, "vFile:stat", "hostio-stat", 0);
16264 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
16266 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
16268 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
16270 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
16272 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
16274 add_packet_config_cmd (PACKET_ConditionalTracepoints,
16275 "ConditionalTracepoints", "conditional-tracepoints",
16278 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
16279 "ConditionalBreakpoints", "conditional-breakpoints",
16282 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
16283 "breakpoint-commands", 0);
16285 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
16286 "fast-tracepoints", 0);
16288 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
16289 "TracepointSource", 0);
16291 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
16293 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
16294 "static-tracepoints", 0);
16296 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
16297 "install-in-trace", 0);
16299 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
16300 "qXfer:statictrace:read", "read-sdata-object", 0);
16302 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
16303 "read-fdpic-loadmap", 0);
16305 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
16306 "disable-randomization", 0);
16308 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
16310 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
16311 "trace-buffer-size", 0);
16313 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
16316 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
16319 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
16322 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
16324 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
16325 "read-btrace-conf", 0);
16327 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
16328 "btrace-conf-bts-size", 0);
16330 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
16331 "multiprocess-feature", 0);
16333 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
16334 "swbreak-feature", 0);
16336 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
16337 "hwbreak-feature", 0);
16339 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
16340 "fork-event-feature", 0);
16342 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
16343 "vfork-event-feature", 0);
16345 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
16346 "btrace-conf-pt-size", 0);
16348 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_ptwrite, "Qbtrace-conf:pt:ptwrite",
16349 "btrace-conf-pt-ptwrite", 0);
16351 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
16352 "verbose-resume-supported", 0);
16354 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
16355 "exec-event-feature", 0);
16357 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
16359 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
16362 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
16363 "thread-options", 0);
16365 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
16366 "no-resumed-stop-reply", 0);
16368 add_packet_config_cmd (PACKET_memory_tagging_feature,
16369 "memory-tagging-feature", "memory-tagging-feature", 0);
16371 add_packet_config_cmd (PACKET_qIsAddressTagged,
16372 "qIsAddressTagged", "memory-tagging-address-check", 0);
16374 add_packet_config_cmd (PACKET_accept_error_message,
16375 "error-message", "error-message", 0);
16377 /* Assert that we've registered "set remote foo-packet" commands
16378 for all packet configs. */
16380 int i;
16382 for (i = 0; i < PACKET_MAX; i++)
16384 /* Ideally all configs would have a command associated. Some
16385 still don't though. */
16386 int excepted;
16388 switch (i)
16390 case PACKET_QNonStop:
16391 case PACKET_EnableDisableTracepoints_feature:
16392 case PACKET_tracenz_feature:
16393 case PACKET_DisconnectedTracing_feature:
16394 case PACKET_augmented_libraries_svr4_read_feature:
16395 case PACKET_qCRC:
16396 /* Additions to this list need to be well justified:
16397 pre-existing packets are OK; new packets are not. */
16398 excepted = 1;
16399 break;
16400 default:
16401 excepted = 0;
16402 break;
16405 /* This catches both forgetting to add a config command, and
16406 forgetting to remove a packet from the exception list. */
16407 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16411 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16412 Z sub-packet has its own set and show commands, but users may
16413 have sets to this variable in their .gdbinit files (or in their
16414 documentation). */
16415 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16416 &remote_Z_packet_detect, _("\
16417 Set use of remote protocol `Z' packets."), _("\
16418 Show use of remote protocol `Z' packets."), _("\
16419 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16420 packets."),
16421 set_remote_protocol_Z_packet_cmd,
16422 show_remote_protocol_Z_packet_cmd,
16423 /* FIXME: i18n: Use of remote protocol
16424 `Z' packets is %s. */
16425 &remote_set_cmdlist, &remote_show_cmdlist);
16427 add_basic_prefix_cmd ("remote", class_files, _("\
16428 Manipulate files on the remote system.\n\
16429 Transfer files to and from the remote target system."),
16430 &remote_cmdlist,
16431 0 /* allow-unknown */, &cmdlist);
16433 add_cmd ("put", class_files, remote_put_command,
16434 _("Copy a local file to the remote system."),
16435 &remote_cmdlist);
16437 add_cmd ("get", class_files, remote_get_command,
16438 _("Copy a remote file to the local system."),
16439 &remote_cmdlist);
16441 add_cmd ("delete", class_files, remote_delete_command,
16442 _("Delete a remote file."),
16443 &remote_cmdlist);
16445 add_setshow_string_noescape_cmd ("exec-file", class_files,
16446 &remote_exec_file_var, _("\
16447 Set the remote pathname for \"run\"."), _("\
16448 Show the remote pathname for \"run\"."), NULL,
16449 set_remote_exec_file,
16450 show_remote_exec_file,
16451 &remote_set_cmdlist,
16452 &remote_show_cmdlist);
16454 add_setshow_boolean_cmd ("range-stepping", class_run,
16455 &use_range_stepping, _("\
16456 Enable or disable range stepping."), _("\
16457 Show whether target-assisted range stepping is enabled."), _("\
16458 If on, and the target supports it, when stepping a source line, GDB\n\
16459 tells the target to step the corresponding range of addresses itself instead\n\
16460 of issuing multiple single-steps. This speeds up source level\n\
16461 stepping. If off, GDB always issues single-steps, even if range\n\
16462 stepping is supported by the target. The default is on."),
16463 set_range_stepping,
16464 show_range_stepping,
16465 &setlist,
16466 &showlist);
16468 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16469 Set watchdog timer."), _("\
16470 Show watchdog timer."), _("\
16471 When non-zero, this timeout is used instead of waiting forever for a target\n\
16472 to finish a low-level step or continue operation. If the specified amount\n\
16473 of time passes without a response from the target, an error occurs."),
16474 NULL,
16475 show_watchdog,
16476 &setlist, &showlist);
16478 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16479 &remote_packet_max_chars, _("\
16480 Set the maximum number of characters to display for each remote packet."), _("\
16481 Show the maximum number of characters to display for each remote packet."), _("\
16482 Specify \"unlimited\" to display all the characters."),
16483 NULL, show_remote_packet_max_chars,
16484 &setdebuglist, &showdebuglist);
16486 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16487 _("Set debugging of remote protocol."),
16488 _("Show debugging of remote protocol."),
16489 _("\
16490 When enabled, each packet sent or received with the remote target\n\
16491 is displayed."),
16492 NULL,
16493 show_remote_debug,
16494 &setdebuglist, &showdebuglist);
16496 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16497 &remote_timeout, _("\
16498 Set timeout limit to wait for target to respond."), _("\
16499 Show timeout limit to wait for target to respond."), _("\
16500 This value is used to set the time limit for gdb to wait for a response\n\
16501 from the target."),
16502 NULL,
16503 show_remote_timeout,
16504 &setlist, &showlist);
16506 /* Eventually initialize fileio. See fileio.c */
16507 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16509 #if GDB_SELF_TEST
16510 selftests::register_test ("remote_memory_tagging",
16511 selftests::test_memory_tagging_functions);
16512 selftests::register_test ("packet_check_result",
16513 selftests::test_packet_check_result);
16514 #endif