]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/remote.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / remote.c
... / ...
CommitLineData
1/* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2025 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20/* See the GDB User Guide for details of the GDB remote protocol. */
21
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 "cli/cli-style.h"
43#include "target-descriptions.h"
44#include "gdb_bfd.h"
45#include "gdbsupport/filestuff.h"
46#include "gdbsupport/rsp-low.h"
47#include "disasm.h"
48#include "location.h"
49
50#include "gdbsupport/gdb_sys_time.h"
51
52#include "gdbsupport/event-loop.h"
53#include "event-top.h"
54#include "inf-loop.h"
55
56#include <signal.h>
57#include "serial.h"
58
59#include "gdbcore.h"
60
61#include "remote-fileio.h"
62#include "gdbsupport/fileio.h"
63#include <sys/stat.h>
64#include "xml-support.h"
65
66#include "memory-map.h"
67
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
71#include "gdbsupport/agent.h"
72#include "btrace.h"
73#include "record-btrace.h"
74#include "gdbsupport/scoped_restore.h"
75#include "gdbsupport/environ.h"
76#include "gdbsupport/byte-vector.h"
77#include "gdbsupport/search.h"
78#include <algorithm>
79#include <iterator>
80#include "async-event.h"
81#include "gdbsupport/selftest.h"
82#include "cli/cli-style.h"
83#include "gdbsupport/remote-args.h"
84
85/* The remote target. */
86
87static const char remote_doc[] = N_("\
88Use a remote computer via a serial line, using a gdb-specific protocol.\n\
89Specify the serial device it is connected to\n\
90(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
91
92/* See remote.h */
93
94bool remote_debug = false;
95
96#define OPAQUETHREADBYTES 8
97
98/* a 64 bit opaque identifier */
99typedef unsigned char threadref[OPAQUETHREADBYTES];
100
101struct gdb_ext_thread_info;
102struct threads_listing_context;
103typedef int (*rmt_thread_action) (threadref *ref, void *context);
104struct protocol_feature;
105struct packet_reg;
106
107struct stop_reply;
108typedef std::unique_ptr<stop_reply> stop_reply_up;
109
110/* Generic configuration support for packets the stub optionally
111 supports. Allows the user to specify the use of the packet as well
112 as allowing GDB to auto-detect support in the remote stub. */
113
114enum packet_support
115 {
116 PACKET_SUPPORT_UNKNOWN = 0,
117 PACKET_ENABLE,
118 PACKET_DISABLE
119 };
120
121/* Convert the packet support auto_boolean to a name used for gdb printing. */
122
123static const char *
124get_packet_support_name (auto_boolean support)
125{
126 switch (support)
127 {
128 case AUTO_BOOLEAN_TRUE:
129 return "on";
130 case AUTO_BOOLEAN_FALSE:
131 return "off";
132 case AUTO_BOOLEAN_AUTO:
133 return "auto";
134 default:
135 gdb_assert_not_reached ("invalid var_auto_boolean");
136 }
137}
138
139/* Convert the target type (future remote target or currently connected target)
140 to a name used for gdb printing. */
141
142static const char *
143get_target_type_name (bool target_connected)
144{
145 if (target_connected)
146 return _("on the current remote target");
147 else
148 return _("on future remote targets");
149}
150
151/* Analyze a packet's return value and update the packet config
152 accordingly. */
153
154enum packet_status
155{
156 PACKET_ERROR,
157 PACKET_OK,
158 PACKET_UNKNOWN
159};
160
161/* Keeps packet's return value. If packet's return value is PACKET_ERROR,
162 err_msg contains an error message string from E.string or the number
163 stored as a string from E.num. */
164class packet_result
165{
166private:
167 /* Private ctors for internal use. Clients should use the public
168 factory static methods instead. */
169
170 /* Construct a PACKET_ERROR packet_result. */
171 packet_result (const char *err_msg, bool textual_err_msg)
172 : m_status (PACKET_ERROR),
173 m_err_msg (err_msg),
174 m_textual_err_msg (textual_err_msg)
175 {}
176
177 /* Construct an PACKET_OK/PACKET_UNKNOWN packet_result. */
178 explicit packet_result (enum packet_status status)
179 : m_status (status)
180 {
181 gdb_assert (status != PACKET_ERROR);
182 }
183
184public:
185 enum packet_status status () const
186 {
187 return this->m_status;
188 }
189
190 const char *err_msg () const
191 {
192 gdb_assert (this->m_status == PACKET_ERROR);
193 return this->m_err_msg.c_str ();
194 }
195
196 bool textual_err_msg () const
197 {
198 gdb_assert (this->m_status == PACKET_ERROR);
199 return this->m_textual_err_msg;
200 }
201
202 static packet_result make_numeric_error (const char *err_msg)
203 {
204 return packet_result (err_msg, false);
205 }
206
207 static packet_result make_textual_error (const char *err_msg)
208 {
209 return packet_result (err_msg, true);
210 }
211
212 static packet_result make_ok ()
213 {
214 return packet_result (PACKET_OK);
215 }
216
217 static packet_result make_unknown ()
218 {
219 return packet_result (PACKET_UNKNOWN);
220 }
221
222private:
223 enum packet_status m_status;
224 std::string m_err_msg;
225
226 /* True if we have a textual error message, from an "E.MESSAGE"
227 response. */
228 bool m_textual_err_msg = false;
229};
230
231/* Enumeration of packets for a remote target. */
232
233enum {
234 PACKET_vCont = 0,
235 PACKET_X,
236 PACKET_x,
237 PACKET_qSymbol,
238 PACKET_P,
239 PACKET_p,
240 PACKET_Z0,
241 PACKET_Z1,
242 PACKET_Z2,
243 PACKET_Z3,
244 PACKET_Z4,
245 PACKET_vFile_setfs,
246 PACKET_vFile_open,
247 PACKET_vFile_pread,
248 PACKET_vFile_pwrite,
249 PACKET_vFile_close,
250 PACKET_vFile_unlink,
251 PACKET_vFile_readlink,
252 PACKET_vFile_fstat,
253 PACKET_vFile_stat,
254 PACKET_vFile_lstat,
255 PACKET_qXfer_auxv,
256 PACKET_qXfer_features,
257 PACKET_qXfer_exec_file,
258 PACKET_qXfer_libraries,
259 PACKET_qXfer_libraries_svr4,
260 PACKET_qXfer_memory_map,
261 PACKET_qXfer_osdata,
262 PACKET_qXfer_threads,
263 PACKET_qXfer_statictrace_read,
264 PACKET_qXfer_traceframe_info,
265 PACKET_qXfer_uib,
266 PACKET_qGetTIBAddr,
267 PACKET_qGetTLSAddr,
268 PACKET_qSupported,
269 PACKET_qTStatus,
270 PACKET_QPassSignals,
271 PACKET_QCatchSyscalls,
272 PACKET_QProgramSignals,
273 PACKET_QSetWorkingDir,
274 PACKET_QStartupWithShell,
275 PACKET_QEnvironmentHexEncoded,
276 PACKET_QEnvironmentReset,
277 PACKET_QEnvironmentUnset,
278 PACKET_qCRC,
279 PACKET_qSearch_memory,
280 PACKET_vAttach,
281 PACKET_vRun,
282 PACKET_QStartNoAckMode,
283 PACKET_vKill,
284 PACKET_qXfer_siginfo_read,
285 PACKET_qXfer_siginfo_write,
286 PACKET_qAttached,
287
288 /* Support for conditional tracepoints. */
289 PACKET_ConditionalTracepoints,
290
291 /* Support for target-side breakpoint conditions. */
292 PACKET_ConditionalBreakpoints,
293
294 /* Support for target-side breakpoint commands. */
295 PACKET_BreakpointCommands,
296
297 /* Support for fast tracepoints. */
298 PACKET_FastTracepoints,
299
300 /* Support for static tracepoints. */
301 PACKET_StaticTracepoints,
302
303 /* Support for installing tracepoints while a trace experiment is
304 running. */
305 PACKET_InstallInTrace,
306
307 PACKET_bc,
308 PACKET_bs,
309 PACKET_TracepointSource,
310 PACKET_QAllow,
311 PACKET_qXfer_fdpic,
312 PACKET_QDisableRandomization,
313 PACKET_QAgent,
314 PACKET_QTBuffer_size,
315 PACKET_Qbtrace_off,
316 PACKET_Qbtrace_bts,
317 PACKET_Qbtrace_pt,
318 PACKET_qXfer_btrace,
319
320 /* Support for the QNonStop packet. */
321 PACKET_QNonStop,
322
323 /* Support for the QThreadEvents packet. */
324 PACKET_QThreadEvents,
325
326 /* Support for the QThreadOptions packet. */
327 PACKET_QThreadOptions,
328
329 /* Support for multi-process extensions. */
330 PACKET_multiprocess_feature,
331
332 /* Support for enabling and disabling tracepoints while a trace
333 experiment is running. */
334 PACKET_EnableDisableTracepoints_feature,
335
336 /* Support for collecting strings using the tracenz bytecode. */
337 PACKET_tracenz_feature,
338
339 /* Support for continuing to run a trace experiment while GDB is
340 disconnected. */
341 PACKET_DisconnectedTracing_feature,
342
343 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
344 PACKET_augmented_libraries_svr4_read_feature,
345
346 /* Support for the qXfer:btrace-conf:read packet. */
347 PACKET_qXfer_btrace_conf,
348
349 /* Support for the Qbtrace-conf:bts:size packet. */
350 PACKET_Qbtrace_conf_bts_size,
351
352 /* Support for swbreak+ feature. */
353 PACKET_swbreak_feature,
354
355 /* Support for hwbreak+ feature. */
356 PACKET_hwbreak_feature,
357
358 /* Support for fork events. */
359 PACKET_fork_event_feature,
360
361 /* Support for vfork events. */
362 PACKET_vfork_event_feature,
363
364 /* Support for the Qbtrace-conf:pt:size packet. */
365 PACKET_Qbtrace_conf_pt_size,
366
367 /* Support for the Qbtrace-conf:pt:ptwrite packet. */
368 PACKET_Qbtrace_conf_pt_ptwrite,
369
370 /* Support for the Qbtrace-conf:pt:event-tracing packet. */
371 PACKET_Qbtrace_conf_pt_event_tracing,
372
373 /* Support for exec events. */
374 PACKET_exec_event_feature,
375
376 /* Support for query supported vCont actions. */
377 PACKET_vContSupported,
378
379 /* Support remote CTRL-C. */
380 PACKET_vCtrlC,
381
382 /* Support TARGET_WAITKIND_NO_RESUMED. */
383 PACKET_no_resumed,
384
385 /* Support for memory tagging, allocation tag fetch/store
386 packets and the tag violation stop replies. */
387 PACKET_memory_tagging_feature,
388
389 /* Support for the qIsAddressTagged packet. */
390 PACKET_qIsAddressTagged,
391
392 /* Support for accepting error message in a E.errtext format.
393 This allows every remote packet to return E.errtext.
394
395 This feature only exists to fix a backwards compatibility issue
396 with the qRcmd and m packets. Historically, these two packets didn't
397 support E.errtext style errors, but when this feature is on
398 these two packets can receive E.errtext style errors.
399
400 All new packets should be written to always accept E.errtext style
401 errors, and so they should not need to check for this feature. */
402 PACKET_accept_error_message,
403
404 PACKET_MAX
405};
406
407struct threads_listing_context;
408
409/* Stub vCont actions support.
410
411 Each field is a boolean flag indicating whether the stub reports
412 support for the corresponding action. */
413
414struct vCont_action_support
415{
416 /* vCont;t */
417 bool t = false;
418
419 /* vCont;r */
420 bool r = false;
421
422 /* vCont;s */
423 bool s = false;
424
425 /* vCont;S */
426 bool S = false;
427};
428
429/* About this many threadids fit in a packet. */
430
431#define MAXTHREADLISTRESULTS 32
432
433/* Data for the vFile:pread readahead cache. */
434
435struct readahead_cache
436{
437 /* Invalidate the readahead cache. */
438 void invalidate ();
439
440 /* Invalidate the readahead cache if it is holding data for FD. */
441 void invalidate_fd (int fd);
442
443 /* Serve pread from the readahead cache. Returns number of bytes
444 read, or 0 if the request can't be served from the cache. */
445 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
446
447 /* The file descriptor for the file that is being cached. -1 if the
448 cache is invalid. */
449 int fd = -1;
450
451 /* The offset into the file that the cache buffer corresponds
452 to. */
453 ULONGEST offset = 0;
454
455 /* The buffer holding the cache contents. */
456 gdb::byte_vector buf;
457
458 /* Cache hit and miss counters. */
459 ULONGEST hit_count = 0;
460 ULONGEST miss_count = 0;
461};
462
463/* Description of the remote protocol for a given architecture. */
464
465struct packet_reg
466{
467 long offset; /* Offset into G packet. */
468 long regnum; /* GDB's internal register number. */
469 LONGEST pnum; /* Remote protocol register number. */
470 bool in_g_packet; /* Always part of G packet. */
471 /* long size in bytes; == register_size (arch, regnum);
472 at present. */
473 /* char *name; == gdbarch_register_name (arch, regnum);
474 at present. */
475};
476
477struct remote_arch_state
478{
479 explicit remote_arch_state (struct gdbarch *gdbarch);
480
481 /* Description of the remote protocol registers. */
482 long sizeof_g_packet;
483
484 /* Description of the remote protocol registers indexed by REGNUM
485 (making an array gdbarch_num_regs in size). */
486 std::unique_ptr<packet_reg[]> regs;
487
488 /* This is the size (in chars) of the first response to the ``g''
489 packet. It is used as a heuristic when determining the maximum
490 size of memory-read and memory-write packets. A target will
491 typically only reserve a buffer large enough to hold the ``g''
492 packet. The size does not include packet overhead (headers and
493 trailers). */
494 long actual_register_packet_size;
495
496 /* This is the maximum size (in chars) of a non read/write packet.
497 It is also used as a cap on the size of read/write packets. */
498 long remote_packet_size;
499};
500
501/* Description of the remote protocol state for the currently
502 connected target. This is per-target state, and independent of the
503 selected architecture. */
504
505class remote_state
506{
507public:
508
509 remote_state ();
510 ~remote_state ();
511
512 /* Get the remote arch state for GDBARCH. */
513 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
514
515 void create_async_event_handler ()
516 {
517 gdb_assert (m_async_event_handler_token == nullptr);
518 m_async_event_handler_token
519 = ::create_async_event_handler ([] (gdb_client_data data)
520 {
521 inferior_event_handler (INF_REG_EVENT);
522 },
523 nullptr, "remote");
524 }
525
526 void mark_async_event_handler ()
527 {
528 gdb_assert (this->is_async_p ());
529 ::mark_async_event_handler (m_async_event_handler_token);
530 }
531
532 void clear_async_event_handler ()
533 { ::clear_async_event_handler (m_async_event_handler_token); }
534
535 bool async_event_handler_marked () const
536 { return ::async_event_handler_marked (m_async_event_handler_token); }
537
538 void delete_async_event_handler ()
539 {
540 if (m_async_event_handler_token != nullptr)
541 ::delete_async_event_handler (&m_async_event_handler_token);
542 }
543
544 bool is_async_p () const
545 {
546 /* We're async whenever the serial device is. */
547 gdb_assert (this->remote_desc != nullptr);
548 return serial_is_async_p (this->remote_desc);
549 }
550
551 bool can_async_p () const
552 {
553 /* We can async whenever the serial device can. */
554 gdb_assert (this->remote_desc != nullptr);
555 return serial_can_async_p (this->remote_desc);
556 }
557
558public: /* data */
559
560 /* A buffer to use for incoming packets, and its current size. The
561 buffer is grown dynamically for larger incoming packets.
562 Outgoing packets may also be constructed in this buffer.
563 The size of the buffer is always at least REMOTE_PACKET_SIZE;
564 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
565 packets. */
566 gdb::char_vector buf;
567
568 /* True if we're going through initial connection setup (finding out
569 about the remote side's threads, relocating symbols, etc.). */
570 bool starting_up = false;
571
572 /* If we negotiated packet size explicitly (and thus can bypass
573 heuristics for the largest packet size that will not overflow
574 a buffer in the stub), this will be set to that packet size.
575 Otherwise zero, meaning to use the guessed size. */
576 long explicit_packet_size = 0;
577
578 /* True, if in no ack mode. That is, neither GDB nor the stub will
579 expect acks from each other. The connection is assumed to be
580 reliable. */
581 bool noack_mode = false;
582
583 /* True if we're connected in extended remote mode. */
584 bool extended = false;
585
586 /* True if we resumed the target and we're waiting for the target to
587 stop. In the mean time, we can't start another command/query.
588 The remote server wouldn't be ready to process it, so we'd
589 timeout waiting for a reply that would never come and eventually
590 we'd close the connection. This can happen in asynchronous mode
591 because we allow GDB commands while the target is running. */
592 bool waiting_for_stop_reply = false;
593
594 /* The status of the stub support for the various vCont actions. */
595 vCont_action_support supports_vCont;
596
597 /* True if the user has pressed Ctrl-C, but the target hasn't
598 responded to that. */
599 bool ctrlc_pending_p = false;
600
601 /* True if we saw a Ctrl-C while reading or writing from/to the
602 remote descriptor. At that point it is not safe to send a remote
603 interrupt packet, so we instead remember we saw the Ctrl-C and
604 process it once we're done with sending/receiving the current
605 packet, which should be shortly. If however that takes too long,
606 and the user presses Ctrl-C again, we offer to disconnect. */
607 bool got_ctrlc_during_io = false;
608
609 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
610 remote_open knows that we don't have a file open when the program
611 starts. */
612 struct serial *remote_desc = nullptr;
613
614 /* These are the threads which we last sent to the remote system. The
615 TID member will be -1 for all or -2 for not sent yet. */
616 ptid_t general_thread = null_ptid;
617 ptid_t continue_thread = null_ptid;
618
619 /* This is the traceframe which we last selected on the remote system.
620 It will be -1 if no traceframe is selected. */
621 int remote_traceframe_number = -1;
622
623 char *last_pass_packet = nullptr;
624
625 /* The last QProgramSignals packet sent to the target. We bypass
626 sending a new program signals list down to the target if the new
627 packet is exactly the same as the last we sent. IOW, we only let
628 the target know about program signals list changes. */
629 char *last_program_signals_packet = nullptr;
630
631 /* Similarly, the last QThreadEvents state we sent to the
632 target. */
633 bool last_thread_events = false;
634
635 gdb_signal last_sent_signal = GDB_SIGNAL_0;
636
637 bool last_sent_step = false;
638
639 /* The execution direction of the last resume we got. */
640 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
641
642 char *finished_object = nullptr;
643 char *finished_annex = nullptr;
644 ULONGEST finished_offset = 0;
645
646 /* Should we try the 'ThreadInfo' query packet?
647
648 This variable (NOT available to the user: auto-detect only!)
649 determines whether GDB will use the new, simpler "ThreadInfo"
650 query or the older, more complex syntax for thread queries.
651 This is an auto-detect variable (set to true at each connect,
652 and set to false when the target fails to recognize it). */
653 bool use_threadinfo_query = false;
654 bool use_threadextra_query = false;
655
656 threadref echo_nextthread {};
657 threadref nextthread {};
658 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
659
660 /* The state of remote notification. */
661 struct remote_notif_state *notif_state = nullptr;
662
663 /* The branch trace configuration. */
664 struct btrace_config btrace_config {};
665
666 /* The argument to the last "vFile:setfs:" packet we sent, used
667 to avoid sending repeated unnecessary "vFile:setfs:" packets.
668 Initialized to -1 to indicate that no "vFile:setfs:" packet
669 has yet been sent. */
670 int fs_pid = -1;
671
672 /* A readahead cache for vFile:pread. Often, reading a binary
673 involves a sequence of small reads. E.g., when parsing an ELF
674 file. A readahead cache helps mostly the case of remote
675 debugging on a connection with higher latency, due to the
676 request/reply nature of the RSP. We only cache data for a single
677 file descriptor at a time. */
678 struct readahead_cache readahead_cache;
679
680 /* The list of already fetched and acknowledged stop events. This
681 queue is used for notification Stop, and other notifications
682 don't need queue for their events, because the notification
683 events of Stop can't be consumed immediately, so that events
684 should be queued first, and be consumed by remote_wait_{ns,as}
685 one per time. Other notifications can consume their events
686 immediately, so queue is not needed for them. */
687 std::vector<stop_reply_up> stop_reply_queue;
688
689 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
690 ``forever'' still use the normal timeout mechanism. This is
691 currently used by the ASYNC code to guarantee that target reads
692 during the initial connect always time-out. Once getpkt has been
693 modified to return a timeout indication and, in turn
694 remote_wait()/wait_for_inferior() have gained a timeout parameter
695 this can go away. */
696 bool wait_forever_enabled_p = true;
697
698 /* The set of thread options the target reported it supports, via
699 qSupported. */
700 gdb_thread_options supported_thread_options = 0;
701
702 /* Contains the regnums of the expedited registers in the last stop
703 reply packet. */
704 gdb::unordered_set<int> last_seen_expedited_registers;
705
706private:
707 /* Asynchronous signal handle registered as event loop source for
708 when we have pending events ready to be passed to the core. */
709 async_event_handler *m_async_event_handler_token = nullptr;
710
711 /* Mapping of remote protocol data for each gdbarch. Usually there
712 is only one entry here, though we may see more with stubs that
713 support multi-process. */
714 gdb::unordered_map<struct gdbarch *, remote_arch_state>
715 m_arch_states;
716};
717
718static const target_info remote_target_info = {
719 "remote",
720 N_("Remote target using gdb-specific protocol"),
721 remote_doc
722};
723
724/* Description of a remote packet. */
725
726struct packet_description
727{
728 /* Name of the packet used for gdb output. */
729 const char *name;
730
731 /* Title of the packet, used by the set/show remote name-packet
732 commands to identify the individual packages and gdb output. */
733 const char *title;
734};
735
736/* Configuration of a remote packet. */
737
738struct packet_config
739{
740 /* If auto, GDB auto-detects support for this packet or feature,
741 either through qSupported, or by trying the packet and looking
742 at the response. If true, GDB assumes the target supports this
743 packet. If false, the packet is disabled. Configs that don't
744 have an associated command always have this set to auto. */
745 enum auto_boolean detect;
746
747 /* Does the target support this packet? */
748 enum packet_support support;
749};
750
751/* User configurable variables for the number of characters in a
752 memory read/write packet. MIN (rsa->remote_packet_size,
753 rsa->sizeof_g_packet) is the default. Some targets need smaller
754 values (fifo overruns, et.al.) and some users need larger values
755 (speed up transfers). The variables ``preferred_*'' (the user
756 request), ``current_*'' (what was actually set) and ``forced_*''
757 (Positive - a soft limit, negative - a hard limit). */
758
759struct memory_packet_config
760{
761 const char *name;
762 long size;
763 int fixed_p;
764};
765
766/* These global variables contain the default configuration for every new
767 remote_feature object. */
768static memory_packet_config memory_read_packet_config =
769{
770 "memory-read-packet-size",
771};
772static memory_packet_config memory_write_packet_config =
773{
774 "memory-write-packet-size",
775};
776
777/* This global array contains packet descriptions (name and title). */
778static packet_description packets_descriptions[PACKET_MAX];
779/* This global array contains the default configuration for every new
780 per-remote target array. */
781static packet_config remote_protocol_packets[PACKET_MAX];
782
783/* Description of a remote target's features. It stores the configuration
784 and provides functions to determine supported features of the target. */
785
786struct remote_features
787{
788 remote_features ()
789 {
790 m_memory_read_packet_config = memory_read_packet_config;
791 m_memory_write_packet_config = memory_write_packet_config;
792
793 std::copy (std::begin (remote_protocol_packets),
794 std::end (remote_protocol_packets),
795 std::begin (m_protocol_packets));
796 }
797 ~remote_features () = default;
798
799 DISABLE_COPY_AND_ASSIGN (remote_features);
800
801 /* Returns whether a given packet defined by its enum value is supported. */
802 enum packet_support packet_support (int) const;
803
804 /* Returns the packet's corresponding "set remote foo-packet" command
805 state. See struct packet_config for more details. */
806 enum auto_boolean packet_set_cmd_state (int packet) const
807 { return m_protocol_packets[packet].detect; }
808
809 /* Returns true if the multi-process extensions are in effect. */
810 int remote_multi_process_p () const
811 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
812
813 /* Returns true if fork events are supported. */
814 int remote_fork_event_p () const
815 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
816
817 /* Returns true if vfork events are supported. */
818 int remote_vfork_event_p () const
819 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
820
821 /* Returns true if exec events are supported. */
822 int remote_exec_event_p () const
823 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
824
825 /* Returns true if memory tagging is supported, false otherwise. */
826 bool remote_memory_tagging_p () const
827 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
828
829 /* Reset all packets back to "unknown support". Called when opening a
830 new connection to a remote target. */
831 void reset_all_packet_configs_support ();
832
833/* Check result value in BUF for packet WHICH_PACKET and update the packet's
834 support configuration accordingly. */
835 packet_result packet_ok (const char *buf, const int which_packet);
836 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
837
838 /* Configuration of a remote target's memory read packet. */
839 memory_packet_config m_memory_read_packet_config;
840 /* Configuration of a remote target's memory write packet. */
841 memory_packet_config m_memory_write_packet_config;
842
843 /* The per-remote target array which stores a remote's packet
844 configurations. */
845 packet_config m_protocol_packets[PACKET_MAX];
846};
847
848class remote_target : public process_stratum_target
849{
850public:
851 remote_target () = default;
852 ~remote_target () override;
853
854 const target_info &info () const override
855 { return remote_target_info; }
856
857 const char *connection_string () override;
858
859 thread_control_capabilities get_thread_control_capabilities () override
860 { return tc_schedlock; }
861
862 /* Open a remote connection. */
863 static void open (const char *, int);
864
865 void close () override;
866
867 void detach (inferior *, int) override;
868 void disconnect (const char *, int) override;
869
870 void commit_requested_thread_options ();
871
872 void commit_resumed () override;
873 void resume (ptid_t, int, enum gdb_signal) override;
874 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
875 bool has_pending_events () override;
876
877 void fetch_registers (struct regcache *, int) override;
878 void store_registers (struct regcache *, int) override;
879 void prepare_to_store (struct regcache *) override;
880
881 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
882
883 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
884 enum remove_bp_reason) override;
885
886
887 bool stopped_by_sw_breakpoint () override;
888 bool supports_stopped_by_sw_breakpoint () override;
889
890 bool stopped_by_hw_breakpoint () override;
891
892 bool supports_stopped_by_hw_breakpoint () override;
893
894 bool stopped_by_watchpoint () override;
895
896 bool stopped_data_address (CORE_ADDR *) override;
897
898 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
899
900 int can_use_hw_breakpoint (enum bptype, int, int) override;
901
902 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
903
904 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
905
906 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
907
908 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
909 struct expression *) override;
910
911 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
912 struct expression *) override;
913
914 void kill () override;
915
916 void load (const char *, int) override;
917
918 void mourn_inferior () override;
919
920 void pass_signals (gdb::array_view<const unsigned char>) override;
921
922 int set_syscall_catchpoint (int, bool, int,
923 gdb::array_view<const int>) override;
924
925 void program_signals (gdb::array_view<const unsigned char>) override;
926
927 bool thread_alive (ptid_t ptid) override;
928
929 const char *thread_name (struct thread_info *) override;
930
931 void update_thread_list () override;
932
933 std::string pid_to_str (ptid_t) override;
934
935 const char *extra_thread_info (struct thread_info *) override;
936
937 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
938
939 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
940 int handle_len,
941 inferior *inf) override;
942
943 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
944 override;
945
946 void stop (ptid_t) override;
947
948 void interrupt () override;
949
950 void pass_ctrlc () override;
951
952 enum target_xfer_status xfer_partial (enum target_object object,
953 const char *annex,
954 gdb_byte *readbuf,
955 const gdb_byte *writebuf,
956 ULONGEST offset, ULONGEST len,
957 ULONGEST *xfered_len) override;
958
959 ULONGEST get_memory_xfer_limit () override;
960
961 void rcmd (const char *command, struct ui_file *output) override;
962
963 const char *pid_to_exec_file (int pid) override;
964
965 void log_command (const char *cmd) override
966 {
967 serial_log_command (this, cmd);
968 }
969
970 CORE_ADDR get_thread_local_address (ptid_t ptid,
971 CORE_ADDR load_module_addr,
972 CORE_ADDR offset) override;
973
974 bool can_execute_reverse () override;
975
976 std::vector<mem_region> memory_map () override;
977
978 void flash_erase (ULONGEST address, LONGEST length) override;
979
980 void flash_done () override;
981
982 const struct target_desc *read_description () override;
983
984 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
985 const gdb_byte *pattern, ULONGEST pattern_len,
986 CORE_ADDR *found_addrp) override;
987
988 bool can_async_p () override;
989
990 bool is_async_p () override;
991
992 void async (bool) override;
993
994 int async_wait_fd () override;
995
996 void thread_events (bool) override;
997
998 bool supports_set_thread_options (gdb_thread_options) override;
999
1000 int can_do_single_step () override;
1001
1002 void terminal_inferior () override;
1003
1004 void terminal_ours () override;
1005
1006 bool supports_non_stop () override;
1007
1008 bool supports_multi_process () override;
1009
1010 bool supports_disable_randomization () override;
1011
1012 bool filesystem_is_local () override;
1013
1014
1015 int fileio_open (struct inferior *inf, const char *filename,
1016 int flags, int mode, int warn_if_slow,
1017 fileio_error *target_errno) override;
1018
1019 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
1020 ULONGEST offset, fileio_error *target_errno) override;
1021
1022 int fileio_pread (int fd, gdb_byte *read_buf, int len,
1023 ULONGEST offset, fileio_error *target_errno) override;
1024
1025 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
1026
1027 int fileio_lstat (struct inferior *inf, const char *filename,
1028 struct stat *sb, fileio_error *target_errno) override;
1029
1030 int fileio_close (int fd, fileio_error *target_errno) override;
1031
1032 int fileio_unlink (struct inferior *inf,
1033 const char *filename,
1034 fileio_error *target_errno) override;
1035
1036 std::optional<std::string>
1037 fileio_readlink (struct inferior *inf,
1038 const char *filename,
1039 fileio_error *target_errno) override;
1040
1041 bool supports_enable_disable_tracepoint () override;
1042
1043 bool supports_string_tracing () override;
1044
1045 int remote_supports_cond_tracepoints ();
1046
1047 bool supports_evaluation_of_breakpoint_conditions () override;
1048
1049 int remote_supports_fast_tracepoints ();
1050
1051 int remote_supports_static_tracepoints ();
1052
1053 int remote_supports_install_in_trace ();
1054
1055 bool can_run_breakpoint_commands () override;
1056
1057 void trace_init () override;
1058
1059 void download_tracepoint (struct bp_location *location) override;
1060
1061 bool can_download_tracepoint () override;
1062
1063 void download_trace_state_variable (const trace_state_variable &tsv) override;
1064
1065 void enable_tracepoint (struct bp_location *location) override;
1066
1067 void disable_tracepoint (struct bp_location *location) override;
1068
1069 void trace_set_readonly_regions () override;
1070
1071 void trace_start () override;
1072
1073 int get_trace_status (struct trace_status *ts) override;
1074
1075 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
1076 override;
1077
1078 void trace_stop () override;
1079
1080 int trace_find (enum trace_find_type type, int num,
1081 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
1082
1083 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
1084
1085 int save_trace_data (const char *filename) override;
1086
1087 int upload_tracepoints (struct uploaded_tp **utpp) override;
1088
1089 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
1090
1091 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
1092
1093 int get_min_fast_tracepoint_insn_len () override;
1094
1095 void set_disconnected_tracing (int val) override;
1096
1097 void set_circular_trace_buffer (int val) override;
1098
1099 void set_trace_buffer_size (LONGEST val) override;
1100
1101 bool set_trace_notes (const char *user, const char *notes,
1102 const char *stopnotes) override;
1103
1104 int core_of_thread (ptid_t ptid) override;
1105
1106 int verify_memory (const gdb_byte *data,
1107 CORE_ADDR memaddr, ULONGEST size) override;
1108
1109
1110 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
1111
1112 void set_permissions () override;
1113
1114 bool static_tracepoint_marker_at (CORE_ADDR,
1115 struct static_tracepoint_marker *marker)
1116 override;
1117
1118 std::vector<static_tracepoint_marker>
1119 static_tracepoint_markers_by_strid (const char *id) override;
1120
1121 traceframe_info_up traceframe_info () override;
1122
1123 bool use_agent (bool use) override;
1124 bool can_use_agent () override;
1125
1126 struct btrace_target_info *
1127 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1128
1129 void disable_btrace (struct btrace_target_info *tinfo) override;
1130
1131 void teardown_btrace (struct btrace_target_info *tinfo) override;
1132
1133 enum btrace_error read_btrace (struct btrace_data *data,
1134 struct btrace_target_info *btinfo,
1135 enum btrace_read_type type) override;
1136
1137 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1138 bool augmented_libraries_svr4_read () override;
1139 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1140 void follow_clone (ptid_t child_ptid) override;
1141 void follow_exec (inferior *, ptid_t, const char *) override;
1142 int insert_fork_catchpoint (int) override;
1143 int remove_fork_catchpoint (int) override;
1144 int insert_vfork_catchpoint (int) override;
1145 int remove_vfork_catchpoint (int) override;
1146 int insert_exec_catchpoint (int) override;
1147 int remove_exec_catchpoint (int) override;
1148 enum exec_direction_kind execution_direction () override;
1149
1150 bool supports_memory_tagging () override;
1151
1152 bool fetch_memtags (CORE_ADDR address, size_t len,
1153 gdb::byte_vector &tags, int type) override;
1154
1155 bool store_memtags (CORE_ADDR address, size_t len,
1156 const gdb::byte_vector &tags, int type) override;
1157
1158 bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
1159
1160public: /* Remote specific methods. */
1161
1162 void remote_download_command_source (int num, ULONGEST addr,
1163 struct command_line *cmds);
1164
1165 void remote_file_put (const char *local_file, const char *remote_file,
1166 int from_tty);
1167 void remote_file_get (const char *remote_file, const char *local_file,
1168 int from_tty);
1169 void remote_file_delete (const char *remote_file, int from_tty);
1170
1171 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1172 ULONGEST offset, fileio_error *remote_errno);
1173 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1174 ULONGEST offset, fileio_error *remote_errno);
1175 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1176 ULONGEST offset, fileio_error *remote_errno);
1177
1178 int remote_hostio_send_command (int command_bytes, int which_packet,
1179 fileio_error *remote_errno, const char **attachment,
1180 int *attachment_len);
1181 int remote_hostio_set_filesystem (struct inferior *inf,
1182 fileio_error *remote_errno);
1183 /* We should get rid of this and use fileio_open directly. */
1184 int remote_hostio_open (struct inferior *inf, const char *filename,
1185 int flags, int mode, int warn_if_slow,
1186 fileio_error *remote_errno);
1187 int remote_hostio_close (int fd, fileio_error *remote_errno);
1188
1189 int remote_hostio_unlink (inferior *inf, const char *filename,
1190 fileio_error *remote_errno);
1191
1192 struct remote_state *get_remote_state ();
1193
1194 long get_remote_packet_size (void);
1195 long get_memory_packet_size (struct memory_packet_config *config);
1196
1197 long get_memory_write_packet_size ();
1198 long get_memory_read_packet_size ();
1199
1200 char *append_pending_thread_resumptions (char *p, char *endp,
1201 ptid_t ptid);
1202 static void open_1 (const char *name, int from_tty, int extended_p);
1203 void start_remote (int from_tty, int extended_p);
1204 void remote_detach_1 (struct inferior *inf, int from_tty);
1205
1206 char *append_resumption (char *p, char *endp,
1207 ptid_t ptid, int step, gdb_signal siggnal);
1208 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1209 gdb_signal siggnal);
1210
1211 thread_info *add_current_inferior_and_thread (const char *wait_status);
1212
1213 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1214 target_wait_flags options);
1215 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1216 target_wait_flags options);
1217
1218 ptid_t process_stop_reply (stop_reply_up stop_reply,
1219 target_waitstatus *status);
1220
1221 ptid_t select_thread_for_ambiguous_stop_reply
1222 (const struct target_waitstatus &status);
1223
1224 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1225
1226 void print_one_stopped_thread (thread_info *thread);
1227 void process_initial_stop_replies (int from_tty);
1228
1229 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1230 bool silent_p);
1231
1232 void btrace_sync_conf (const btrace_config *conf);
1233
1234 void remote_btrace_maybe_reopen ();
1235
1236 void remove_new_children (threads_listing_context *context);
1237 void kill_new_fork_children (inferior *inf);
1238 void discard_pending_stop_replies (struct inferior *inf);
1239 int stop_reply_queue_length ();
1240
1241 void check_pending_events_prevent_wildcard_vcont
1242 (bool *may_global_wildcard_vcont);
1243
1244 void discard_pending_stop_replies_in_queue ();
1245 stop_reply_up remote_notif_remove_queued_reply (ptid_t ptid);
1246 stop_reply_up queued_stop_reply (ptid_t ptid);
1247 int peek_stop_reply (ptid_t ptid);
1248 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1249
1250 void remote_stop_ns (ptid_t ptid);
1251 void remote_interrupt_as ();
1252 void remote_interrupt_ns ();
1253
1254 char *remote_get_noisy_reply ();
1255 int remote_query_attached (int pid);
1256 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1257 int try_open_exec);
1258
1259 ptid_t remote_current_thread (ptid_t oldpid);
1260 ptid_t get_current_thread (const char *wait_status);
1261
1262 void set_thread (ptid_t ptid, int gen);
1263 void set_general_thread (ptid_t ptid);
1264 void set_continue_thread (ptid_t ptid);
1265 void set_general_process ();
1266
1267 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1268
1269 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1270 gdb_ext_thread_info *info);
1271 int remote_get_threadinfo (threadref *threadid, int fieldset,
1272 gdb_ext_thread_info *info);
1273
1274 int parse_threadlist_response (const char *pkt, int result_limit,
1275 threadref *original_echo,
1276 threadref *resultlist,
1277 int *doneflag);
1278 int remote_get_threadlist (int startflag, threadref *nextthread,
1279 int result_limit, int *done, int *result_count,
1280 threadref *threadlist);
1281
1282 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1283 void *context, int looplimit);
1284
1285 int remote_get_threads_with_ql (threads_listing_context *context);
1286 int remote_get_threads_with_qxfer (threads_listing_context *context);
1287 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1288
1289 void extended_remote_restart ();
1290
1291 void get_offsets ();
1292
1293 void remote_check_symbols ();
1294
1295 void remote_supported_packet (const struct protocol_feature *feature,
1296 enum packet_support support,
1297 const char *argument);
1298
1299 void remote_query_supported ();
1300
1301 void remote_packet_size (const protocol_feature *feature,
1302 packet_support support, const char *value);
1303 void remote_supported_thread_options (const protocol_feature *feature,
1304 enum packet_support support,
1305 const char *value);
1306
1307 void remote_serial_quit_handler ();
1308
1309 void remote_detach_pid (int pid);
1310
1311 void remote_vcont_probe ();
1312
1313 void remote_resume_with_hc (ptid_t ptid, int step,
1314 gdb_signal siggnal);
1315
1316 void send_interrupt_sequence ();
1317 void interrupt_query ();
1318
1319 void remote_notif_get_pending_events (const notif_client *nc);
1320
1321 int fetch_register_using_p (struct regcache *regcache,
1322 packet_reg *reg);
1323 int send_g_packet ();
1324 void process_g_packet (struct regcache *regcache);
1325 void fetch_registers_using_g (struct regcache *regcache);
1326 int store_register_using_P (const struct regcache *regcache,
1327 packet_reg *reg);
1328 void store_registers_using_G (const struct regcache *regcache);
1329
1330 void set_remote_traceframe ();
1331
1332 void check_binary_download (CORE_ADDR addr);
1333
1334 target_xfer_status remote_write_bytes_aux (const char *header,
1335 CORE_ADDR memaddr,
1336 const gdb_byte *myaddr,
1337 ULONGEST len_units,
1338 int unit_size,
1339 ULONGEST *xfered_len_units,
1340 char packet_format,
1341 int use_length);
1342
1343 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1344 const gdb_byte *myaddr, ULONGEST len,
1345 int unit_size, ULONGEST *xfered_len);
1346
1347 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1348 ULONGEST len_units,
1349 int unit_size, ULONGEST *xfered_len_units);
1350
1351 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1352 ULONGEST memaddr,
1353 ULONGEST len,
1354 int unit_size,
1355 ULONGEST *xfered_len);
1356
1357 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1358 gdb_byte *myaddr, ULONGEST len,
1359 int unit_size,
1360 ULONGEST *xfered_len);
1361
1362 packet_status remote_send_printf (const char *format, ...)
1363 ATTRIBUTE_PRINTF (2, 3);
1364
1365 target_xfer_status remote_flash_write (ULONGEST address,
1366 ULONGEST length, ULONGEST *xfered_len,
1367 const gdb_byte *data);
1368
1369 int readchar (int timeout);
1370
1371 void remote_serial_write (const char *str, int len);
1372 void remote_serial_send_break ();
1373
1374 int putpkt (const char *buf);
1375 int putpkt_binary (const char *buf, int cnt);
1376
1377 int putpkt (const gdb::char_vector &buf)
1378 {
1379 return putpkt (buf.data ());
1380 }
1381
1382 void skip_frame ();
1383 long read_frame (gdb::char_vector *buf_p);
1384 int getpkt (gdb::char_vector *buf, bool forever = false,
1385 bool *is_notif = nullptr);
1386 int remote_vkill (int pid);
1387 void remote_kill_k ();
1388
1389 void extended_remote_disable_randomization (int val);
1390 int extended_remote_run (const std::string &args);
1391
1392 void send_environment_packet (const char *action,
1393 const char *packet,
1394 const char *value);
1395
1396 void extended_remote_environment_support ();
1397 void extended_remote_set_inferior_cwd ();
1398
1399 target_xfer_status remote_write_qxfer (const char *object_name,
1400 const char *annex,
1401 const gdb_byte *writebuf,
1402 ULONGEST offset, LONGEST len,
1403 ULONGEST *xfered_len,
1404 const unsigned int which_packet);
1405
1406 target_xfer_status remote_read_qxfer (const char *object_name,
1407 const char *annex,
1408 gdb_byte *readbuf, ULONGEST offset,
1409 LONGEST len,
1410 ULONGEST *xfered_len,
1411 const unsigned int which_packet);
1412
1413 void push_stop_reply (stop_reply_up new_event);
1414
1415 bool vcont_r_supported ();
1416
1417 remote_features m_features;
1418
1419private:
1420
1421 bool start_remote_1 (int from_tty, int extended_p);
1422
1423 /* The remote state. Don't reference this directly. Use the
1424 get_remote_state method instead. */
1425 remote_state m_remote_state;
1426};
1427
1428static const target_info extended_remote_target_info = {
1429 "extended-remote",
1430 N_("Extended remote target using gdb-specific protocol"),
1431 remote_doc
1432};
1433
1434/* Set up the extended remote target by extending the standard remote
1435 target and adding to it. */
1436
1437class extended_remote_target final : public remote_target
1438{
1439public:
1440 const target_info &info () const override
1441 { return extended_remote_target_info; }
1442
1443 /* Open an extended-remote connection. */
1444 static void open (const char *, int);
1445
1446 bool can_create_inferior () override { return true; }
1447 void create_inferior (const char *, const std::string &,
1448 char **, int) override;
1449
1450 void detach (inferior *, int) override;
1451
1452 bool can_attach () override { return true; }
1453 void attach (const char *, int) override;
1454
1455 void post_attach (int) override;
1456 bool supports_disable_randomization () override;
1457};
1458
1459struct stop_reply : public notif_event
1460{
1461 /* The identifier of the thread about this event */
1462 ptid_t ptid;
1463
1464 /* The remote state this event is associated with. When the remote
1465 connection, represented by a remote_state object, is closed,
1466 all the associated stop_reply events should be released. */
1467 struct remote_state *rs;
1468
1469 struct target_waitstatus ws;
1470
1471 /* The architecture associated with the expedited registers. */
1472 gdbarch *arch;
1473
1474 /* Expedited registers. This makes remote debugging a bit more
1475 efficient for those targets that provide critical registers as
1476 part of their normal status mechanism (as another roundtrip to
1477 fetch them is avoided). */
1478 std::vector<cached_reg_t> regcache;
1479
1480 enum target_stop_reason stop_reason;
1481
1482 CORE_ADDR watch_data_address;
1483
1484 int core;
1485};
1486
1487/* Return TARGET as a remote_target if it is one, else nullptr. */
1488
1489static remote_target *
1490as_remote_target (process_stratum_target *target)
1491{
1492 return dynamic_cast<remote_target *> (target);
1493}
1494
1495/* See remote.h. */
1496
1497bool
1498is_remote_target (process_stratum_target *target)
1499{
1500 return as_remote_target (target) != nullptr;
1501}
1502
1503/* See remote.h. */
1504
1505bool
1506remote_register_is_expedited (int regnum)
1507{
1508 remote_target *rt = as_remote_target (current_inferior ()->process_target ());
1509
1510 if (rt == nullptr)
1511 return false;
1512
1513 remote_state *rs = rt->get_remote_state ();
1514 return rs->last_seen_expedited_registers.count (regnum) > 0;
1515}
1516
1517/* Per-program-space data key. */
1518static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1519 remote_pspace_data;
1520
1521/* The variable registered as the control variable used by the
1522 remote exec-file commands. While the remote exec-file setting is
1523 per-program-space, the set/show machinery uses this as the
1524 location of the remote exec-file value. */
1525static std::string remote_exec_file_var;
1526
1527/* The size to align memory write packets, when practical. The protocol
1528 does not guarantee any alignment, and gdb will generate short
1529 writes and unaligned writes, but even as a best-effort attempt this
1530 can improve bulk transfers. For instance, if a write is misaligned
1531 relative to the target's data bus, the stub may need to make an extra
1532 round trip fetching data from the target. This doesn't make a
1533 huge difference, but it's easy to do, so we try to be helpful.
1534
1535 The alignment chosen is arbitrary; usually data bus width is
1536 important here, not the possibly larger cache line size. */
1537enum { REMOTE_ALIGN_WRITES = 16 };
1538
1539/* Prototypes for local functions. */
1540
1541static int hexnumlen (ULONGEST num);
1542
1543static int stubhex (int ch);
1544
1545static int hexnumstr (char *, ULONGEST);
1546
1547static int hexnumnstr (char *, ULONGEST, int);
1548
1549static CORE_ADDR remote_address_masked (CORE_ADDR);
1550
1551static int stub_unpack_int (const char *buff, int fieldlength);
1552
1553static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1554 cmd_list_element *c);
1555
1556static void show_packet_config_cmd (ui_file *file,
1557 const unsigned int which_packet,
1558 remote_target *remote);
1559
1560static void show_remote_protocol_packet_cmd (struct ui_file *file,
1561 int from_tty,
1562 struct cmd_list_element *c,
1563 const char *value);
1564
1565static ptid_t read_ptid (const char *buf, const char **obuf);
1566
1567static bool remote_read_description_p (struct target_ops *target);
1568
1569static void remote_console_output (const char *msg, ui_file *stream);
1570
1571static void remote_btrace_reset (remote_state *rs);
1572
1573[[noreturn]] static void remote_unpush_and_throw (remote_target *target);
1574
1575/* For "remote". */
1576
1577static struct cmd_list_element *remote_cmdlist;
1578
1579/* For "set remote" and "show remote". */
1580
1581static struct cmd_list_element *remote_set_cmdlist;
1582static struct cmd_list_element *remote_show_cmdlist;
1583
1584/* Controls whether GDB is willing to use range stepping. */
1585
1586static bool use_range_stepping = true;
1587
1588/* From the remote target's point of view, each thread is in one of these three
1589 states. */
1590enum class resume_state
1591{
1592 /* Not resumed - we haven't been asked to resume this thread. */
1593 NOT_RESUMED,
1594
1595 /* We have been asked to resume this thread, but haven't sent a vCont action
1596 for it yet. We'll need to consider it next time commit_resume is
1597 called. */
1598 RESUMED_PENDING_VCONT,
1599
1600 /* We have been asked to resume this thread, and we have sent a vCont action
1601 for it. */
1602 RESUMED,
1603};
1604
1605/* Information about a thread's pending vCont-resume. Used when a thread is in
1606 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1607 stores this information which is then picked up by
1608 remote_target::commit_resume to know which is the proper action for this
1609 thread to include in the vCont packet. */
1610struct resumed_pending_vcont_info
1611{
1612 /* True if the last resume call for this thread was a step request, false
1613 if a continue request. */
1614 bool step;
1615
1616 /* The signal specified in the last resume call for this thread. */
1617 gdb_signal sig;
1618};
1619
1620/* Private data that we'll store in (struct thread_info)->priv. */
1621struct remote_thread_info : public private_thread_info
1622{
1623 std::string extra;
1624 std::string name;
1625 int core = -1;
1626
1627 /* The string representation for the thread's id.
1628
1629 The target specifies this if they want to display the thread id
1630 in a specific way. If empty, the default approach is used. */
1631 std::string id_str;
1632
1633 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1634 sequence of bytes. */
1635 gdb::byte_vector thread_handle;
1636
1637 /* Whether the target stopped for a breakpoint/watchpoint. */
1638 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1639
1640 /* This is set to the data address of the access causing the target
1641 to stop for a watchpoint. */
1642 CORE_ADDR watch_data_address = 0;
1643
1644 /* Get the thread's resume state. */
1645 enum resume_state get_resume_state () const
1646 {
1647 return m_resume_state;
1648 }
1649
1650 /* Put the thread in the NOT_RESUMED state. */
1651 void set_not_resumed ()
1652 {
1653 m_resume_state = resume_state::NOT_RESUMED;
1654 }
1655
1656 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1657 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1658 {
1659 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1660 m_resumed_pending_vcont_info.step = step;
1661 m_resumed_pending_vcont_info.sig = sig;
1662 }
1663
1664 /* Get the information this thread's pending vCont-resumption.
1665
1666 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1667 state. */
1668 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1669 {
1670 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1671
1672 return m_resumed_pending_vcont_info;
1673 }
1674
1675 /* Put the thread in the VCONT_RESUMED state. */
1676 void set_resumed ()
1677 {
1678 m_resume_state = resume_state::RESUMED;
1679 }
1680
1681private:
1682 /* Resume state for this thread. This is used to implement vCont action
1683 coalescing (only when the target operates in non-stop mode).
1684
1685 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1686 which notes that this thread must be considered in the next commit_resume
1687 call.
1688
1689 remote_target::commit_resume sends a vCont packet with actions for the
1690 threads in the RESUMED_PENDING_VCONT state and moves them to the
1691 VCONT_RESUMED state.
1692
1693 When reporting a stop to the core for a thread, that thread is moved back
1694 to the NOT_RESUMED state. */
1695 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1696
1697 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1698 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1699};
1700
1701remote_state::remote_state ()
1702 : buf (400)
1703{
1704}
1705
1706remote_state::~remote_state ()
1707{
1708 xfree (this->last_pass_packet);
1709 xfree (this->last_program_signals_packet);
1710 xfree (this->finished_object);
1711 xfree (this->finished_annex);
1712}
1713
1714/* Utility: generate error from an incoming stub packet. */
1715static void
1716trace_error (char *buf)
1717{
1718 if (*buf++ != 'E')
1719 return; /* not an error msg */
1720 switch (*buf)
1721 {
1722 case '1': /* malformed packet error */
1723 if (*++buf == '0') /* general case: */
1724 error (_("remote.c: error in outgoing packet."));
1725 else
1726 error (_("remote.c: error in outgoing packet at field #%ld."),
1727 strtol (buf, NULL, 16));
1728 default:
1729 error (_("Target returns error code '%s'."), buf);
1730 }
1731}
1732
1733/* Utility: wait for reply from stub, while accepting "O" packets. */
1734
1735char *
1736remote_target::remote_get_noisy_reply ()
1737{
1738 struct remote_state *rs = get_remote_state ();
1739
1740 do /* Loop on reply from remote stub. */
1741 {
1742 char *buf;
1743
1744 QUIT; /* Allow user to bail out with ^C. */
1745 getpkt (&rs->buf);
1746 buf = rs->buf.data ();
1747 if (buf[0] == 'E')
1748 trace_error (buf);
1749 else if (startswith (buf, "qRelocInsn:"))
1750 {
1751 ULONGEST ul;
1752 CORE_ADDR from, to, org_to;
1753 const char *p, *pp;
1754 int adjusted_size = 0;
1755 int relocated = 0;
1756
1757 p = buf + strlen ("qRelocInsn:");
1758 pp = unpack_varlen_hex (p, &ul);
1759 if (*pp != ';')
1760 error (_("invalid qRelocInsn packet: %s"), buf);
1761 from = ul;
1762
1763 p = pp + 1;
1764 unpack_varlen_hex (p, &ul);
1765 to = ul;
1766
1767 org_to = to;
1768
1769 try
1770 {
1771 gdbarch_relocate_instruction (current_inferior ()->arch (),
1772 &to, from);
1773 relocated = 1;
1774 }
1775 catch (const gdb_exception &ex)
1776 {
1777 if (ex.error == MEMORY_ERROR)
1778 {
1779 /* Propagate memory errors silently back to the
1780 target. The stub may have limited the range of
1781 addresses we can write to, for example. */
1782 }
1783 else
1784 {
1785 /* Something unexpectedly bad happened. Be verbose
1786 so we can tell what, and propagate the error back
1787 to the stub, so it doesn't get stuck waiting for
1788 a response. */
1789 exception_fprintf (gdb_stderr, ex,
1790 _("warning: relocating instruction: "));
1791 }
1792 putpkt ("E01");
1793 }
1794
1795 if (relocated)
1796 {
1797 adjusted_size = to - org_to;
1798
1799 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1800 putpkt (buf);
1801 }
1802 }
1803 else if (buf[0] == 'O' && buf[1] != 'K')
1804 {
1805 /* 'O' message from stub */
1806 remote_console_output (buf + 1, gdb_stdtarg);
1807 }
1808 else
1809 return buf; /* Here's the actual reply. */
1810 }
1811 while (1);
1812}
1813
1814struct remote_arch_state *
1815remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1816{
1817 remote_arch_state *rsa;
1818
1819 auto it = this->m_arch_states.find (gdbarch);
1820 if (it == this->m_arch_states.end ())
1821 {
1822 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1823 std::forward_as_tuple (gdbarch),
1824 std::forward_as_tuple (gdbarch));
1825 rsa = &p.first->second;
1826
1827 /* Make sure that the packet buffer is plenty big enough for
1828 this architecture. */
1829 if (this->buf.size () < rsa->remote_packet_size)
1830 this->buf.resize (2 * rsa->remote_packet_size);
1831 }
1832 else
1833 rsa = &it->second;
1834
1835 return rsa;
1836}
1837
1838/* Fetch the global remote target state. */
1839
1840remote_state *
1841remote_target::get_remote_state ()
1842{
1843 /* Make sure that the remote architecture state has been
1844 initialized, because doing so might reallocate rs->buf. Any
1845 function which calls getpkt also needs to be mindful of changes
1846 to rs->buf, but this call limits the number of places which run
1847 into trouble. */
1848 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1849
1850 return &m_remote_state;
1851}
1852
1853/* Fetch the remote exec-file from the current program space. */
1854
1855static const char *
1856get_remote_exec_file (void)
1857{
1858 char *remote_exec_file;
1859
1860 remote_exec_file = remote_pspace_data.get (current_program_space);
1861 if (remote_exec_file == NULL)
1862 return "";
1863
1864 return remote_exec_file;
1865}
1866
1867/* Set the remote exec file for PSPACE. */
1868
1869static void
1870set_pspace_remote_exec_file (struct program_space *pspace,
1871 const char *remote_exec_file)
1872{
1873 char *old_file = remote_pspace_data.get (pspace);
1874
1875 xfree (old_file);
1876 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1877}
1878
1879/* The "set/show remote exec-file" set command hook. */
1880
1881static void
1882set_remote_exec_file (const char *ignored, int from_tty,
1883 struct cmd_list_element *c)
1884{
1885 set_pspace_remote_exec_file (current_program_space,
1886 remote_exec_file_var.c_str ());
1887}
1888
1889/* The "set/show remote exec-file" show command hook. */
1890
1891static void
1892show_remote_exec_file (struct ui_file *file, int from_tty,
1893 struct cmd_list_element *cmd, const char *value)
1894{
1895 gdb_printf (file, "%s\n", get_remote_exec_file ());
1896}
1897
1898static int
1899map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1900{
1901 int regnum, num_remote_regs, offset;
1902 struct packet_reg **remote_regs;
1903
1904 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1905 {
1906 struct packet_reg *r = &regs[regnum];
1907
1908 if (register_size (gdbarch, regnum) == 0)
1909 /* Do not try to fetch zero-sized (placeholder) registers. */
1910 r->pnum = -1;
1911 else
1912 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1913
1914 r->regnum = regnum;
1915 }
1916
1917 /* Define the g/G packet format as the contents of each register
1918 with a remote protocol number, in order of ascending protocol
1919 number. */
1920
1921 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1922 for (num_remote_regs = 0, regnum = 0;
1923 regnum < gdbarch_num_regs (gdbarch);
1924 regnum++)
1925 if (regs[regnum].pnum != -1)
1926 remote_regs[num_remote_regs++] = &regs[regnum];
1927
1928 std::sort (remote_regs, remote_regs + num_remote_regs,
1929 [] (const packet_reg *a, const packet_reg *b)
1930 { return a->pnum < b->pnum; });
1931
1932 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1933 {
1934 remote_regs[regnum]->in_g_packet = true;
1935 remote_regs[regnum]->offset = offset;
1936 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1937 }
1938
1939 return offset;
1940}
1941
1942/* Given the architecture described by GDBARCH, return the remote
1943 protocol register's number and the register's offset in the g/G
1944 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1945 If the target does not have a mapping for REGNUM, return false,
1946 otherwise, return true. */
1947
1948int
1949remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1950 int *pnum, int *poffset)
1951{
1952 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1953
1954 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1955
1956 map_regcache_remote_table (gdbarch, regs.data ());
1957
1958 *pnum = regs[regnum].pnum;
1959 *poffset = regs[regnum].offset;
1960
1961 return *pnum != -1;
1962}
1963
1964remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1965{
1966 /* Use the architecture to build a regnum<->pnum table, which will be
1967 1:1 unless a feature set specifies otherwise. */
1968 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1969
1970 /* Record the maximum possible size of the g packet - it may turn out
1971 to be smaller. */
1972 this->sizeof_g_packet
1973 = map_regcache_remote_table (gdbarch, this->regs.get ());
1974
1975 /* Default maximum number of characters in a packet body. Many
1976 remote stubs have a hardwired buffer size of 400 bytes
1977 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1978 as the maximum packet-size to ensure that the packet and an extra
1979 NUL character can always fit in the buffer. This stops GDB
1980 trashing stubs that try to squeeze an extra NUL into what is
1981 already a full buffer (As of 1999-12-04 that was most stubs). */
1982 this->remote_packet_size = 400 - 1;
1983
1984 /* This one is filled in when a ``g'' packet is received. */
1985 this->actual_register_packet_size = 0;
1986
1987 /* Should rsa->sizeof_g_packet needs more space than the
1988 default, adjust the size accordingly. Remember that each byte is
1989 encoded as two characters. 32 is the overhead for the packet
1990 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1991 (``$NN:G...#NN'') is a better guess, the below has been padded a
1992 little. */
1993 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1994 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1995}
1996
1997/* Get a pointer to the current remote target. If not connected to a
1998 remote target, return NULL. */
1999
2000static remote_target *
2001get_current_remote_target ()
2002{
2003 target_ops *proc_target = current_inferior ()->process_target ();
2004 return dynamic_cast<remote_target *> (proc_target);
2005}
2006
2007/* Return the current allowed size of a remote packet. This is
2008 inferred from the current architecture, and should be used to
2009 limit the length of outgoing packets. */
2010long
2011remote_target::get_remote_packet_size ()
2012{
2013 struct remote_state *rs = get_remote_state ();
2014 remote_arch_state *rsa
2015 = rs->get_remote_arch_state (current_inferior ()->arch ());
2016
2017 if (rs->explicit_packet_size)
2018 return rs->explicit_packet_size;
2019
2020 return rsa->remote_packet_size;
2021}
2022
2023static struct packet_reg *
2024packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
2025 long regnum)
2026{
2027 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
2028 return NULL;
2029 else
2030 {
2031 struct packet_reg *r = &rsa->regs[regnum];
2032
2033 gdb_assert (r->regnum == regnum);
2034 return r;
2035 }
2036}
2037
2038static struct packet_reg *
2039packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
2040 LONGEST pnum)
2041{
2042 int i;
2043
2044 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
2045 {
2046 struct packet_reg *r = &rsa->regs[i];
2047
2048 if (r->pnum == pnum)
2049 return r;
2050 }
2051 return NULL;
2052}
2053
2054/* Allow the user to specify what sequence to send to the remote
2055 when he requests a program interruption: Although ^C is usually
2056 what remote systems expect (this is the default, here), it is
2057 sometimes preferable to send a break. On other systems such
2058 as the Linux kernel, a break followed by g, which is Magic SysRq g
2059 is required in order to interrupt the execution. */
2060const char interrupt_sequence_control_c[] = "Ctrl-C";
2061const char interrupt_sequence_break[] = "BREAK";
2062const char interrupt_sequence_break_g[] = "BREAK-g";
2063static const char *const interrupt_sequence_modes[] =
2064 {
2065 interrupt_sequence_control_c,
2066 interrupt_sequence_break,
2067 interrupt_sequence_break_g,
2068 NULL
2069 };
2070static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
2071
2072static void
2073show_interrupt_sequence (struct ui_file *file, int from_tty,
2074 struct cmd_list_element *c,
2075 const char *value)
2076{
2077 if (interrupt_sequence_mode == interrupt_sequence_control_c)
2078 gdb_printf (file,
2079 _("Send the ASCII ETX character (Ctrl-c) "
2080 "to the remote target to interrupt the "
2081 "execution of the program.\n"));
2082 else if (interrupt_sequence_mode == interrupt_sequence_break)
2083 gdb_printf (file,
2084 _("send a break signal to the remote target "
2085 "to interrupt the execution of the program.\n"));
2086 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
2087 gdb_printf (file,
2088 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
2089 "the remote target to interrupt the execution "
2090 "of Linux kernel.\n"));
2091 else
2092 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
2093 interrupt_sequence_mode);
2094}
2095
2096/* This boolean variable specifies whether interrupt_sequence is sent
2097 to the remote target when gdb connects to it.
2098 This is mostly needed when you debug the Linux kernel: The Linux kernel
2099 expects BREAK g which is Magic SysRq g for connecting gdb. */
2100static bool interrupt_on_connect = false;
2101
2102/* This variable is used to implement the "set/show remotebreak" commands.
2103 Since these commands are now deprecated in favor of "set/show remote
2104 interrupt-sequence", it no longer has any effect on the code. */
2105static bool remote_break;
2106
2107static void
2108set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
2109{
2110 if (remote_break)
2111 interrupt_sequence_mode = interrupt_sequence_break;
2112 else
2113 interrupt_sequence_mode = interrupt_sequence_control_c;
2114}
2115
2116static void
2117show_remotebreak (struct ui_file *file, int from_tty,
2118 struct cmd_list_element *c,
2119 const char *value)
2120{
2121}
2122
2123/* This variable sets the number of bits in an address that are to be
2124 sent in a memory ("M" or "m") packet. Normally, after stripping
2125 leading zeros, the entire address would be sent. This variable
2126 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2127 initial implementation of remote.c restricted the address sent in
2128 memory packets to ``host::sizeof long'' bytes - (typically 32
2129 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2130 address was never sent. Since fixing this bug may cause a break in
2131 some remote targets this variable is principally provided to
2132 facilitate backward compatibility. */
2133
2134static unsigned int remote_address_size;
2135
2136\f
2137/* The default max memory-write-packet-size, when the setting is
2138 "fixed". The 16k is historical. (It came from older GDB's using
2139 alloca for buffers and the knowledge (folklore?) that some hosts
2140 don't cope very well with large alloca calls.) */
2141#define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2142
2143/* The minimum remote packet size for memory transfers. Ensures we
2144 can write at least one byte. */
2145#define MIN_MEMORY_PACKET_SIZE 20
2146
2147/* Get the memory packet size, assuming it is fixed. */
2148
2149static long
2150get_fixed_memory_packet_size (struct memory_packet_config *config)
2151{
2152 gdb_assert (config->fixed_p);
2153
2154 if (config->size <= 0)
2155 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2156 else
2157 return config->size;
2158}
2159
2160/* Compute the current size of a read/write packet. Since this makes
2161 use of ``actual_register_packet_size'' the computation is dynamic. */
2162
2163long
2164remote_target::get_memory_packet_size (struct memory_packet_config *config)
2165{
2166 struct remote_state *rs = get_remote_state ();
2167 remote_arch_state *rsa
2168 = rs->get_remote_arch_state (current_inferior ()->arch ());
2169
2170 long what_they_get;
2171 if (config->fixed_p)
2172 what_they_get = get_fixed_memory_packet_size (config);
2173 else
2174 {
2175 what_they_get = get_remote_packet_size ();
2176 /* Limit the packet to the size specified by the user. */
2177 if (config->size > 0
2178 && what_they_get > config->size)
2179 what_they_get = config->size;
2180
2181 /* Limit it to the size of the targets ``g'' response unless we have
2182 permission from the stub to use a larger packet size. */
2183 if (rs->explicit_packet_size == 0
2184 && rsa->actual_register_packet_size > 0
2185 && what_they_get > rsa->actual_register_packet_size)
2186 what_they_get = rsa->actual_register_packet_size;
2187 }
2188 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2189 what_they_get = MIN_MEMORY_PACKET_SIZE;
2190
2191 /* Make sure there is room in the global buffer for this packet
2192 (including its trailing NUL byte). */
2193 if (rs->buf.size () < what_they_get + 1)
2194 rs->buf.resize (2 * what_they_get);
2195
2196 return what_they_get;
2197}
2198
2199/* Update the size of a read/write packet. If they user wants
2200 something really big then do a sanity check. */
2201
2202static void
2203set_memory_packet_size (const char *args, struct memory_packet_config *config,
2204 bool target_connected)
2205{
2206 int fixed_p = config->fixed_p;
2207 long size = config->size;
2208
2209 if (args == NULL)
2210 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2211 else if (strcmp (args, "hard") == 0
2212 || strcmp (args, "fixed") == 0)
2213 fixed_p = 1;
2214 else if (strcmp (args, "soft") == 0
2215 || strcmp (args, "limit") == 0)
2216 fixed_p = 0;
2217 else
2218 {
2219 char *end;
2220
2221 size = strtoul (args, &end, 0);
2222 if (args == end)
2223 error (_("Invalid %s (bad syntax)."), config->name);
2224
2225 /* Instead of explicitly capping the size of a packet to or
2226 disallowing it, the user is allowed to set the size to
2227 something arbitrarily large. */
2228 }
2229
2230 /* Extra checks? */
2231 if (fixed_p && !config->fixed_p)
2232 {
2233 /* So that the query shows the correct value. */
2234 long query_size = (size <= 0
2235 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2236 : size);
2237
2238 if (target_connected
2239 && !query (_("The target may not be able to correctly handle a %s\n"
2240 "of %ld bytes. Change the packet size? "),
2241 config->name, query_size))
2242 error (_("Packet size not changed."));
2243 else if (!target_connected
2244 && !query (_("Future remote targets may not be able to "
2245 "correctly handle a %s\nof %ld bytes. Change the "
2246 "packet size for future remote targets? "),
2247 config->name, query_size))
2248 error (_("Packet size not changed."));
2249 }
2250 /* Update the config. */
2251 config->fixed_p = fixed_p;
2252 config->size = size;
2253
2254 const char *target_type = get_target_type_name (target_connected);
2255 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2256 args);
2257
2258}
2259
2260/* Show the memory-read or write-packet size configuration CONFIG of the
2261 target REMOTE. If REMOTE is nullptr, the default configuration for future
2262 remote targets should be passed in CONFIG. */
2263
2264static void
2265show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2266{
2267 const char *target_type = get_target_type_name (remote != nullptr);
2268
2269 if (config->size == 0)
2270 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2271 else
2272 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2273 config->size);
2274
2275 if (config->fixed_p)
2276 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2277 get_fixed_memory_packet_size (config));
2278 else
2279 {
2280 if (remote != nullptr)
2281 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2282 remote->get_memory_packet_size (config));
2283 else
2284 gdb_puts ("The actual limit will be further reduced "
2285 "dependent on the target.\n");
2286 }
2287}
2288
2289/* Configure the memory-write-packet size of the currently selected target. If
2290 no target is available, the default configuration for future remote targets
2291 is configured. */
2292
2293static void
2294set_memory_write_packet_size (const char *args, int from_tty)
2295{
2296 remote_target *remote = get_current_remote_target ();
2297 if (remote != nullptr)
2298 {
2299 set_memory_packet_size
2300 (args, &remote->m_features.m_memory_write_packet_config, true);
2301 }
2302 else
2303 {
2304 memory_packet_config* config = &memory_write_packet_config;
2305 set_memory_packet_size (args, config, false);
2306 }
2307}
2308
2309/* Display the memory-write-packet size of the currently selected target. If
2310 no target is available, the default configuration for future remote targets
2311 is shown. */
2312
2313static void
2314show_memory_write_packet_size (const char *args, int from_tty)
2315{
2316 remote_target *remote = get_current_remote_target ();
2317 if (remote != nullptr)
2318 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2319 remote);
2320 else
2321 show_memory_packet_size (&memory_write_packet_config, nullptr);
2322}
2323
2324/* Show the number of hardware watchpoints that can be used. */
2325
2326static void
2327show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2328 struct cmd_list_element *c,
2329 const char *value)
2330{
2331 gdb_printf (file, _("The maximum number of target hardware "
2332 "watchpoints is %s.\n"), value);
2333}
2334
2335/* Show the length limit (in bytes) for hardware watchpoints. */
2336
2337static void
2338show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2339 struct cmd_list_element *c,
2340 const char *value)
2341{
2342 gdb_printf (file, _("The maximum length (in bytes) of a target "
2343 "hardware watchpoint is %s.\n"), value);
2344}
2345
2346/* Show the number of hardware breakpoints that can be used. */
2347
2348static void
2349show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2350 struct cmd_list_element *c,
2351 const char *value)
2352{
2353 gdb_printf (file, _("The maximum number of target hardware "
2354 "breakpoints is %s.\n"), value);
2355}
2356
2357/* Controls the maximum number of characters to display in the debug output
2358 for each remote packet. The remaining characters are omitted. */
2359
2360static int remote_packet_max_chars = 512;
2361
2362/* Show the maximum number of characters to display for each remote packet
2363 when remote debugging is enabled. */
2364
2365static void
2366show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2367 struct cmd_list_element *c,
2368 const char *value)
2369{
2370 gdb_printf (file, _("Number of remote packet characters to "
2371 "display is %s.\n"), value);
2372}
2373
2374long
2375remote_target::get_memory_write_packet_size ()
2376{
2377 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2378}
2379
2380/* Configure the memory-read-packet size of the currently selected target. If
2381 no target is available, the default configuration for future remote targets
2382 is adapted. */
2383
2384static void
2385set_memory_read_packet_size (const char *args, int from_tty)
2386{
2387 remote_target *remote = get_current_remote_target ();
2388 if (remote != nullptr)
2389 set_memory_packet_size
2390 (args, &remote->m_features.m_memory_read_packet_config, true);
2391 else
2392 {
2393 memory_packet_config* config = &memory_read_packet_config;
2394 set_memory_packet_size (args, config, false);
2395 }
2396
2397}
2398
2399/* Display the memory-read-packet size of the currently selected target. If
2400 no target is available, the default configuration for future remote targets
2401 is shown. */
2402
2403static void
2404show_memory_read_packet_size (const char *args, int from_tty)
2405{
2406 remote_target *remote = get_current_remote_target ();
2407 if (remote != nullptr)
2408 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2409 remote);
2410 else
2411 show_memory_packet_size (&memory_read_packet_config, nullptr);
2412}
2413
2414long
2415remote_target::get_memory_read_packet_size ()
2416{
2417 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2418
2419 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2420 extra buffer size argument before the memory read size can be
2421 increased beyond this. */
2422 if (size > get_remote_packet_size ())
2423 size = get_remote_packet_size ();
2424 return size;
2425}
2426
2427static enum packet_support packet_config_support (const packet_config *config);
2428
2429
2430static void
2431set_remote_protocol_packet_cmd (const char *args, int from_tty,
2432 cmd_list_element *c)
2433{
2434 remote_target *remote = get_current_remote_target ();
2435 gdb_assert (c->var.has_value ());
2436
2437 auto *default_config = static_cast<packet_config *> (c->context ());
2438 const int packet_idx = std::distance (remote_protocol_packets,
2439 default_config);
2440
2441 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2442 {
2443 const char *name = packets_descriptions[packet_idx].name;
2444 const auto_boolean value = c->var->get<auto_boolean> ();
2445 const char *support = get_packet_support_name (value);
2446 const char *target_type = get_target_type_name (remote != nullptr);
2447
2448 if (remote != nullptr)
2449 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2450 else
2451 remote_protocol_packets[packet_idx].detect = value;
2452
2453 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2454 target_type, support);
2455 return;
2456 }
2457
2458 internal_error (_("Could not find config for %s"), c->name);
2459}
2460
2461static void
2462show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2463 remote_target *remote)
2464{
2465 const char *support = "internal-error";
2466 const char *target_type = get_target_type_name (remote != nullptr);
2467
2468 packet_config *config;
2469 if (remote != nullptr)
2470 config = &remote->m_features.m_protocol_packets[which_packet];
2471 else
2472 config = &remote_protocol_packets[which_packet];
2473
2474 switch (packet_config_support (config))
2475 {
2476 case PACKET_ENABLE:
2477 support = "enabled";
2478 break;
2479 case PACKET_DISABLE:
2480 support = "disabled";
2481 break;
2482 case PACKET_SUPPORT_UNKNOWN:
2483 support = "unknown";
2484 break;
2485 }
2486 switch (config->detect)
2487 {
2488 case AUTO_BOOLEAN_AUTO:
2489 gdb_printf (file,
2490 _("Support for the '%s' packet %s is \"auto\", "
2491 "currently %s.\n"),
2492 packets_descriptions[which_packet].name, target_type,
2493 support);
2494 break;
2495 case AUTO_BOOLEAN_TRUE:
2496 case AUTO_BOOLEAN_FALSE:
2497 gdb_printf (file,
2498 _("Support for the '%s' packet %s is \"%s\".\n"),
2499 packets_descriptions[which_packet].name, target_type,
2500 get_packet_support_name (config->detect));
2501 break;
2502 }
2503}
2504
2505static void
2506add_packet_config_cmd (const unsigned int which_packet, const char *name,
2507 const char *title, int legacy)
2508{
2509 packets_descriptions[which_packet].name = name;
2510 packets_descriptions[which_packet].title = title;
2511
2512 packet_config *config = &remote_protocol_packets[which_packet];
2513
2514 gdb::unique_xmalloc_ptr<char> set_doc
2515 = xstrprintf ("Set use of remote protocol `%s' packet.", name);
2516 gdb::unique_xmalloc_ptr<char> show_doc
2517 = xstrprintf ("Show current use of remote protocol `%s' packet.", name);
2518 /* set/show TITLE-packet {auto,on,off} */
2519 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2520 set_show_commands cmds
2521 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2522 &config->detect, set_doc.get (),
2523 show_doc.get (), NULL, /* help_doc */
2524 set_remote_protocol_packet_cmd,
2525 show_remote_protocol_packet_cmd,
2526 &remote_set_cmdlist, &remote_show_cmdlist);
2527 cmds.show->set_context (config);
2528 cmds.set->set_context (config);
2529
2530 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2531 if (legacy)
2532 {
2533 /* It's not clear who should take ownership of the LEGACY_NAME string
2534 created below, so, for now, place the string into a static vector
2535 which ensures the strings is released when GDB exits. */
2536 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2537 gdb::unique_xmalloc_ptr<char> legacy_name
2538 = xstrprintf ("%s-packet", name);
2539 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2540 &remote_set_cmdlist);
2541 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2542 &remote_show_cmdlist);
2543 legacy_names.emplace_back (std::move (legacy_name));
2544 }
2545}
2546
2547/* Check GDBserver's reply packet. Return packet_result structure
2548 which contains the packet_status enum and an error message for the
2549 PACKET_ERROR case.
2550
2551 An error packet can always take the form Exx (where xx is a hex
2552 code). */
2553static packet_result
2554packet_check_result (const char *buf)
2555{
2556 if (buf[0] != '\0')
2557 {
2558 /* The stub recognized the packet request. Check that the
2559 operation succeeded. */
2560 if (buf[0] == 'E'
2561 && isxdigit (buf[1]) && isxdigit (buf[2])
2562 && buf[3] == '\0')
2563 /* "Enn" - definitely an error. */
2564 return packet_result::make_numeric_error (buf + 1);
2565
2566 /* Always treat "E." as an error. This will be used for
2567 more verbose error messages, such as E.memtypes. */
2568 if (buf[0] == 'E' && buf[1] == '.')
2569 {
2570 if (buf[2] != '\0')
2571 return packet_result::make_textual_error (buf + 2);
2572 else
2573 return packet_result::make_textual_error ("no error provided");
2574 }
2575
2576 /* The packet may or may not be OK. Just assume it is. */
2577 return packet_result::make_ok ();
2578 }
2579 else
2580 {
2581 /* The stub does not support the packet. */
2582 return packet_result::make_unknown ();
2583 }
2584}
2585
2586static packet_result
2587packet_check_result (const gdb::char_vector &buf)
2588{
2589 return packet_check_result (buf.data ());
2590}
2591
2592packet_result
2593remote_features::packet_ok (const char *buf, const int which_packet)
2594{
2595 packet_config *config = &m_protocol_packets[which_packet];
2596 packet_description *descr = &packets_descriptions[which_packet];
2597
2598 if (config->detect != AUTO_BOOLEAN_TRUE
2599 && config->support == PACKET_DISABLE)
2600 internal_error (_("packet_ok: attempt to use a disabled packet"));
2601
2602 packet_result result = packet_check_result (buf);
2603 switch (result.status ())
2604 {
2605 case PACKET_OK:
2606 case PACKET_ERROR:
2607 /* The stub recognized the packet request. */
2608 if (config->support == PACKET_SUPPORT_UNKNOWN)
2609 {
2610 remote_debug_printf ("Packet %s (%s) is supported",
2611 descr->name, descr->title);
2612 config->support = PACKET_ENABLE;
2613 }
2614 break;
2615 case PACKET_UNKNOWN:
2616 /* The stub does not support the packet. */
2617 if (config->detect == AUTO_BOOLEAN_AUTO
2618 && config->support == PACKET_ENABLE)
2619 {
2620 /* If the stub previously indicated that the packet was
2621 supported then there is a protocol error. */
2622 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2623 descr->name, descr->title);
2624 }
2625 else if (config->detect == AUTO_BOOLEAN_TRUE)
2626 {
2627 /* The user set it wrong. */
2628 error (_("Enabled packet %s (%s) not recognized by stub"),
2629 descr->name, descr->title);
2630 }
2631
2632 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2633 descr->title);
2634 config->support = PACKET_DISABLE;
2635 break;
2636 }
2637
2638 return result;
2639}
2640
2641packet_result
2642remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2643{
2644 return packet_ok (buf.data (), which_packet);
2645}
2646
2647/* Returns whether a given packet or feature is supported. This takes
2648 into account the state of the corresponding "set remote foo-packet"
2649 command, which may be used to bypass auto-detection. */
2650
2651static enum packet_support
2652packet_config_support (const packet_config *config)
2653{
2654 switch (config->detect)
2655 {
2656 case AUTO_BOOLEAN_TRUE:
2657 return PACKET_ENABLE;
2658 case AUTO_BOOLEAN_FALSE:
2659 return PACKET_DISABLE;
2660 case AUTO_BOOLEAN_AUTO:
2661 return config->support;
2662 default:
2663 gdb_assert_not_reached ("bad switch");
2664 }
2665}
2666
2667packet_support
2668remote_features::packet_support (int packet) const
2669{
2670 const packet_config *config = &m_protocol_packets[packet];
2671 return packet_config_support (config);
2672}
2673
2674static void
2675show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2676 struct cmd_list_element *c,
2677 const char *value)
2678{
2679 remote_target *remote = get_current_remote_target ();
2680 gdb_assert (c->var.has_value ());
2681
2682 auto *default_config = static_cast<packet_config *> (c->context ());
2683 const int packet_idx = std::distance (remote_protocol_packets,
2684 default_config);
2685
2686 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2687 {
2688 show_packet_config_cmd (file, packet_idx, remote);
2689 return;
2690 }
2691 internal_error (_("Could not find config for %s"), c->name);
2692}
2693
2694/* Should we try one of the 'Z' requests? */
2695
2696enum Z_packet_type
2697{
2698 Z_PACKET_SOFTWARE_BP,
2699 Z_PACKET_HARDWARE_BP,
2700 Z_PACKET_WRITE_WP,
2701 Z_PACKET_READ_WP,
2702 Z_PACKET_ACCESS_WP,
2703 NR_Z_PACKET_TYPES
2704};
2705
2706/* For compatibility with older distributions. Provide a ``set remote
2707 Z-packet ...'' command that updates all the Z packet types. */
2708
2709static enum auto_boolean remote_Z_packet_detect;
2710
2711static void
2712set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2713 struct cmd_list_element *c)
2714{
2715 remote_target *remote = get_current_remote_target ();
2716 int i;
2717
2718 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2719 {
2720 if (remote != nullptr)
2721 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2722 = remote_Z_packet_detect;
2723 else
2724 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2725 }
2726
2727 const char *support = get_packet_support_name (remote_Z_packet_detect);
2728 const char *target_type = get_target_type_name (remote != nullptr);
2729 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2730 support);
2731
2732}
2733
2734static void
2735show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2736 struct cmd_list_element *c,
2737 const char *value)
2738{
2739 remote_target *remote = get_current_remote_target ();
2740 int i;
2741
2742 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2743 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2744}
2745
2746/* Insert fork catchpoint target routine. If fork events are enabled
2747 then return success, nothing more to do. */
2748
2749int
2750remote_target::insert_fork_catchpoint (int pid)
2751{
2752 return !m_features.remote_fork_event_p ();
2753}
2754
2755/* Remove fork catchpoint target routine. Nothing to do, just
2756 return success. */
2757
2758int
2759remote_target::remove_fork_catchpoint (int pid)
2760{
2761 return 0;
2762}
2763
2764/* Insert vfork catchpoint target routine. If vfork events are enabled
2765 then return success, nothing more to do. */
2766
2767int
2768remote_target::insert_vfork_catchpoint (int pid)
2769{
2770 return !m_features.remote_vfork_event_p ();
2771}
2772
2773/* Remove vfork catchpoint target routine. Nothing to do, just
2774 return success. */
2775
2776int
2777remote_target::remove_vfork_catchpoint (int pid)
2778{
2779 return 0;
2780}
2781
2782/* Insert exec catchpoint target routine. If exec events are
2783 enabled, just return success. */
2784
2785int
2786remote_target::insert_exec_catchpoint (int pid)
2787{
2788 return !m_features.remote_exec_event_p ();
2789}
2790
2791/* Remove exec catchpoint target routine. Nothing to do, just
2792 return success. */
2793
2794int
2795remote_target::remove_exec_catchpoint (int pid)
2796{
2797 return 0;
2798}
2799
2800\f
2801
2802/* Take advantage of the fact that the TID field is not used, to tag
2803 special ptids with it set to != 0. */
2804static const ptid_t magic_null_ptid (42000, -1, 1);
2805static const ptid_t not_sent_ptid (42000, -2, 1);
2806static const ptid_t any_thread_ptid (42000, 0, 1);
2807
2808/* Find out if the stub attached to PID (and hence GDB should offer to
2809 detach instead of killing it when bailing out). */
2810
2811int
2812remote_target::remote_query_attached (int pid)
2813{
2814 struct remote_state *rs = get_remote_state ();
2815 size_t size = get_remote_packet_size ();
2816
2817 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2818 return 0;
2819
2820 if (m_features.remote_multi_process_p ())
2821 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2822 else
2823 xsnprintf (rs->buf.data (), size, "qAttached");
2824
2825 putpkt (rs->buf);
2826 getpkt (&rs->buf);
2827
2828 packet_result result = m_features.packet_ok (rs->buf, PACKET_qAttached);
2829 switch (result.status ())
2830 {
2831 case PACKET_OK:
2832 if (strcmp (rs->buf.data (), "1") == 0)
2833 return 1;
2834 break;
2835 case PACKET_ERROR:
2836 warning (_("Remote failure reply: %s"), result.err_msg ());
2837 break;
2838 case PACKET_UNKNOWN:
2839 break;
2840 }
2841
2842 return 0;
2843}
2844
2845/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2846 has been invented by GDB, instead of reported by the target. Since
2847 we can be connected to a remote system before before knowing about
2848 any inferior, mark the target with execution when we find the first
2849 inferior. If ATTACHED is 1, then we had just attached to this
2850 inferior. If it is 0, then we just created this inferior. If it
2851 is -1, then try querying the remote stub to find out if it had
2852 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2853 attempt to open this inferior's executable as the main executable
2854 if no main executable is open already. */
2855
2856inferior *
2857remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2858 int try_open_exec)
2859{
2860 struct inferior *inf;
2861
2862 /* Check whether this process we're learning about is to be
2863 considered attached, or if is to be considered to have been
2864 spawned by the stub. */
2865 if (attached == -1)
2866 attached = remote_query_attached (pid);
2867
2868 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2869 {
2870 /* If the target shares code across all inferiors, then every
2871 attach adds a new inferior. */
2872 inf = add_inferior (pid);
2873
2874 /* ... and every inferior is bound to the same program space.
2875 However, each inferior may still have its own address
2876 space. */
2877 inf->aspace = maybe_new_address_space ();
2878 inf->pspace = current_program_space;
2879 }
2880 else
2881 {
2882 /* In the traditional debugging scenario, there's a 1-1 match
2883 between program/address spaces. We simply bind the inferior
2884 to the program space's address space. */
2885 inf = current_inferior ();
2886
2887 /* However, if the current inferior is already bound to a
2888 process, find some other empty inferior. */
2889 if (inf->pid != 0)
2890 {
2891 inf = nullptr;
2892 for (inferior *it : all_inferiors ())
2893 if (it->pid == 0)
2894 {
2895 inf = it;
2896 break;
2897 }
2898 }
2899 if (inf == nullptr)
2900 {
2901 /* Since all inferiors were already bound to a process, add
2902 a new inferior. */
2903 inf = add_inferior_with_spaces ();
2904 }
2905 switch_to_inferior_no_thread (inf);
2906 inf->push_target (this);
2907 inferior_appeared (inf, pid);
2908 }
2909
2910 inf->attach_flag = attached;
2911 inf->fake_pid_p = fake_pid_p;
2912
2913 /* If no main executable is currently open then attempt to
2914 open the file that was executed to create this inferior. */
2915 if (try_open_exec && current_program_space->exec_filename () == nullptr)
2916 exec_file_locate_attach (pid, 0, 1);
2917
2918 /* Check for exec file mismatch, and let the user solve it. */
2919 validate_exec_file (1);
2920
2921 return inf;
2922}
2923
2924static remote_thread_info *get_remote_thread_info (thread_info *thread);
2925static remote_thread_info *get_remote_thread_info (remote_target *target,
2926 ptid_t ptid);
2927
2928/* Add thread PTID to GDB's thread list. Tag it as executing/running
2929 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2930 remote_state::starting_up flag) is true then the new thread is added
2931 silently, otherwise the new thread will be announced to the user. */
2932
2933thread_info *
2934remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2935 bool silent_p)
2936{
2937 struct remote_state *rs = get_remote_state ();
2938 struct thread_info *thread;
2939
2940 /* GDB historically didn't pull threads in the initial connection
2941 setup. If the remote target doesn't even have a concept of
2942 threads (e.g., a bare-metal target), even if internally we
2943 consider that a single-threaded target, mentioning a new thread
2944 might be confusing to the user. Be silent then, preserving the
2945 age old behavior. */
2946 if (rs->starting_up || silent_p)
2947 thread = add_thread_silent (this, ptid);
2948 else
2949 thread = add_thread (this, ptid);
2950
2951 if (executing)
2952 get_remote_thread_info (thread)->set_resumed ();
2953 set_executing (this, ptid, executing);
2954 set_running (this, ptid, running);
2955
2956 return thread;
2957}
2958
2959/* Come here when we learn about a thread id from the remote target.
2960 It may be the first time we hear about such thread, so take the
2961 opportunity to add it to GDB's thread list. In case this is the
2962 first time we're noticing its corresponding inferior, add it to
2963 GDB's inferior list as well. EXECUTING indicates whether the
2964 thread is (internally) executing or stopped. */
2965
2966void
2967remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2968{
2969 /* In non-stop mode, we assume new found threads are (externally)
2970 running until proven otherwise with a stop reply. In all-stop,
2971 we can only get here if all threads are stopped. */
2972 bool running = target_is_non_stop_p ();
2973
2974 /* If this is a new thread, add it to GDB's thread list.
2975 If we leave it up to WFI to do this, bad things will happen. */
2976
2977 thread_info *tp = this->find_thread (currthread);
2978 if (tp != NULL && tp->state == THREAD_EXITED)
2979 {
2980 /* We're seeing an event on a thread id we knew had exited.
2981 This has to be a new thread reusing the old id. Add it. */
2982 remote_add_thread (currthread, running, executing, false);
2983 return;
2984 }
2985
2986 if (!in_thread_list (this, currthread))
2987 {
2988 struct inferior *inf = NULL;
2989 int pid = currthread.pid ();
2990
2991 if (inferior_ptid.is_pid ()
2992 && pid == inferior_ptid.pid ())
2993 {
2994 /* inferior_ptid has no thread member yet. This can happen
2995 with the vAttach -> remote_wait,"TAAthread:" path if the
2996 stub doesn't support qC. This is the first stop reported
2997 after an attach, so this is the main thread. Update the
2998 ptid in the thread list. */
2999 if (in_thread_list (this, ptid_t (pid)))
3000 thread_change_ptid (this, inferior_ptid, currthread);
3001 else
3002 {
3003 thread_info *thr
3004 = remote_add_thread (currthread, running, executing, false);
3005 switch_to_thread (thr);
3006 }
3007 return;
3008 }
3009
3010 if (magic_null_ptid == inferior_ptid)
3011 {
3012 /* inferior_ptid is not set yet. This can happen with the
3013 vRun -> remote_wait,"TAAthread:" path if the stub
3014 doesn't support qC. This is the first stop reported
3015 after an attach, so this is the main thread. Update the
3016 ptid in the thread list. */
3017 thread_change_ptid (this, inferior_ptid, currthread);
3018 return;
3019 }
3020
3021 /* When connecting to a target remote, or to a target
3022 extended-remote which already was debugging an inferior, we
3023 may not know about it yet. Add it before adding its child
3024 thread, so notifications are emitted in a sensible order. */
3025 if (find_inferior_pid (this, currthread.pid ()) == NULL)
3026 {
3027 bool fake_pid_p = !m_features.remote_multi_process_p ();
3028
3029 inf = remote_add_inferior (fake_pid_p,
3030 currthread.pid (), -1, 1);
3031 }
3032
3033 /* This is really a new thread. Add it. */
3034 thread_info *new_thr
3035 = remote_add_thread (currthread, running, executing, false);
3036
3037 /* If we found a new inferior, let the common code do whatever
3038 it needs to with it (e.g., read shared libraries, insert
3039 breakpoints), unless we're just setting up an all-stop
3040 connection. */
3041 if (inf != NULL)
3042 {
3043 struct remote_state *rs = get_remote_state ();
3044
3045 if (!rs->starting_up)
3046 notice_new_inferior (new_thr, executing, 0);
3047 }
3048 }
3049}
3050
3051/* Return THREAD's private thread data, creating it if necessary. */
3052
3053static remote_thread_info *
3054get_remote_thread_info (thread_info *thread)
3055{
3056 gdb_assert (thread != NULL);
3057
3058 if (thread->priv == NULL)
3059 thread->priv = std::make_unique<remote_thread_info> ();
3060
3061 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
3062}
3063
3064/* Return PTID's private thread data, creating it if necessary. */
3065
3066static remote_thread_info *
3067get_remote_thread_info (remote_target *target, ptid_t ptid)
3068{
3069 thread_info *thr = target->find_thread (ptid);
3070 return get_remote_thread_info (thr);
3071}
3072
3073/* Call this function as a result of
3074 1) A halt indication (T packet) containing a thread id
3075 2) A direct query of currthread
3076 3) Successful execution of set thread */
3077
3078static void
3079record_currthread (struct remote_state *rs, ptid_t currthread)
3080{
3081 rs->general_thread = currthread;
3082}
3083
3084/* If 'QPassSignals' is supported, tell the remote stub what signals
3085 it can simply pass through to the inferior without reporting. */
3086
3087void
3088remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
3089{
3090 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
3091 {
3092 char *pass_packet, *p;
3093 int count = 0;
3094 struct remote_state *rs = get_remote_state ();
3095
3096 gdb_assert (pass_signals.size () < 256);
3097 for (size_t i = 0; i < pass_signals.size (); i++)
3098 {
3099 if (pass_signals[i])
3100 count++;
3101 }
3102 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
3103 strcpy (pass_packet, "QPassSignals:");
3104 p = pass_packet + strlen (pass_packet);
3105 for (size_t i = 0; i < pass_signals.size (); i++)
3106 {
3107 if (pass_signals[i])
3108 {
3109 if (i >= 16)
3110 *p++ = tohex (i >> 4);
3111 *p++ = tohex (i & 15);
3112 if (count)
3113 *p++ = ';';
3114 else
3115 break;
3116 count--;
3117 }
3118 }
3119 *p = 0;
3120 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
3121 {
3122 putpkt (pass_packet);
3123 getpkt (&rs->buf);
3124 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
3125 xfree (rs->last_pass_packet);
3126 rs->last_pass_packet = pass_packet;
3127 }
3128 else
3129 xfree (pass_packet);
3130 }
3131}
3132
3133/* If 'QCatchSyscalls' is supported, tell the remote stub
3134 to report syscalls to GDB. */
3135
3136int
3137remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3138 gdb::array_view<const int> syscall_counts)
3139{
3140 const char *catch_packet;
3141 int n_sysno = 0;
3142
3143 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3144 {
3145 /* Not supported. */
3146 return 1;
3147 }
3148
3149 if (needed && any_count == 0)
3150 {
3151 /* Count how many syscalls are to be caught. */
3152 for (size_t i = 0; i < syscall_counts.size (); i++)
3153 {
3154 if (syscall_counts[i] != 0)
3155 n_sysno++;
3156 }
3157 }
3158
3159 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3160 pid, needed, any_count, n_sysno);
3161
3162 std::string built_packet;
3163 if (needed)
3164 {
3165 /* Prepare a packet with the sysno list, assuming max 8+1
3166 characters for a sysno. If the resulting packet size is too
3167 big, fallback on the non-selective packet. */
3168 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3169 built_packet.reserve (maxpktsz);
3170 built_packet = "QCatchSyscalls:1";
3171 if (any_count == 0)
3172 {
3173 /* Add in each syscall to be caught. */
3174 for (size_t i = 0; i < syscall_counts.size (); i++)
3175 {
3176 if (syscall_counts[i] != 0)
3177 string_appendf (built_packet, ";%zx", i);
3178 }
3179 }
3180 if (built_packet.size () > get_remote_packet_size ())
3181 {
3182 /* catch_packet too big. Fallback to less efficient
3183 non selective mode, with GDB doing the filtering. */
3184 catch_packet = "QCatchSyscalls:1";
3185 }
3186 else
3187 catch_packet = built_packet.c_str ();
3188 }
3189 else
3190 catch_packet = "QCatchSyscalls:0";
3191
3192 struct remote_state *rs = get_remote_state ();
3193
3194 putpkt (catch_packet);
3195 getpkt (&rs->buf);
3196 packet_result result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3197 if (result.status () == PACKET_OK)
3198 return 0;
3199 else
3200 return -1;
3201}
3202
3203/* If 'QProgramSignals' is supported, tell the remote stub what
3204 signals it should pass through to the inferior when detaching. */
3205
3206void
3207remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3208{
3209 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3210 {
3211 char *packet, *p;
3212 int count = 0;
3213 struct remote_state *rs = get_remote_state ();
3214
3215 gdb_assert (signals.size () < 256);
3216 for (size_t i = 0; i < signals.size (); i++)
3217 {
3218 if (signals[i])
3219 count++;
3220 }
3221 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3222 strcpy (packet, "QProgramSignals:");
3223 p = packet + strlen (packet);
3224 for (size_t i = 0; i < signals.size (); i++)
3225 {
3226 if (signal_pass_state (i))
3227 {
3228 if (i >= 16)
3229 *p++ = tohex (i >> 4);
3230 *p++ = tohex (i & 15);
3231 if (count)
3232 *p++ = ';';
3233 else
3234 break;
3235 count--;
3236 }
3237 }
3238 *p = 0;
3239 if (!rs->last_program_signals_packet
3240 || strcmp (rs->last_program_signals_packet, packet) != 0)
3241 {
3242 putpkt (packet);
3243 getpkt (&rs->buf);
3244 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3245 xfree (rs->last_program_signals_packet);
3246 rs->last_program_signals_packet = packet;
3247 }
3248 else
3249 xfree (packet);
3250 }
3251}
3252
3253/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3254 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3255 thread. If GEN is set, set the general thread, if not, then set
3256 the step/continue thread. */
3257void
3258remote_target::set_thread (ptid_t ptid, int gen)
3259{
3260 struct remote_state *rs = get_remote_state ();
3261 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3262 char *buf = rs->buf.data ();
3263 char *endbuf = buf + get_remote_packet_size ();
3264
3265 if (state == ptid)
3266 return;
3267
3268 *buf++ = 'H';
3269 *buf++ = gen ? 'g' : 'c';
3270 if (ptid == magic_null_ptid)
3271 xsnprintf (buf, endbuf - buf, "0");
3272 else if (ptid == any_thread_ptid)
3273 xsnprintf (buf, endbuf - buf, "0");
3274 else if (ptid == minus_one_ptid)
3275 xsnprintf (buf, endbuf - buf, "-1");
3276 else
3277 write_ptid (buf, endbuf, ptid);
3278 putpkt (rs->buf);
3279 getpkt (&rs->buf);
3280 if (gen)
3281 rs->general_thread = ptid;
3282 else
3283 rs->continue_thread = ptid;
3284}
3285
3286void
3287remote_target::set_general_thread (ptid_t ptid)
3288{
3289 set_thread (ptid, 1);
3290}
3291
3292void
3293remote_target::set_continue_thread (ptid_t ptid)
3294{
3295 set_thread (ptid, 0);
3296}
3297
3298/* Change the remote current process. Which thread within the process
3299 ends up selected isn't important, as long as it is the same process
3300 as what INFERIOR_PTID points to.
3301
3302 This comes from that fact that there is no explicit notion of
3303 "selected process" in the protocol. The selected process for
3304 general operations is the process the selected general thread
3305 belongs to. */
3306
3307void
3308remote_target::set_general_process ()
3309{
3310 /* If the remote can't handle multiple processes, don't bother. */
3311 if (!m_features.remote_multi_process_p ())
3312 return;
3313
3314 remote_state *rs = get_remote_state ();
3315
3316 /* We only need to change the remote current thread if it's pointing
3317 at some other process. */
3318 if (rs->general_thread.pid () != inferior_ptid.pid ())
3319 set_general_thread (inferior_ptid);
3320}
3321
3322\f
3323/* Return nonzero if this is the main thread that we made up ourselves
3324 to model non-threaded targets as single-threaded. */
3325
3326static int
3327remote_thread_always_alive (ptid_t ptid)
3328{
3329 if (ptid == magic_null_ptid)
3330 /* The main thread is always alive. */
3331 return 1;
3332
3333 if (ptid.pid () != 0 && ptid.lwp () == 0)
3334 /* The main thread is always alive. This can happen after a
3335 vAttach, if the remote side doesn't support
3336 multi-threading. */
3337 return 1;
3338
3339 return 0;
3340}
3341
3342/* Return nonzero if the thread PTID is still alive on the remote
3343 system. */
3344
3345bool
3346remote_target::thread_alive (ptid_t ptid)
3347{
3348 struct remote_state *rs = get_remote_state ();
3349 char *p, *endp;
3350
3351 /* Check if this is a thread that we made up ourselves to model
3352 non-threaded targets as single-threaded. */
3353 if (remote_thread_always_alive (ptid))
3354 return 1;
3355
3356 p = rs->buf.data ();
3357 endp = p + get_remote_packet_size ();
3358
3359 *p++ = 'T';
3360 write_ptid (p, endp, ptid);
3361
3362 putpkt (rs->buf);
3363 getpkt (&rs->buf);
3364 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3365}
3366
3367/* Return a pointer to a thread name if we know it and NULL otherwise.
3368 The thread_info object owns the memory for the name. */
3369
3370const char *
3371remote_target::thread_name (struct thread_info *info)
3372{
3373 if (info->priv != NULL)
3374 {
3375 const std::string &name = get_remote_thread_info (info)->name;
3376 return !name.empty () ? name.c_str () : NULL;
3377 }
3378
3379 return NULL;
3380}
3381
3382/* About these extended threadlist and threadinfo packets. They are
3383 variable length packets but, the fields within them are often fixed
3384 length. They are redundant enough to send over UDP as is the
3385 remote protocol in general. There is a matching unit test module
3386 in libstub. */
3387
3388/* WARNING: This threadref data structure comes from the remote O.S.,
3389 libstub protocol encoding, and remote.c. It is not particularly
3390 changeable. */
3391
3392/* Right now, the internal structure is int. We want it to be bigger.
3393 Plan to fix this. */
3394
3395typedef int gdb_threadref; /* Internal GDB thread reference. */
3396
3397/* gdb_ext_thread_info is an internal GDB data structure which is
3398 equivalent to the reply of the remote threadinfo packet. */
3399
3400struct gdb_ext_thread_info
3401 {
3402 threadref threadid; /* External form of thread reference. */
3403 int active; /* Has state interesting to GDB?
3404 regs, stack. */
3405 char display[256]; /* Brief state display, name,
3406 blocked/suspended. */
3407 char shortname[32]; /* To be used to name threads. */
3408 char more_display[256]; /* Long info, statistics, queue depth,
3409 whatever. */
3410 };
3411
3412#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3413
3414static const char *unpack_nibble (const char *buf, int *val);
3415
3416static const char *unpack_byte (const char *buf, int *value);
3417
3418static char *pack_int (char *buf, int value);
3419
3420static const char *unpack_int (const char *buf, int *value);
3421
3422static const char *unpack_string (const char *src, char *dest, int length);
3423
3424static char *pack_threadid (char *pkt, threadref *id);
3425
3426static const char *unpack_threadid (const char *inbuf, threadref *id);
3427
3428void int_to_threadref (threadref *id, int value);
3429
3430static int threadref_to_int (threadref *ref);
3431
3432static void copy_threadref (threadref *dest, threadref *src);
3433
3434static int threadmatch (threadref *dest, threadref *src);
3435
3436static char *pack_threadinfo_request (char *pkt, int mode,
3437 threadref *id);
3438
3439static char *pack_threadlist_request (char *pkt, int startflag,
3440 int threadcount,
3441 threadref *nextthread);
3442
3443static int remote_newthread_step (threadref *ref, void *context);
3444
3445
3446/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3447 buffer we're allowed to write to. Returns
3448 BUF+CHARACTERS_WRITTEN. */
3449
3450char *
3451remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3452{
3453 int pid, tid;
3454
3455 if (m_features.remote_multi_process_p ())
3456 {
3457 pid = ptid.pid ();
3458 if (pid < 0)
3459 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3460 else
3461 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3462 }
3463 tid = ptid.lwp ();
3464 if (tid < 0)
3465 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3466 else
3467 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3468
3469 return buf;
3470}
3471
3472/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3473 last parsed char. Returns null_ptid if no thread id is found, and
3474 throws an error if the thread id has an invalid format. */
3475
3476static ptid_t
3477read_ptid (const char *buf, const char **obuf)
3478{
3479 const char *p = buf;
3480 const char *pp;
3481 ULONGEST pid = 0, tid = 0;
3482
3483 if (*p == 'p')
3484 {
3485 /* Multi-process ptid. */
3486 pp = unpack_varlen_hex (p + 1, &pid);
3487 if (*pp != '.')
3488 error (_("invalid remote ptid: %s"), p);
3489
3490 p = pp;
3491 pp = unpack_varlen_hex (p + 1, &tid);
3492 if (obuf)
3493 *obuf = pp;
3494 return ptid_t (pid, tid);
3495 }
3496
3497 /* No multi-process. Just a tid. */
3498 pp = unpack_varlen_hex (p, &tid);
3499
3500 /* Return null_ptid when no thread id is found. */
3501 if (p == pp)
3502 {
3503 if (obuf)
3504 *obuf = pp;
3505 return null_ptid;
3506 }
3507
3508 /* Since the stub is not sending a process id, default to what's
3509 current_inferior, unless it doesn't have a PID yet. If so,
3510 then since there's no way to know the pid of the reported
3511 threads, use the magic number. */
3512 inferior *inf = current_inferior ();
3513 if (inf->pid == 0)
3514 pid = magic_null_ptid.pid ();
3515 else
3516 pid = inf->pid;
3517
3518 if (obuf)
3519 *obuf = pp;
3520 return ptid_t (pid, tid);
3521}
3522
3523static int
3524stubhex (int ch)
3525{
3526 if (ch >= 'a' && ch <= 'f')
3527 return ch - 'a' + 10;
3528 if (ch >= '0' && ch <= '9')
3529 return ch - '0';
3530 if (ch >= 'A' && ch <= 'F')
3531 return ch - 'A' + 10;
3532 return -1;
3533}
3534
3535static int
3536stub_unpack_int (const char *buff, int fieldlength)
3537{
3538 int nibble;
3539 int retval = 0;
3540
3541 while (fieldlength)
3542 {
3543 nibble = stubhex (*buff++);
3544 retval |= nibble;
3545 fieldlength--;
3546 if (fieldlength)
3547 retval = retval << 4;
3548 }
3549 return retval;
3550}
3551
3552static const char *
3553unpack_nibble (const char *buf, int *val)
3554{
3555 *val = fromhex (*buf++);
3556 return buf;
3557}
3558
3559static const char *
3560unpack_byte (const char *buf, int *value)
3561{
3562 *value = stub_unpack_int (buf, 2);
3563 return buf + 2;
3564}
3565
3566static char *
3567pack_int (char *buf, int value)
3568{
3569 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3570 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3571 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3572 buf = pack_hex_byte (buf, (value & 0xff));
3573 return buf;
3574}
3575
3576static const char *
3577unpack_int (const char *buf, int *value)
3578{
3579 *value = stub_unpack_int (buf, 8);
3580 return buf + 8;
3581}
3582
3583#if 0 /* Currently unused, uncomment when needed. */
3584static char *pack_string (char *pkt, char *string);
3585
3586static char *
3587pack_string (char *pkt, char *string)
3588{
3589 char ch;
3590 int len;
3591
3592 len = strlen (string);
3593 if (len > 200)
3594 len = 200; /* Bigger than most GDB packets, junk??? */
3595 pkt = pack_hex_byte (pkt, len);
3596 while (len-- > 0)
3597 {
3598 ch = *string++;
3599 if ((ch == '\0') || (ch == '#'))
3600 ch = '*'; /* Protect encapsulation. */
3601 *pkt++ = ch;
3602 }
3603 return pkt;
3604}
3605#endif /* 0 (unused) */
3606
3607static const char *
3608unpack_string (const char *src, char *dest, int length)
3609{
3610 while (length--)
3611 *dest++ = *src++;
3612 *dest = '\0';
3613 return src;
3614}
3615
3616static char *
3617pack_threadid (char *pkt, threadref *id)
3618{
3619 char *limit;
3620 unsigned char *altid;
3621
3622 altid = (unsigned char *) id;
3623 limit = pkt + BUF_THREAD_ID_SIZE;
3624 while (pkt < limit)
3625 pkt = pack_hex_byte (pkt, *altid++);
3626 return pkt;
3627}
3628
3629
3630static const char *
3631unpack_threadid (const char *inbuf, threadref *id)
3632{
3633 char *altref;
3634 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3635 int x, y;
3636
3637 altref = (char *) id;
3638
3639 while (inbuf < limit)
3640 {
3641 x = stubhex (*inbuf++);
3642 y = stubhex (*inbuf++);
3643 *altref++ = (x << 4) | y;
3644 }
3645 return inbuf;
3646}
3647
3648/* Externally, threadrefs are 64 bits but internally, they are still
3649 ints. This is due to a mismatch of specifications. We would like
3650 to use 64bit thread references internally. This is an adapter
3651 function. */
3652
3653void
3654int_to_threadref (threadref *id, int value)
3655{
3656 unsigned char *scan;
3657
3658 scan = (unsigned char *) id;
3659 {
3660 int i = 4;
3661 while (i--)
3662 *scan++ = 0;
3663 }
3664 *scan++ = (value >> 24) & 0xff;
3665 *scan++ = (value >> 16) & 0xff;
3666 *scan++ = (value >> 8) & 0xff;
3667 *scan++ = (value & 0xff);
3668}
3669
3670static int
3671threadref_to_int (threadref *ref)
3672{
3673 int i, value = 0;
3674 unsigned char *scan;
3675
3676 scan = *ref;
3677 scan += 4;
3678 i = 4;
3679 while (i-- > 0)
3680 value = (value << 8) | ((*scan++) & 0xff);
3681 return value;
3682}
3683
3684static void
3685copy_threadref (threadref *dest, threadref *src)
3686{
3687 int i;
3688 unsigned char *csrc, *cdest;
3689
3690 csrc = (unsigned char *) src;
3691 cdest = (unsigned char *) dest;
3692 i = 8;
3693 while (i--)
3694 *cdest++ = *csrc++;
3695}
3696
3697static int
3698threadmatch (threadref *dest, threadref *src)
3699{
3700 /* Things are broken right now, so just assume we got a match. */
3701#if 0
3702 unsigned char *srcp, *destp;
3703 int i, result;
3704 srcp = (char *) src;
3705 destp = (char *) dest;
3706
3707 result = 1;
3708 while (i-- > 0)
3709 result &= (*srcp++ == *destp++) ? 1 : 0;
3710 return result;
3711#endif
3712 return 1;
3713}
3714
3715/*
3716 threadid:1, # always request threadid
3717 context_exists:2,
3718 display:4,
3719 unique_name:8,
3720 more_display:16
3721 */
3722
3723/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3724
3725static char *
3726pack_threadinfo_request (char *pkt, int mode, threadref *id)
3727{
3728 *pkt++ = 'q'; /* Info Query */
3729 *pkt++ = 'P'; /* process or thread info */
3730 pkt = pack_int (pkt, mode); /* mode */
3731 pkt = pack_threadid (pkt, id); /* threadid */
3732 *pkt = '\0'; /* terminate */
3733 return pkt;
3734}
3735
3736/* These values tag the fields in a thread info response packet. */
3737/* Tagging the fields allows us to request specific fields and to
3738 add more fields as time goes by. */
3739
3740#define TAG_THREADID 1 /* Echo the thread identifier. */
3741#define TAG_EXISTS 2 /* Is this process defined enough to
3742 fetch registers and its stack? */
3743#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3744#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3745#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3746 the process. */
3747
3748int
3749remote_target::remote_unpack_thread_info_response (const char *pkt,
3750 threadref *expectedref,
3751 gdb_ext_thread_info *info)
3752{
3753 struct remote_state *rs = get_remote_state ();
3754 int mask, length;
3755 int tag;
3756 threadref ref;
3757 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3758 int retval = 1;
3759
3760 /* info->threadid = 0; FIXME: implement zero_threadref. */
3761 info->active = 0;
3762 info->display[0] = '\0';
3763 info->shortname[0] = '\0';
3764 info->more_display[0] = '\0';
3765
3766 /* Assume the characters indicating the packet type have been
3767 stripped. */
3768 pkt = unpack_int (pkt, &mask); /* arg mask */
3769 pkt = unpack_threadid (pkt, &ref);
3770
3771 if (mask == 0)
3772 warning (_("Incomplete response to threadinfo request."));
3773 if (!threadmatch (&ref, expectedref))
3774 { /* This is an answer to a different request. */
3775 warning (_("ERROR RMT Thread info mismatch."));
3776 return 0;
3777 }
3778 copy_threadref (&info->threadid, &ref);
3779
3780 /* Loop on tagged fields , try to bail if something goes wrong. */
3781
3782 /* Packets are terminated with nulls. */
3783 while ((pkt < limit) && mask && *pkt)
3784 {
3785 pkt = unpack_int (pkt, &tag); /* tag */
3786 pkt = unpack_byte (pkt, &length); /* length */
3787 if (!(tag & mask)) /* Tags out of synch with mask. */
3788 {
3789 warning (_("ERROR RMT: threadinfo tag mismatch."));
3790 retval = 0;
3791 break;
3792 }
3793 if (tag == TAG_THREADID)
3794 {
3795 if (length != 16)
3796 {
3797 warning (_("ERROR RMT: length of threadid is not 16."));
3798 retval = 0;
3799 break;
3800 }
3801 pkt = unpack_threadid (pkt, &ref);
3802 mask = mask & ~TAG_THREADID;
3803 continue;
3804 }
3805 if (tag == TAG_EXISTS)
3806 {
3807 info->active = stub_unpack_int (pkt, length);
3808 pkt += length;
3809 mask = mask & ~(TAG_EXISTS);
3810 if (length > 8)
3811 {
3812 warning (_("ERROR RMT: 'exists' length too long."));
3813 retval = 0;
3814 break;
3815 }
3816 continue;
3817 }
3818 if (tag == TAG_THREADNAME)
3819 {
3820 pkt = unpack_string (pkt, &info->shortname[0], length);
3821 mask = mask & ~TAG_THREADNAME;
3822 continue;
3823 }
3824 if (tag == TAG_DISPLAY)
3825 {
3826 pkt = unpack_string (pkt, &info->display[0], length);
3827 mask = mask & ~TAG_DISPLAY;
3828 continue;
3829 }
3830 if (tag == TAG_MOREDISPLAY)
3831 {
3832 pkt = unpack_string (pkt, &info->more_display[0], length);
3833 mask = mask & ~TAG_MOREDISPLAY;
3834 continue;
3835 }
3836 warning (_("ERROR RMT: unknown thread info tag."));
3837 break; /* Not a tag we know about. */
3838 }
3839 return retval;
3840}
3841
3842int
3843remote_target::remote_get_threadinfo (threadref *threadid,
3844 int fieldset,
3845 gdb_ext_thread_info *info)
3846{
3847 struct remote_state *rs = get_remote_state ();
3848 int result;
3849
3850 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3851 putpkt (rs->buf);
3852 getpkt (&rs->buf);
3853
3854 if (rs->buf[0] == '\0')
3855 return 0;
3856
3857 result = remote_unpack_thread_info_response (&rs->buf[2],
3858 threadid, info);
3859 return result;
3860}
3861
3862/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3863
3864static char *
3865pack_threadlist_request (char *pkt, int startflag, int threadcount,
3866 threadref *nextthread)
3867{
3868 *pkt++ = 'q'; /* info query packet */
3869 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3870 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3871 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3872 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3873 *pkt = '\0';
3874 return pkt;
3875}
3876
3877/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3878
3879int
3880remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3881 threadref *original_echo,
3882 threadref *resultlist,
3883 int *doneflag)
3884{
3885 struct remote_state *rs = get_remote_state ();
3886 int count, resultcount, done;
3887
3888 resultcount = 0;
3889 /* Assume the 'q' and 'M chars have been stripped. */
3890 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3891 /* done parse past here */
3892 pkt = unpack_byte (pkt, &count); /* count field */
3893 pkt = unpack_nibble (pkt, &done);
3894 /* The first threadid is the argument threadid. */
3895 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3896 while ((count-- > 0) && (pkt < limit))
3897 {
3898 pkt = unpack_threadid (pkt, resultlist++);
3899 if (resultcount++ >= result_limit)
3900 break;
3901 }
3902 if (doneflag)
3903 *doneflag = done;
3904 return resultcount;
3905}
3906
3907/* Fetch the next batch of threads from the remote. Returns -1 if the
3908 qL packet is not supported, 0 on error and 1 on success. */
3909
3910int
3911remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3912 int result_limit, int *done, int *result_count,
3913 threadref *threadlist)
3914{
3915 struct remote_state *rs = get_remote_state ();
3916 int result = 1;
3917
3918 /* Truncate result limit to be smaller than the packet size. */
3919 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3920 >= get_remote_packet_size ())
3921 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3922
3923 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3924 nextthread);
3925 putpkt (rs->buf);
3926 getpkt (&rs->buf);
3927 if (rs->buf[0] == '\0')
3928 {
3929 /* Packet not supported. */
3930 return -1;
3931 }
3932
3933 *result_count =
3934 parse_threadlist_response (&rs->buf[2], result_limit,
3935 &rs->echo_nextthread, threadlist, done);
3936
3937 if (!threadmatch (&rs->echo_nextthread, nextthread))
3938 {
3939 /* FIXME: This is a good reason to drop the packet. */
3940 /* Possibly, there is a duplicate response. */
3941 /* Possibilities :
3942 retransmit immediately - race conditions
3943 retransmit after timeout - yes
3944 exit
3945 wait for packet, then exit
3946 */
3947 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3948 return 0; /* I choose simply exiting. */
3949 }
3950 if (*result_count <= 0)
3951 {
3952 if (*done != 1)
3953 {
3954 warning (_("RMT ERROR : failed to get remote thread list."));
3955 result = 0;
3956 }
3957 return result; /* break; */
3958 }
3959 if (*result_count > result_limit)
3960 {
3961 *result_count = 0;
3962 warning (_("RMT ERROR: threadlist response longer than requested."));
3963 return 0;
3964 }
3965 return result;
3966}
3967
3968/* Fetch the list of remote threads, with the qL packet, and call
3969 STEPFUNCTION for each thread found. Stops iterating and returns 1
3970 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3971 STEPFUNCTION returns false. If the packet is not supported,
3972 returns -1. */
3973
3974int
3975remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3976 void *context, int looplimit)
3977{
3978 struct remote_state *rs = get_remote_state ();
3979 int done, i, result_count;
3980 int startflag = 1;
3981 int result = 1;
3982 int loopcount = 0;
3983
3984 done = 0;
3985 while (!done)
3986 {
3987 if (loopcount++ > looplimit)
3988 {
3989 result = 0;
3990 warning (_("Remote fetch threadlist -infinite loop-."));
3991 break;
3992 }
3993 result = remote_get_threadlist (startflag, &rs->nextthread,
3994 MAXTHREADLISTRESULTS,
3995 &done, &result_count,
3996 rs->resultthreadlist);
3997 if (result <= 0)
3998 break;
3999 /* Clear for later iterations. */
4000 startflag = 0;
4001 /* Setup to resume next batch of thread references, set nextthread. */
4002 if (result_count >= 1)
4003 copy_threadref (&rs->nextthread,
4004 &rs->resultthreadlist[result_count - 1]);
4005 i = 0;
4006 while (result_count--)
4007 {
4008 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
4009 {
4010 result = 0;
4011 break;
4012 }
4013 }
4014 }
4015 return result;
4016}
4017
4018/* A thread found on the remote target. */
4019
4020struct thread_item
4021{
4022 explicit thread_item (ptid_t ptid_)
4023 : ptid (ptid_)
4024 {}
4025
4026 thread_item (thread_item &&other) = default;
4027 thread_item &operator= (thread_item &&other) = default;
4028
4029 DISABLE_COPY_AND_ASSIGN (thread_item);
4030
4031 /* The thread's PTID. */
4032 ptid_t ptid;
4033
4034 /* The thread's extra info. */
4035 std::string extra;
4036
4037 /* The thread's name. */
4038 std::string name;
4039
4040 /* The thread's id, translated to a string for displaying. */
4041 std::string id_str;
4042
4043 /* The core the thread was running on. -1 if not known. */
4044 int core = -1;
4045
4046 /* The thread handle associated with the thread. */
4047 gdb::byte_vector thread_handle;
4048};
4049
4050/* Context passed around to the various methods listing remote
4051 threads. As new threads are found, they're added to the ITEMS
4052 vector. */
4053
4054struct threads_listing_context
4055{
4056 /* Return true if this object contains an entry for a thread with ptid
4057 PTID. */
4058
4059 bool contains_thread (ptid_t ptid) const
4060 {
4061 auto match_ptid = [&] (const thread_item &item)
4062 {
4063 return item.ptid == ptid;
4064 };
4065
4066 auto it = std::find_if (this->items.begin (),
4067 this->items.end (),
4068 match_ptid);
4069
4070 return it != this->items.end ();
4071 }
4072
4073 /* Remove the thread with ptid PTID. */
4074
4075 void remove_thread (ptid_t ptid)
4076 {
4077 auto match_ptid = [&] (const thread_item &item)
4078 {
4079 return item.ptid == ptid;
4080 };
4081
4082 auto it = std::remove_if (this->items.begin (),
4083 this->items.end (),
4084 match_ptid);
4085
4086 if (it != this->items.end ())
4087 this->items.erase (it);
4088 }
4089
4090 /* The threads found on the remote target. */
4091 std::vector<thread_item> items;
4092};
4093
4094static int
4095remote_newthread_step (threadref *ref, void *data)
4096{
4097 struct threads_listing_context *context
4098 = (struct threads_listing_context *) data;
4099 int pid = inferior_ptid.pid ();
4100 int lwp = threadref_to_int (ref);
4101 ptid_t ptid (pid, lwp);
4102
4103 context->items.emplace_back (ptid);
4104
4105 return 1; /* continue iterator */
4106}
4107
4108#define CRAZY_MAX_THREADS 1000
4109
4110ptid_t
4111remote_target::remote_current_thread (ptid_t oldpid)
4112{
4113 struct remote_state *rs = get_remote_state ();
4114
4115 putpkt ("qC");
4116 getpkt (&rs->buf);
4117 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
4118 {
4119 const char *obuf;
4120 ptid_t result;
4121
4122 result = read_ptid (&rs->buf[2], &obuf);
4123 if (*obuf != '\0')
4124 remote_debug_printf ("warning: garbage in qC reply");
4125
4126 return result;
4127 }
4128 else
4129 return oldpid;
4130}
4131
4132/* List remote threads using the deprecated qL packet. */
4133
4134int
4135remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4136{
4137 if (remote_threadlist_iterator (remote_newthread_step, context,
4138 CRAZY_MAX_THREADS) >= 0)
4139 return 1;
4140
4141 return 0;
4142}
4143
4144#if defined(HAVE_LIBEXPAT)
4145
4146static void
4147start_thread (struct gdb_xml_parser *parser,
4148 const struct gdb_xml_element *element,
4149 void *user_data,
4150 std::vector<gdb_xml_value> &attributes)
4151{
4152 struct threads_listing_context *data
4153 = (struct threads_listing_context *) user_data;
4154 struct gdb_xml_value *attr;
4155
4156 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4157 ptid_t ptid = read_ptid (id, NULL);
4158
4159 thread_item &item = data->items.emplace_back (ptid);
4160
4161 attr = xml_find_attribute (attributes, "core");
4162 if (attr != NULL)
4163 item.core = *(ULONGEST *) attr->value.get ();
4164
4165 attr = xml_find_attribute (attributes, "name");
4166 if (attr != NULL)
4167 item.name = (const char *) attr->value.get ();
4168
4169 attr = xml_find_attribute (attributes, "id_str");
4170 if (attr != nullptr)
4171 item.id_str = (const char *) attr->value.get ();
4172
4173 attr = xml_find_attribute (attributes, "handle");
4174 if (attr != NULL)
4175 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4176}
4177
4178static void
4179end_thread (struct gdb_xml_parser *parser,
4180 const struct gdb_xml_element *element,
4181 void *user_data, const char *body_text)
4182{
4183 struct threads_listing_context *data
4184 = (struct threads_listing_context *) user_data;
4185
4186 if (body_text != NULL && *body_text != '\0')
4187 data->items.back ().extra = body_text;
4188}
4189
4190const struct gdb_xml_attribute thread_attributes[] = {
4191 { "id", GDB_XML_AF_NONE, NULL, NULL },
4192 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4193 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4194 { "id_str", GDB_XML_AF_OPTIONAL, NULL, NULL },
4195 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4196 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4197};
4198
4199const struct gdb_xml_element thread_children[] = {
4200 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4201};
4202
4203const struct gdb_xml_element threads_children[] = {
4204 { "thread", thread_attributes, thread_children,
4205 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4206 start_thread, end_thread },
4207 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4208};
4209
4210const struct gdb_xml_element threads_elements[] = {
4211 { "threads", NULL, threads_children,
4212 GDB_XML_EF_NONE, NULL, NULL },
4213 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4214};
4215
4216#endif
4217
4218/* List remote threads using qXfer:threads:read. */
4219
4220int
4221remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4222{
4223#if defined(HAVE_LIBEXPAT)
4224 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4225 {
4226 std::optional<gdb::char_vector> xml
4227 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4228
4229 if (xml && (*xml)[0] != '\0')
4230 {
4231 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4232 threads_elements, xml->data (), context);
4233 }
4234
4235 return 1;
4236 }
4237#endif
4238
4239 return 0;
4240}
4241
4242/* List remote threads using qfThreadInfo/qsThreadInfo. */
4243
4244int
4245remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4246{
4247 struct remote_state *rs = get_remote_state ();
4248
4249 if (rs->use_threadinfo_query)
4250 {
4251 const char *bufp;
4252
4253 putpkt ("qfThreadInfo");
4254 getpkt (&rs->buf);
4255 bufp = rs->buf.data ();
4256 if (bufp[0] != '\0') /* q packet recognized */
4257 {
4258 while (*bufp++ == 'm') /* reply contains one or more TID */
4259 {
4260 do
4261 {
4262 ptid_t ptid = read_ptid (bufp, &bufp);
4263 context->items.emplace_back (ptid);
4264 }
4265 while (*bufp++ == ','); /* comma-separated list */
4266 putpkt ("qsThreadInfo");
4267 getpkt (&rs->buf);
4268 bufp = rs->buf.data ();
4269 }
4270 return 1;
4271 }
4272 else
4273 {
4274 /* Packet not recognized. */
4275 rs->use_threadinfo_query = 0;
4276 }
4277 }
4278
4279 return 0;
4280}
4281
4282/* Return true if INF only has one non-exited thread. */
4283
4284static bool
4285has_single_non_exited_thread (inferior *inf)
4286{
4287 int count = 0;
4288 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4289 if (++count > 1)
4290 break;
4291 return count == 1;
4292}
4293
4294/* Implement the to_update_thread_list function for the remote
4295 targets. */
4296
4297void
4298remote_target::update_thread_list ()
4299{
4300 struct threads_listing_context context;
4301 int got_list = 0;
4302
4303 /* We have a few different mechanisms to fetch the thread list. Try
4304 them all, starting with the most preferred one first, falling
4305 back to older methods. */
4306 if (remote_get_threads_with_qxfer (&context)
4307 || remote_get_threads_with_qthreadinfo (&context)
4308 || remote_get_threads_with_ql (&context))
4309 {
4310 got_list = 1;
4311
4312 if (context.items.empty ()
4313 && remote_thread_always_alive (inferior_ptid))
4314 {
4315 /* Some targets don't really support threads, but still
4316 reply an (empty) thread list in response to the thread
4317 listing packets, instead of replying "packet not
4318 supported". Exit early so we don't delete the main
4319 thread. */
4320 return;
4321 }
4322
4323 /* CONTEXT now holds the current thread list on the remote
4324 target end. Delete GDB-side threads no longer found on the
4325 target. */
4326 for (thread_info *tp : all_threads_safe ())
4327 {
4328 if (tp->inf->process_target () != this)
4329 continue;
4330
4331 if (!context.contains_thread (tp->ptid))
4332 {
4333 /* Do not remove the thread if it is the last thread in
4334 the inferior. This situation happens when we have a
4335 pending exit process status to process. Otherwise we
4336 may end up with a seemingly live inferior (i.e. pid
4337 != 0) that has no threads. */
4338 if (has_single_non_exited_thread (tp->inf))
4339 continue;
4340
4341 /* Do not remove the thread if we've requested to be
4342 notified of its exit. For example, the thread may be
4343 displaced stepping, infrun will need to handle the
4344 exit event, and displaced stepping info is recorded
4345 in the thread object. If we deleted the thread now,
4346 we'd lose that info. */
4347 if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
4348 continue;
4349
4350 /* Not found. */
4351 delete_thread (tp);
4352 }
4353 }
4354
4355 /* Remove any unreported fork/vfork/clone child threads from
4356 CONTEXT so that we don't interfere with follow
4357 fork/vfork/clone, which is where creation of such threads is
4358 handled. */
4359 remove_new_children (&context);
4360
4361 /* And now add threads we don't know about yet to our list. */
4362 for (thread_item &item : context.items)
4363 {
4364 if (item.ptid != null_ptid)
4365 {
4366 /* In non-stop mode, we assume new found threads are
4367 executing until proven otherwise with a stop reply.
4368 In all-stop, we can only get here if all threads are
4369 stopped. */
4370 bool executing = target_is_non_stop_p ();
4371
4372 remote_notice_new_inferior (item.ptid, executing);
4373
4374 thread_info *tp = this->find_thread (item.ptid);
4375 remote_thread_info *info = get_remote_thread_info (tp);
4376 info->core = item.core;
4377 info->extra = std::move (item.extra);
4378 info->name = std::move (item.name);
4379 info->id_str = std::move (item.id_str);
4380 info->thread_handle = std::move (item.thread_handle);
4381 }
4382 }
4383 }
4384
4385 if (!got_list)
4386 {
4387 /* If no thread listing method is supported, then query whether
4388 each known thread is alive, one by one, with the T packet.
4389 If the target doesn't support threads at all, then this is a
4390 no-op. See remote_thread_alive. */
4391 prune_threads ();
4392 }
4393}
4394
4395/*
4396 * Collect a descriptive string about the given thread.
4397 * The target may say anything it wants to about the thread
4398 * (typically info about its blocked / runnable state, name, etc.).
4399 * This string will appear in the info threads display.
4400 *
4401 * Optional: targets are not required to implement this function.
4402 */
4403
4404const char *
4405remote_target::extra_thread_info (thread_info *tp)
4406{
4407 struct remote_state *rs = get_remote_state ();
4408 int set;
4409 threadref id;
4410 struct gdb_ext_thread_info threadinfo;
4411
4412 if (rs->remote_desc == 0) /* paranoia */
4413 internal_error (_("remote_threads_extra_info"));
4414
4415 if (tp->ptid == magic_null_ptid
4416 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4417 /* This is the main thread which was added by GDB. The remote
4418 server doesn't know about it. */
4419 return NULL;
4420
4421 std::string &extra = get_remote_thread_info (tp)->extra;
4422
4423 /* If already have cached info, use it. */
4424 if (!extra.empty ())
4425 return extra.c_str ();
4426
4427 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4428 {
4429 /* If we're using qXfer:threads:read, then the extra info is
4430 included in the XML. So if we didn't have anything cached,
4431 it's because there's really no extra info. */
4432 return NULL;
4433 }
4434
4435 if (rs->use_threadextra_query)
4436 {
4437 char *b = rs->buf.data ();
4438 char *endb = b + get_remote_packet_size ();
4439
4440 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4441 b += strlen (b);
4442 write_ptid (b, endb, tp->ptid);
4443
4444 putpkt (rs->buf);
4445 getpkt (&rs->buf);
4446 if (rs->buf[0] != 0)
4447 {
4448 extra.resize (strlen (rs->buf.data ()) / 2);
4449 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4450 return extra.c_str ();
4451 }
4452 }
4453
4454 /* If the above query fails, fall back to the old method. */
4455 rs->use_threadextra_query = 0;
4456 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4457 | TAG_MOREDISPLAY | TAG_DISPLAY;
4458 int_to_threadref (&id, tp->ptid.lwp ());
4459 if (remote_get_threadinfo (&id, set, &threadinfo))
4460 if (threadinfo.active)
4461 {
4462 if (*threadinfo.shortname)
4463 string_appendf (extra, " Name: %s", threadinfo.shortname);
4464 if (*threadinfo.display)
4465 {
4466 if (!extra.empty ())
4467 extra += ',';
4468 string_appendf (extra, " State: %s", threadinfo.display);
4469 }
4470 if (*threadinfo.more_display)
4471 {
4472 if (!extra.empty ())
4473 extra += ',';
4474 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4475 }
4476 return extra.c_str ();
4477 }
4478 return NULL;
4479}
4480\f
4481
4482bool
4483remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4484 struct static_tracepoint_marker *marker)
4485{
4486 struct remote_state *rs = get_remote_state ();
4487 char *p = rs->buf.data ();
4488
4489 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4490 p += strlen (p);
4491 p += hexnumstr (p, addr);
4492 putpkt (rs->buf);
4493 getpkt (&rs->buf);
4494 p = rs->buf.data ();
4495
4496 if (*p == 'E')
4497 error (_("Remote failure reply: %s"), p);
4498
4499 if (*p++ == 'm')
4500 {
4501 parse_static_tracepoint_marker_definition (p, NULL, marker);
4502 return true;
4503 }
4504
4505 return false;
4506}
4507
4508std::vector<static_tracepoint_marker>
4509remote_target::static_tracepoint_markers_by_strid (const char *strid)
4510{
4511 struct remote_state *rs = get_remote_state ();
4512 std::vector<static_tracepoint_marker> markers;
4513 const char *p;
4514 static_tracepoint_marker marker;
4515
4516 /* Ask for a first packet of static tracepoint marker
4517 definition. */
4518 putpkt ("qTfSTM");
4519 getpkt (&rs->buf);
4520 p = rs->buf.data ();
4521 if (*p == 'E')
4522 error (_("Remote failure reply: %s"), p);
4523
4524 while (*p++ == 'm')
4525 {
4526 do
4527 {
4528 parse_static_tracepoint_marker_definition (p, &p, &marker);
4529
4530 if (strid == NULL || marker.str_id == strid)
4531 markers.push_back (std::move (marker));
4532 }
4533 while (*p++ == ','); /* comma-separated list */
4534 /* Ask for another packet of static tracepoint definition. */
4535 putpkt ("qTsSTM");
4536 getpkt (&rs->buf);
4537 p = rs->buf.data ();
4538 }
4539
4540 return markers;
4541}
4542
4543\f
4544/* Implement the to_get_ada_task_ptid function for the remote targets. */
4545
4546ptid_t
4547remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4548{
4549 return ptid_t (inferior_ptid.pid (), lwp);
4550}
4551\f
4552
4553/* Restart the remote side; this is an extended protocol operation. */
4554
4555void
4556remote_target::extended_remote_restart ()
4557{
4558 struct remote_state *rs = get_remote_state ();
4559
4560 /* Send the restart command; for reasons I don't understand the
4561 remote side really expects a number after the "R". */
4562 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4563 putpkt (rs->buf);
4564
4565 remote_fileio_reset ();
4566}
4567\f
4568/* Clean up connection to a remote debugger. */
4569
4570void
4571remote_target::close ()
4572{
4573 /* Make sure we leave stdin registered in the event loop. */
4574 terminal_ours ();
4575
4576 trace_reset_local_state ();
4577
4578 delete this;
4579}
4580
4581remote_target::~remote_target ()
4582{
4583 struct remote_state *rs = get_remote_state ();
4584
4585 /* Check for NULL because we may get here with a partially
4586 constructed target/connection. */
4587 if (rs->remote_desc == nullptr)
4588 return;
4589
4590 serial_close (rs->remote_desc);
4591
4592 /* We are destroying the remote target, so we should discard
4593 everything of this target. */
4594 discard_pending_stop_replies_in_queue ();
4595
4596 rs->delete_async_event_handler ();
4597
4598 delete rs->notif_state;
4599}
4600
4601/* Query the remote side for the text, data and bss offsets. */
4602
4603void
4604remote_target::get_offsets ()
4605{
4606 struct remote_state *rs = get_remote_state ();
4607 char *buf;
4608 char *ptr;
4609 int lose, num_segments = 0, do_sections, do_segments;
4610 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4611
4612 if (current_program_space->symfile_object_file == NULL)
4613 return;
4614
4615 putpkt ("qOffsets");
4616 getpkt (&rs->buf);
4617 buf = rs->buf.data ();
4618
4619 if (buf[0] == '\000')
4620 return; /* Return silently. Stub doesn't support
4621 this command. */
4622 if (buf[0] == 'E')
4623 {
4624 warning (_("Remote failure reply: %s"), buf);
4625 return;
4626 }
4627
4628 /* Pick up each field in turn. This used to be done with scanf, but
4629 scanf will make trouble if CORE_ADDR size doesn't match
4630 conversion directives correctly. The following code will work
4631 with any size of CORE_ADDR. */
4632 text_addr = data_addr = bss_addr = 0;
4633 ptr = buf;
4634 lose = 0;
4635
4636 if (startswith (ptr, "Text="))
4637 {
4638 ptr += 5;
4639 /* Don't use strtol, could lose on big values. */
4640 while (*ptr && *ptr != ';')
4641 text_addr = (text_addr << 4) + fromhex (*ptr++);
4642
4643 if (startswith (ptr, ";Data="))
4644 {
4645 ptr += 6;
4646 while (*ptr && *ptr != ';')
4647 data_addr = (data_addr << 4) + fromhex (*ptr++);
4648 }
4649 else
4650 lose = 1;
4651
4652 if (!lose && startswith (ptr, ";Bss="))
4653 {
4654 ptr += 5;
4655 while (*ptr && *ptr != ';')
4656 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4657
4658 if (bss_addr != data_addr)
4659 warning (_("Target reported unsupported offsets: %s"), buf);
4660 }
4661 else
4662 lose = 1;
4663 }
4664 else if (startswith (ptr, "TextSeg="))
4665 {
4666 ptr += 8;
4667 /* Don't use strtol, could lose on big values. */
4668 while (*ptr && *ptr != ';')
4669 text_addr = (text_addr << 4) + fromhex (*ptr++);
4670 num_segments = 1;
4671
4672 if (startswith (ptr, ";DataSeg="))
4673 {
4674 ptr += 9;
4675 while (*ptr && *ptr != ';')
4676 data_addr = (data_addr << 4) + fromhex (*ptr++);
4677 num_segments++;
4678 }
4679 }
4680 else
4681 lose = 1;
4682
4683 if (lose)
4684 error (_("Malformed response to offset query, %s"), buf);
4685 else if (*ptr != '\0')
4686 warning (_("Target reported unsupported offsets: %s"), buf);
4687
4688 objfile *objf = current_program_space->symfile_object_file;
4689 section_offsets offs = objf->section_offsets;
4690
4691 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4692 do_segments = (data != NULL);
4693 do_sections = num_segments == 0;
4694
4695 if (num_segments > 0)
4696 {
4697 segments[0] = text_addr;
4698 segments[1] = data_addr;
4699 }
4700 /* If we have two segments, we can still try to relocate everything
4701 by assuming that the .text and .data offsets apply to the whole
4702 text and data segments. Convert the offsets given in the packet
4703 to base addresses for symfile_map_offsets_to_segments. */
4704 else if (data != nullptr && data->segments.size () == 2)
4705 {
4706 segments[0] = data->segments[0].base + text_addr;
4707 segments[1] = data->segments[1].base + data_addr;
4708 num_segments = 2;
4709 }
4710 /* If the object file has only one segment, assume that it is text
4711 rather than data; main programs with no writable data are rare,
4712 but programs with no code are useless. Of course the code might
4713 have ended up in the data segment... to detect that we would need
4714 the permissions here. */
4715 else if (data && data->segments.size () == 1)
4716 {
4717 segments[0] = data->segments[0].base + text_addr;
4718 num_segments = 1;
4719 }
4720 /* There's no way to relocate by segment. */
4721 else
4722 do_segments = 0;
4723
4724 if (do_segments)
4725 {
4726 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4727 data.get (), offs,
4728 num_segments, segments);
4729
4730 if (ret == 0 && !do_sections)
4731 error (_("Can not handle qOffsets TextSeg "
4732 "response with this symbol file"));
4733
4734 if (ret > 0)
4735 do_sections = 0;
4736 }
4737
4738 if (do_sections)
4739 {
4740 offs[SECT_OFF_TEXT (objf)] = text_addr;
4741
4742 /* This is a temporary kludge to force data and bss to use the
4743 same offsets because that's what nlmconv does now. The real
4744 solution requires changes to the stub and remote.c that I
4745 don't have time to do right now. */
4746
4747 offs[SECT_OFF_DATA (objf)] = data_addr;
4748 offs[SECT_OFF_BSS (objf)] = data_addr;
4749 }
4750
4751 objfile_relocate (objf, offs);
4752}
4753
4754/* Send interrupt_sequence to remote target. */
4755
4756void
4757remote_target::send_interrupt_sequence ()
4758{
4759 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4760 remote_serial_write ("\x03", 1);
4761 else if (interrupt_sequence_mode == interrupt_sequence_break)
4762 remote_serial_send_break ();
4763 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4764 {
4765 remote_serial_send_break ();
4766 remote_serial_write ("g", 1);
4767 }
4768 else
4769 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4770 interrupt_sequence_mode);
4771}
4772
4773/* If STOP_REPLY is a T stop reply, look for the "thread" register,
4774 and extract the PTID. Returns NULL_PTID if not found. */
4775
4776static ptid_t
4777stop_reply_extract_thread (const char *stop_reply)
4778{
4779 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4780 {
4781 const char *p;
4782
4783 /* Txx r:val ; r:val (...) */
4784 p = &stop_reply[3];
4785
4786 /* Look for "register" named "thread". */
4787 while (*p != '\0')
4788 {
4789 const char *p1;
4790
4791 p1 = strchr (p, ':');
4792 if (p1 == NULL)
4793 return null_ptid;
4794
4795 if (strncmp (p, "thread", p1 - p) == 0)
4796 return read_ptid (++p1, &p);
4797
4798 p1 = strchr (p, ';');
4799 if (p1 == NULL)
4800 return null_ptid;
4801 p1++;
4802
4803 p = p1;
4804 }
4805 }
4806
4807 return null_ptid;
4808}
4809
4810/* Determine the remote side's current thread. If we have a stop
4811 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4812 "thread" register we can extract the current thread from. If not,
4813 ask the remote which is the current thread with qC. The former
4814 method avoids a roundtrip. */
4815
4816ptid_t
4817remote_target::get_current_thread (const char *wait_status)
4818{
4819 ptid_t ptid = null_ptid;
4820
4821 /* Note we don't use remote_parse_stop_reply as that makes use of
4822 the target architecture, which we haven't yet fully determined at
4823 this point. */
4824 if (wait_status != NULL)
4825 ptid = stop_reply_extract_thread (wait_status);
4826 if (ptid == null_ptid)
4827 ptid = remote_current_thread (inferior_ptid);
4828
4829 return ptid;
4830}
4831
4832/* Query the remote target for which is the current thread/process,
4833 add it to our tables, and update INFERIOR_PTID. The caller is
4834 responsible for setting the state such that the remote end is ready
4835 to return the current thread.
4836
4837 This function is called after handling the '?' or 'vRun' packets,
4838 whose response is a stop reply from which we can also try
4839 extracting the thread. If the target doesn't support the explicit
4840 qC query, we infer the current thread from that stop reply, passed
4841 in in WAIT_STATUS, which may be NULL.
4842
4843 The function returns pointer to the main thread of the inferior. */
4844
4845thread_info *
4846remote_target::add_current_inferior_and_thread (const char *wait_status)
4847{
4848 bool fake_pid_p = false;
4849
4850 switch_to_no_thread ();
4851
4852 /* Now, if we have thread information, update the current thread's
4853 ptid. */
4854 ptid_t curr_ptid = get_current_thread (wait_status);
4855
4856 if (curr_ptid != null_ptid)
4857 {
4858 if (!m_features.remote_multi_process_p ())
4859 fake_pid_p = true;
4860 }
4861 else
4862 {
4863 /* Without this, some commands which require an active target
4864 (such as kill) won't work. This variable serves (at least)
4865 double duty as both the pid of the target process (if it has
4866 such), and as a flag indicating that a target is active. */
4867 curr_ptid = magic_null_ptid;
4868 fake_pid_p = true;
4869 }
4870
4871 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4872
4873 /* Add the main thread and switch to it. Don't try reading
4874 registers yet, since we haven't fetched the target description
4875 yet. */
4876 thread_info *tp = add_thread_silent (this, curr_ptid);
4877 switch_to_thread_no_regs (tp);
4878
4879 return tp;
4880}
4881
4882/* Print info about a thread that was found already stopped on
4883 connection. */
4884
4885void
4886remote_target::print_one_stopped_thread (thread_info *thread)
4887{
4888 target_waitstatus ws;
4889
4890 /* If there is a pending waitstatus, use it. If there isn't it's because
4891 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4892 and process_initial_stop_replies decided it wasn't interesting to save
4893 and report to the core. */
4894 if (thread->has_pending_waitstatus ())
4895 {
4896 ws = thread->pending_waitstatus ();
4897 thread->clear_pending_waitstatus ();
4898 }
4899 else
4900 {
4901 ws.set_stopped (GDB_SIGNAL_0);
4902 }
4903
4904 switch_to_thread (thread);
4905 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4906 set_current_sal_from_frame (get_current_frame ());
4907
4908 /* For "info program". */
4909 set_last_target_status (this, thread->ptid, ws);
4910
4911 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4912 {
4913 enum gdb_signal sig = ws.sig ();
4914
4915 if (signal_print_state (sig))
4916 notify_signal_received (sig);
4917 }
4918
4919 notify_normal_stop (nullptr, 1);
4920}
4921
4922/* Process all initial stop replies the remote side sent in response
4923 to the ? packet. These indicate threads that were already stopped
4924 on initial connection. We mark these threads as stopped and print
4925 their current frame before giving the user the prompt. */
4926
4927void
4928remote_target::process_initial_stop_replies (int from_tty)
4929{
4930 int pending_stop_replies = stop_reply_queue_length ();
4931 struct thread_info *selected = NULL;
4932 struct thread_info *lowest_stopped = NULL;
4933 struct thread_info *first = NULL;
4934
4935 /* This is only used when the target is non-stop. */
4936 gdb_assert (target_is_non_stop_p ());
4937
4938 /* Consume the initial pending events. */
4939 while (pending_stop_replies-- > 0)
4940 {
4941 ptid_t waiton_ptid = minus_one_ptid;
4942 ptid_t event_ptid;
4943 struct target_waitstatus ws;
4944 int ignore_event = 0;
4945
4946 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4947 if (remote_debug)
4948 print_target_wait_results (waiton_ptid, event_ptid, ws, this);
4949
4950 switch (ws.kind ())
4951 {
4952 case TARGET_WAITKIND_IGNORE:
4953 case TARGET_WAITKIND_NO_RESUMED:
4954 case TARGET_WAITKIND_SIGNALLED:
4955 case TARGET_WAITKIND_EXITED:
4956 /* We shouldn't see these, but if we do, just ignore. */
4957 remote_debug_printf ("event ignored");
4958 ignore_event = 1;
4959 break;
4960
4961 default:
4962 break;
4963 }
4964
4965 if (ignore_event)
4966 continue;
4967
4968 thread_info *evthread = this->find_thread (event_ptid);
4969
4970 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4971 {
4972 enum gdb_signal sig = ws.sig ();
4973
4974 /* Stubs traditionally report SIGTRAP as initial signal,
4975 instead of signal 0. Suppress it. */
4976 if (sig == GDB_SIGNAL_TRAP)
4977 sig = GDB_SIGNAL_0;
4978 evthread->set_stop_signal (sig);
4979 ws.set_stopped (sig);
4980 }
4981
4982 if (ws.kind () != TARGET_WAITKIND_STOPPED
4983 || ws.sig () != GDB_SIGNAL_0)
4984 evthread->set_pending_waitstatus (ws);
4985
4986 set_executing (this, event_ptid, false);
4987 set_running (this, event_ptid, false);
4988 get_remote_thread_info (evthread)->set_not_resumed ();
4989 }
4990
4991 /* "Notice" the new inferiors before anything related to
4992 registers/memory. */
4993 for (inferior *inf : all_non_exited_inferiors (this))
4994 {
4995 inf->needs_setup = true;
4996
4997 if (non_stop)
4998 {
4999 thread_info *thread = any_live_thread_of_inferior (inf);
5000 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
5001 from_tty);
5002 }
5003 }
5004
5005 /* If all-stop on top of non-stop, pause all threads. Note this
5006 records the threads' stop pc, so must be done after "noticing"
5007 the inferiors. */
5008 if (!non_stop)
5009 {
5010 {
5011 /* At this point, the remote target is not async. It needs to be for
5012 the poll in stop_all_threads to consider events from it, so enable
5013 it temporarily. */
5014 gdb_assert (!this->is_async_p ());
5015 SCOPE_EXIT { target_async (false); };
5016 target_async (true);
5017 stop_all_threads ("remote connect in all-stop");
5018 }
5019
5020 /* If all threads of an inferior were already stopped, we
5021 haven't setup the inferior yet. */
5022 for (inferior *inf : all_non_exited_inferiors (this))
5023 {
5024 if (inf->needs_setup)
5025 {
5026 thread_info *thread = any_live_thread_of_inferior (inf);
5027 switch_to_thread_no_regs (thread);
5028 setup_inferior (0);
5029 }
5030 }
5031 }
5032
5033 /* Now go over all threads that are stopped, and print their current
5034 frame. If all-stop, then if there's a signalled thread, pick
5035 that as current. */
5036 for (thread_info *thread : all_non_exited_threads (this))
5037 {
5038 if (first == NULL)
5039 first = thread;
5040
5041 if (!non_stop)
5042 thread->set_running (false);
5043 else if (thread->state != THREAD_STOPPED)
5044 continue;
5045
5046 if (selected == nullptr && thread->has_pending_waitstatus ())
5047 selected = thread;
5048
5049 if (lowest_stopped == NULL
5050 || thread->inf->num < lowest_stopped->inf->num
5051 || thread->per_inf_num < lowest_stopped->per_inf_num)
5052 lowest_stopped = thread;
5053
5054 if (non_stop)
5055 print_one_stopped_thread (thread);
5056 }
5057
5058 /* In all-stop, we only print the status of one thread, and leave
5059 others with their status pending. */
5060 if (!non_stop)
5061 {
5062 thread_info *thread = selected;
5063 if (thread == NULL)
5064 thread = lowest_stopped;
5065 if (thread == NULL)
5066 thread = first;
5067
5068 print_one_stopped_thread (thread);
5069 }
5070}
5071
5072/* Mark a remote_target as starting (by setting the starting_up flag within
5073 its remote_state) for the lifetime of this object. The reference count
5074 on the remote target is temporarily incremented, to prevent the target
5075 being deleted under our feet. */
5076
5077struct scoped_mark_target_starting
5078{
5079 /* Constructor, TARGET is the target to be marked as starting, its
5080 reference count will be incremented. */
5081 scoped_mark_target_starting (remote_target *target)
5082 : m_remote_target (remote_target_ref::new_reference (target)),
5083 m_restore_starting_up (set_starting_up_flag (target))
5084 { /* Nothing. */ }
5085
5086private:
5087
5088 /* Helper function, set the starting_up flag on TARGET and return an
5089 object which, when it goes out of scope, will restore the previous
5090 value of the starting_up flag. */
5091 static scoped_restore_tmpl<bool>
5092 set_starting_up_flag (remote_target *target)
5093 {
5094 remote_state *rs = target->get_remote_state ();
5095 gdb_assert (!rs->starting_up);
5096 return make_scoped_restore (&rs->starting_up, true);
5097 }
5098
5099 /* A gdb::ref_ptr pointer to a remote_target. */
5100 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
5101
5102 /* A reference to the target on which we are operating. */
5103 remote_target_ref m_remote_target;
5104
5105 /* An object which restores the previous value of the starting_up flag
5106 when it goes out of scope. */
5107 scoped_restore_tmpl<bool> m_restore_starting_up;
5108};
5109
5110/* Transfer ownership of the stop_reply owned by EVENT to a
5111 stop_reply_up object. */
5112
5113static stop_reply_up
5114as_stop_reply_up (notif_event_up event)
5115{
5116 auto *stop_reply = static_cast<struct stop_reply *> (event.release ());
5117 return stop_reply_up (stop_reply);
5118}
5119
5120/* Helper for remote_target::start_remote, start the remote connection and
5121 sync state. Return true if everything goes OK, otherwise, return false.
5122 This function exists so that the scoped_restore created within it will
5123 expire before we return to remote_target::start_remote. */
5124
5125bool
5126remote_target::start_remote_1 (int from_tty, int extended_p)
5127{
5128 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
5129
5130 struct remote_state *rs = get_remote_state ();
5131
5132 /* Signal other parts that we're going through the initial setup,
5133 and so things may not be stable yet. E.g., we don't try to
5134 install tracepoints until we've relocated symbols. Also, a
5135 Ctrl-C before we're connected and synced up can't interrupt the
5136 target. Instead, it offers to drop the (potentially wedged)
5137 connection. */
5138 scoped_mark_target_starting target_is_starting (this);
5139
5140 QUIT;
5141
5142 if (interrupt_on_connect)
5143 send_interrupt_sequence ();
5144
5145 /* Ack any packet which the remote side has already sent. */
5146 remote_serial_write ("+", 1);
5147
5148 /* The first packet we send to the target is the optional "supported
5149 packets" request. If the target can answer this, it will tell us
5150 which later probes to skip. */
5151 remote_query_supported ();
5152
5153 /* Check vCont support and set the remote state's vCont_action_support
5154 attribute. */
5155 remote_vcont_probe ();
5156
5157 /* If the stub wants to get a QAllow, compose one and send it. */
5158 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5159 set_permissions ();
5160
5161 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5162 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5163 as a reply to known packet. For packet "vFile:setfs:" it is an
5164 invalid reply and GDB would return error in
5165 remote_hostio_set_filesystem, making remote files access impossible.
5166 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5167 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5168 {
5169 const char v_mustreplyempty[] = "vMustReplyEmpty";
5170
5171 putpkt (v_mustreplyempty);
5172 getpkt (&rs->buf);
5173 if (strcmp (rs->buf.data (), "OK") == 0)
5174 {
5175 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5176 = PACKET_DISABLE;
5177 }
5178 else if (strcmp (rs->buf.data (), "") != 0)
5179 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5180 rs->buf.data ());
5181 }
5182
5183 /* Next, we possibly activate noack mode.
5184
5185 If the QStartNoAckMode packet configuration is set to AUTO,
5186 enable noack mode if the stub reported a wish for it with
5187 qSupported.
5188
5189 If set to TRUE, then enable noack mode even if the stub didn't
5190 report it in qSupported. If the stub doesn't reply OK, the
5191 session ends with an error.
5192
5193 If FALSE, then don't activate noack mode, regardless of what the
5194 stub claimed should be the default with qSupported. */
5195
5196 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5197 {
5198 putpkt ("QStartNoAckMode");
5199 getpkt (&rs->buf);
5200 if ((m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode)).status ()
5201 == PACKET_OK)
5202 rs->noack_mode = 1;
5203 }
5204
5205 if (extended_p)
5206 {
5207 /* Tell the remote that we are using the extended protocol. */
5208 putpkt ("!");
5209 getpkt (&rs->buf);
5210 }
5211
5212 /* Let the target know which signals it is allowed to pass down to
5213 the program. */
5214 update_signals_program_target ();
5215
5216 /* Next, if the target can specify a description, read it. We do
5217 this before anything involving memory or registers. */
5218 target_find_description ();
5219
5220 /* Next, now that we know something about the target, update the
5221 address spaces in the program spaces. */
5222 update_address_spaces ();
5223
5224 /* On OSs where the list of libraries is global to all
5225 processes, we fetch them early. */
5226 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5227 solib_add (NULL, from_tty, auto_solib_add);
5228
5229 if (target_is_non_stop_p ())
5230 {
5231 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5232 error (_("Non-stop mode requested, but remote "
5233 "does not support non-stop"));
5234
5235 putpkt ("QNonStop:1");
5236 getpkt (&rs->buf);
5237
5238 if (strcmp (rs->buf.data (), "OK") != 0)
5239 error (_("Remote refused setting non-stop mode with: %s"),
5240 rs->buf.data ());
5241
5242 /* Find about threads and processes the stub is already
5243 controlling. We default to adding them in the running state.
5244 The '?' query below will then tell us about which threads are
5245 stopped. */
5246 this->update_thread_list ();
5247 }
5248 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5249 {
5250 /* Don't assume that the stub can operate in all-stop mode.
5251 Request it explicitly. */
5252 putpkt ("QNonStop:0");
5253 getpkt (&rs->buf);
5254
5255 if (strcmp (rs->buf.data (), "OK") != 0)
5256 error (_("Remote refused setting all-stop mode with: %s"),
5257 rs->buf.data ());
5258 }
5259
5260 /* Upload TSVs regardless of whether the target is running or not. The
5261 remote stub, such as GDBserver, may have some predefined or builtin
5262 TSVs, even if the target is not running. */
5263 if (get_trace_status (current_trace_status ()) != -1)
5264 {
5265 struct uploaded_tsv *uploaded_tsvs = NULL;
5266
5267 upload_trace_state_variables (&uploaded_tsvs);
5268 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5269 }
5270
5271 /* Check whether the target is running now. */
5272 putpkt ("?");
5273 getpkt (&rs->buf);
5274
5275 if (!target_is_non_stop_p ())
5276 {
5277 char *wait_status = NULL;
5278
5279 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5280 {
5281 if (!extended_p)
5282 error (_("The target is not running (try extended-remote?)"));
5283 return false;
5284 }
5285 else
5286 {
5287 /* Save the reply for later. */
5288 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5289 strcpy (wait_status, rs->buf.data ());
5290 }
5291
5292 /* Fetch thread list. */
5293 target_update_thread_list ();
5294
5295 /* Let the stub know that we want it to return the thread. */
5296 set_continue_thread (minus_one_ptid);
5297
5298 if (thread_count (this) == 0)
5299 {
5300 /* Target has no concept of threads at all. GDB treats
5301 non-threaded target as single-threaded; add a main
5302 thread. */
5303 thread_info *tp = add_current_inferior_and_thread (wait_status);
5304 get_remote_thread_info (tp)->set_resumed ();
5305 }
5306 else
5307 {
5308 /* We have thread information; select the thread the target
5309 says should be current. If we're reconnecting to a
5310 multi-threaded program, this will ideally be the thread
5311 that last reported an event before GDB disconnected. */
5312 ptid_t curr_thread = get_current_thread (wait_status);
5313 if (curr_thread == null_ptid)
5314 {
5315 /* Odd... The target was able to list threads, but not
5316 tell us which thread was current (no "thread"
5317 register in T stop reply?). Just pick the first
5318 thread in the thread list then. */
5319
5320 remote_debug_printf ("warning: couldn't determine remote "
5321 "current thread; picking first in list.");
5322
5323 for (thread_info *tp : all_non_exited_threads (this,
5324 minus_one_ptid))
5325 {
5326 switch_to_thread (tp);
5327 break;
5328 }
5329 }
5330 else
5331 switch_to_thread (this->find_thread (curr_thread));
5332
5333 get_remote_thread_info (inferior_thread ())->set_resumed ();
5334 }
5335
5336 /* init_wait_for_inferior should be called before get_offsets in order
5337 to manage `inserted' flag in bp loc in a correct state.
5338 breakpoint_init_inferior, called from init_wait_for_inferior, set
5339 `inserted' flag to 0, while before breakpoint_re_set, called from
5340 start_remote, set `inserted' flag to 1. In the initialization of
5341 inferior, breakpoint_init_inferior should be called first, and then
5342 breakpoint_re_set can be called. If this order is broken, state of
5343 `inserted' flag is wrong, and cause some problems on breakpoint
5344 manipulation. */
5345 init_wait_for_inferior ();
5346
5347 get_offsets (); /* Get text, data & bss offsets. */
5348
5349 /* If we could not find a description using qXfer, and we know
5350 how to do it some other way, try again. This is not
5351 supported for non-stop; it could be, but it is tricky if
5352 there are no stopped threads when we connect. */
5353 if (remote_read_description_p (this)
5354 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5355 {
5356 target_clear_description ();
5357 target_find_description ();
5358 }
5359
5360 /* Use the previously fetched status. */
5361 gdb_assert (wait_status != NULL);
5362 notif_event_up reply
5363 = remote_notif_parse (this, &notif_client_stop, wait_status);
5364 push_stop_reply (as_stop_reply_up (std::move (reply)));
5365
5366 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5367 }
5368 else
5369 {
5370 /* Clear WFI global state. Do this before finding about new
5371 threads and inferiors, and setting the current inferior.
5372 Otherwise we would clear the proceed status of the current
5373 inferior when we want its stop_soon state to be preserved
5374 (see notice_new_inferior). */
5375 init_wait_for_inferior ();
5376
5377 /* In non-stop, we will either get an "OK", meaning that there
5378 are no stopped threads at this time; or, a regular stop
5379 reply. In the latter case, there may be more than one thread
5380 stopped --- we pull them all out using the vStopped
5381 mechanism. */
5382 if (strcmp (rs->buf.data (), "OK") != 0)
5383 {
5384 const notif_client *notif = &notif_client_stop;
5385
5386 /* remote_notif_get_pending_replies acks this one, and gets
5387 the rest out. */
5388 rs->notif_state->pending_event[notif_client_stop.id]
5389 = remote_notif_parse (this, notif, rs->buf.data ());
5390 remote_notif_get_pending_events (notif);
5391 }
5392
5393 if (thread_count (this) == 0)
5394 {
5395 if (!extended_p)
5396 error (_("The target is not running (try extended-remote?)"));
5397 return false;
5398 }
5399
5400 /* Report all signals during attach/startup. */
5401 pass_signals ({});
5402
5403 /* If there are already stopped threads, mark them stopped and
5404 report their stops before giving the prompt to the user. */
5405 process_initial_stop_replies (from_tty);
5406
5407 if (target_can_async_p ())
5408 target_async (true);
5409 }
5410
5411 /* Give the target a chance to look up symbols. */
5412 for (inferior *inf : all_inferiors (this))
5413 {
5414 /* The inferiors that exist at this point were created from what
5415 was found already running on the remote side, so we know they
5416 have execution. */
5417 gdb_assert (this->has_execution (inf));
5418
5419 /* No use without a symbol-file. */
5420 if (inf->pspace->symfile_object_file == nullptr)
5421 continue;
5422
5423 /* Need to switch to a specific thread, because remote_check_symbols
5424 uses INFERIOR_PTID to set the general thread. */
5425 scoped_restore_current_thread restore_thread;
5426 thread_info *thread = any_thread_of_inferior (inf);
5427 switch_to_thread (thread);
5428 this->remote_check_symbols ();
5429 }
5430
5431 /* Possibly the target has been engaged in a trace run started
5432 previously; find out where things are at. */
5433 if (get_trace_status (current_trace_status ()) != -1)
5434 {
5435 struct uploaded_tp *uploaded_tps = NULL;
5436
5437 if (current_trace_status ()->running)
5438 gdb_printf (_("Trace is already running on the target.\n"));
5439
5440 upload_tracepoints (&uploaded_tps);
5441
5442 merge_uploaded_tracepoints (&uploaded_tps);
5443 }
5444
5445 /* Possibly the target has been engaged in a btrace record started
5446 previously; find out where things are at. */
5447 remote_btrace_maybe_reopen ();
5448
5449 return true;
5450}
5451
5452/* Start the remote connection and sync state. */
5453
5454void
5455remote_target::start_remote (int from_tty, int extended_p)
5456{
5457 if (start_remote_1 (from_tty, extended_p)
5458 && breakpoints_should_be_inserted_now ())
5459 insert_breakpoints ();
5460}
5461
5462const char *
5463remote_target::connection_string ()
5464{
5465 remote_state *rs = get_remote_state ();
5466
5467 if (rs->remote_desc->name != NULL)
5468 return rs->remote_desc->name;
5469 else
5470 return NULL;
5471}
5472
5473/* Open a connection to a remote debugger.
5474 NAME is the filename used for communication. */
5475
5476void
5477remote_target::open (const char *name, int from_tty)
5478{
5479 open_1 (name, from_tty, 0);
5480}
5481
5482/* Open a connection to a remote debugger using the extended
5483 remote gdb protocol. NAME is the filename used for communication. */
5484
5485void
5486extended_remote_target::open (const char *name, int from_tty)
5487{
5488 open_1 (name, from_tty, 1 /*extended_p */);
5489}
5490
5491void
5492remote_features::reset_all_packet_configs_support ()
5493{
5494 int i;
5495
5496 for (i = 0; i < PACKET_MAX; i++)
5497 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5498}
5499
5500/* Initialize all packet configs. */
5501
5502static void
5503init_all_packet_configs (void)
5504{
5505 int i;
5506
5507 for (i = 0; i < PACKET_MAX; i++)
5508 {
5509 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5510 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5511 }
5512}
5513
5514/* Symbol look-up. */
5515
5516void
5517remote_target::remote_check_symbols ()
5518{
5519 char *tmp;
5520 int end;
5521
5522 /* It doesn't make sense to send a qSymbol packet for an inferior that
5523 doesn't have execution, because the remote side doesn't know about
5524 inferiors without execution. */
5525 gdb_assert (target_has_execution ());
5526
5527 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5528 return;
5529
5530 /* Make sure the remote is pointing at the right process. Note
5531 there's no way to select "no process". */
5532 set_general_process ();
5533
5534 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5535 because we need both at the same time. */
5536 gdb::char_vector msg (get_remote_packet_size ());
5537 gdb::char_vector reply (get_remote_packet_size ());
5538
5539 /* Invite target to request symbol lookups. */
5540
5541 putpkt ("qSymbol::");
5542 getpkt (&reply);
5543 m_features.packet_ok (reply, PACKET_qSymbol);
5544
5545 while (startswith (reply.data (), "qSymbol:"))
5546 {
5547 tmp = &reply[8];
5548 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5549 strlen (tmp) / 2);
5550 msg[end] = '\0';
5551 bound_minimal_symbol sym
5552 = lookup_minimal_symbol (current_program_space, msg.data ());
5553 if (sym.minsym == NULL)
5554 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5555 &reply[8]);
5556 else
5557 {
5558 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5559 CORE_ADDR sym_addr = sym.value_address ();
5560
5561 /* If this is a function address, return the start of code
5562 instead of any data function descriptor. */
5563 sym_addr = gdbarch_convert_from_func_ptr_addr
5564 (current_inferior ()->arch (), sym_addr,
5565 current_inferior ()->top_target ());
5566
5567 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5568 phex_nz (sym_addr, addr_size), &reply[8]);
5569 }
5570
5571 putpkt (msg.data ());
5572 getpkt (&reply);
5573 }
5574}
5575
5576static struct serial *
5577remote_serial_open (const char *name)
5578{
5579 static int udp_warning = 0;
5580
5581 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5582 of in ser-tcp.c, because it is the remote protocol assuming that the
5583 serial connection is reliable and not the serial connection promising
5584 to be. */
5585 if (!udp_warning && startswith (name, "udp:"))
5586 {
5587 warning (_("The remote protocol may be unreliable over UDP.\n"
5588 "Some events may be lost, rendering further debugging "
5589 "impossible."));
5590 udp_warning = 1;
5591 }
5592
5593 return serial_open (name);
5594}
5595
5596/* Inform the target of our permission settings. The permission flags
5597 work without this, but if the target knows the settings, it can do
5598 a couple things. First, it can add its own check, to catch cases
5599 that somehow manage to get by the permissions checks in target
5600 methods. Second, if the target is wired to disallow particular
5601 settings (for instance, a system in the field that is not set up to
5602 be able to stop at a breakpoint), it can object to any unavailable
5603 permissions. */
5604
5605void
5606remote_target::set_permissions ()
5607{
5608 struct remote_state *rs = get_remote_state ();
5609
5610 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5611 "WriteReg:%x;WriteMem:%x;"
5612 "InsertBreak:%x;InsertTrace:%x;"
5613 "InsertFastTrace:%x;Stop:%x",
5614 may_write_registers, may_write_memory,
5615 may_insert_breakpoints, may_insert_tracepoints,
5616 may_insert_fast_tracepoints, may_stop);
5617 putpkt (rs->buf);
5618 getpkt (&rs->buf);
5619
5620 /* If the target didn't like the packet, warn the user. Do not try
5621 to undo the user's settings, that would just be maddening. */
5622 if (strcmp (rs->buf.data (), "OK") != 0)
5623 warning (_("Remote refused setting permissions with: %s"),
5624 rs->buf.data ());
5625}
5626
5627/* This type describes each known response to the qSupported
5628 packet. */
5629struct protocol_feature
5630{
5631 /* The name of this protocol feature. */
5632 const char *name;
5633
5634 /* The default for this protocol feature. */
5635 enum packet_support default_support;
5636
5637 /* The function to call when this feature is reported, or after
5638 qSupported processing if the feature is not supported.
5639 The first argument points to this structure. The second
5640 argument indicates whether the packet requested support be
5641 enabled, disabled, or probed (or the default, if this function
5642 is being called at the end of processing and this feature was
5643 not reported). The third argument may be NULL; if not NULL, it
5644 is a NUL-terminated string taken from the packet following
5645 this feature's name and an equals sign. */
5646 void (*func) (remote_target *remote, const struct protocol_feature *,
5647 enum packet_support, const char *);
5648
5649 /* The corresponding packet for this feature. Only used if
5650 FUNC is remote_supported_packet. */
5651 int packet;
5652};
5653
5654static void
5655remote_supported_packet (remote_target *remote,
5656 const struct protocol_feature *feature,
5657 enum packet_support support,
5658 const char *argument)
5659{
5660 if (argument)
5661 {
5662 warning (_("Remote qSupported response supplied an unexpected value for"
5663 " \"%s\"."), feature->name);
5664 return;
5665 }
5666
5667 remote->m_features.m_protocol_packets[feature->packet].support = support;
5668}
5669
5670void
5671remote_target::remote_packet_size (const protocol_feature *feature,
5672 enum packet_support support,
5673 const char *value)
5674{
5675 struct remote_state *rs = get_remote_state ();
5676
5677 int packet_size;
5678 char *value_end;
5679
5680 if (support != PACKET_ENABLE)
5681 return;
5682
5683 if (value == NULL || *value == '\0')
5684 {
5685 warning (_("Remote target reported \"%s\" without a size."),
5686 feature->name);
5687 return;
5688 }
5689
5690 errno = 0;
5691 packet_size = strtol (value, &value_end, 16);
5692 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5693 {
5694 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5695 feature->name, value);
5696 return;
5697 }
5698
5699 /* Record the new maximum packet size. */
5700 rs->explicit_packet_size = packet_size;
5701}
5702
5703static void
5704remote_packet_size (remote_target *remote, const protocol_feature *feature,
5705 enum packet_support support, const char *value)
5706{
5707 remote->remote_packet_size (feature, support, value);
5708}
5709
5710void
5711remote_target::remote_supported_thread_options (const protocol_feature *feature,
5712 enum packet_support support,
5713 const char *value)
5714{
5715 struct remote_state *rs = get_remote_state ();
5716
5717 m_features.m_protocol_packets[feature->packet].support = support;
5718
5719 if (support != PACKET_ENABLE)
5720 return;
5721
5722 if (value == nullptr || *value == '\0')
5723 {
5724 warning (_("Remote target reported \"%s\" without supported options."),
5725 feature->name);
5726 return;
5727 }
5728
5729 ULONGEST options = 0;
5730 const char *p = unpack_varlen_hex (value, &options);
5731
5732 if (*p != '\0')
5733 {
5734 warning (_("Remote target reported \"%s\" with "
5735 "bad thread options: \"%s\"."),
5736 feature->name, value);
5737 return;
5738 }
5739
5740 /* Record the set of supported options. */
5741 rs->supported_thread_options = (gdb_thread_option) options;
5742}
5743
5744static void
5745remote_supported_thread_options (remote_target *remote,
5746 const protocol_feature *feature,
5747 enum packet_support support,
5748 const char *value)
5749{
5750 remote->remote_supported_thread_options (feature, support, value);
5751}
5752
5753static const struct protocol_feature remote_protocol_features[] = {
5754 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5755 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5756 PACKET_qXfer_auxv },
5757 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5758 PACKET_qXfer_exec_file },
5759 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5760 PACKET_qXfer_features },
5761 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5762 PACKET_qXfer_libraries },
5763 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5764 PACKET_qXfer_libraries_svr4 },
5765 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5766 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5767 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5768 PACKET_qXfer_memory_map },
5769 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5770 PACKET_qXfer_osdata },
5771 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5772 PACKET_qXfer_threads },
5773 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5774 PACKET_qXfer_traceframe_info },
5775 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5776 PACKET_QPassSignals },
5777 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5778 PACKET_QCatchSyscalls },
5779 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5780 PACKET_QProgramSignals },
5781 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5782 PACKET_QSetWorkingDir },
5783 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5784 PACKET_QStartupWithShell },
5785 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5786 PACKET_QEnvironmentHexEncoded },
5787 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5788 PACKET_QEnvironmentReset },
5789 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5790 PACKET_QEnvironmentUnset },
5791 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5792 PACKET_QStartNoAckMode },
5793 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5794 PACKET_multiprocess_feature },
5795 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5796 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5797 PACKET_qXfer_siginfo_read },
5798 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5799 PACKET_qXfer_siginfo_write },
5800 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5801 PACKET_ConditionalTracepoints },
5802 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5803 PACKET_ConditionalBreakpoints },
5804 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5805 PACKET_BreakpointCommands },
5806 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5807 PACKET_FastTracepoints },
5808 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5809 PACKET_StaticTracepoints },
5810 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5811 PACKET_InstallInTrace},
5812 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5813 PACKET_DisconnectedTracing_feature },
5814 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5815 PACKET_bc },
5816 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5817 PACKET_bs },
5818 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5819 PACKET_TracepointSource },
5820 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5821 PACKET_QAllow },
5822 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5823 PACKET_EnableDisableTracepoints_feature },
5824 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5825 PACKET_qXfer_fdpic },
5826 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5827 PACKET_qXfer_uib },
5828 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5829 PACKET_QDisableRandomization },
5830 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5831 { "QTBuffer:size", PACKET_DISABLE,
5832 remote_supported_packet, PACKET_QTBuffer_size},
5833 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5834 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5835 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5836 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5837 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5838 PACKET_qXfer_btrace },
5839 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5840 PACKET_qXfer_btrace_conf },
5841 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5842 PACKET_Qbtrace_conf_bts_size },
5843 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5844 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5845 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5846 PACKET_fork_event_feature },
5847 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5848 PACKET_vfork_event_feature },
5849 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5850 PACKET_exec_event_feature },
5851 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5852 PACKET_Qbtrace_conf_pt_size },
5853 { "Qbtrace-conf:pt:ptwrite", PACKET_DISABLE, remote_supported_packet,
5854 PACKET_Qbtrace_conf_pt_ptwrite },
5855 { "Qbtrace-conf:pt:event-tracing", PACKET_DISABLE, remote_supported_packet,
5856 PACKET_Qbtrace_conf_pt_event_tracing },
5857 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5858 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5859 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5860 PACKET_QThreadOptions },
5861 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5862 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5863 PACKET_memory_tagging_feature },
5864 { "error-message", PACKET_ENABLE, remote_supported_packet,
5865 PACKET_accept_error_message },
5866 { "binary-upload", PACKET_DISABLE, remote_supported_packet, PACKET_x },
5867};
5868
5869static char *remote_support_xml;
5870
5871/* Register string appended to "xmlRegisters=" in qSupported query. */
5872
5873void
5874register_remote_support_xml (const char *xml)
5875{
5876#if defined(HAVE_LIBEXPAT)
5877 if (remote_support_xml == NULL)
5878 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5879 else
5880 {
5881 char *copy = xstrdup (remote_support_xml + 13);
5882 char *saveptr;
5883 char *p = strtok_r (copy, ",", &saveptr);
5884
5885 do
5886 {
5887 if (strcmp (p, xml) == 0)
5888 {
5889 /* already there */
5890 xfree (copy);
5891 return;
5892 }
5893 }
5894 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5895 xfree (copy);
5896
5897 remote_support_xml = reconcat (remote_support_xml,
5898 remote_support_xml, ",", xml,
5899 (char *) NULL);
5900 }
5901#endif
5902}
5903
5904static void
5905remote_query_supported_append (std::string *msg, const char *append)
5906{
5907 if (!msg->empty ())
5908 msg->append (";");
5909 msg->append (append);
5910}
5911
5912void
5913remote_target::remote_query_supported ()
5914{
5915 struct remote_state *rs = get_remote_state ();
5916 char *next;
5917 int i;
5918 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5919
5920 /* The packet support flags are handled differently for this packet
5921 than for most others. We treat an error, a disabled packet, and
5922 an empty response identically: any features which must be reported
5923 to be used will be automatically disabled. An empty buffer
5924 accomplishes this, since that is also the representation for a list
5925 containing no features. */
5926
5927 rs->buf[0] = 0;
5928 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5929 {
5930 std::string q;
5931
5932 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5933 != AUTO_BOOLEAN_FALSE)
5934 remote_query_supported_append (&q, "multiprocess+");
5935
5936 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5937 != AUTO_BOOLEAN_FALSE)
5938 remote_query_supported_append (&q, "swbreak+");
5939
5940 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5941 != AUTO_BOOLEAN_FALSE)
5942 remote_query_supported_append (&q, "hwbreak+");
5943
5944 remote_query_supported_append (&q, "qRelocInsn+");
5945
5946 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5947 != AUTO_BOOLEAN_FALSE)
5948 remote_query_supported_append (&q, "fork-events+");
5949
5950 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5951 != AUTO_BOOLEAN_FALSE)
5952 remote_query_supported_append (&q, "vfork-events+");
5953
5954 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5955 != AUTO_BOOLEAN_FALSE)
5956 remote_query_supported_append (&q, "exec-events+");
5957
5958 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5959 != AUTO_BOOLEAN_FALSE)
5960 remote_query_supported_append (&q, "vContSupported+");
5961
5962 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5963 != AUTO_BOOLEAN_FALSE)
5964 remote_query_supported_append (&q, "QThreadEvents+");
5965
5966 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5967 != AUTO_BOOLEAN_FALSE)
5968 remote_query_supported_append (&q, "QThreadOptions+");
5969
5970 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5971 != AUTO_BOOLEAN_FALSE)
5972 remote_query_supported_append (&q, "no-resumed+");
5973
5974 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5975 != AUTO_BOOLEAN_FALSE)
5976 remote_query_supported_append (&q, "memory-tagging+");
5977
5978 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5979 the qSupported:xmlRegisters=i386 handling. */
5980 if (remote_support_xml != NULL
5981 && (m_features.packet_support (PACKET_qXfer_features)
5982 != PACKET_DISABLE))
5983 remote_query_supported_append (&q, remote_support_xml);
5984
5985 if (m_features.packet_set_cmd_state (PACKET_accept_error_message)
5986 != AUTO_BOOLEAN_FALSE)
5987 remote_query_supported_append (&q, "error-message+");
5988
5989 q = "qSupported:" + q;
5990 putpkt (q.c_str ());
5991
5992 getpkt (&rs->buf);
5993
5994 /* If an error occurred, warn, but do not return - just reset the
5995 buffer to empty and go on to disable features. */
5996 packet_result result = m_features.packet_ok (rs->buf, PACKET_qSupported);
5997 if (result.status () == PACKET_ERROR)
5998 {
5999 warning (_("Remote failure reply: %s"), result.err_msg ());
6000 rs->buf[0] = 0;
6001 }
6002 }
6003
6004 memset (seen, 0, sizeof (seen));
6005
6006 next = rs->buf.data ();
6007 while (*next)
6008 {
6009 enum packet_support is_supported;
6010 char *p, *end, *name_end, *value;
6011
6012 /* First separate out this item from the rest of the packet. If
6013 there's another item after this, we overwrite the separator
6014 (terminated strings are much easier to work with). */
6015 p = next;
6016 end = strchr (p, ';');
6017 if (end == NULL)
6018 {
6019 end = p + strlen (p);
6020 next = end;
6021 }
6022 else
6023 {
6024 *end = '\0';
6025 next = end + 1;
6026
6027 if (end == p)
6028 {
6029 warning (_("empty item in \"qSupported\" response"));
6030 continue;
6031 }
6032 }
6033
6034 name_end = strchr (p, '=');
6035 if (name_end)
6036 {
6037 /* This is a name=value entry. */
6038 is_supported = PACKET_ENABLE;
6039 value = name_end + 1;
6040 *name_end = '\0';
6041 }
6042 else
6043 {
6044 value = NULL;
6045 switch (end[-1])
6046 {
6047 case '+':
6048 is_supported = PACKET_ENABLE;
6049 break;
6050
6051 case '-':
6052 is_supported = PACKET_DISABLE;
6053 break;
6054
6055 case '?':
6056 is_supported = PACKET_SUPPORT_UNKNOWN;
6057 break;
6058
6059 default:
6060 warning (_("unrecognized item \"%s\" "
6061 "in \"qSupported\" response"), p);
6062 continue;
6063 }
6064 end[-1] = '\0';
6065 }
6066
6067 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6068 if (strcmp (remote_protocol_features[i].name, p) == 0)
6069 {
6070 const struct protocol_feature *feature;
6071
6072 seen[i] = 1;
6073 feature = &remote_protocol_features[i];
6074 feature->func (this, feature, is_supported, value);
6075 break;
6076 }
6077 }
6078
6079 /* If we increased the packet size, make sure to increase the global
6080 buffer size also. We delay this until after parsing the entire
6081 qSupported packet, because this is the same buffer we were
6082 parsing. */
6083 if (rs->buf.size () < rs->explicit_packet_size)
6084 rs->buf.resize (rs->explicit_packet_size);
6085
6086 /* Handle the defaults for unmentioned features. */
6087 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6088 if (!seen[i])
6089 {
6090 const struct protocol_feature *feature;
6091
6092 feature = &remote_protocol_features[i];
6093 feature->func (this, feature, feature->default_support, NULL);
6094 }
6095}
6096
6097/* Serial QUIT handler for the remote serial descriptor.
6098
6099 Defers handling a Ctrl-C until we're done with the current
6100 command/response packet sequence, unless:
6101
6102 - We're setting up the connection. Don't send a remote interrupt
6103 request, as we're not fully synced yet. Quit immediately
6104 instead.
6105
6106 - The target has been resumed in the foreground
6107 (target_terminal::is_ours is false) with a synchronous resume
6108 packet, and we're blocked waiting for the stop reply, thus a
6109 Ctrl-C should be immediately sent to the target.
6110
6111 - We get a second Ctrl-C while still within the same serial read or
6112 write. In that case the serial is seemingly wedged --- offer to
6113 quit/disconnect.
6114
6115 - We see a second Ctrl-C without target response, after having
6116 previously interrupted the target. In that case the target/stub
6117 is probably wedged --- offer to quit/disconnect.
6118*/
6119
6120void
6121remote_target::remote_serial_quit_handler ()
6122{
6123 struct remote_state *rs = get_remote_state ();
6124
6125 if (check_quit_flag ())
6126 {
6127 /* If we're starting up, we're not fully synced yet. Quit
6128 immediately. */
6129 if (rs->starting_up)
6130 quit ();
6131 else if (rs->got_ctrlc_during_io)
6132 {
6133 if (query (_("The target is not responding to GDB commands.\n"
6134 "Stop debugging it? ")))
6135 remote_unpush_and_throw (this);
6136 }
6137 /* If ^C has already been sent once, offer to disconnect. */
6138 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
6139 interrupt_query ();
6140 /* All-stop protocol, and blocked waiting for stop reply. Send
6141 an interrupt request. */
6142 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
6143 target_interrupt ();
6144 else
6145 rs->got_ctrlc_during_io = 1;
6146 }
6147}
6148
6149/* The remote_target that is current while the quit handler is
6150 overridden with remote_serial_quit_handler. */
6151static remote_target *curr_quit_handler_target;
6152
6153static void
6154remote_serial_quit_handler ()
6155{
6156 curr_quit_handler_target->remote_serial_quit_handler ();
6157}
6158
6159/* Remove the remote target from the target stack of each inferior
6160 that is using it. Upper targets depend on it so remove them
6161 first. */
6162
6163static void
6164remote_unpush_target (remote_target *target)
6165{
6166 /* We have to unpush the target from all inferiors, even those that
6167 aren't running. */
6168 scoped_restore_current_inferior restore_current_inferior;
6169
6170 for (inferior *inf : all_inferiors (target))
6171 {
6172 switch_to_inferior_no_thread (inf);
6173 inf->pop_all_targets_at_and_above (process_stratum);
6174 generic_mourn_inferior ();
6175 }
6176
6177 /* Don't rely on target_close doing this when the target is popped
6178 from the last remote inferior above, because something may be
6179 holding a reference to the target higher up on the stack, meaning
6180 target_close won't be called yet. We lost the connection to the
6181 target, so clear these now, otherwise we may later throw
6182 TARGET_CLOSE_ERROR while trying to tell the remote target to
6183 close the file. */
6184 fileio_handles_invalidate_target (target);
6185}
6186
6187[[noreturn]] static void
6188remote_unpush_and_throw (remote_target *target)
6189{
6190 remote_unpush_target (target);
6191 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6192}
6193
6194void
6195remote_target::open_1 (const char *name, int from_tty, int extended_p)
6196{
6197 remote_target *curr_remote = get_current_remote_target ();
6198
6199 if (name == 0)
6200 error (_("To open a remote debug connection, you need to specify what\n"
6201 "serial device is attached to the remote system\n"
6202 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6203
6204 /* If we're connected to a running target, target_preopen will kill it.
6205 Ask this question first, before target_preopen has a chance to kill
6206 anything. */
6207 if (curr_remote != NULL && !target_has_execution ())
6208 {
6209 if (from_tty
6210 && !query (_("Already connected to a remote target. Disconnect? ")))
6211 error (_("Still connected."));
6212 }
6213
6214 /* Here the possibly existing remote target gets unpushed. */
6215 target_preopen (from_tty);
6216
6217 remote_fileio_reset ();
6218 reopen_exec_file ();
6219 reread_symbols (from_tty);
6220
6221 remote_target *remote
6222 = (extended_p ? new extended_remote_target () : new remote_target ());
6223 target_ops_up target_holder (remote);
6224
6225 remote_state *rs = remote->get_remote_state ();
6226
6227 /* See FIXME above. */
6228 if (!target_async_permitted)
6229 rs->wait_forever_enabled_p = true;
6230
6231 rs->remote_desc = remote_serial_open (name);
6232
6233 if (baud_rate != -1)
6234 {
6235 try
6236 {
6237 serial_setbaudrate (rs->remote_desc, baud_rate);
6238 }
6239 catch (const gdb_exception_error &)
6240 {
6241 /* The requested speed could not be set. Error out to
6242 top level after closing remote_desc. Take care to
6243 set remote_desc to NULL to avoid closing remote_desc
6244 more than once. */
6245 serial_close (rs->remote_desc);
6246 rs->remote_desc = NULL;
6247 throw;
6248 }
6249 }
6250
6251 serial_setparity (rs->remote_desc, serial_parity);
6252 serial_raw (rs->remote_desc);
6253
6254 /* If there is something sitting in the buffer we might take it as a
6255 response to a command, which would be bad. */
6256 serial_flush_input (rs->remote_desc);
6257
6258 if (from_tty)
6259 {
6260 gdb_puts ("Remote debugging using ");
6261 gdb_puts (name);
6262 gdb_puts ("\n");
6263 }
6264
6265 /* Switch to using the remote target now. */
6266 current_inferior ()->push_target (std::move (target_holder));
6267
6268 /* Register extra event sources in the event loop. */
6269 rs->create_async_event_handler ();
6270
6271 rs->notif_state = remote_notif_state_allocate (remote);
6272
6273 /* Reset the target state; these things will be queried either by
6274 remote_query_supported or as they are needed. */
6275 remote->m_features.reset_all_packet_configs_support ();
6276 rs->explicit_packet_size = 0;
6277 rs->noack_mode = 0;
6278 rs->extended = extended_p;
6279 rs->waiting_for_stop_reply = 0;
6280 rs->ctrlc_pending_p = 0;
6281 rs->got_ctrlc_during_io = 0;
6282
6283 rs->general_thread = not_sent_ptid;
6284 rs->continue_thread = not_sent_ptid;
6285 rs->remote_traceframe_number = -1;
6286
6287 rs->last_resume_exec_dir = EXEC_FORWARD;
6288
6289 /* Probe for ability to use "ThreadInfo" query, as required. */
6290 rs->use_threadinfo_query = 1;
6291 rs->use_threadextra_query = 1;
6292
6293 rs->readahead_cache.invalidate ();
6294
6295 if (target_async_permitted)
6296 {
6297 /* FIXME: cagney/1999-09-23: During the initial connection it is
6298 assumed that the target is already ready and able to respond to
6299 requests. Unfortunately remote_start_remote() eventually calls
6300 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6301 around this. Eventually a mechanism that allows
6302 wait_for_inferior() to expect/get timeouts will be
6303 implemented. */
6304 rs->wait_forever_enabled_p = false;
6305 }
6306
6307 /* First delete any symbols previously loaded from shared libraries. */
6308 no_shared_libraries (current_program_space);
6309
6310 /* Start the remote connection. If error() or QUIT, discard this
6311 target (we'd otherwise be in an inconsistent state) and then
6312 propagate the error on up the exception chain. This ensures that
6313 the caller doesn't stumble along blindly assuming that the
6314 function succeeded. The CLI doesn't have this problem but other
6315 UI's, such as MI do.
6316
6317 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6318 this function should return an error indication letting the
6319 caller restore the previous state. Unfortunately the command
6320 ``target remote'' is directly wired to this function making that
6321 impossible. On a positive note, the CLI side of this problem has
6322 been fixed - the function set_cmd_context() makes it possible for
6323 all the ``target ....'' commands to share a common callback
6324 function. See cli-dump.c. */
6325 {
6326
6327 try
6328 {
6329 remote->start_remote (from_tty, extended_p);
6330 }
6331 catch (const gdb_exception &ex)
6332 {
6333 /* Pop the partially set up target - unless something else did
6334 already before throwing the exception. */
6335 if (ex.error != TARGET_CLOSE_ERROR)
6336 remote_unpush_target (remote);
6337 throw;
6338 }
6339 }
6340
6341 remote_btrace_reset (rs);
6342
6343 if (target_async_permitted)
6344 rs->wait_forever_enabled_p = true;
6345}
6346
6347/* Determine if WS represents a fork status. */
6348
6349static bool
6350is_fork_status (target_waitkind kind)
6351{
6352 return (kind == TARGET_WAITKIND_FORKED
6353 || kind == TARGET_WAITKIND_VFORKED);
6354}
6355
6356/* Return a reference to the field where a pending child status, if
6357 there's one, is recorded. If there's no child event pending, the
6358 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6359
6360static const target_waitstatus &
6361thread_pending_status (struct thread_info *thread)
6362{
6363 return (thread->has_pending_waitstatus ()
6364 ? thread->pending_waitstatus ()
6365 : thread->pending_follow);
6366}
6367
6368/* Return THREAD's pending status if it is a pending fork/vfork (but
6369 not clone) parent, else return nullptr. */
6370
6371static const target_waitstatus *
6372thread_pending_fork_status (struct thread_info *thread)
6373{
6374 const target_waitstatus &ws = thread_pending_status (thread);
6375
6376 if (!is_fork_status (ws.kind ()))
6377 return nullptr;
6378
6379 return &ws;
6380}
6381
6382/* Return THREAD's pending status if is is a pending fork/vfork/clone
6383 event, else return nullptr. */
6384
6385static const target_waitstatus *
6386thread_pending_child_status (thread_info *thread)
6387{
6388 const target_waitstatus &ws = thread_pending_status (thread);
6389
6390 if (!is_new_child_status (ws.kind ()))
6391 return nullptr;
6392
6393 return &ws;
6394}
6395
6396/* Detach the specified process. */
6397
6398void
6399remote_target::remote_detach_pid (int pid)
6400{
6401 struct remote_state *rs = get_remote_state ();
6402
6403 /* This should not be necessary, but the handling for D;PID in
6404 GDBserver versions prior to 8.2 incorrectly assumes that the
6405 selected process points to the same process we're detaching,
6406 leading to misbehavior (and possibly GDBserver crashing) when it
6407 does not. Since it's easy and cheap, work around it by forcing
6408 GDBserver to select GDB's current process. */
6409 set_general_process ();
6410
6411 if (m_features.remote_multi_process_p ())
6412 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6413 else
6414 strcpy (rs->buf.data (), "D");
6415
6416 putpkt (rs->buf);
6417 getpkt (&rs->buf);
6418
6419 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6420 ;
6421 else if (rs->buf[0] == '\0')
6422 error (_("Remote doesn't know how to detach"));
6423 else
6424 {
6425 /* It is possible that we have an unprocessed exit event for this
6426 pid. If this is the case then we can ignore the failure to detach
6427 and just pretend that the detach worked, as far as the user is
6428 concerned, the process exited immediately after the detach. */
6429 bool process_has_already_exited = false;
6430 remote_notif_get_pending_events (&notif_client_stop);
6431 for (stop_reply_up &reply : rs->stop_reply_queue)
6432 {
6433 if (reply->ptid.pid () != pid)
6434 continue;
6435
6436 enum target_waitkind kind = reply->ws.kind ();
6437 if (kind == TARGET_WAITKIND_EXITED
6438 || kind == TARGET_WAITKIND_SIGNALLED)
6439 {
6440 process_has_already_exited = true;
6441 remote_debug_printf
6442 ("detach failed, but process already exited");
6443 break;
6444 }
6445 }
6446
6447 if (!process_has_already_exited)
6448 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6449 }
6450}
6451
6452/* This detaches a program to which we previously attached, using
6453 inferior_ptid to identify the process. After this is done, GDB
6454 can be used to debug some other program. We better not have left
6455 any breakpoints in the target program or it'll die when it hits
6456 one. */
6457
6458void
6459remote_target::remote_detach_1 (inferior *inf, int from_tty)
6460{
6461 int pid = inferior_ptid.pid ();
6462 struct remote_state *rs = get_remote_state ();
6463 int is_fork_parent;
6464
6465 if (!target_has_execution ())
6466 error (_("No process to detach from."));
6467
6468 target_announce_detach (from_tty);
6469
6470 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6471 {
6472 /* If we're in breakpoints-always-inserted mode, or the inferior
6473 is running, we have to remove breakpoints before detaching.
6474 We don't do this in common code instead because not all
6475 targets support removing breakpoints while the target is
6476 running. The remote target / gdbserver does, though. */
6477 remove_breakpoints_inf (current_inferior ());
6478 }
6479
6480 /* Tell the remote target to detach. */
6481 remote_detach_pid (pid);
6482
6483 /* Exit only if this is the only active inferior. */
6484 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6485 gdb_puts (_("Ending remote debugging.\n"));
6486
6487 /* See if any thread of the inferior we are detaching has a pending fork
6488 status. In that case, we must detach from the child resulting from
6489 that fork. */
6490 for (thread_info *thread : inf->non_exited_threads ())
6491 {
6492 const target_waitstatus *ws = thread_pending_fork_status (thread);
6493
6494 if (ws == nullptr)
6495 continue;
6496
6497 remote_detach_pid (ws->child_ptid ().pid ());
6498 }
6499
6500 /* Check also for any pending fork events in the stop reply queue. */
6501 remote_notif_get_pending_events (&notif_client_stop);
6502 for (stop_reply_up &reply : rs->stop_reply_queue)
6503 {
6504 if (reply->ptid.pid () != pid)
6505 continue;
6506
6507 if (!is_fork_status (reply->ws.kind ()))
6508 continue;
6509
6510 remote_detach_pid (reply->ws.child_ptid ().pid ());
6511 }
6512
6513 thread_info *tp = this->find_thread (inferior_ptid);
6514
6515 /* Check to see if we are detaching a fork parent. Note that if we
6516 are detaching a fork child, tp == NULL. */
6517 is_fork_parent = (tp != NULL
6518 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6519
6520 /* If doing detach-on-fork, we don't mourn, because that will delete
6521 breakpoints that should be available for the followed inferior. */
6522 if (!is_fork_parent)
6523 {
6524 /* Save the pid as a string before mourning, since that will
6525 unpush the remote target, and we need the string after. */
6526 std::string infpid = target_pid_to_str (ptid_t (pid));
6527
6528 target_mourn_inferior (inferior_ptid);
6529 if (print_inferior_events)
6530 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6531 inf->num, infpid.c_str ());
6532 }
6533 else
6534 {
6535 switch_to_no_thread ();
6536 detach_inferior (current_inferior ());
6537 }
6538}
6539
6540void
6541remote_target::detach (inferior *inf, int from_tty)
6542{
6543 remote_detach_1 (inf, from_tty);
6544}
6545
6546void
6547extended_remote_target::detach (inferior *inf, int from_tty)
6548{
6549 remote_detach_1 (inf, from_tty);
6550}
6551
6552/* Target follow-fork function for remote targets. On entry, and
6553 at return, the current inferior is the fork parent.
6554
6555 Note that although this is currently only used for extended-remote,
6556 it is named remote_follow_fork in anticipation of using it for the
6557 remote target as well. */
6558
6559void
6560remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6561 target_waitkind fork_kind, bool follow_child,
6562 bool detach_fork)
6563{
6564 process_stratum_target::follow_fork (child_inf, child_ptid,
6565 fork_kind, follow_child, detach_fork);
6566
6567 if ((fork_kind == TARGET_WAITKIND_FORKED
6568 && m_features.remote_fork_event_p ())
6569 || (fork_kind == TARGET_WAITKIND_VFORKED
6570 && m_features.remote_vfork_event_p ()))
6571 {
6572 /* When following the parent and detaching the child, we detach
6573 the child here. For the case of following the child and
6574 detaching the parent, the detach is done in the target-
6575 independent follow fork code in infrun.c. We can't use
6576 target_detach when detaching an unfollowed child because
6577 the client side doesn't know anything about the child. */
6578 if (detach_fork && !follow_child)
6579 {
6580 /* Detach the fork child. */
6581 remote_detach_pid (child_ptid.pid ());
6582 }
6583 }
6584}
6585
6586void
6587remote_target::follow_clone (ptid_t child_ptid)
6588{
6589 remote_add_thread (child_ptid, false, false, false);
6590}
6591
6592/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6593 in the program space of the new inferior. */
6594
6595void
6596remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6597 const char *execd_pathname)
6598{
6599 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6600
6601 /* We know that this is a target file name, so if it has the "target:"
6602 prefix we strip it off before saving it in the program space. */
6603 if (is_target_filename (execd_pathname))
6604 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6605
6606 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6607}
6608
6609/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6610
6611void
6612remote_target::disconnect (const char *args, int from_tty)
6613{
6614 if (args)
6615 error (_("Argument given to \"disconnect\" when remotely debugging."));
6616
6617 /* Make sure we unpush even the extended remote targets. Calling
6618 target_mourn_inferior won't unpush, and
6619 remote_target::mourn_inferior won't unpush if there is more than
6620 one inferior left. */
6621 remote_unpush_target (this);
6622
6623 if (from_tty)
6624 gdb_puts ("Ending remote debugging.\n");
6625}
6626
6627/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6628 be chatty about it. */
6629
6630void
6631extended_remote_target::attach (const char *args, int from_tty)
6632{
6633 struct remote_state *rs = get_remote_state ();
6634 int pid;
6635 char *wait_status = NULL;
6636
6637 pid = parse_pid_to_attach (args);
6638
6639 /* Remote PID can be freely equal to getpid, do not check it here the same
6640 way as in other targets. */
6641
6642 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6643 error (_("This target does not support attaching to a process"));
6644
6645 target_announce_attach (from_tty, pid);
6646
6647 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6648 putpkt (rs->buf);
6649 getpkt (&rs->buf);
6650
6651 packet_result result = m_features.packet_ok (rs->buf, PACKET_vAttach);
6652 switch (result.status ())
6653 {
6654 case PACKET_OK:
6655 if (!target_is_non_stop_p ())
6656 {
6657 /* Save the reply for later. */
6658 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6659 strcpy (wait_status, rs->buf.data ());
6660 }
6661 else if (strcmp (rs->buf.data (), "OK") != 0)
6662 error (_("Attaching to %s failed with: %s"),
6663 target_pid_to_str (ptid_t (pid)).c_str (),
6664 rs->buf.data ());
6665 break;
6666 case PACKET_UNKNOWN:
6667 error (_("This target does not support attaching to a process"));
6668 case PACKET_ERROR:
6669 error (_("Attaching to %s failed: %s"),
6670 target_pid_to_str (ptid_t (pid)).c_str (), result.err_msg ());
6671 }
6672
6673 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6674
6675 inferior_ptid = ptid_t (pid);
6676
6677 if (target_is_non_stop_p ())
6678 {
6679 /* Get list of threads. */
6680 update_thread_list ();
6681
6682 thread_info *thread = first_thread_of_inferior (current_inferior ());
6683 if (thread != nullptr)
6684 switch_to_thread (thread);
6685
6686 /* Invalidate our notion of the remote current thread. */
6687 record_currthread (rs, minus_one_ptid);
6688 }
6689 else
6690 {
6691 /* Now, if we have thread information, update the main thread's
6692 ptid. */
6693 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6694
6695 /* Add the main thread to the thread list. We add the thread
6696 silently in this case (the final true parameter). */
6697 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6698
6699 switch_to_thread (thr);
6700 }
6701
6702 /* Next, if the target can specify a description, read it. We do
6703 this before anything involving memory or registers. */
6704 target_find_description ();
6705
6706 if (!target_is_non_stop_p ())
6707 {
6708 /* Use the previously fetched status. */
6709 gdb_assert (wait_status != NULL);
6710
6711 notif_event_up reply
6712 = remote_notif_parse (this, &notif_client_stop, wait_status);
6713 push_stop_reply (as_stop_reply_up (std::move (reply)));
6714 }
6715 else
6716 {
6717 gdb_assert (wait_status == NULL);
6718
6719 gdb_assert (target_can_async_p ());
6720 }
6721}
6722
6723/* Implementation of the to_post_attach method. */
6724
6725void
6726extended_remote_target::post_attach (int pid)
6727{
6728 /* Get text, data & bss offsets. */
6729 get_offsets ();
6730
6731 /* In certain cases GDB might not have had the chance to start
6732 symbol lookup up until now. This could happen if the debugged
6733 binary is not using shared libraries, the vsyscall page is not
6734 present (on Linux) and the binary itself hadn't changed since the
6735 debugging process was started. */
6736 if (current_program_space->symfile_object_file != NULL)
6737 remote_check_symbols();
6738}
6739
6740\f
6741/* Check for the availability of vCont. This function should also check
6742 the response. */
6743
6744void
6745remote_target::remote_vcont_probe ()
6746{
6747 remote_state *rs = get_remote_state ();
6748 char *buf;
6749
6750 strcpy (rs->buf.data (), "vCont?");
6751 putpkt (rs->buf);
6752 getpkt (&rs->buf);
6753 buf = rs->buf.data ();
6754
6755 /* Make sure that the features we assume are supported. */
6756 if (startswith (buf, "vCont"))
6757 {
6758 char *p = &buf[5];
6759 int support_c, support_C;
6760
6761 rs->supports_vCont.s = 0;
6762 rs->supports_vCont.S = 0;
6763 support_c = 0;
6764 support_C = 0;
6765 rs->supports_vCont.t = 0;
6766 rs->supports_vCont.r = 0;
6767 while (p && *p == ';')
6768 {
6769 p++;
6770 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6771 rs->supports_vCont.s = 1;
6772 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6773 rs->supports_vCont.S = 1;
6774 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6775 support_c = 1;
6776 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6777 support_C = 1;
6778 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6779 rs->supports_vCont.t = 1;
6780 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6781 rs->supports_vCont.r = 1;
6782
6783 p = strchr (p, ';');
6784 }
6785
6786 /* If c, and C are not all supported, we can't use vCont. Clearing
6787 BUF will make packet_ok disable the packet. */
6788 if (!support_c || !support_C)
6789 buf[0] = 0;
6790 }
6791
6792 m_features.packet_ok (rs->buf, PACKET_vCont);
6793}
6794
6795/* Helper function for building "vCont" resumptions. Write a
6796 resumption to P. ENDP points to one-passed-the-end of the buffer
6797 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6798 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6799 resumed thread should be single-stepped and/or signalled. If PTID
6800 equals minus_one_ptid, then all threads are resumed; if PTID
6801 represents a process, then all threads of the process are
6802 resumed. */
6803
6804char *
6805remote_target::append_resumption (char *p, char *endp,
6806 ptid_t ptid, int step, gdb_signal siggnal)
6807{
6808 struct remote_state *rs = get_remote_state ();
6809
6810 if (step && siggnal != GDB_SIGNAL_0)
6811 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6812 else if (step
6813 /* GDB is willing to range step. */
6814 && use_range_stepping
6815 /* Target supports range stepping. */
6816 && rs->supports_vCont.r
6817 /* We don't currently support range stepping multiple
6818 threads with a wildcard (though the protocol allows it,
6819 so stubs shouldn't make an active effort to forbid
6820 it). */
6821 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6822 {
6823 struct thread_info *tp;
6824
6825 if (ptid == minus_one_ptid)
6826 {
6827 /* If we don't know about the target thread's tid, then
6828 we're resuming magic_null_ptid (see caller). */
6829 tp = this->find_thread (magic_null_ptid);
6830 }
6831 else
6832 tp = this->find_thread (ptid);
6833 gdb_assert (tp != NULL);
6834
6835 if (tp->control.may_range_step)
6836 {
6837 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6838
6839 p += xsnprintf (p, endp - p, ";r%s,%s",
6840 phex_nz (tp->control.step_range_start,
6841 addr_size),
6842 phex_nz (tp->control.step_range_end,
6843 addr_size));
6844 }
6845 else
6846 p += xsnprintf (p, endp - p, ";s");
6847 }
6848 else if (step)
6849 p += xsnprintf (p, endp - p, ";s");
6850 else if (siggnal != GDB_SIGNAL_0)
6851 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6852 else
6853 p += xsnprintf (p, endp - p, ";c");
6854
6855 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6856 {
6857 ptid_t nptid;
6858
6859 /* All (-1) threads of process. */
6860 nptid = ptid_t (ptid.pid (), -1);
6861
6862 p += xsnprintf (p, endp - p, ":");
6863 p = write_ptid (p, endp, nptid);
6864 }
6865 else if (ptid != minus_one_ptid)
6866 {
6867 p += xsnprintf (p, endp - p, ":");
6868 p = write_ptid (p, endp, ptid);
6869 }
6870
6871 return p;
6872}
6873
6874/* Clear the thread's private info on resume. */
6875
6876static void
6877resume_clear_thread_private_info (struct thread_info *thread)
6878{
6879 if (thread->priv != NULL)
6880 {
6881 remote_thread_info *priv = get_remote_thread_info (thread);
6882
6883 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6884 priv->watch_data_address = 0;
6885 }
6886}
6887
6888/* Append a vCont continue-with-signal action for threads that have a
6889 non-zero stop signal. */
6890
6891char *
6892remote_target::append_pending_thread_resumptions (char *p, char *endp,
6893 ptid_t ptid)
6894{
6895 for (thread_info *thread : all_non_exited_threads (this, ptid))
6896 if (inferior_ptid != thread->ptid
6897 && thread->stop_signal () != GDB_SIGNAL_0)
6898 {
6899 p = append_resumption (p, endp, thread->ptid,
6900 0, thread->stop_signal ());
6901 thread->set_stop_signal (GDB_SIGNAL_0);
6902 resume_clear_thread_private_info (thread);
6903 }
6904
6905 return p;
6906}
6907
6908/* Set the target running, using the packets that use Hc
6909 (c/s/C/S). */
6910
6911void
6912remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6913 gdb_signal siggnal)
6914{
6915 struct remote_state *rs = get_remote_state ();
6916 char *buf;
6917
6918 rs->last_sent_signal = siggnal;
6919 rs->last_sent_step = step;
6920
6921 /* The c/s/C/S resume packets use Hc, so set the continue
6922 thread. */
6923 if (ptid == minus_one_ptid)
6924 set_continue_thread (any_thread_ptid);
6925 else
6926 set_continue_thread (ptid);
6927
6928 for (thread_info *thread : all_non_exited_threads (this))
6929 resume_clear_thread_private_info (thread);
6930
6931 buf = rs->buf.data ();
6932 if (::execution_direction == EXEC_REVERSE)
6933 {
6934 /* We don't pass signals to the target in reverse exec mode. */
6935 if (info_verbose && siggnal != GDB_SIGNAL_0)
6936 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6937 siggnal);
6938
6939 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6940 error (_("Remote reverse-step not supported."));
6941 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6942 error (_("Remote reverse-continue not supported."));
6943
6944 strcpy (buf, step ? "bs" : "bc");
6945 }
6946 else if (siggnal != GDB_SIGNAL_0)
6947 {
6948 buf[0] = step ? 'S' : 'C';
6949 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6950 buf[2] = tohex (((int) siggnal) & 0xf);
6951 buf[3] = '\0';
6952 }
6953 else
6954 strcpy (buf, step ? "s" : "c");
6955
6956 putpkt (buf);
6957}
6958
6959/* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6960 STEP, and SIGGNAL have the same meaning as in target_resume. This
6961 function returns non-zero iff it resumes the inferior.
6962
6963 This function issues a strict subset of all possible vCont commands
6964 at the moment. */
6965
6966int
6967remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6968 enum gdb_signal siggnal)
6969{
6970 struct remote_state *rs = get_remote_state ();
6971 char *p;
6972 char *endp;
6973
6974 /* No reverse execution actions defined for vCont. */
6975 if (::execution_direction == EXEC_REVERSE)
6976 return 0;
6977
6978 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6979 return 0;
6980
6981 p = rs->buf.data ();
6982 endp = p + get_remote_packet_size ();
6983
6984 /* If we could generate a wider range of packets, we'd have to worry
6985 about overflowing BUF. Should there be a generic
6986 "multi-part-packet" packet? */
6987
6988 p += xsnprintf (p, endp - p, "vCont");
6989
6990 if (scope_ptid == magic_null_ptid)
6991 {
6992 /* MAGIC_NULL_PTID means that we don't have any active threads,
6993 so we don't have any TID numbers the inferior will
6994 understand. Make sure to only send forms that do not specify
6995 a TID. */
6996 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6997 }
6998 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6999 {
7000 /* Resume all threads (of all processes, or of a single
7001 process), with preference for INFERIOR_PTID. This assumes
7002 inferior_ptid belongs to the set of all threads we are about
7003 to resume. */
7004 if (step || siggnal != GDB_SIGNAL_0)
7005 {
7006 /* Step inferior_ptid, with or without signal. */
7007 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
7008 }
7009
7010 /* Also pass down any pending signaled resumption for other
7011 threads not the current. */
7012 p = append_pending_thread_resumptions (p, endp, scope_ptid);
7013
7014 /* And continue others without a signal. */
7015 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
7016 }
7017 else
7018 {
7019 /* Scheduler locking; resume only SCOPE_PTID. */
7020 append_resumption (p, endp, scope_ptid, step, siggnal);
7021 }
7022
7023 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
7024 putpkt (rs->buf);
7025
7026 if (target_is_non_stop_p ())
7027 {
7028 /* In non-stop, the stub replies to vCont with "OK". The stop
7029 reply will be reported asynchronously by means of a `%Stop'
7030 notification. */
7031 getpkt (&rs->buf);
7032 if (strcmp (rs->buf.data (), "OK") != 0)
7033 error (_("Unexpected vCont reply in non-stop mode: %s"),
7034 rs->buf.data ());
7035 }
7036
7037 return 1;
7038}
7039
7040/* Tell the remote machine to resume. */
7041
7042void
7043remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
7044{
7045 struct remote_state *rs = get_remote_state ();
7046
7047 /* When connected in non-stop mode, the core resumes threads
7048 individually. Resuming remote threads directly in target_resume
7049 would thus result in sending one packet per thread. Instead, to
7050 minimize roundtrip latency, here we just store the resume
7051 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
7052 resumption will be done in remote_target::commit_resume, where we'll be
7053 able to do vCont action coalescing. */
7054 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
7055 {
7056 remote_thread_info *remote_thr
7057 = get_remote_thread_info (inferior_thread ());
7058
7059 /* We don't expect the core to ask to resume an already resumed (from
7060 its point of view) thread. */
7061 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
7062
7063 remote_thr->set_resumed_pending_vcont (step, siggnal);
7064
7065 /* There's actually nothing that says that the core can't
7066 request a wildcard resume in non-stop mode, though. It's
7067 just that we know it doesn't currently, so we don't bother
7068 with it. */
7069 gdb_assert (scope_ptid == inferior_ptid);
7070 return;
7071 }
7072
7073 commit_requested_thread_options ();
7074
7075 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
7076 (explained in remote-notif.c:handle_notification) so
7077 remote_notif_process is not called. We need find a place where
7078 it is safe to start a 'vNotif' sequence. It is good to do it
7079 before resuming inferior, because inferior was stopped and no RSP
7080 traffic at that moment. */
7081 if (!target_is_non_stop_p ())
7082 remote_notif_process (rs->notif_state, &notif_client_stop);
7083
7084 rs->last_resume_exec_dir = ::execution_direction;
7085
7086 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
7087 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
7088 remote_resume_with_hc (scope_ptid, step, siggnal);
7089
7090 /* Update resumed state tracked by the remote target. */
7091 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
7092 get_remote_thread_info (tp)->set_resumed ();
7093
7094 /* We've just told the target to resume. The remote server will
7095 wait for the inferior to stop, and then send a stop reply. In
7096 the mean time, we can't start another command/query ourselves
7097 because the stub wouldn't be ready to process it. This applies
7098 only to the base all-stop protocol, however. In non-stop (which
7099 only supports vCont), the stub replies with an "OK", and is
7100 immediate able to process further serial input. */
7101 if (!target_is_non_stop_p ())
7102 rs->waiting_for_stop_reply = 1;
7103}
7104
7105/* Private per-inferior info for target remote processes. */
7106
7107struct remote_inferior : public private_inferior
7108{
7109 /* Whether we can send a wildcard vCont for this process. */
7110 bool may_wildcard_vcont = true;
7111};
7112
7113/* Get the remote private inferior data associated to INF. */
7114
7115static remote_inferior *
7116get_remote_inferior (inferior *inf)
7117{
7118 if (inf->priv == NULL)
7119 inf->priv = std::make_unique<remote_inferior> ();
7120
7121 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
7122}
7123
7124/* Class used to track the construction of a vCont packet in the
7125 outgoing packet buffer. This is used to send multiple vCont
7126 packets if we have more actions than would fit a single packet. */
7127
7128class vcont_builder
7129{
7130public:
7131 explicit vcont_builder (remote_target *remote)
7132 : m_remote (remote)
7133 {
7134 restart ();
7135 }
7136
7137 void flush ();
7138 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
7139
7140private:
7141 void restart ();
7142
7143 /* The remote target. */
7144 remote_target *m_remote;
7145
7146 /* Pointer to the first action. P points here if no action has been
7147 appended yet. */
7148 char *m_first_action;
7149
7150 /* Where the next action will be appended. */
7151 char *m_p;
7152
7153 /* The end of the buffer. Must never write past this. */
7154 char *m_endp;
7155};
7156
7157/* Prepare the outgoing buffer for a new vCont packet. */
7158
7159void
7160vcont_builder::restart ()
7161{
7162 struct remote_state *rs = m_remote->get_remote_state ();
7163
7164 m_p = rs->buf.data ();
7165 m_endp = m_p + m_remote->get_remote_packet_size ();
7166 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7167 m_first_action = m_p;
7168}
7169
7170/* If the vCont packet being built has any action, send it to the
7171 remote end. */
7172
7173void
7174vcont_builder::flush ()
7175{
7176 struct remote_state *rs;
7177
7178 if (m_p == m_first_action)
7179 return;
7180
7181 rs = m_remote->get_remote_state ();
7182 m_remote->putpkt (rs->buf);
7183 m_remote->getpkt (&rs->buf);
7184 if (strcmp (rs->buf.data (), "OK") != 0)
7185 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7186}
7187
7188/* The largest action is range-stepping, with its two addresses. This
7189 is more than sufficient. If a new, bigger action is created, it'll
7190 quickly trigger a failed assertion in append_resumption (and we'll
7191 just bump this). */
7192#define MAX_ACTION_SIZE 200
7193
7194/* Append a new vCont action in the outgoing packet being built. If
7195 the action doesn't fit the packet along with previous actions, push
7196 what we've got so far to the remote end and start over a new vCont
7197 packet (with the new action). */
7198
7199void
7200vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7201{
7202 char buf[MAX_ACTION_SIZE + 1];
7203
7204 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7205 ptid, step, siggnal);
7206
7207 /* Check whether this new action would fit in the vCont packet along
7208 with previous actions. If not, send what we've got so far and
7209 start a new vCont packet. */
7210 size_t rsize = endp - buf;
7211 if (rsize > m_endp - m_p)
7212 {
7213 flush ();
7214 restart ();
7215
7216 /* Should now fit. */
7217 gdb_assert (rsize <= m_endp - m_p);
7218 }
7219
7220 memcpy (m_p, buf, rsize);
7221 m_p += rsize;
7222 *m_p = '\0';
7223}
7224
7225/* to_commit_resume implementation. */
7226
7227void
7228remote_target::commit_resumed ()
7229{
7230 /* If connected in all-stop mode, we'd send the remote resume
7231 request directly from remote_resume. Likewise if
7232 reverse-debugging, as there are no defined vCont actions for
7233 reverse execution. */
7234 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7235 return;
7236
7237 commit_requested_thread_options ();
7238
7239 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7240 instead of resuming all threads of each process individually.
7241 However, if any thread of a process must remain halted, we can't
7242 send wildcard resumes and must send one action per thread.
7243
7244 Care must be taken to not resume threads/processes the server
7245 side already told us are stopped, but the core doesn't know about
7246 yet, because the events are still in the vStopped notification
7247 queue. For example:
7248
7249 #1 => vCont s:p1.1;c
7250 #2 <= OK
7251 #3 <= %Stopped T05 p1.1
7252 #4 => vStopped
7253 #5 <= T05 p1.2
7254 #6 => vStopped
7255 #7 <= OK
7256 #8 (infrun handles the stop for p1.1 and continues stepping)
7257 #9 => vCont s:p1.1;c
7258
7259 The last vCont above would resume thread p1.2 by mistake, because
7260 the server has no idea that the event for p1.2 had not been
7261 handled yet.
7262
7263 The server side must similarly ignore resume actions for the
7264 thread that has a pending %Stopped notification (and any other
7265 threads with events pending), until GDB acks the notification
7266 with vStopped. Otherwise, e.g., the following case is
7267 mishandled:
7268
7269 #1 => g (or any other packet)
7270 #2 <= [registers]
7271 #3 <= %Stopped T05 p1.2
7272 #4 => vCont s:p1.1;c
7273 #5 <= OK
7274
7275 Above, the server must not resume thread p1.2. GDB can't know
7276 that p1.2 stopped until it acks the %Stopped notification, and
7277 since from GDB's perspective all threads should be running, it
7278 sends a "c" action.
7279
7280 Finally, special care must also be given to handling fork/vfork
7281 events. A (v)fork event actually tells us that two processes
7282 stopped -- the parent and the child. Until we follow the fork,
7283 we must not resume the child. Therefore, if we have a pending
7284 fork follow, we must not send a global wildcard resume action
7285 (vCont;c). We can still send process-wide wildcards though. */
7286
7287 /* Start by assuming a global wildcard (vCont;c) is possible. */
7288 bool may_global_wildcard_vcont = true;
7289
7290 /* And assume every process is individually wildcard-able too. */
7291 for (inferior *inf : all_non_exited_inferiors (this))
7292 {
7293 remote_inferior *priv = get_remote_inferior (inf);
7294
7295 priv->may_wildcard_vcont = true;
7296 }
7297
7298 /* Check for any pending events (not reported or processed yet) and
7299 disable process and global wildcard resumes appropriately. */
7300 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7301
7302 bool any_pending_vcont_resume = false;
7303
7304 for (thread_info *tp : all_non_exited_threads (this))
7305 {
7306 remote_thread_info *priv = get_remote_thread_info (tp);
7307
7308 /* If a thread of a process is not meant to be resumed, then we
7309 can't wildcard that process. */
7310 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7311 {
7312 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7313
7314 /* And if we can't wildcard a process, we can't wildcard
7315 everything either. */
7316 may_global_wildcard_vcont = false;
7317 continue;
7318 }
7319
7320 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7321 any_pending_vcont_resume = true;
7322
7323 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7324 then we can't do a global wildcard, as that would resume the
7325 pending child. */
7326 if (thread_pending_child_status (tp) != nullptr)
7327 may_global_wildcard_vcont = false;
7328 }
7329
7330 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7331 do. */
7332 if (!any_pending_vcont_resume)
7333 return;
7334
7335 /* Now let's build the vCont packet(s). Actions must be appended
7336 from narrower to wider scopes (thread -> process -> global). If
7337 we end up with too many actions for a single packet vcont_builder
7338 flushes the current vCont packet to the remote side and starts a
7339 new one. */
7340 struct vcont_builder vcont_builder (this);
7341
7342 /* Threads first. */
7343 for (thread_info *tp : all_non_exited_threads (this))
7344 {
7345 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7346
7347 /* If the thread was previously vCont-resumed, no need to send a specific
7348 action for it. If we didn't receive a resume request for it, don't
7349 send an action for it either. */
7350 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7351 continue;
7352
7353 gdb_assert (!thread_is_in_step_over_chain (tp));
7354
7355 /* We should never be commit-resuming a thread that has a stop reply.
7356 Otherwise, we would end up reporting a stop event for a thread while
7357 it is running on the remote target. */
7358 remote_state *rs = get_remote_state ();
7359 for (const auto &stop_reply : rs->stop_reply_queue)
7360 gdb_assert (stop_reply->ptid != tp->ptid);
7361
7362 const resumed_pending_vcont_info &info
7363 = remote_thr->resumed_pending_vcont_info ();
7364
7365 /* Check if we need to send a specific action for this thread. If not,
7366 it will be included in a wildcard resume instead. */
7367 if (info.step || info.sig != GDB_SIGNAL_0
7368 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7369 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7370
7371 remote_thr->set_resumed ();
7372 }
7373
7374 /* Now check whether we can send any process-wide wildcard. This is
7375 to avoid sending a global wildcard in the case nothing is
7376 supposed to be resumed. */
7377 bool any_process_wildcard = false;
7378
7379 for (inferior *inf : all_non_exited_inferiors (this))
7380 {
7381 if (get_remote_inferior (inf)->may_wildcard_vcont)
7382 {
7383 any_process_wildcard = true;
7384 break;
7385 }
7386 }
7387
7388 if (any_process_wildcard)
7389 {
7390 /* If all processes are wildcard-able, then send a single "c"
7391 action, otherwise, send an "all (-1) threads of process"
7392 continue action for each running process, if any. */
7393 if (may_global_wildcard_vcont)
7394 {
7395 vcont_builder.push_action (minus_one_ptid,
7396 false, GDB_SIGNAL_0);
7397 }
7398 else
7399 {
7400 for (inferior *inf : all_non_exited_inferiors (this))
7401 {
7402 if (get_remote_inferior (inf)->may_wildcard_vcont)
7403 {
7404 vcont_builder.push_action (ptid_t (inf->pid),
7405 false, GDB_SIGNAL_0);
7406 }
7407 }
7408 }
7409 }
7410
7411 vcont_builder.flush ();
7412}
7413
7414/* Implementation of target_has_pending_events. */
7415
7416bool
7417remote_target::has_pending_events ()
7418{
7419 if (target_can_async_p ())
7420 {
7421 remote_state *rs = get_remote_state ();
7422
7423 if (rs->async_event_handler_marked ())
7424 return true;
7425
7426 /* Note that BUFCNT can be negative, indicating sticky
7427 error. */
7428 if (rs->remote_desc->bufcnt != 0)
7429 return true;
7430 }
7431 return false;
7432}
7433
7434\f
7435
7436/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7437 thread, all threads of a remote process, or all threads of all
7438 processes. */
7439
7440void
7441remote_target::remote_stop_ns (ptid_t ptid)
7442{
7443 struct remote_state *rs = get_remote_state ();
7444 char *p = rs->buf.data ();
7445 char *endp = p + get_remote_packet_size ();
7446
7447 /* If any thread that needs to stop was resumed but pending a vCont
7448 resume, generate a phony stop_reply. However, first check
7449 whether the thread wasn't resumed with a signal. Generating a
7450 phony stop in that case would result in losing the signal. */
7451 bool needs_commit = false;
7452 for (thread_info *tp : all_non_exited_threads (this, ptid))
7453 {
7454 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7455
7456 if (remote_thr->get_resume_state ()
7457 == resume_state::RESUMED_PENDING_VCONT)
7458 {
7459 const resumed_pending_vcont_info &info
7460 = remote_thr->resumed_pending_vcont_info ();
7461 if (info.sig != GDB_SIGNAL_0)
7462 {
7463 /* This signal must be forwarded to the inferior. We
7464 could commit-resume just this thread, but its simpler
7465 to just commit-resume everything. */
7466 needs_commit = true;
7467 break;
7468 }
7469 }
7470 }
7471
7472 if (needs_commit)
7473 commit_resumed ();
7474 else
7475 for (thread_info *tp : all_non_exited_threads (this, ptid))
7476 {
7477 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7478
7479 if (remote_thr->get_resume_state ()
7480 == resume_state::RESUMED_PENDING_VCONT)
7481 {
7482 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7483 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7484 tp->ptid.lwp (),
7485 pulongest (tp->ptid.tid ()));
7486
7487 /* Check that the thread wasn't resumed with a signal.
7488 Generating a phony stop would result in losing the
7489 signal. */
7490 const resumed_pending_vcont_info &info
7491 = remote_thr->resumed_pending_vcont_info ();
7492 gdb_assert (info.sig == GDB_SIGNAL_0);
7493
7494 stop_reply_up sr = std::make_unique<stop_reply> ();
7495 sr->ptid = tp->ptid;
7496 sr->rs = rs;
7497 sr->ws.set_stopped (GDB_SIGNAL_0);
7498 sr->arch = tp->inf->arch ();
7499 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7500 sr->watch_data_address = 0;
7501 sr->core = 0;
7502 this->push_stop_reply (std::move (sr));
7503
7504 /* Pretend that this thread was actually resumed on the
7505 remote target, then stopped. If we leave it in the
7506 RESUMED_PENDING_VCONT state and the commit_resumed
7507 method is called while the stop reply is still in the
7508 queue, we'll end up reporting a stop event to the core
7509 for that thread while it is running on the remote
7510 target... that would be bad. */
7511 remote_thr->set_resumed ();
7512 }
7513 }
7514
7515 if (!rs->supports_vCont.t)
7516 error (_("Remote server does not support stopping threads"));
7517
7518 if (ptid == minus_one_ptid
7519 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7520 p += xsnprintf (p, endp - p, "vCont;t");
7521 else
7522 {
7523 ptid_t nptid;
7524
7525 p += xsnprintf (p, endp - p, "vCont;t:");
7526
7527 if (ptid.is_pid ())
7528 /* All (-1) threads of process. */
7529 nptid = ptid_t (ptid.pid (), -1);
7530 else
7531 {
7532 /* Small optimization: if we already have a stop reply for
7533 this thread, no use in telling the stub we want this
7534 stopped. */
7535 if (peek_stop_reply (ptid))
7536 return;
7537
7538 nptid = ptid;
7539 }
7540
7541 write_ptid (p, endp, nptid);
7542 }
7543
7544 /* In non-stop, we get an immediate OK reply. The stop reply will
7545 come in asynchronously by notification. */
7546 putpkt (rs->buf);
7547 getpkt (&rs->buf);
7548 if (strcmp (rs->buf.data (), "OK") != 0)
7549 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7550 rs->buf.data ());
7551}
7552
7553/* All-stop version of target_interrupt. Sends a break or a ^C to
7554 interrupt the remote target. It is undefined which thread of which
7555 process reports the interrupt. */
7556
7557void
7558remote_target::remote_interrupt_as ()
7559{
7560 struct remote_state *rs = get_remote_state ();
7561
7562 rs->ctrlc_pending_p = 1;
7563
7564 /* If the inferior is stopped already, but the core didn't know
7565 about it yet, just ignore the request. The pending stop events
7566 will be collected in remote_wait. */
7567 if (stop_reply_queue_length () > 0)
7568 return;
7569
7570 /* Send interrupt_sequence to remote target. */
7571 send_interrupt_sequence ();
7572}
7573
7574/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7575 the remote target. It is undefined which thread of which process
7576 reports the interrupt. Throws an error if the packet is not
7577 supported by the server. */
7578
7579void
7580remote_target::remote_interrupt_ns ()
7581{
7582 struct remote_state *rs = get_remote_state ();
7583 char *p = rs->buf.data ();
7584 char *endp = p + get_remote_packet_size ();
7585
7586 xsnprintf (p, endp - p, "vCtrlC");
7587
7588 /* In non-stop, we get an immediate OK reply. The stop reply will
7589 come in asynchronously by notification. */
7590 putpkt (rs->buf);
7591 getpkt (&rs->buf);
7592
7593 packet_result result = m_features.packet_ok (rs->buf, PACKET_vCtrlC);
7594 switch (result.status ())
7595 {
7596 case PACKET_OK:
7597 break;
7598 case PACKET_UNKNOWN:
7599 error (_("No support for interrupting the remote target."));
7600 case PACKET_ERROR:
7601 error (_("Interrupting target failed: %s"), result.err_msg ());
7602 }
7603}
7604
7605/* Implement the to_stop function for the remote targets. */
7606
7607void
7608remote_target::stop (ptid_t ptid)
7609{
7610 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7611
7612 if (target_is_non_stop_p ())
7613 remote_stop_ns (ptid);
7614 else
7615 {
7616 /* We don't currently have a way to transparently pause the
7617 remote target in all-stop mode. Interrupt it instead. */
7618 remote_interrupt_as ();
7619 }
7620}
7621
7622/* Implement the to_interrupt function for the remote targets. */
7623
7624void
7625remote_target::interrupt ()
7626{
7627 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7628
7629 if (target_is_non_stop_p ())
7630 remote_interrupt_ns ();
7631 else
7632 remote_interrupt_as ();
7633}
7634
7635/* Implement the to_pass_ctrlc function for the remote targets. */
7636
7637void
7638remote_target::pass_ctrlc ()
7639{
7640 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7641
7642 struct remote_state *rs = get_remote_state ();
7643
7644 /* If we're starting up, we're not fully synced yet. Quit
7645 immediately. */
7646 if (rs->starting_up)
7647 quit ();
7648 /* If ^C has already been sent once, offer to disconnect. */
7649 else if (rs->ctrlc_pending_p)
7650 interrupt_query ();
7651 else
7652 target_interrupt ();
7653}
7654
7655/* Ask the user what to do when an interrupt is received. */
7656
7657void
7658remote_target::interrupt_query ()
7659{
7660 struct remote_state *rs = get_remote_state ();
7661
7662 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7663 {
7664 if (query (_("The target is not responding to interrupt requests.\n"
7665 "Stop debugging it? ")))
7666 {
7667 remote_unpush_target (this);
7668 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7669 }
7670 }
7671 else
7672 {
7673 if (query (_("Interrupted while waiting for the program.\n"
7674 "Give up waiting? ")))
7675 quit ();
7676 }
7677}
7678
7679/* Enable/disable target terminal ownership. Most targets can use
7680 terminal groups to control terminal ownership. Remote targets are
7681 different in that explicit transfer of ownership to/from GDB/target
7682 is required. */
7683
7684void
7685remote_target::terminal_inferior ()
7686{
7687 /* NOTE: At this point we could also register our selves as the
7688 recipient of all input. Any characters typed could then be
7689 passed on down to the target. */
7690}
7691
7692void
7693remote_target::terminal_ours ()
7694{
7695}
7696
7697static void
7698remote_console_output (const char *msg, ui_file *stream)
7699{
7700 const char *p;
7701
7702 for (p = msg; p[0] && p[1]; p += 2)
7703 {
7704 char tb[2];
7705 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7706
7707 tb[0] = c;
7708 tb[1] = 0;
7709 stream->puts (tb);
7710 }
7711 stream->flush ();
7712}
7713
7714/* Return the length of the stop reply queue. */
7715
7716int
7717remote_target::stop_reply_queue_length ()
7718{
7719 remote_state *rs = get_remote_state ();
7720 return rs->stop_reply_queue.size ();
7721}
7722
7723static void
7724remote_notif_stop_parse (remote_target *remote,
7725 const notif_client *self, const char *buf,
7726 struct notif_event *event)
7727{
7728 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7729}
7730
7731static void
7732remote_notif_stop_ack (remote_target *remote,
7733 const notif_client *self, const char *buf,
7734 notif_event_up event)
7735{
7736 stop_reply_up stop_reply = as_stop_reply_up (std::move (event));
7737
7738 /* acknowledge */
7739 putpkt (remote, self->ack_command);
7740
7741 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7742 the notification. It was left in the queue because we need to
7743 acknowledge it and pull the rest of the notifications out. */
7744 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7745 remote->push_stop_reply (std::move (stop_reply));
7746}
7747
7748static int
7749remote_notif_stop_can_get_pending_events (remote_target *remote,
7750 const notif_client *self)
7751{
7752 /* We can't get pending events in remote_notif_process for
7753 notification stop, and we have to do this in remote_wait_ns
7754 instead. If we fetch all queued events from stub, remote stub
7755 may exit and we have no chance to process them back in
7756 remote_wait_ns. */
7757 remote_state *rs = remote->get_remote_state ();
7758 rs->mark_async_event_handler ();
7759 return 0;
7760}
7761
7762static notif_event_up
7763remote_notif_stop_alloc_reply ()
7764{
7765 return notif_event_up (new struct stop_reply ());
7766}
7767
7768/* A client of notification Stop. */
7769
7770const notif_client notif_client_stop =
7771{
7772 "Stop",
7773 "vStopped",
7774 remote_notif_stop_parse,
7775 remote_notif_stop_ack,
7776 remote_notif_stop_can_get_pending_events,
7777 remote_notif_stop_alloc_reply,
7778 REMOTE_NOTIF_STOP,
7779};
7780
7781/* If CONTEXT contains any fork/vfork/clone child threads that have
7782 not been reported yet, remove them from the CONTEXT list. If such
7783 a thread exists it is because we are stopped at a fork/vfork/clone
7784 catchpoint and have not yet called follow_fork/follow_clone, which
7785 will set up the host-side data structures for the new child. */
7786
7787void
7788remote_target::remove_new_children (threads_listing_context *context)
7789{
7790 const notif_client *notif = &notif_client_stop;
7791
7792 /* For any threads stopped at a (v)fork/clone event, remove the
7793 corresponding child threads from the CONTEXT list. */
7794 for (thread_info *thread : all_non_exited_threads (this))
7795 {
7796 const target_waitstatus *ws = thread_pending_child_status (thread);
7797
7798 if (ws == nullptr)
7799 continue;
7800
7801 context->remove_thread (ws->child_ptid ());
7802 }
7803
7804 /* Check for any pending (v)fork/clone events (not reported or
7805 processed yet) in process PID and remove those child threads from
7806 the CONTEXT list as well. */
7807 remote_notif_get_pending_events (notif);
7808 for (auto &event : get_remote_state ()->stop_reply_queue)
7809 if (is_new_child_status (event->ws.kind ()))
7810 context->remove_thread (event->ws.child_ptid ());
7811 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7812 context->remove_thread (event->ptid);
7813}
7814
7815/* Check whether any event pending in the vStopped queue would prevent a
7816 global or process wildcard vCont action. Set *may_global_wildcard to
7817 false if we can't do a global wildcard (vCont;c), and clear the event
7818 inferior's may_wildcard_vcont flag if we can't do a process-wide
7819 wildcard resume (vCont;c:pPID.-1). */
7820
7821void
7822remote_target::check_pending_events_prevent_wildcard_vcont
7823 (bool *may_global_wildcard)
7824{
7825 const notif_client *notif = &notif_client_stop;
7826
7827 remote_notif_get_pending_events (notif);
7828 for (auto &event : get_remote_state ()->stop_reply_queue)
7829 {
7830 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7831 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7832 continue;
7833
7834 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7835 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7836 *may_global_wildcard = false;
7837
7838 /* This may be the first time we heard about this process.
7839 Regardless, we must not do a global wildcard resume, otherwise
7840 we'd resume this process too. */
7841 *may_global_wildcard = false;
7842 if (event->ptid != null_ptid)
7843 {
7844 inferior *inf = find_inferior_ptid (this, event->ptid);
7845 if (inf != NULL)
7846 get_remote_inferior (inf)->may_wildcard_vcont = false;
7847 }
7848 }
7849}
7850
7851/* Discard all pending stop replies of inferior INF. */
7852
7853void
7854remote_target::discard_pending_stop_replies (struct inferior *inf)
7855{
7856 struct remote_state *rs = get_remote_state ();
7857 struct remote_notif_state *rns = rs->notif_state;
7858
7859 /* This function can be notified when an inferior exists. When the
7860 target is not remote, the notification state is NULL. */
7861 if (rs->remote_desc == NULL)
7862 return;
7863
7864 struct notif_event *notif_event
7865 = rns->pending_event[notif_client_stop.id].get ();
7866 auto *reply = static_cast<stop_reply *> (notif_event);
7867
7868 /* Discard the in-flight notification. */
7869 if (reply != NULL && reply->ptid.pid () == inf->pid)
7870 {
7871 /* Leave the notification pending, since the server expects that
7872 we acknowledge it with vStopped. But clear its contents, so
7873 that later on when we acknowledge it, we also discard it. */
7874 remote_debug_printf
7875 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7876 reply->ptid.to_string().c_str(),
7877 reply->ws.to_string ().c_str ());
7878 reply->ws.set_ignore ();
7879 }
7880
7881 /* Discard the stop replies we have already pulled with
7882 vStopped. */
7883 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7884 rs->stop_reply_queue.end (),
7885 [=] (const stop_reply_up &event)
7886 {
7887 return event->ptid.pid () == inf->pid;
7888 });
7889 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7890 remote_debug_printf
7891 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7892 (*it)->ptid.to_string().c_str(),
7893 (*it)->ws.to_string ().c_str ());
7894 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7895}
7896
7897/* Discard the stop replies for RS in stop_reply_queue. */
7898
7899void
7900remote_target::discard_pending_stop_replies_in_queue ()
7901{
7902 remote_state *rs = get_remote_state ();
7903
7904 /* Discard the stop replies we have already pulled with
7905 vStopped. */
7906 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7907 rs->stop_reply_queue.end (),
7908 [=] (const stop_reply_up &event)
7909 {
7910 return event->rs == rs;
7911 });
7912 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7913}
7914
7915/* Remove the first reply in 'stop_reply_queue' which matches
7916 PTID. */
7917
7918stop_reply_up
7919remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7920{
7921 remote_state *rs = get_remote_state ();
7922
7923 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7924 rs->stop_reply_queue.end (),
7925 [=] (const stop_reply_up &event)
7926 {
7927 return event->ptid.matches (ptid);
7928 });
7929 stop_reply_up result;
7930 if (iter != rs->stop_reply_queue.end ())
7931 {
7932 result = std::move (*iter);
7933 rs->stop_reply_queue.erase (iter);
7934 }
7935
7936 if (notif_debug)
7937 gdb_printf (gdb_stdlog,
7938 "notif: discard queued event: 'Stop' in %s\n",
7939 ptid.to_string ().c_str ());
7940
7941 return result;
7942}
7943
7944/* Look for a queued stop reply belonging to PTID. If one is found,
7945 remove it from the queue, and return it. Returns NULL if none is
7946 found. If there are still queued events left to process, tell the
7947 event loop to get back to target_wait soon. */
7948
7949stop_reply_up
7950remote_target::queued_stop_reply (ptid_t ptid)
7951{
7952 remote_state *rs = get_remote_state ();
7953 stop_reply_up r = remote_notif_remove_queued_reply (ptid);
7954
7955 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7956 {
7957 /* There's still at least an event left. */
7958 rs->mark_async_event_handler ();
7959 }
7960
7961 return r;
7962}
7963
7964/* Push a fully parsed stop reply in the stop reply queue. Since we
7965 know that we now have at least one queued event left to pass to the
7966 core side, tell the event loop to get back to target_wait soon. */
7967
7968void
7969remote_target::push_stop_reply (stop_reply_up new_event)
7970{
7971 remote_state *rs = get_remote_state ();
7972 rs->stop_reply_queue.push_back (std::move (new_event));
7973
7974 if (notif_debug)
7975 gdb_printf (gdb_stdlog,
7976 "notif: push 'Stop' %s to queue %d\n",
7977 new_event->ptid.to_string ().c_str (),
7978 int (rs->stop_reply_queue.size ()));
7979
7980 /* Mark the pending event queue only if async mode is currently enabled.
7981 If async mode is not currently enabled, then, if it later becomes
7982 enabled, and there are events in this queue, we will mark the event
7983 token at that point, see remote_target::async. */
7984 if (target_is_async_p ())
7985 rs->mark_async_event_handler ();
7986}
7987
7988/* Returns true if we have a stop reply for PTID. */
7989
7990int
7991remote_target::peek_stop_reply (ptid_t ptid)
7992{
7993 remote_state *rs = get_remote_state ();
7994 for (auto &event : rs->stop_reply_queue)
7995 if (ptid == event->ptid
7996 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7997 return 1;
7998 return 0;
7999}
8000
8001/* Helper for remote_parse_stop_reply. Return nonzero if the substring
8002 starting with P and ending with PEND matches PREFIX. */
8003
8004static int
8005strprefix (const char *p, const char *pend, const char *prefix)
8006{
8007 for ( ; p < pend; p++, prefix++)
8008 if (*p != *prefix)
8009 return 0;
8010 return *prefix == '\0';
8011}
8012
8013/* Parse the stop reply in BUF. Either the function succeeds, and the
8014 result is stored in EVENT, or throws an error. */
8015
8016void
8017remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
8018{
8019 remote_arch_state *rsa = NULL;
8020 ULONGEST addr;
8021 const char *p;
8022 int skipregs = 0;
8023
8024 event->ptid = null_ptid;
8025 event->rs = get_remote_state ();
8026 event->ws.set_ignore ();
8027 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
8028 event->regcache.clear ();
8029 event->core = -1;
8030
8031 switch (buf[0])
8032 {
8033 case 'T': /* Status with PC, SP, FP, ... */
8034 /* Expedited reply, containing Signal, {regno, reg} repeat. */
8035 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
8036 ss = signal number
8037 n... = register number
8038 r... = register contents
8039 */
8040
8041 p = &buf[3]; /* after Txx */
8042 while (*p)
8043 {
8044 const char *p1;
8045 int fieldsize;
8046
8047 p1 = strchr (p, ':');
8048 if (p1 == NULL)
8049 error (_("Malformed packet(a) (missing colon): %s\n\
8050Packet: '%s'\n"),
8051 p, buf);
8052 if (p == p1)
8053 error (_("Malformed packet(a) (missing register number): %s\n\
8054Packet: '%s'\n"),
8055 p, buf);
8056
8057 /* Some "registers" are actually extended stop information.
8058 Note if you're adding a new entry here: GDB 7.9 and
8059 earlier assume that all register "numbers" that start
8060 with an hex digit are real register numbers. Make sure
8061 the server only sends such a packet if it knows the
8062 client understands it. */
8063
8064 if (strprefix (p, p1, "thread"))
8065 event->ptid = read_ptid (++p1, &p);
8066 else if (strprefix (p, p1, "syscall_entry"))
8067 {
8068 ULONGEST sysno;
8069
8070 p = unpack_varlen_hex (++p1, &sysno);
8071 event->ws.set_syscall_entry ((int) sysno);
8072 }
8073 else if (strprefix (p, p1, "syscall_return"))
8074 {
8075 ULONGEST sysno;
8076
8077 p = unpack_varlen_hex (++p1, &sysno);
8078 event->ws.set_syscall_return ((int) sysno);
8079 }
8080 else if (strprefix (p, p1, "watch")
8081 || strprefix (p, p1, "rwatch")
8082 || strprefix (p, p1, "awatch"))
8083 {
8084 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
8085 p = unpack_varlen_hex (++p1, &addr);
8086 event->watch_data_address = (CORE_ADDR) addr;
8087 }
8088 else if (strprefix (p, p1, "swbreak"))
8089 {
8090 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
8091
8092 /* Make sure the stub doesn't forget to indicate support
8093 with qSupported. */
8094 if (m_features.packet_support (PACKET_swbreak_feature)
8095 != PACKET_ENABLE)
8096 error (_("Unexpected swbreak stop reason"));
8097
8098 /* The value part is documented as "must be empty",
8099 though we ignore it, in case we ever decide to make
8100 use of it in a backward compatible way. */
8101 p = strchrnul (p1 + 1, ';');
8102 }
8103 else if (strprefix (p, p1, "hwbreak"))
8104 {
8105 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
8106
8107 /* Make sure the stub doesn't forget to indicate support
8108 with qSupported. */
8109 if (m_features.packet_support (PACKET_hwbreak_feature)
8110 != PACKET_ENABLE)
8111 error (_("Unexpected hwbreak stop reason"));
8112
8113 /* See above. */
8114 p = strchrnul (p1 + 1, ';');
8115 }
8116 else if (strprefix (p, p1, "library"))
8117 {
8118 event->ws.set_loaded ();
8119 p = strchrnul (p1 + 1, ';');
8120 }
8121 else if (strprefix (p, p1, "replaylog"))
8122 {
8123 event->ws.set_no_history ();
8124 /* p1 will indicate "begin" or "end", but it makes
8125 no difference for now, so ignore it. */
8126 p = strchrnul (p1 + 1, ';');
8127 }
8128 else if (strprefix (p, p1, "core"))
8129 {
8130 ULONGEST c;
8131
8132 p = unpack_varlen_hex (++p1, &c);
8133 event->core = c;
8134 }
8135 else if (strprefix (p, p1, "fork"))
8136 event->ws.set_forked (read_ptid (++p1, &p));
8137 else if (strprefix (p, p1, "vfork"))
8138 event->ws.set_vforked (read_ptid (++p1, &p));
8139 else if (strprefix (p, p1, "clone"))
8140 event->ws.set_thread_cloned (read_ptid (++p1, &p));
8141 else if (strprefix (p, p1, "vforkdone"))
8142 {
8143 event->ws.set_vfork_done ();
8144 p = strchrnul (p1 + 1, ';');
8145 }
8146 else if (strprefix (p, p1, "exec"))
8147 {
8148 ULONGEST ignored;
8149 int pathlen;
8150
8151 /* Determine the length of the execd pathname. */
8152 p = unpack_varlen_hex (++p1, &ignored);
8153 pathlen = (p - p1) / 2;
8154
8155 /* Save the pathname for event reporting and for
8156 the next run command. */
8157 gdb::unique_xmalloc_ptr<char> pathname
8158 ((char *) xmalloc (pathlen + 1));
8159 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8160 pathname.get ()[pathlen] = '\0';
8161
8162 /* This is freed during event handling. */
8163 event->ws.set_execd (std::move (pathname));
8164
8165 /* Skip the registers included in this packet, since
8166 they may be for an architecture different from the
8167 one used by the original program. */
8168 skipregs = 1;
8169 }
8170 else if (strprefix (p, p1, "create"))
8171 {
8172 event->ws.set_thread_created ();
8173 p = strchrnul (p1 + 1, ';');
8174 }
8175 else
8176 {
8177 ULONGEST pnum;
8178 const char *p_temp;
8179
8180 if (skipregs)
8181 {
8182 p = strchrnul (p1 + 1, ';');
8183 p++;
8184 continue;
8185 }
8186
8187 /* Maybe a real ``P'' register number. */
8188 p_temp = unpack_varlen_hex (p, &pnum);
8189 /* If the first invalid character is the colon, we got a
8190 register number. Otherwise, it's an unknown stop
8191 reason. */
8192 if (p_temp == p1)
8193 {
8194 /* If we haven't parsed the event's thread yet, find
8195 it now, in order to find the architecture of the
8196 reported expedited registers. */
8197 if (event->ptid == null_ptid)
8198 {
8199 /* If there is no thread-id information then leave
8200 the event->ptid as null_ptid. Later in
8201 process_stop_reply we will pick a suitable
8202 thread. */
8203 const char *thr = strstr (p1 + 1, ";thread:");
8204 if (thr != NULL)
8205 event->ptid = read_ptid (thr + strlen (";thread:"),
8206 NULL);
8207 }
8208
8209 if (rsa == NULL)
8210 {
8211 inferior *inf
8212 = (event->ptid == null_ptid
8213 ? NULL
8214 : find_inferior_ptid (this, event->ptid));
8215 /* If this is the first time we learn anything
8216 about this process, skip the registers
8217 included in this packet, since we don't yet
8218 know which architecture to use to parse them.
8219 We'll determine the architecture later when
8220 we process the stop reply and retrieve the
8221 target description, via
8222 remote_notice_new_inferior ->
8223 post_create_inferior. */
8224 if (inf == NULL)
8225 {
8226 p = strchrnul (p1 + 1, ';');
8227 p++;
8228 continue;
8229 }
8230
8231 event->arch = inf->arch ();
8232 rsa = event->rs->get_remote_arch_state (event->arch);
8233 }
8234
8235 packet_reg *reg
8236 = packet_reg_from_pnum (event->arch, rsa, pnum);
8237 cached_reg_t cached_reg;
8238
8239 if (reg == NULL)
8240 error (_("Remote sent bad register number %s: %s\n\
8241Packet: '%s'\n"),
8242 hex_string (pnum), p, buf);
8243
8244 int reg_size = register_size (event->arch, reg->regnum);
8245 cached_reg.num = reg->regnum;
8246 cached_reg.data.resize (reg_size);
8247
8248 p = p1 + 1;
8249 fieldsize = hex2bin (p, cached_reg.data.data (),
8250 cached_reg.data.size ());
8251 p += 2 * fieldsize;
8252 if (fieldsize < reg_size)
8253 warning (_("Remote reply is too short: %s"), buf);
8254
8255 event->regcache.push_back (std::move (cached_reg));
8256 }
8257 else
8258 {
8259 /* Not a number. Silently skip unknown optional
8260 info. */
8261 p = strchrnul (p1 + 1, ';');
8262 }
8263 }
8264
8265 if (*p != ';')
8266 error (_("Remote register badly formatted: %s\nhere: %s"),
8267 buf, p);
8268 ++p;
8269 }
8270
8271 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8272 break;
8273
8274 [[fallthrough]];
8275 case 'S': /* Old style status, just signal only. */
8276 {
8277 int sig;
8278
8279 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8280 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8281 event->ws.set_stopped ((enum gdb_signal) sig);
8282 else
8283 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8284 }
8285 break;
8286 case 'w': /* Thread exited. */
8287 {
8288 ULONGEST value;
8289
8290 p = unpack_varlen_hex (&buf[1], &value);
8291 event->ws.set_thread_exited (value);
8292 if (*p != ';')
8293 error (_("stop reply packet badly formatted: %s"), buf);
8294 event->ptid = read_ptid (++p, NULL);
8295 break;
8296 }
8297 case 'W': /* Target exited. */
8298 case 'X':
8299 {
8300 ULONGEST value;
8301
8302 /* GDB used to accept only 2 hex chars here. Stubs should
8303 only send more if they detect GDB supports multi-process
8304 support. */
8305 p = unpack_varlen_hex (&buf[1], &value);
8306
8307 if (buf[0] == 'W')
8308 {
8309 /* The remote process exited. */
8310 event->ws.set_exited (value);
8311 }
8312 else
8313 {
8314 /* The remote process exited with a signal. */
8315 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8316 event->ws.set_signalled ((enum gdb_signal) value);
8317 else
8318 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8319 }
8320
8321 /* If no process is specified, return null_ptid, and let the
8322 caller figure out the right process to use. */
8323 int pid = 0;
8324 if (*p == '\0')
8325 ;
8326 else if (*p == ';')
8327 {
8328 p++;
8329
8330 if (*p == '\0')
8331 ;
8332 else if (startswith (p, "process:"))
8333 {
8334 ULONGEST upid;
8335
8336 p += sizeof ("process:") - 1;
8337 unpack_varlen_hex (p, &upid);
8338 pid = upid;
8339 }
8340 else
8341 error (_("unknown stop reply packet: %s"), buf);
8342 }
8343 else
8344 error (_("unknown stop reply packet: %s"), buf);
8345 event->ptid = ptid_t (pid);
8346 }
8347 break;
8348 case 'N':
8349 event->ws.set_no_resumed ();
8350 event->ptid = minus_one_ptid;
8351 break;
8352 }
8353}
8354
8355/* When the stub wants to tell GDB about a new notification reply, it
8356 sends a notification (%Stop, for example). Those can come it at
8357 any time, hence, we have to make sure that any pending
8358 putpkt/getpkt sequence we're making is finished, before querying
8359 the stub for more events with the corresponding ack command
8360 (vStopped, for example). E.g., if we started a vStopped sequence
8361 immediately upon receiving the notification, something like this
8362 could happen:
8363
8364 1.1) --> Hg 1
8365 1.2) <-- OK
8366 1.3) --> g
8367 1.4) <-- %Stop
8368 1.5) --> vStopped
8369 1.6) <-- (registers reply to step #1.3)
8370
8371 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8372 query.
8373
8374 To solve this, whenever we parse a %Stop notification successfully,
8375 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8376 doing whatever we were doing:
8377
8378 2.1) --> Hg 1
8379 2.2) <-- OK
8380 2.3) --> g
8381 2.4) <-- %Stop
8382 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8383 2.5) <-- (registers reply to step #2.3)
8384
8385 Eventually after step #2.5, we return to the event loop, which
8386 notices there's an event on the
8387 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8388 associated callback --- the function below. At this point, we're
8389 always safe to start a vStopped sequence. :
8390
8391 2.6) --> vStopped
8392 2.7) <-- T05 thread:2
8393 2.8) --> vStopped
8394 2.9) --> OK
8395*/
8396
8397void
8398remote_target::remote_notif_get_pending_events (const notif_client *nc)
8399{
8400 struct remote_state *rs = get_remote_state ();
8401
8402 if (rs->notif_state->pending_event[nc->id] != NULL)
8403 {
8404 if (notif_debug)
8405 gdb_printf (gdb_stdlog,
8406 "notif: process: '%s' ack pending event\n",
8407 nc->name);
8408
8409 /* acknowledge */
8410 nc->ack (this, nc, rs->buf.data (),
8411 std::move (rs->notif_state->pending_event[nc->id]));
8412
8413 while (1)
8414 {
8415 getpkt (&rs->buf);
8416 if (strcmp (rs->buf.data (), "OK") == 0)
8417 break;
8418 else
8419 remote_notif_ack (this, nc, rs->buf.data ());
8420 }
8421 }
8422 else
8423 {
8424 if (notif_debug)
8425 gdb_printf (gdb_stdlog,
8426 "notif: process: '%s' no pending reply\n",
8427 nc->name);
8428 }
8429}
8430
8431/* Wrapper around remote_target::remote_notif_get_pending_events to
8432 avoid having to export the whole remote_target class. */
8433
8434void
8435remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8436{
8437 remote->remote_notif_get_pending_events (nc);
8438}
8439
8440/* Called from process_stop_reply when the stop packet we are responding
8441 to didn't include a process-id or thread-id. STATUS is the stop event
8442 we are responding to.
8443
8444 It is the task of this function to select a suitable thread (or process)
8445 and return its ptid, this is the thread (or process) we will assume the
8446 stop event came from.
8447
8448 In some cases there isn't really any choice about which thread (or
8449 process) is selected, a basic remote with a single process containing a
8450 single thread might choose not to send any process-id or thread-id in
8451 its stop packets, this function will select and return the one and only
8452 thread.
8453
8454 However, if a target supports multiple threads (or processes) and still
8455 doesn't include a thread-id (or process-id) in its stop packet then
8456 first, this is a badly behaving target, and second, we're going to have
8457 to select a thread (or process) at random and use that. This function
8458 will print a warning to the user if it detects that there is the
8459 possibility that GDB is guessing which thread (or process) to
8460 report.
8461
8462 Note that this is called before GDB fetches the updated thread list from the
8463 target. So it's possible for the stop reply to be ambiguous and for GDB to
8464 not realize it. For example, if there's initially one thread, the target
8465 spawns a second thread, and then sends a stop reply without an id that
8466 concerns the first thread. GDB will assume the stop reply is about the
8467 first thread - the only thread it knows about - without printing a warning.
8468 Anyway, if the remote meant for the stop reply to be about the second thread,
8469 then it would be really broken, because GDB doesn't know about that thread
8470 yet. */
8471
8472ptid_t
8473remote_target::select_thread_for_ambiguous_stop_reply
8474 (const target_waitstatus &status)
8475{
8476 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8477
8478 /* Some stop events apply to all threads in an inferior, while others
8479 only apply to a single thread. */
8480 bool process_wide_stop
8481 = (status.kind () == TARGET_WAITKIND_EXITED
8482 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8483
8484 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8485
8486 thread_info *first_resumed_thread = nullptr;
8487 bool ambiguous = false;
8488
8489 /* Consider all non-exited threads of the target, find the first resumed
8490 one. */
8491 for (thread_info *thr : all_non_exited_threads (this))
8492 {
8493 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8494
8495 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8496 continue;
8497
8498 if (first_resumed_thread == nullptr)
8499 first_resumed_thread = thr;
8500 else if (!process_wide_stop
8501 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8502 ambiguous = true;
8503 }
8504
8505 gdb_assert (first_resumed_thread != nullptr);
8506
8507 remote_debug_printf ("first resumed thread is %s",
8508 pid_to_str (first_resumed_thread->ptid).c_str ());
8509 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8510
8511 /* Warn if the remote target is sending ambiguous stop replies. */
8512 if (ambiguous)
8513 {
8514 static bool warned = false;
8515
8516 if (!warned)
8517 {
8518 /* If you are seeing this warning then the remote target has
8519 stopped without specifying a thread-id, but the target
8520 does have multiple threads (or inferiors), and so GDB is
8521 having to guess which thread stopped.
8522
8523 Examples of what might cause this are the target sending
8524 and 'S' stop packet, or a 'T' stop packet and not
8525 including a thread-id.
8526
8527 Additionally, the target might send a 'W' or 'X packet
8528 without including a process-id, when the target has
8529 multiple running inferiors. */
8530 if (process_wide_stop)
8531 warning (_("multi-inferior target stopped without "
8532 "sending a process-id, using first "
8533 "non-exited inferior"));
8534 else
8535 warning (_("multi-threaded target stopped without "
8536 "sending a thread-id, using first "
8537 "non-exited thread"));
8538 warned = true;
8539 }
8540 }
8541
8542 /* If this is a stop for all threads then don't use a particular threads
8543 ptid, instead create a new ptid where only the pid field is set. */
8544 if (process_wide_stop)
8545 return ptid_t (first_resumed_thread->ptid.pid ());
8546 else
8547 return first_resumed_thread->ptid;
8548}
8549
8550/* Called when it is decided that STOP_REPLY holds the info of the
8551 event that is to be returned to the core. This function always
8552 destroys STOP_REPLY. */
8553
8554ptid_t
8555remote_target::process_stop_reply (stop_reply_up stop_reply,
8556 struct target_waitstatus *status)
8557{
8558 *status = stop_reply->ws;
8559 ptid_t ptid = stop_reply->ptid;
8560 struct remote_state *rs = get_remote_state ();
8561
8562 /* Forget about last reply's expedited registers. */
8563 rs->last_seen_expedited_registers.clear ();
8564
8565 /* If no thread/process was reported by the stub then select a suitable
8566 thread/process. */
8567 if (ptid == null_ptid)
8568 ptid = select_thread_for_ambiguous_stop_reply (*status);
8569 gdb_assert (ptid != null_ptid);
8570
8571 if (status->kind () != TARGET_WAITKIND_EXITED
8572 && status->kind () != TARGET_WAITKIND_SIGNALLED
8573 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8574 {
8575 remote_notice_new_inferior (ptid, false);
8576
8577 /* Expedited registers. */
8578 if (!stop_reply->regcache.empty ())
8579 {
8580 /* 'w' stop replies don't cary expedited registers (which
8581 wouldn't make any sense for a thread that is gone
8582 already). */
8583 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8584
8585 regcache *regcache
8586 = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
8587 stop_reply->arch);
8588
8589 for (cached_reg_t &reg : stop_reply->regcache)
8590 {
8591 regcache->raw_supply (reg.num, reg.data);
8592 rs->last_seen_expedited_registers.insert (reg.num);
8593 }
8594 }
8595
8596 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8597 remote_thr->core = stop_reply->core;
8598 remote_thr->stop_reason = stop_reply->stop_reason;
8599 remote_thr->watch_data_address = stop_reply->watch_data_address;
8600
8601 if (target_is_non_stop_p ())
8602 {
8603 /* If the target works in non-stop mode, a stop-reply indicates that
8604 only this thread stopped. */
8605 remote_thr->set_not_resumed ();
8606 }
8607 else
8608 {
8609 /* If the target works in all-stop mode, a stop-reply indicates that
8610 all the target's threads stopped. */
8611 for (thread_info *tp : all_non_exited_threads (this))
8612 get_remote_thread_info (tp)->set_not_resumed ();
8613 }
8614 }
8615
8616 return ptid;
8617}
8618
8619/* The non-stop mode version of target_wait. */
8620
8621ptid_t
8622remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8623 target_wait_flags options)
8624{
8625 struct remote_state *rs = get_remote_state ();
8626 int ret;
8627 bool is_notif = false;
8628
8629 /* If in non-stop mode, get out of getpkt even if a
8630 notification is received. */
8631
8632 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8633 while (1)
8634 {
8635 if (ret != -1 && !is_notif)
8636 switch (rs->buf[0])
8637 {
8638 case 'E': /* Error of some sort. */
8639 /* We're out of sync with the target now. Did it continue
8640 or not? We can't tell which thread it was in non-stop,
8641 so just ignore this. */
8642 warning (_("Remote failure reply: %s"), rs->buf.data ());
8643 break;
8644 case 'O': /* Console output. */
8645 remote_console_output (&rs->buf[1], gdb_stdtarg);
8646 break;
8647 default:
8648 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8649 break;
8650 }
8651
8652 /* Acknowledge a pending stop reply that may have arrived in the
8653 mean time. */
8654 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8655 remote_notif_get_pending_events (&notif_client_stop);
8656
8657 /* If indeed we noticed a stop reply, we're done. */
8658 stop_reply_up stop_reply = queued_stop_reply (ptid);
8659 if (stop_reply != NULL)
8660 return process_stop_reply (std::move (stop_reply), status);
8661
8662 /* Still no event. If we're just polling for an event, then
8663 return to the event loop. */
8664 if (options & TARGET_WNOHANG)
8665 {
8666 status->set_ignore ();
8667 return minus_one_ptid;
8668 }
8669
8670 /* Otherwise do a blocking wait. */
8671 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8672 }
8673}
8674
8675/* Return the first resumed thread. */
8676
8677static ptid_t
8678first_remote_resumed_thread (remote_target *target)
8679{
8680 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8681 if (tp->resumed ())
8682 return tp->ptid;
8683 return null_ptid;
8684}
8685
8686/* Wait until the remote machine stops, then return, storing status in
8687 STATUS just as `wait' would. */
8688
8689ptid_t
8690remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8691 target_wait_flags options)
8692{
8693 struct remote_state *rs = get_remote_state ();
8694 ptid_t event_ptid = null_ptid;
8695 char *buf;
8696 stop_reply_up stop_reply;
8697
8698 again:
8699
8700 status->set_ignore ();
8701
8702 stop_reply = queued_stop_reply (ptid);
8703 if (stop_reply != NULL)
8704 {
8705 /* None of the paths that push a stop reply onto the queue should
8706 have set the waiting_for_stop_reply flag. */
8707 gdb_assert (!rs->waiting_for_stop_reply);
8708 event_ptid = process_stop_reply (std::move (stop_reply), status);
8709 }
8710 else
8711 {
8712 bool forever = ((options & TARGET_WNOHANG) == 0
8713 && rs->wait_forever_enabled_p);
8714
8715 if (!rs->waiting_for_stop_reply)
8716 {
8717 status->set_no_resumed ();
8718 return minus_one_ptid;
8719 }
8720
8721 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8722 _never_ wait for ever -> test on target_is_async_p().
8723 However, before we do that we need to ensure that the caller
8724 knows how to take the target into/out of async mode. */
8725 bool is_notif;
8726 int ret = getpkt (&rs->buf, forever, &is_notif);
8727
8728 /* GDB gets a notification. Return to core as this event is
8729 not interesting. */
8730 if (ret != -1 && is_notif)
8731 return minus_one_ptid;
8732
8733 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8734 return minus_one_ptid;
8735
8736 buf = rs->buf.data ();
8737
8738 /* Assume that the target has acknowledged Ctrl-C unless we receive
8739 an 'F' or 'O' packet. */
8740 if (buf[0] != 'F' && buf[0] != 'O')
8741 rs->ctrlc_pending_p = 0;
8742
8743 switch (buf[0])
8744 {
8745 case 'E': /* Error of some sort. */
8746 /* We're out of sync with the target now. Did it continue or
8747 not? Not is more likely, so report a stop. */
8748 rs->waiting_for_stop_reply = 0;
8749
8750 warning (_("Remote failure reply: %s"), buf);
8751 status->set_stopped (GDB_SIGNAL_0);
8752 break;
8753 case 'F': /* File-I/O request. */
8754 /* GDB may access the inferior memory while handling the File-I/O
8755 request, but we don't want GDB accessing memory while waiting
8756 for a stop reply. See the comments in putpkt_binary. Set
8757 waiting_for_stop_reply to 0 temporarily. */
8758 rs->waiting_for_stop_reply = 0;
8759 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8760 rs->ctrlc_pending_p = 0;
8761 /* GDB handled the File-I/O request, and the target is running
8762 again. Keep waiting for events. */
8763 rs->waiting_for_stop_reply = 1;
8764 break;
8765 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8766 {
8767 /* There is a stop reply to handle. */
8768 rs->waiting_for_stop_reply = 0;
8769
8770 stop_reply
8771 = as_stop_reply_up (remote_notif_parse (this,
8772 &notif_client_stop,
8773 rs->buf.data ()));
8774
8775 event_ptid = process_stop_reply (std::move (stop_reply), status);
8776 break;
8777 }
8778 case 'O': /* Console output. */
8779 remote_console_output (buf + 1, gdb_stdtarg);
8780 break;
8781 case '\0':
8782 if (rs->last_sent_signal != GDB_SIGNAL_0)
8783 {
8784 /* Zero length reply means that we tried 'S' or 'C' and the
8785 remote system doesn't support it. */
8786 target_terminal::ours_for_output ();
8787 gdb_printf
8788 ("Can't send signals to this remote system. %s not sent.\n",
8789 gdb_signal_to_name (rs->last_sent_signal));
8790 rs->last_sent_signal = GDB_SIGNAL_0;
8791 target_terminal::inferior ();
8792
8793 strcpy (buf, rs->last_sent_step ? "s" : "c");
8794 putpkt (buf);
8795 break;
8796 }
8797 [[fallthrough]];
8798 default:
8799 warning (_("Invalid remote reply: %s"), buf);
8800 break;
8801 }
8802 }
8803
8804 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8805 return minus_one_ptid;
8806 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8807 {
8808 /* Nothing interesting happened. If we're doing a non-blocking
8809 poll, we're done. Otherwise, go back to waiting. */
8810 if (options & TARGET_WNOHANG)
8811 return minus_one_ptid;
8812 else
8813 goto again;
8814 }
8815 else if (status->kind () != TARGET_WAITKIND_EXITED
8816 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8817 {
8818 if (event_ptid != null_ptid)
8819 record_currthread (rs, event_ptid);
8820 else
8821 event_ptid = first_remote_resumed_thread (this);
8822 }
8823 else
8824 {
8825 /* A process exit. Invalidate our notion of current thread. */
8826 record_currthread (rs, minus_one_ptid);
8827 /* It's possible that the packet did not include a pid. */
8828 if (event_ptid == null_ptid)
8829 event_ptid = first_remote_resumed_thread (this);
8830 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8831 if (event_ptid == null_ptid)
8832 event_ptid = magic_null_ptid;
8833 }
8834
8835 return event_ptid;
8836}
8837
8838/* Wait until the remote machine stops, then return, storing status in
8839 STATUS just as `wait' would. */
8840
8841ptid_t
8842remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8843 target_wait_flags options)
8844{
8845 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8846
8847 remote_state *rs = get_remote_state ();
8848
8849 /* Start by clearing the flag that asks for our wait method to be called,
8850 we'll mark it again at the end if needed. If the target is not in
8851 async mode then the async token should not be marked. */
8852 if (target_is_async_p ())
8853 rs->clear_async_event_handler ();
8854 else
8855 gdb_assert (!rs->async_event_handler_marked ());
8856
8857 ptid_t event_ptid;
8858
8859 if (target_is_non_stop_p ())
8860 event_ptid = wait_ns (ptid, status, options);
8861 else
8862 event_ptid = wait_as (ptid, status, options);
8863
8864 if (target_is_async_p ())
8865 {
8866 /* If there are events left in the queue, or unacknowledged
8867 notifications, then tell the event loop to call us again. */
8868 if (!rs->stop_reply_queue.empty ()
8869 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8870 rs->mark_async_event_handler ();
8871 }
8872
8873 return event_ptid;
8874}
8875
8876/* Fetch a single register using a 'p' packet. */
8877
8878int
8879remote_target::fetch_register_using_p (struct regcache *regcache,
8880 packet_reg *reg)
8881{
8882 struct gdbarch *gdbarch = regcache->arch ();
8883 struct remote_state *rs = get_remote_state ();
8884 char *buf, *p;
8885 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8886 int i;
8887
8888 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8889 return 0;
8890
8891 if (reg->pnum == -1)
8892 return 0;
8893
8894 p = rs->buf.data ();
8895 *p++ = 'p';
8896 p += hexnumstr (p, reg->pnum);
8897 *p++ = '\0';
8898 putpkt (rs->buf);
8899 getpkt (&rs->buf);
8900
8901 buf = rs->buf.data ();
8902
8903 packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
8904 switch (result.status ())
8905 {
8906 case PACKET_OK:
8907 break;
8908 case PACKET_UNKNOWN:
8909 return 0;
8910 case PACKET_ERROR:
8911 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8912 gdbarch_register_name (regcache->arch (), reg->regnum),
8913 result.err_msg ());
8914 }
8915
8916 /* If this register is unfetchable, tell the regcache. */
8917 if (buf[0] == 'x')
8918 {
8919 regcache->raw_supply (reg->regnum, NULL);
8920 return 1;
8921 }
8922
8923 /* Otherwise, parse and supply the value. */
8924 p = buf;
8925 i = 0;
8926 while (p[0] != 0)
8927 {
8928 if (p[1] == 0)
8929 error (_("fetch_register_using_p: early buf termination"));
8930
8931 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8932 p += 2;
8933 }
8934 regcache->raw_supply (reg->regnum, regp);
8935 return 1;
8936}
8937
8938/* Fetch the registers included in the target's 'g' packet. */
8939
8940int
8941remote_target::send_g_packet ()
8942{
8943 struct remote_state *rs = get_remote_state ();
8944 int buf_len;
8945
8946 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8947 putpkt (rs->buf);
8948 getpkt (&rs->buf);
8949 packet_result result = packet_check_result (rs->buf);
8950 if (result.status () == PACKET_ERROR)
8951 error (_("Could not read registers; remote failure reply '%s'"),
8952 result.err_msg ());
8953
8954 /* We can get out of synch in various cases. If the first character
8955 in the buffer is not a hex character, assume that has happened
8956 and try to fetch another packet to read. */
8957 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8958 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8959 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8960 && rs->buf[0] != 'x') /* New: unavailable register value. */
8961 {
8962 remote_debug_printf ("Bad register packet; fetching a new packet");
8963 getpkt (&rs->buf);
8964 }
8965
8966 buf_len = strlen (rs->buf.data ());
8967
8968 /* Sanity check the received packet. */
8969 if (buf_len % 2 != 0)
8970 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8971
8972 return buf_len / 2;
8973}
8974
8975void
8976remote_target::process_g_packet (struct regcache *regcache)
8977{
8978 struct gdbarch *gdbarch = regcache->arch ();
8979 struct remote_state *rs = get_remote_state ();
8980 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8981 int i, buf_len;
8982 char *p;
8983 char *regs;
8984
8985 buf_len = strlen (rs->buf.data ());
8986
8987 /* Further sanity checks, with knowledge of the architecture. */
8988 if (buf_len > 2 * rsa->sizeof_g_packet)
8989 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8990 "bytes): %s"),
8991 rsa->sizeof_g_packet, buf_len / 2,
8992 rs->buf.data ());
8993
8994 /* Save the size of the packet sent to us by the target. It is used
8995 as a heuristic when determining the max size of packets that the
8996 target can safely receive. */
8997 if (rsa->actual_register_packet_size == 0)
8998 rsa->actual_register_packet_size = buf_len;
8999
9000 /* If this is smaller than we guessed the 'g' packet would be,
9001 update our records. A 'g' reply that doesn't include a register's
9002 value implies either that the register is not available, or that
9003 the 'p' packet must be used. */
9004 if (buf_len < 2 * rsa->sizeof_g_packet)
9005 {
9006 long sizeof_g_packet = buf_len / 2;
9007
9008 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9009 {
9010 long offset = rsa->regs[i].offset;
9011 long reg_size = register_size (gdbarch, i);
9012
9013 if (rsa->regs[i].pnum == -1)
9014 continue;
9015
9016 if (offset >= sizeof_g_packet)
9017 rsa->regs[i].in_g_packet = false;
9018 else if (offset + reg_size > sizeof_g_packet)
9019 error (_("Truncated register %d in remote 'g' packet"), i);
9020 else
9021 rsa->regs[i].in_g_packet = true;
9022 }
9023
9024 /* Looks valid enough, we can assume this is the correct length
9025 for a 'g' packet. It's important not to adjust
9026 rsa->sizeof_g_packet if we have truncated registers otherwise
9027 this "if" won't be run the next time the method is called
9028 with a packet of the same size and one of the internal errors
9029 below will trigger instead. */
9030 rsa->sizeof_g_packet = sizeof_g_packet;
9031 }
9032
9033 regs = (char *) alloca (rsa->sizeof_g_packet);
9034
9035 /* Unimplemented registers read as all bits zero. */
9036 memset (regs, 0, rsa->sizeof_g_packet);
9037
9038 /* Reply describes registers byte by byte, each byte encoded as two
9039 hex characters. Suck them all up, then supply them to the
9040 register caching/storage mechanism. */
9041
9042 p = rs->buf.data ();
9043 for (i = 0; i < rsa->sizeof_g_packet; i++)
9044 {
9045 if (p[0] == 0 || p[1] == 0)
9046 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
9047 internal_error (_("unexpected end of 'g' packet reply"));
9048
9049 if (p[0] == 'x' && p[1] == 'x')
9050 regs[i] = 0; /* 'x' */
9051 else
9052 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
9053 p += 2;
9054 }
9055
9056 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9057 {
9058 struct packet_reg *r = &rsa->regs[i];
9059 long reg_size = register_size (gdbarch, i);
9060
9061 if (r->in_g_packet)
9062 {
9063 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
9064 /* This shouldn't happen - we adjusted in_g_packet above. */
9065 internal_error (_("unexpected end of 'g' packet reply"));
9066 else if (rs->buf[r->offset * 2] == 'x')
9067 {
9068 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
9069 /* The register isn't available, mark it as such (at
9070 the same time setting the value to zero). */
9071 regcache->raw_supply (r->regnum, NULL);
9072 }
9073 else
9074 regcache->raw_supply (r->regnum, regs + r->offset);
9075 }
9076 }
9077}
9078
9079void
9080remote_target::fetch_registers_using_g (struct regcache *regcache)
9081{
9082 send_g_packet ();
9083 process_g_packet (regcache);
9084}
9085
9086/* Make the remote selected traceframe match GDB's selected
9087 traceframe. */
9088
9089void
9090remote_target::set_remote_traceframe ()
9091{
9092 int newnum;
9093 struct remote_state *rs = get_remote_state ();
9094
9095 if (rs->remote_traceframe_number == get_traceframe_number ())
9096 return;
9097
9098 /* Avoid recursion, remote_trace_find calls us again. */
9099 rs->remote_traceframe_number = get_traceframe_number ();
9100
9101 newnum = target_trace_find (tfind_number,
9102 get_traceframe_number (), 0, 0, NULL);
9103
9104 /* Should not happen. If it does, all bets are off. */
9105 if (newnum != get_traceframe_number ())
9106 warning (_("could not set remote traceframe"));
9107}
9108
9109void
9110remote_target::fetch_registers (struct regcache *regcache, int regnum)
9111{
9112 struct gdbarch *gdbarch = regcache->arch ();
9113 struct remote_state *rs = get_remote_state ();
9114 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9115 int i;
9116
9117 set_remote_traceframe ();
9118 set_general_thread (regcache->ptid ());
9119
9120 if (regnum >= 0)
9121 {
9122 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9123
9124 gdb_assert (reg != NULL);
9125
9126 /* If this register might be in the 'g' packet, try that first -
9127 we are likely to read more than one register. If this is the
9128 first 'g' packet, we might be overly optimistic about its
9129 contents, so fall back to 'p'. */
9130 if (reg->in_g_packet)
9131 {
9132 fetch_registers_using_g (regcache);
9133 if (reg->in_g_packet)
9134 return;
9135 }
9136
9137 if (fetch_register_using_p (regcache, reg))
9138 return;
9139
9140 /* This register is not available. */
9141 regcache->raw_supply (reg->regnum, NULL);
9142
9143 return;
9144 }
9145
9146 fetch_registers_using_g (regcache);
9147
9148 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9149 if (!rsa->regs[i].in_g_packet)
9150 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
9151 {
9152 /* This register is not available. */
9153 regcache->raw_supply (i, NULL);
9154 }
9155}
9156
9157/* Prepare to store registers. Since we may send them all (using a
9158 'G' request), we have to read out the ones we don't want to change
9159 first. */
9160
9161void
9162remote_target::prepare_to_store (struct regcache *regcache)
9163{
9164 struct remote_state *rs = get_remote_state ();
9165 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9166 int i;
9167
9168 /* Make sure the entire registers array is valid. */
9169 switch (m_features.packet_support (PACKET_P))
9170 {
9171 case PACKET_DISABLE:
9172 case PACKET_SUPPORT_UNKNOWN:
9173 /* Make sure all the necessary registers are cached. */
9174 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9175 if (rsa->regs[i].in_g_packet)
9176 regcache->raw_update (rsa->regs[i].regnum);
9177 break;
9178 case PACKET_ENABLE:
9179 break;
9180 }
9181}
9182
9183/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9184 packet was not recognized. */
9185
9186int
9187remote_target::store_register_using_P (const struct regcache *regcache,
9188 packet_reg *reg)
9189{
9190 struct gdbarch *gdbarch = regcache->arch ();
9191 struct remote_state *rs = get_remote_state ();
9192 /* Try storing a single register. */
9193 char *buf = rs->buf.data ();
9194 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9195 char *p;
9196
9197 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9198 return 0;
9199
9200 if (reg->pnum == -1)
9201 return 0;
9202
9203 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9204 p = buf + strlen (buf);
9205 regcache->raw_collect (reg->regnum, regp);
9206 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9207 putpkt (rs->buf);
9208 getpkt (&rs->buf);
9209
9210 packet_result result = m_features.packet_ok (rs->buf, PACKET_P);
9211 switch (result.status ())
9212 {
9213 case PACKET_OK:
9214 return 1;
9215 case PACKET_ERROR:
9216 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9217 gdbarch_register_name (gdbarch, reg->regnum), result.err_msg ());
9218 case PACKET_UNKNOWN:
9219 return 0;
9220 default:
9221 internal_error (_("Bad result from packet_ok"));
9222 }
9223}
9224
9225/* Store register REGNUM, or all registers if REGNUM == -1, from the
9226 contents of the register cache buffer. FIXME: ignores errors. */
9227
9228void
9229remote_target::store_registers_using_G (const struct regcache *regcache)
9230{
9231 struct remote_state *rs = get_remote_state ();
9232 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9233 gdb_byte *regs;
9234 char *p;
9235
9236 /* Extract all the registers in the regcache copying them into a
9237 local buffer. */
9238 {
9239 int i;
9240
9241 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9242 memset (regs, 0, rsa->sizeof_g_packet);
9243 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9244 {
9245 struct packet_reg *r = &rsa->regs[i];
9246
9247 if (r->in_g_packet)
9248 regcache->raw_collect (r->regnum, regs + r->offset);
9249 }
9250 }
9251
9252 /* Command describes registers byte by byte,
9253 each byte encoded as two hex characters. */
9254 p = rs->buf.data ();
9255 *p++ = 'G';
9256 bin2hex (regs, p, rsa->sizeof_g_packet);
9257 putpkt (rs->buf);
9258 getpkt (&rs->buf);
9259 packet_result pkt_status = packet_check_result (rs->buf);
9260 if (pkt_status.status () == PACKET_ERROR)
9261 error (_("Could not write registers; remote failure reply '%s'"),
9262 pkt_status.err_msg ());
9263}
9264
9265/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9266 of the register cache buffer. FIXME: ignores errors. */
9267
9268void
9269remote_target::store_registers (struct regcache *regcache, int regnum)
9270{
9271 struct gdbarch *gdbarch = regcache->arch ();
9272 struct remote_state *rs = get_remote_state ();
9273 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9274 int i;
9275
9276 set_remote_traceframe ();
9277 set_general_thread (regcache->ptid ());
9278
9279 if (regnum >= 0)
9280 {
9281 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9282
9283 gdb_assert (reg != NULL);
9284
9285 /* Always prefer to store registers using the 'P' packet if
9286 possible; we often change only a small number of registers.
9287 Sometimes we change a larger number; we'd need help from a
9288 higher layer to know to use 'G'. */
9289 if (store_register_using_P (regcache, reg))
9290 return;
9291
9292 /* For now, don't complain if we have no way to write the
9293 register. GDB loses track of unavailable registers too
9294 easily. Some day, this may be an error. We don't have
9295 any way to read the register, either... */
9296 if (!reg->in_g_packet)
9297 return;
9298
9299 store_registers_using_G (regcache);
9300 return;
9301 }
9302
9303 store_registers_using_G (regcache);
9304
9305 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9306 if (!rsa->regs[i].in_g_packet)
9307 if (!store_register_using_P (regcache, &rsa->regs[i]))
9308 /* See above for why we do not issue an error here. */
9309 continue;
9310}
9311\f
9312
9313/* Return the number of hex digits in num. */
9314
9315static int
9316hexnumlen (ULONGEST num)
9317{
9318 int i;
9319
9320 for (i = 0; num != 0; i++)
9321 num >>= 4;
9322
9323 return std::max (i, 1);
9324}
9325
9326/* Set BUF to the minimum number of hex digits representing NUM. */
9327
9328static int
9329hexnumstr (char *buf, ULONGEST num)
9330{
9331 int len = hexnumlen (num);
9332
9333 return hexnumnstr (buf, num, len);
9334}
9335
9336
9337/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9338
9339static int
9340hexnumnstr (char *buf, ULONGEST num, int width)
9341{
9342 int i;
9343
9344 buf[width] = '\0';
9345
9346 for (i = width - 1; i >= 0; i--)
9347 {
9348 buf[i] = "0123456789abcdef"[(num & 0xf)];
9349 num >>= 4;
9350 }
9351
9352 return width;
9353}
9354
9355/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9356
9357static CORE_ADDR
9358remote_address_masked (CORE_ADDR addr)
9359{
9360 unsigned int address_size = remote_address_size;
9361
9362 /* If "remoteaddresssize" was not set, default to target address size. */
9363 if (!address_size)
9364 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9365
9366 if (address_size > 0
9367 && address_size < (sizeof (ULONGEST) * 8))
9368 {
9369 /* Only create a mask when that mask can safely be constructed
9370 in a ULONGEST variable. */
9371 ULONGEST mask = 1;
9372
9373 mask = (mask << address_size) - 1;
9374 addr &= mask;
9375 }
9376 return addr;
9377}
9378
9379/* Determine whether the remote target supports binary downloading.
9380 This is accomplished by sending a no-op memory write of zero length
9381 to the target at the specified address. It does not suffice to send
9382 the whole packet, since many stubs strip the eighth bit and
9383 subsequently compute a wrong checksum, which causes real havoc with
9384 remote_write_bytes.
9385
9386 NOTE: This can still lose if the serial line is not eight-bit
9387 clean. In cases like this, the user should clear "remote
9388 X-packet". */
9389
9390void
9391remote_target::check_binary_download (CORE_ADDR addr)
9392{
9393 struct remote_state *rs = get_remote_state ();
9394
9395 switch (m_features.packet_support (PACKET_X))
9396 {
9397 case PACKET_DISABLE:
9398 break;
9399 case PACKET_ENABLE:
9400 break;
9401 case PACKET_SUPPORT_UNKNOWN:
9402 {
9403 char *p;
9404
9405 p = rs->buf.data ();
9406 *p++ = 'X';
9407 p += hexnumstr (p, (ULONGEST) addr);
9408 *p++ = ',';
9409 p += hexnumstr (p, (ULONGEST) 0);
9410 *p++ = ':';
9411 *p = '\0';
9412
9413 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9414 getpkt (&rs->buf);
9415
9416 if (rs->buf[0] == '\0')
9417 {
9418 remote_debug_printf ("binary downloading NOT supported by target");
9419 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9420 }
9421 else
9422 {
9423 remote_debug_printf ("binary downloading supported by target");
9424 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9425 }
9426 break;
9427 }
9428 }
9429}
9430
9431/* Helper function to resize the payload in order to try to get a good
9432 alignment. We try to write an amount of data such that the next write will
9433 start on an address aligned on REMOTE_ALIGN_WRITES. */
9434
9435static int
9436align_for_efficient_write (int todo, CORE_ADDR memaddr)
9437{
9438 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9439}
9440
9441/* Write memory data directly to the remote machine.
9442 This does not inform the data cache; the data cache uses this.
9443 HEADER is the starting part of the packet.
9444 MEMADDR is the address in the remote memory space.
9445 MYADDR is the address of the buffer in our space.
9446 LEN_UNITS is the number of addressable units to write.
9447 UNIT_SIZE is the length in bytes of an addressable unit.
9448 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9449 should send data as binary ('X'), or hex-encoded ('M').
9450
9451 The function creates packet of the form
9452 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9453
9454 where encoding of <DATA> is terminated by PACKET_FORMAT.
9455
9456 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9457 are omitted.
9458
9459 Return the transferred status, error or OK (an
9460 'enum target_xfer_status' value). Save the number of addressable units
9461 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9462
9463 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9464 exchange between gdb and the stub could look like (?? in place of the
9465 checksum):
9466
9467 -> $m1000,4#??
9468 <- aaaabbbbccccdddd
9469
9470 -> $M1000,3:eeeeffffeeee#??
9471 <- OK
9472
9473 -> $m1000,4#??
9474 <- eeeeffffeeeedddd */
9475
9476target_xfer_status
9477remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9478 const gdb_byte *myaddr,
9479 ULONGEST len_units,
9480 int unit_size,
9481 ULONGEST *xfered_len_units,
9482 char packet_format, int use_length)
9483{
9484 struct remote_state *rs = get_remote_state ();
9485 char *p;
9486 char *plen = NULL;
9487 int plenlen = 0;
9488 int todo_units;
9489 int units_written;
9490 int payload_capacity_bytes;
9491 int payload_length_bytes;
9492
9493 if (packet_format != 'X' && packet_format != 'M')
9494 internal_error (_("remote_write_bytes_aux: bad packet format"));
9495
9496 if (len_units == 0)
9497 return TARGET_XFER_EOF;
9498
9499 payload_capacity_bytes = get_memory_write_packet_size ();
9500
9501 /* The packet buffer will be large enough for the payload;
9502 get_memory_packet_size ensures this. */
9503 rs->buf[0] = '\0';
9504
9505 /* Compute the size of the actual payload by subtracting out the
9506 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9507
9508 payload_capacity_bytes -= strlen ("$,:#NN");
9509 if (!use_length)
9510 /* The comma won't be used. */
9511 payload_capacity_bytes += 1;
9512 payload_capacity_bytes -= strlen (header);
9513 payload_capacity_bytes -= hexnumlen (memaddr);
9514
9515 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9516
9517 strcat (rs->buf.data (), header);
9518 p = rs->buf.data () + strlen (header);
9519
9520 /* Compute a best guess of the number of bytes actually transferred. */
9521 if (packet_format == 'X')
9522 {
9523 /* Best guess at number of bytes that will fit. */
9524 todo_units = std::min (len_units,
9525 (ULONGEST) payload_capacity_bytes / unit_size);
9526 if (use_length)
9527 payload_capacity_bytes -= hexnumlen (todo_units);
9528 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9529 }
9530 else
9531 {
9532 /* Number of bytes that will fit. */
9533 todo_units
9534 = std::min (len_units,
9535 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9536 if (use_length)
9537 payload_capacity_bytes -= hexnumlen (todo_units);
9538 todo_units = std::min (todo_units,
9539 (payload_capacity_bytes / unit_size) / 2);
9540 }
9541
9542 if (todo_units <= 0)
9543 internal_error (_("minimum packet size too small to write data"));
9544
9545 /* If we already need another packet, then try to align the end
9546 of this packet to a useful boundary. */
9547 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9548 todo_units = align_for_efficient_write (todo_units, memaddr);
9549
9550 /* Append "<memaddr>". */
9551 memaddr = remote_address_masked (memaddr);
9552 p += hexnumstr (p, (ULONGEST) memaddr);
9553
9554 if (use_length)
9555 {
9556 /* Append ",". */
9557 *p++ = ',';
9558
9559 /* Append the length and retain its location and size. It may need to be
9560 adjusted once the packet body has been created. */
9561 plen = p;
9562 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9563 p += plenlen;
9564 }
9565
9566 /* Append ":". */
9567 *p++ = ':';
9568 *p = '\0';
9569
9570 /* Append the packet body. */
9571 if (packet_format == 'X')
9572 {
9573 /* Binary mode. Send target system values byte by byte, in
9574 increasing byte addresses. Only escape certain critical
9575 characters. */
9576 payload_length_bytes =
9577 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9578 &units_written, payload_capacity_bytes);
9579
9580 /* If not all TODO units fit, then we'll need another packet. Make
9581 a second try to keep the end of the packet aligned. Don't do
9582 this if the packet is tiny. */
9583 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9584 {
9585 int new_todo_units;
9586
9587 new_todo_units = align_for_efficient_write (units_written, memaddr);
9588
9589 if (new_todo_units != units_written)
9590 payload_length_bytes =
9591 remote_escape_output (myaddr, new_todo_units, unit_size,
9592 (gdb_byte *) p, &units_written,
9593 payload_capacity_bytes);
9594 }
9595
9596 p += payload_length_bytes;
9597 if (use_length && units_written < todo_units)
9598 {
9599 /* Escape chars have filled up the buffer prematurely,
9600 and we have actually sent fewer units than planned.
9601 Fix-up the length field of the packet. Use the same
9602 number of characters as before. */
9603 plen += hexnumnstr (plen, (ULONGEST) units_written,
9604 plenlen);
9605 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9606 }
9607 }
9608 else
9609 {
9610 /* Normal mode: Send target system values byte by byte, in
9611 increasing byte addresses. Each byte is encoded as a two hex
9612 value. */
9613 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9614 units_written = todo_units;
9615 }
9616
9617 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9618 getpkt (&rs->buf);
9619
9620 if (rs->buf[0] == 'E')
9621 return TARGET_XFER_E_IO;
9622
9623 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9624 send fewer units than we'd planned. */
9625 *xfered_len_units = (ULONGEST) units_written;
9626 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9627}
9628
9629/* Write memory data directly to the remote machine.
9630 This does not inform the data cache; the data cache uses this.
9631 MEMADDR is the address in the remote memory space.
9632 MYADDR is the address of the buffer in our space.
9633 LEN is the number of bytes.
9634
9635 Return the transferred status, error or OK (an
9636 'enum target_xfer_status' value). Save the number of bytes
9637 transferred in *XFERED_LEN. Only transfer a single packet. */
9638
9639target_xfer_status
9640remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9641 ULONGEST len, int unit_size,
9642 ULONGEST *xfered_len)
9643{
9644 const char *packet_format = NULL;
9645
9646 /* Check whether the target supports binary download. */
9647 check_binary_download (memaddr);
9648
9649 switch (m_features.packet_support (PACKET_X))
9650 {
9651 case PACKET_ENABLE:
9652 packet_format = "X";
9653 break;
9654 case PACKET_DISABLE:
9655 packet_format = "M";
9656 break;
9657 case PACKET_SUPPORT_UNKNOWN:
9658 internal_error (_("remote_write_bytes: bad internal state"));
9659 default:
9660 internal_error (_("bad switch"));
9661 }
9662
9663 return remote_write_bytes_aux (packet_format,
9664 memaddr, myaddr, len, unit_size, xfered_len,
9665 packet_format[0], 1);
9666}
9667
9668/* Read memory data directly from the remote machine.
9669 This does not use the data cache; the data cache uses this.
9670 MEMADDR is the address in the remote memory space.
9671 MYADDR is the address of the buffer in our space.
9672 LEN_UNITS is the number of addressable memory units to read..
9673 UNIT_SIZE is the length in bytes of an addressable unit.
9674
9675 Return the transferred status, error or OK (an
9676 'enum target_xfer_status' value). Save the number of bytes
9677 transferred in *XFERED_LEN_UNITS.
9678
9679 See the comment of remote_write_bytes_aux for an example of
9680 memory read/write exchange between gdb and the stub. */
9681
9682target_xfer_status
9683remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9684 ULONGEST len_units,
9685 int unit_size, ULONGEST *xfered_len_units)
9686{
9687 struct remote_state *rs = get_remote_state ();
9688 int buf_size_bytes; /* Max size of packet output buffer. */
9689 int todo_units;
9690 int decoded_bytes;
9691
9692 buf_size_bytes = get_memory_read_packet_size ();
9693 /* The packet buffer will be large enough for the payload;
9694 get_memory_packet_size ensures this. */
9695
9696 /* Number of units that will fit. */
9697 todo_units = std::min (len_units,
9698 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9699
9700 memaddr = remote_address_masked (memaddr);
9701
9702 /* Construct "m/x"<memaddr>","<len>". */
9703 auto send_request = [this, rs, memaddr, todo_units] (char format) -> void
9704 {
9705 char *buffer = rs->buf.data ();
9706 *buffer++ = format;
9707 buffer += hexnumstr (buffer, (ULONGEST) memaddr);
9708 *buffer++ = ',';
9709 buffer += hexnumstr (buffer, (ULONGEST) todo_units);
9710 *buffer = '\0';
9711 putpkt (rs->buf);
9712 };
9713
9714 /* Determine which packet format to use. The target's support for
9715 'x' may be unknown. We just try. If it doesn't work, we try
9716 again using 'm'. */
9717 char packet_format;
9718 if (m_features.packet_support (PACKET_x) == PACKET_DISABLE)
9719 packet_format = 'm';
9720 else
9721 packet_format = 'x';
9722
9723 send_request (packet_format);
9724 int packet_len = getpkt (&rs->buf);
9725 if (packet_len < 0)
9726 return TARGET_XFER_E_IO;
9727
9728 if (m_features.packet_support (PACKET_x) == PACKET_SUPPORT_UNKNOWN)
9729 {
9730 if (rs->buf[0] == '\0')
9731 {
9732 remote_debug_printf ("binary uploading NOT supported by target");
9733 m_features.m_protocol_packets[PACKET_x].support = PACKET_DISABLE;
9734
9735 /* Try again using 'm'. */
9736 packet_format = 'm';
9737 send_request (packet_format);
9738 packet_len = getpkt (&rs->buf);
9739 if (packet_len < 0)
9740 return TARGET_XFER_E_IO;
9741 }
9742 else
9743 {
9744 remote_debug_printf ("binary uploading supported by target");
9745 m_features.m_protocol_packets[PACKET_x].support = PACKET_ENABLE;
9746 }
9747 }
9748
9749 packet_result result = packet_check_result (rs->buf);
9750 if (result.status () == PACKET_ERROR)
9751 return TARGET_XFER_E_IO;
9752
9753 char *p = rs->buf.data ();
9754 if (packet_format == 'x')
9755 {
9756 if (*p != 'b')
9757 return TARGET_XFER_E_IO;
9758
9759 /* Adjust for 'b'. */
9760 p++;
9761 packet_len--;
9762 decoded_bytes = remote_unescape_input ((const gdb_byte *) p,
9763 packet_len, myaddr,
9764 todo_units * unit_size);
9765 }
9766 else
9767 {
9768 /* Reply describes memory byte by byte, each byte encoded as two hex
9769 characters. */
9770 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9771 }
9772
9773 /* Return what we have. Let higher layers handle partial reads. */
9774 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9775 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9776}
9777
9778/* Using the set of read-only target sections of remote, read live
9779 read-only memory.
9780
9781 For interface/parameters/return description see target.h,
9782 to_xfer_partial. */
9783
9784target_xfer_status
9785remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9786 ULONGEST memaddr,
9787 ULONGEST len,
9788 int unit_size,
9789 ULONGEST *xfered_len)
9790{
9791 const struct target_section *secp;
9792
9793 secp = target_section_by_addr (this, memaddr);
9794 if (secp != NULL
9795 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9796 {
9797 ULONGEST memend = memaddr + len;
9798
9799 const std::vector<target_section> *table
9800 = target_get_section_table (this);
9801 for (const target_section &p : *table)
9802 {
9803 if (memaddr >= p.addr)
9804 {
9805 if (memend <= p.endaddr)
9806 {
9807 /* Entire transfer is within this section. */
9808 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9809 xfered_len);
9810 }
9811 else if (memaddr >= p.endaddr)
9812 {
9813 /* This section ends before the transfer starts. */
9814 continue;
9815 }
9816 else
9817 {
9818 /* This section overlaps the transfer. Just do half. */
9819 len = p.endaddr - memaddr;
9820 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9821 xfered_len);
9822 }
9823 }
9824 }
9825 }
9826
9827 return TARGET_XFER_EOF;
9828}
9829
9830/* Similar to remote_read_bytes_1, but it reads from the remote stub
9831 first if the requested memory is unavailable in traceframe.
9832 Otherwise, fall back to remote_read_bytes_1. */
9833
9834target_xfer_status
9835remote_target::remote_read_bytes (CORE_ADDR memaddr,
9836 gdb_byte *myaddr, ULONGEST len, int unit_size,
9837 ULONGEST *xfered_len)
9838{
9839 if (len == 0)
9840 return TARGET_XFER_EOF;
9841
9842 if (get_traceframe_number () != -1)
9843 {
9844 std::vector<mem_range> available;
9845
9846 /* If we fail to get the set of available memory, then the
9847 target does not support querying traceframe info, and so we
9848 attempt reading from the traceframe anyway (assuming the
9849 target implements the old QTro packet then). */
9850 if (traceframe_available_memory (&available, memaddr, len))
9851 {
9852 if (available.empty () || available[0].start != memaddr)
9853 {
9854 enum target_xfer_status res;
9855
9856 /* Don't read into the traceframe's available
9857 memory. */
9858 if (!available.empty ())
9859 {
9860 LONGEST oldlen = len;
9861
9862 len = available[0].start - memaddr;
9863 gdb_assert (len <= oldlen);
9864 }
9865
9866 /* This goes through the topmost target again. */
9867 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9868 len, unit_size, xfered_len);
9869 if (res == TARGET_XFER_OK)
9870 return TARGET_XFER_OK;
9871 else
9872 {
9873 /* No use trying further, we know some memory starting
9874 at MEMADDR isn't available. */
9875 *xfered_len = len;
9876 return (*xfered_len != 0) ?
9877 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9878 }
9879 }
9880
9881 /* Don't try to read more than how much is available, in
9882 case the target implements the deprecated QTro packet to
9883 cater for older GDBs (the target's knowledge of read-only
9884 sections may be outdated by now). */
9885 len = available[0].length;
9886 }
9887 }
9888
9889 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9890}
9891
9892\f
9893
9894/* Sends a packet with content determined by the printf format string
9895 FORMAT and the remaining arguments, then gets the reply. Returns
9896 whether the packet was a success, a failure, or unknown. */
9897
9898packet_status
9899remote_target::remote_send_printf (const char *format, ...)
9900{
9901 struct remote_state *rs = get_remote_state ();
9902 int max_size = get_remote_packet_size ();
9903 va_list ap;
9904
9905 va_start (ap, format);
9906
9907 rs->buf[0] = '\0';
9908 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9909
9910 va_end (ap);
9911
9912 if (size >= max_size)
9913 internal_error (_("Too long remote packet."));
9914
9915 if (putpkt (rs->buf) < 0)
9916 error (_("Communication problem with target."));
9917
9918 rs->buf[0] = '\0';
9919 getpkt (&rs->buf);
9920
9921 return packet_check_result (rs->buf).status ();
9922}
9923
9924/* Flash writing can take quite some time. We'll set
9925 effectively infinite timeout for flash operations.
9926 In future, we'll need to decide on a better approach. */
9927static const int remote_flash_timeout = 1000;
9928
9929void
9930remote_target::flash_erase (ULONGEST address, LONGEST length)
9931{
9932 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9933 enum packet_status ret;
9934 scoped_restore restore_timeout
9935 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9936
9937 ret = remote_send_printf ("vFlashErase:%s,%s",
9938 phex (address, addr_size),
9939 phex (length, 4));
9940 switch (ret)
9941 {
9942 case PACKET_UNKNOWN:
9943 error (_("Remote target does not support flash erase"));
9944 case PACKET_ERROR:
9945 error (_("Error erasing flash with vFlashErase packet"));
9946 default:
9947 break;
9948 }
9949}
9950
9951target_xfer_status
9952remote_target::remote_flash_write (ULONGEST address,
9953 ULONGEST length, ULONGEST *xfered_len,
9954 const gdb_byte *data)
9955{
9956 scoped_restore restore_timeout
9957 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9958 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9959 xfered_len,'X', 0);
9960}
9961
9962void
9963remote_target::flash_done ()
9964{
9965 int ret;
9966
9967 scoped_restore restore_timeout
9968 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9969
9970 ret = remote_send_printf ("vFlashDone");
9971
9972 switch (ret)
9973 {
9974 case PACKET_UNKNOWN:
9975 error (_("Remote target does not support vFlashDone"));
9976 case PACKET_ERROR:
9977 error (_("Error finishing flash operation"));
9978 default:
9979 break;
9980 }
9981}
9982
9983\f
9984/* Stuff for dealing with the packets which are part of this protocol.
9985 See comment at top of file for details. */
9986
9987/* Read a single character from the remote end. The current quit
9988 handler is overridden to avoid quitting in the middle of packet
9989 sequence, as that would break communication with the remote server.
9990 See remote_serial_quit_handler for more detail. */
9991
9992int
9993remote_target::readchar (int timeout)
9994{
9995 int ch;
9996 struct remote_state *rs = get_remote_state ();
9997
9998 try
9999 {
10000 scoped_restore restore_quit_target
10001 = make_scoped_restore (&curr_quit_handler_target, this);
10002 scoped_restore restore_quit
10003 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
10004
10005 rs->got_ctrlc_during_io = 0;
10006
10007 ch = serial_readchar (rs->remote_desc, timeout);
10008
10009 if (rs->got_ctrlc_during_io)
10010 set_quit_flag ();
10011 }
10012 catch (const gdb_exception_error &ex)
10013 {
10014 remote_unpush_target (this);
10015 throw_error (TARGET_CLOSE_ERROR,
10016 _("Remote communication error. "
10017 "Target disconnected: %s"),
10018 ex.what ());
10019 }
10020
10021 if (ch >= 0)
10022 return ch;
10023
10024 if (ch == SERIAL_EOF)
10025 {
10026 remote_unpush_target (this);
10027 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
10028 }
10029
10030 return ch;
10031}
10032
10033/* Wrapper for serial_write that closes the target and throws if
10034 writing fails. The current quit handler is overridden to avoid
10035 quitting in the middle of packet sequence, as that would break
10036 communication with the remote server. See
10037 remote_serial_quit_handler for more detail. */
10038
10039void
10040remote_target::remote_serial_write (const char *str, int len)
10041{
10042 struct remote_state *rs = get_remote_state ();
10043
10044 scoped_restore restore_quit_target
10045 = make_scoped_restore (&curr_quit_handler_target, this);
10046 scoped_restore restore_quit
10047 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
10048
10049 rs->got_ctrlc_during_io = 0;
10050
10051 try
10052 {
10053 serial_write (rs->remote_desc, str, len);
10054 }
10055 catch (const gdb_exception_error &ex)
10056 {
10057 remote_unpush_target (this);
10058 throw_error (TARGET_CLOSE_ERROR,
10059 _("Remote communication error. "
10060 "Target disconnected: %s"),
10061 ex.what ());
10062 }
10063
10064 if (rs->got_ctrlc_during_io)
10065 set_quit_flag ();
10066}
10067
10068void
10069remote_target::remote_serial_send_break ()
10070{
10071 struct remote_state *rs = get_remote_state ();
10072
10073 try
10074 {
10075 serial_send_break (rs->remote_desc);
10076 }
10077 catch (const gdb_exception_error &ex)
10078 {
10079 remote_unpush_target (this);
10080 throw_error (TARGET_CLOSE_ERROR,
10081 _("Remote communication error. "
10082 "Target disconnected: %s"),
10083 ex.what ());
10084 }
10085}
10086
10087/* Return a string representing an escaped version of BUF, of len N.
10088 E.g. \n is converted to \\n, \t to \\t, etc. */
10089
10090static std::string
10091escape_buffer (const char *buf, int n)
10092{
10093 string_file stb;
10094
10095 stb.putstrn (buf, n, '\\');
10096 return stb.release ();
10097}
10098
10099int
10100remote_target::putpkt (const char *buf)
10101{
10102 return putpkt_binary (buf, strlen (buf));
10103}
10104
10105/* Wrapper around remote_target::putpkt to avoid exporting
10106 remote_target. */
10107
10108int
10109putpkt (remote_target *remote, const char *buf)
10110{
10111 return remote->putpkt (buf);
10112}
10113
10114/* Send a packet to the remote machine, with error checking. The data
10115 of the packet is in BUF. The string in BUF can be at most
10116 get_remote_packet_size () - 5 to account for the $, # and checksum,
10117 and for a possible /0 if we are debugging (remote_debug) and want
10118 to print the sent packet as a string. */
10119
10120int
10121remote_target::putpkt_binary (const char *buf, int cnt)
10122{
10123 struct remote_state *rs = get_remote_state ();
10124 int i;
10125 unsigned char csum = 0;
10126 gdb::def_vector<char> data (cnt + 6);
10127 char *buf2 = data.data ();
10128
10129 int ch;
10130 int tcount = 0;
10131 char *p;
10132
10133 /* Catch cases like trying to read memory or listing threads while
10134 we're waiting for a stop reply. The remote server wouldn't be
10135 ready to handle this request, so we'd hang and timeout. We don't
10136 have to worry about this in synchronous mode, because in that
10137 case it's not possible to issue a command while the target is
10138 running. This is not a problem in non-stop mode, because in that
10139 case, the stub is always ready to process serial input. */
10140 if (!target_is_non_stop_p ()
10141 && target_is_async_p ()
10142 && rs->waiting_for_stop_reply)
10143 {
10144 error (_("Cannot execute this command while the target is running.\n"
10145 "Use the \"interrupt\" command to stop the target\n"
10146 "and then try again."));
10147 }
10148
10149 /* Copy the packet into buffer BUF2, encapsulating it
10150 and giving it a checksum. */
10151
10152 p = buf2;
10153 *p++ = '$';
10154
10155 for (i = 0; i < cnt; i++)
10156 {
10157 csum += buf[i];
10158 *p++ = buf[i];
10159 }
10160 *p++ = '#';
10161 *p++ = tohex ((csum >> 4) & 0xf);
10162 *p++ = tohex (csum & 0xf);
10163
10164 /* Send it over and over until we get a positive ack. */
10165
10166 while (1)
10167 {
10168 if (remote_debug)
10169 {
10170 *p = '\0';
10171
10172 int len = (int) (p - buf2);
10173 int max_chars;
10174
10175 if (remote_packet_max_chars < 0)
10176 max_chars = len;
10177 else
10178 max_chars = remote_packet_max_chars;
10179
10180 std::string str
10181 = escape_buffer (buf2, std::min (len, max_chars));
10182
10183 if (len > max_chars)
10184 remote_debug_printf_nofunc
10185 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
10186 len - max_chars);
10187 else
10188 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
10189 }
10190 remote_serial_write (buf2, p - buf2);
10191
10192 /* If this is a no acks version of the remote protocol, send the
10193 packet and move on. */
10194 if (rs->noack_mode)
10195 break;
10196
10197 /* Read until either a timeout occurs (-2) or '+' is read.
10198 Handle any notification that arrives in the mean time. */
10199 while (1)
10200 {
10201 ch = readchar (remote_timeout);
10202
10203 switch (ch)
10204 {
10205 case '+':
10206 remote_debug_printf_nofunc ("Received Ack");
10207 return 1;
10208 case '-':
10209 remote_debug_printf_nofunc ("Received Nak");
10210 [[fallthrough]];
10211 case SERIAL_TIMEOUT:
10212 tcount++;
10213 if (tcount > 3)
10214 return 0;
10215 break; /* Retransmit buffer. */
10216 case '$':
10217 {
10218 remote_debug_printf ("Packet instead of Ack, ignoring it");
10219 /* It's probably an old response sent because an ACK
10220 was lost. Gobble up the packet and ack it so it
10221 doesn't get retransmitted when we resend this
10222 packet. */
10223 skip_frame ();
10224 remote_serial_write ("+", 1);
10225 continue; /* Now, go look for +. */
10226 }
10227
10228 case '%':
10229 {
10230 int val;
10231
10232 /* If we got a notification, handle it, and go back to looking
10233 for an ack. */
10234 /* We've found the start of a notification. Now
10235 collect the data. */
10236 val = read_frame (&rs->buf);
10237 if (val >= 0)
10238 {
10239 remote_debug_printf_nofunc
10240 (" Notification received: %s",
10241 escape_buffer (rs->buf.data (), val).c_str ());
10242
10243 handle_notification (rs->notif_state, rs->buf.data ());
10244 /* We're in sync now, rewait for the ack. */
10245 tcount = 0;
10246 }
10247 else
10248 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10249 rs->buf.data ());
10250 continue;
10251 }
10252 default:
10253 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10254 rs->buf.data ());
10255 continue;
10256 }
10257 break; /* Here to retransmit. */
10258 }
10259
10260#if 0
10261 /* This is wrong. If doing a long backtrace, the user should be
10262 able to get out next time we call QUIT, without anything as
10263 violent as interrupt_query. If we want to provide a way out of
10264 here without getting to the next QUIT, it should be based on
10265 hitting ^C twice as in remote_wait. */
10266 if (quit_flag)
10267 {
10268 quit_flag = 0;
10269 interrupt_query ();
10270 }
10271#endif
10272 }
10273
10274 return 0;
10275}
10276
10277/* Come here after finding the start of a frame when we expected an
10278 ack. Do our best to discard the rest of this packet. */
10279
10280void
10281remote_target::skip_frame ()
10282{
10283 int c;
10284
10285 while (1)
10286 {
10287 c = readchar (remote_timeout);
10288 switch (c)
10289 {
10290 case SERIAL_TIMEOUT:
10291 /* Nothing we can do. */
10292 return;
10293 case '#':
10294 /* Discard the two bytes of checksum and stop. */
10295 c = readchar (remote_timeout);
10296 if (c >= 0)
10297 c = readchar (remote_timeout);
10298
10299 return;
10300 case '*': /* Run length encoding. */
10301 /* Discard the repeat count. */
10302 c = readchar (remote_timeout);
10303 if (c < 0)
10304 return;
10305 break;
10306 default:
10307 /* A regular character. */
10308 break;
10309 }
10310 }
10311}
10312
10313/* Come here after finding the start of the frame. Collect the rest
10314 into *BUF, verifying the checksum, length, and handling run-length
10315 compression. NUL terminate the buffer. If there is not enough room,
10316 expand *BUF.
10317
10318 Returns -1 on error, number of characters in buffer (ignoring the
10319 trailing NULL) on success. (could be extended to return one of the
10320 SERIAL status indications). */
10321
10322long
10323remote_target::read_frame (gdb::char_vector *buf_p)
10324{
10325 unsigned char csum;
10326 long bc;
10327 int c;
10328 char *buf = buf_p->data ();
10329 struct remote_state *rs = get_remote_state ();
10330
10331 csum = 0;
10332 bc = 0;
10333
10334 while (1)
10335 {
10336 c = readchar (remote_timeout);
10337 switch (c)
10338 {
10339 case SERIAL_TIMEOUT:
10340 remote_debug_printf ("Timeout in mid-packet, retrying");
10341 return -1;
10342
10343 case '$':
10344 remote_debug_printf ("Saw new packet start in middle of old one");
10345 return -1; /* Start a new packet, count retries. */
10346
10347 case '#':
10348 {
10349 unsigned char pktcsum;
10350 int check_0 = 0;
10351 int check_1 = 0;
10352
10353 buf[bc] = '\0';
10354
10355 check_0 = readchar (remote_timeout);
10356 if (check_0 >= 0)
10357 check_1 = readchar (remote_timeout);
10358
10359 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10360 {
10361 remote_debug_printf ("Timeout in checksum, retrying");
10362 return -1;
10363 }
10364 else if (check_0 < 0 || check_1 < 0)
10365 {
10366 remote_debug_printf ("Communication error in checksum");
10367 return -1;
10368 }
10369
10370 /* Don't recompute the checksum; with no ack packets we
10371 don't have any way to indicate a packet retransmission
10372 is necessary. */
10373 if (rs->noack_mode)
10374 return bc;
10375
10376 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10377 if (csum == pktcsum)
10378 return bc;
10379
10380 remote_debug_printf
10381 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10382 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10383
10384 /* Number of characters in buffer ignoring trailing
10385 NULL. */
10386 return -1;
10387 }
10388 case '*': /* Run length encoding. */
10389 {
10390 int repeat;
10391
10392 csum += c;
10393 c = readchar (remote_timeout);
10394 csum += c;
10395 repeat = c - ' ' + 3; /* Compute repeat count. */
10396
10397 /* The character before ``*'' is repeated. */
10398
10399 if (repeat > 0 && repeat <= 255 && bc > 0)
10400 {
10401 if (bc + repeat - 1 >= buf_p->size () - 1)
10402 {
10403 /* Make some more room in the buffer. */
10404 buf_p->resize (buf_p->size () + repeat);
10405 buf = buf_p->data ();
10406 }
10407
10408 memset (&buf[bc], buf[bc - 1], repeat);
10409 bc += repeat;
10410 continue;
10411 }
10412
10413 buf[bc] = '\0';
10414 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10415 return -1;
10416 }
10417 default:
10418 if (bc >= buf_p->size () - 1)
10419 {
10420 /* Make some more room in the buffer. */
10421 buf_p->resize (buf_p->size () * 2);
10422 buf = buf_p->data ();
10423 }
10424
10425 buf[bc++] = c;
10426 csum += c;
10427 continue;
10428 }
10429 }
10430}
10431
10432/* Set this to the maximum number of seconds to wait instead of waiting forever
10433 in target_wait(). If this timer times out, then it generates an error and
10434 the command is aborted. This replaces most of the need for timeouts in the
10435 GDB test suite, and makes it possible to distinguish between a hung target
10436 and one with slow communications. */
10437
10438static int watchdog = 0;
10439static void
10440show_watchdog (struct ui_file *file, int from_tty,
10441 struct cmd_list_element *c, const char *value)
10442{
10443 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10444}
10445
10446/* Read a packet from the remote machine, with error checking, and
10447 store it in *BUF. Resize *BUF if necessary to hold the result. If
10448 FOREVER, wait forever rather than timing out; this is used (in
10449 synchronous mode) to wait for a target that is is executing user
10450 code to stop. If FOREVER == false, this function is allowed to time
10451 out gracefully and return an indication of this to the caller.
10452 Otherwise return the number of bytes read. If IS_NOTIF is not
10453 NULL, then consider receiving a notification enough reason to
10454 return to the caller. In this case, *IS_NOTIF is an output boolean
10455 that indicates whether *BUF holds a notification or not (a regular
10456 packet). */
10457
10458int
10459remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10460{
10461 struct remote_state *rs = get_remote_state ();
10462 int c;
10463 int tries;
10464 int timeout;
10465 int val = -1;
10466
10467 strcpy (buf->data (), "timeout");
10468
10469 if (forever)
10470 timeout = watchdog > 0 ? watchdog : -1;
10471 else if (is_notif != nullptr)
10472 timeout = 0; /* There should already be a char in the buffer. If
10473 not, bail out. */
10474 else
10475 timeout = remote_timeout;
10476
10477#define MAX_TRIES 3
10478
10479 /* Process any number of notifications, and then return when
10480 we get a packet. */
10481 for (;;)
10482 {
10483 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10484 times. */
10485 for (tries = 1; tries <= MAX_TRIES; tries++)
10486 {
10487 /* This can loop forever if the remote side sends us
10488 characters continuously, but if it pauses, we'll get
10489 SERIAL_TIMEOUT from readchar because of timeout. Then
10490 we'll count that as a retry.
10491
10492 Note that even when forever is set, we will only wait
10493 forever prior to the start of a packet. After that, we
10494 expect characters to arrive at a brisk pace. They should
10495 show up within remote_timeout intervals. */
10496 do
10497 c = readchar (timeout);
10498 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10499
10500 if (c == SERIAL_TIMEOUT)
10501 {
10502 if (is_notif != nullptr)
10503 return -1; /* Don't complain, it's normal to not get
10504 anything in this case. */
10505
10506 if (forever) /* Watchdog went off? Kill the target. */
10507 {
10508 remote_unpush_target (this);
10509 throw_error (TARGET_CLOSE_ERROR,
10510 _("Watchdog timeout has expired. "
10511 "Target detached."));
10512 }
10513
10514 remote_debug_printf ("Timed out.");
10515 }
10516 else
10517 {
10518 /* We've found the start of a packet or notification.
10519 Now collect the data. */
10520 val = read_frame (buf);
10521 if (val >= 0)
10522 break;
10523 }
10524
10525 remote_serial_write ("-", 1);
10526 }
10527
10528 if (tries > MAX_TRIES)
10529 {
10530 /* We have tried hard enough, and just can't receive the
10531 packet/notification. Give up. */
10532 gdb_printf (_("Ignoring packet error, continuing...\n"));
10533
10534 /* Skip the ack char if we're in no-ack mode. */
10535 if (!rs->noack_mode)
10536 remote_serial_write ("+", 1);
10537 return -1;
10538 }
10539
10540 /* If we got an ordinary packet, return that to our caller. */
10541 if (c == '$')
10542 {
10543 if (remote_debug)
10544 {
10545 int max_chars;
10546
10547 if (remote_packet_max_chars < 0)
10548 max_chars = val;
10549 else
10550 max_chars = remote_packet_max_chars;
10551
10552 std::string str
10553 = escape_buffer (buf->data (),
10554 std::min (val, max_chars));
10555
10556 if (val > max_chars)
10557 remote_debug_printf_nofunc
10558 ("Packet received: %s [%d of %d bytes omitted]", str.c_str (),
10559 val - max_chars, val);
10560 else
10561 remote_debug_printf_nofunc ("Packet received: %s",
10562 str.c_str ());
10563 }
10564
10565 /* Skip the ack char if we're in no-ack mode. */
10566 if (!rs->noack_mode)
10567 remote_serial_write ("+", 1);
10568 if (is_notif != NULL)
10569 *is_notif = false;
10570 return val;
10571 }
10572
10573 /* If we got a notification, handle it, and go back to looking
10574 for a packet. */
10575 else
10576 {
10577 gdb_assert (c == '%');
10578
10579 remote_debug_printf_nofunc
10580 (" Notification received: %s",
10581 escape_buffer (buf->data (), val).c_str ());
10582
10583 if (is_notif != NULL)
10584 *is_notif = true;
10585
10586 handle_notification (rs->notif_state, buf->data ());
10587
10588 /* Notifications require no acknowledgement. */
10589
10590 if (is_notif != nullptr)
10591 return val;
10592 }
10593 }
10594}
10595
10596/* Kill any new fork children of inferior INF that haven't been
10597 processed by follow_fork. */
10598
10599void
10600remote_target::kill_new_fork_children (inferior *inf)
10601{
10602 remote_state *rs = get_remote_state ();
10603 const notif_client *notif = &notif_client_stop;
10604
10605 /* Kill the fork child threads of any threads in inferior INF that are stopped
10606 at a fork event. */
10607 for (thread_info *thread : inf->non_exited_threads ())
10608 {
10609 const target_waitstatus *ws = thread_pending_fork_status (thread);
10610
10611 if (ws == nullptr)
10612 continue;
10613
10614 int child_pid = ws->child_ptid ().pid ();
10615 int res = remote_vkill (child_pid);
10616
10617 if (res != 0)
10618 error (_("Can't kill fork child process %d"), child_pid);
10619 }
10620
10621 /* Check for any pending fork events (not reported or processed yet)
10622 in inferior INF and kill those fork child threads as well. */
10623 remote_notif_get_pending_events (notif);
10624 for (auto &event : rs->stop_reply_queue)
10625 {
10626 if (event->ptid.pid () != inf->pid)
10627 continue;
10628
10629 if (!is_fork_status (event->ws.kind ()))
10630 continue;
10631
10632 int child_pid = event->ws.child_ptid ().pid ();
10633 int res = remote_vkill (child_pid);
10634
10635 if (res != 0)
10636 error (_("Can't kill fork child process %d"), child_pid);
10637 }
10638}
10639
10640\f
10641/* Target hook to kill the current inferior. */
10642
10643void
10644remote_target::kill ()
10645{
10646 int res = -1;
10647 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10648
10649 gdb_assert (inf != nullptr);
10650
10651 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10652 {
10653 /* If we're stopped while forking and we haven't followed yet,
10654 kill the child task. We need to do this before killing the
10655 parent task because if this is a vfork then the parent will
10656 be sleeping. */
10657 kill_new_fork_children (inf);
10658
10659 res = remote_vkill (inf->pid);
10660 if (res == 0)
10661 {
10662 target_mourn_inferior (inferior_ptid);
10663 return;
10664 }
10665 }
10666
10667 /* If we are in 'target remote' mode and we are killing the only
10668 inferior, then we will tell gdbserver to exit and unpush the
10669 target. */
10670 if (res == -1 && !m_features.remote_multi_process_p ()
10671 && number_of_live_inferiors (this) == 1)
10672 {
10673 remote_kill_k ();
10674
10675 /* We've killed the remote end, we get to mourn it. If we are
10676 not in extended mode, mourning the inferior also unpushes
10677 remote_ops from the target stack, which closes the remote
10678 connection. */
10679 target_mourn_inferior (inferior_ptid);
10680
10681 return;
10682 }
10683
10684 error (_("Can't kill process"));
10685}
10686
10687/* Send a kill request to the target using the 'vKill' packet. */
10688
10689int
10690remote_target::remote_vkill (int pid)
10691{
10692 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10693 return -1;
10694
10695 remote_state *rs = get_remote_state ();
10696
10697 /* Tell the remote target to detach. */
10698 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10699 putpkt (rs->buf);
10700 getpkt (&rs->buf);
10701
10702 switch ((m_features.packet_ok (rs->buf, PACKET_vKill)).status ())
10703 {
10704 case PACKET_OK:
10705 return 0;
10706 case PACKET_ERROR:
10707 return 1;
10708 case PACKET_UNKNOWN:
10709 return -1;
10710 default:
10711 internal_error (_("Bad result from packet_ok"));
10712 }
10713}
10714
10715/* Send a kill request to the target using the 'k' packet. */
10716
10717void
10718remote_target::remote_kill_k ()
10719{
10720 /* Catch errors so the user can quit from gdb even when we
10721 aren't on speaking terms with the remote system. */
10722 try
10723 {
10724 putpkt ("k");
10725 }
10726 catch (const gdb_exception_error &ex)
10727 {
10728 if (ex.error == TARGET_CLOSE_ERROR)
10729 {
10730 /* If we got an (EOF) error that caused the target
10731 to go away, then we're done, that's what we wanted.
10732 "k" is susceptible to cause a premature EOF, given
10733 that the remote server isn't actually required to
10734 reply to "k", and it can happen that it doesn't
10735 even get to reply ACK to the "k". */
10736 return;
10737 }
10738
10739 /* Otherwise, something went wrong. We didn't actually kill
10740 the target. Just propagate the exception, and let the
10741 user or higher layers decide what to do. */
10742 throw;
10743 }
10744}
10745
10746void
10747remote_target::mourn_inferior ()
10748{
10749 struct remote_state *rs = get_remote_state ();
10750
10751 /* We're no longer interested in notification events of an inferior
10752 that exited or was killed/detached. */
10753 discard_pending_stop_replies (current_inferior ());
10754
10755 /* In 'target remote' mode with one inferior, we close the connection. */
10756 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10757 {
10758 remote_unpush_target (this);
10759 return;
10760 }
10761
10762 /* In case we got here due to an error, but we're going to stay
10763 connected. */
10764 rs->waiting_for_stop_reply = 0;
10765
10766 /* If the current general thread belonged to the process we just
10767 detached from or has exited, the remote side current general
10768 thread becomes undefined. Considering a case like this:
10769
10770 - We just got here due to a detach.
10771 - The process that we're detaching from happens to immediately
10772 report a global breakpoint being hit in non-stop mode, in the
10773 same thread we had selected before.
10774 - GDB attaches to this process again.
10775 - This event happens to be the next event we handle.
10776
10777 GDB would consider that the current general thread didn't need to
10778 be set on the stub side (with Hg), since for all it knew,
10779 GENERAL_THREAD hadn't changed.
10780
10781 Notice that although in all-stop mode, the remote server always
10782 sets the current thread to the thread reporting the stop event,
10783 that doesn't happen in non-stop mode; in non-stop, the stub *must
10784 not* change the current thread when reporting a breakpoint hit,
10785 due to the decoupling of event reporting and event handling.
10786
10787 To keep things simple, we always invalidate our notion of the
10788 current thread. */
10789 record_currthread (rs, minus_one_ptid);
10790
10791 /* Call common code to mark the inferior as not running. */
10792 generic_mourn_inferior ();
10793}
10794
10795bool
10796extended_remote_target::supports_disable_randomization ()
10797{
10798 return (m_features.packet_support (PACKET_QDisableRandomization)
10799 == PACKET_ENABLE);
10800}
10801
10802void
10803remote_target::extended_remote_disable_randomization (int val)
10804{
10805 struct remote_state *rs = get_remote_state ();
10806 char *reply;
10807
10808 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10809 "QDisableRandomization:%x", val);
10810 putpkt (rs->buf);
10811 reply = remote_get_noisy_reply ();
10812 if (*reply == '\0')
10813 error (_("Target does not support QDisableRandomization."));
10814 if (strcmp (reply, "OK") != 0)
10815 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10816}
10817
10818int
10819remote_target::extended_remote_run (const std::string &args)
10820{
10821 struct remote_state *rs = get_remote_state ();
10822 int len;
10823 const char *remote_exec_file = get_remote_exec_file ();
10824
10825 /* If the user has disabled vRun support, or we have detected that
10826 support is not available, do not try it. */
10827 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10828 return -1;
10829
10830 strcpy (rs->buf.data (), "vRun;");
10831 len = strlen (rs->buf.data ());
10832
10833 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10834 error (_("Remote file name too long for run packet"));
10835 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10836 strlen (remote_exec_file));
10837
10838 if (!args.empty ())
10839 {
10840 std::vector<std::string> split_args = gdb::remote_args::split (args);
10841
10842 for (const auto &a : split_args)
10843 {
10844 if (a.size () * 2 + 1 + len >= get_remote_packet_size ())
10845 error (_("Argument list too long for run packet"));
10846 rs->buf[len++] = ';';
10847 len += 2 * bin2hex ((gdb_byte *) a.c_str (), rs->buf.data () + len,
10848 a.size ());
10849 }
10850 }
10851
10852 rs->buf[len++] = '\0';
10853
10854 putpkt (rs->buf);
10855 getpkt (&rs->buf);
10856
10857 packet_result result = m_features.packet_ok (rs->buf, PACKET_vRun);
10858 switch (result.status ())
10859 {
10860 case PACKET_OK:
10861 /* We have a wait response. All is well. */
10862 return 0;
10863 case PACKET_UNKNOWN:
10864 return -1;
10865 case PACKET_ERROR:
10866 /* If we have a textual error message, print just that. This
10867 makes remote debugging output the same as native output, when
10868 possible. */
10869 if (result.textual_err_msg ())
10870 error (("%s"), result.err_msg ());
10871 if (remote_exec_file[0] == '\0')
10872 error (_("Running the default executable on the remote target failed; "
10873 "try \"set remote exec-file\"?"));
10874 else
10875 error (_("Running \"%s\" on the remote target failed"),
10876 remote_exec_file);
10877 default:
10878 gdb_assert_not_reached ("bad switch");
10879 }
10880}
10881
10882/* Helper function to send set/unset environment packets. ACTION is
10883 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10884 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10885 sent. */
10886
10887void
10888remote_target::send_environment_packet (const char *action,
10889 const char *packet,
10890 const char *value)
10891{
10892 remote_state *rs = get_remote_state ();
10893
10894 /* Convert the environment variable to an hex string, which
10895 is the best format to be transmitted over the wire. */
10896 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10897 strlen (value));
10898
10899 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10900 "%s:%s", packet, encoded_value.c_str ());
10901
10902 putpkt (rs->buf);
10903 getpkt (&rs->buf);
10904 if (strcmp (rs->buf.data (), "OK") != 0)
10905 warning (_("Unable to %s environment variable '%s' on remote."),
10906 action, value);
10907}
10908
10909/* Helper function to handle the QEnvironment* packets. */
10910
10911void
10912remote_target::extended_remote_environment_support ()
10913{
10914 remote_state *rs = get_remote_state ();
10915
10916 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10917 {
10918 putpkt ("QEnvironmentReset");
10919 getpkt (&rs->buf);
10920 if (strcmp (rs->buf.data (), "OK") != 0)
10921 warning (_("Unable to reset environment on remote."));
10922 }
10923
10924 gdb_environ *e = &current_inferior ()->environment;
10925
10926 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10927 != PACKET_DISABLE)
10928 {
10929 for (const std::string &el : e->user_set_env ())
10930 send_environment_packet ("set", "QEnvironmentHexEncoded",
10931 el.c_str ());
10932 }
10933
10934
10935 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10936 for (const std::string &el : e->user_unset_env ())
10937 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10938}
10939
10940/* Helper function to set the current working directory for the
10941 inferior in the remote target. */
10942
10943void
10944remote_target::extended_remote_set_inferior_cwd ()
10945{
10946 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10947 {
10948 const std::string &inferior_cwd = current_inferior ()->cwd ();
10949 remote_state *rs = get_remote_state ();
10950
10951 if (!inferior_cwd.empty ())
10952 {
10953 std::string hexpath
10954 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10955 inferior_cwd.size ());
10956
10957 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10958 "QSetWorkingDir:%s", hexpath.c_str ());
10959 }
10960 else
10961 {
10962 /* An empty inferior_cwd means that the user wants us to
10963 reset the remote server's inferior's cwd. */
10964 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10965 "QSetWorkingDir:");
10966 }
10967
10968 putpkt (rs->buf);
10969 getpkt (&rs->buf);
10970 packet_result result = m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir);
10971 if (result.status () == PACKET_ERROR)
10972 error (_("\
10973Remote replied unexpectedly while setting the inferior's working\n\
10974directory: %s"),
10975 result.err_msg ());
10976 if (result.status () == PACKET_UNKNOWN)
10977 error (_("Remote target failed to process setting the inferior's working directory"));
10978
10979 }
10980}
10981
10982/* In the extended protocol we want to be able to do things like
10983 "run" and have them basically work as expected. So we need
10984 a special create_inferior function. We support changing the
10985 executable file and the command line arguments, but not the
10986 environment. */
10987
10988void
10989extended_remote_target::create_inferior (const char *exec_file,
10990 const std::string &args,
10991 char **env, int from_tty)
10992{
10993 int run_worked;
10994 char *stop_reply;
10995 struct remote_state *rs = get_remote_state ();
10996 const char *remote_exec_file = get_remote_exec_file ();
10997
10998 /* If running asynchronously, register the target file descriptor
10999 with the event loop. */
11000 if (target_can_async_p ())
11001 target_async (true);
11002
11003 /* Disable address space randomization if requested (and supported). */
11004 if (supports_disable_randomization ())
11005 extended_remote_disable_randomization (disable_randomization);
11006
11007 /* If startup-with-shell is on, we inform gdbserver to start the
11008 remote inferior using a shell. */
11009 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
11010 {
11011 xsnprintf (rs->buf.data (), get_remote_packet_size (),
11012 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
11013 putpkt (rs->buf);
11014 getpkt (&rs->buf);
11015 if (strcmp (rs->buf.data (), "OK") != 0)
11016 error (_("\
11017Remote replied unexpectedly while setting startup-with-shell: %s"),
11018 rs->buf.data ());
11019 }
11020
11021 extended_remote_environment_support ();
11022
11023 extended_remote_set_inferior_cwd ();
11024
11025 /* Now restart the remote server. */
11026 run_worked = extended_remote_run (args) != -1;
11027 if (!run_worked)
11028 {
11029 /* vRun was not supported. Fail if we need it to do what the
11030 user requested. */
11031 if (remote_exec_file[0])
11032 error (_("Remote target does not support \"set remote exec-file\""));
11033 if (!args.empty ())
11034 error (_("Remote target does not support \"set args\" or run ARGS"));
11035
11036 /* Fall back to "R". */
11037 extended_remote_restart ();
11038 }
11039
11040 /* vRun's success return is a stop reply. */
11041 stop_reply = run_worked ? rs->buf.data () : NULL;
11042 add_current_inferior_and_thread (stop_reply);
11043
11044 /* Get updated offsets, if the stub uses qOffsets. */
11045 get_offsets ();
11046}
11047\f
11048
11049/* Given a location's target info BP_TGT and the packet buffer BUF, output
11050 the list of conditions (in agent expression bytecode format), if any, the
11051 target needs to evaluate. The output is placed into the packet buffer
11052 started from BUF and ended at BUF_END. */
11053
11054static int
11055remote_add_target_side_condition (struct gdbarch *gdbarch,
11056 struct bp_target_info *bp_tgt, char *buf,
11057 char *buf_end)
11058{
11059 if (bp_tgt->conditions.empty ())
11060 return 0;
11061
11062 buf += strlen (buf);
11063 xsnprintf (buf, buf_end - buf, "%s", ";");
11064 buf++;
11065
11066 /* Send conditions to the target. */
11067 for (agent_expr *aexpr : bp_tgt->conditions)
11068 {
11069 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
11070 buf += strlen (buf);
11071 for (int i = 0; i < aexpr->buf.size (); ++i)
11072 buf = pack_hex_byte (buf, aexpr->buf[i]);
11073 *buf = '\0';
11074 }
11075 return 0;
11076}
11077
11078static void
11079remote_add_target_side_commands (struct gdbarch *gdbarch,
11080 struct bp_target_info *bp_tgt, char *buf)
11081{
11082 if (bp_tgt->tcommands.empty ())
11083 return;
11084
11085 buf += strlen (buf);
11086
11087 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
11088 buf += strlen (buf);
11089
11090 /* Concatenate all the agent expressions that are commands into the
11091 cmds parameter. */
11092 for (agent_expr *aexpr : bp_tgt->tcommands)
11093 {
11094 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
11095 buf += strlen (buf);
11096 for (int i = 0; i < aexpr->buf.size (); ++i)
11097 buf = pack_hex_byte (buf, aexpr->buf[i]);
11098 *buf = '\0';
11099 }
11100}
11101
11102/* Insert a breakpoint. On targets that have software breakpoint
11103 support, we ask the remote target to do the work; on targets
11104 which don't, we insert a traditional memory breakpoint. */
11105
11106int
11107remote_target::insert_breakpoint (struct gdbarch *gdbarch,
11108 struct bp_target_info *bp_tgt)
11109{
11110 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
11111 If it succeeds, then set the support to PACKET_ENABLE. If it
11112 fails, and the user has explicitly requested the Z support then
11113 report an error, otherwise, mark it disabled and go on. */
11114
11115 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11116 {
11117 CORE_ADDR addr = bp_tgt->reqstd_address;
11118 struct remote_state *rs;
11119 char *p, *endbuf;
11120
11121 /* Make sure the remote is pointing at the right process, if
11122 necessary. */
11123 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11124 set_general_process ();
11125
11126 rs = get_remote_state ();
11127 p = rs->buf.data ();
11128 endbuf = p + get_remote_packet_size ();
11129
11130 *(p++) = 'Z';
11131 *(p++) = '0';
11132 *(p++) = ',';
11133 addr = (ULONGEST) remote_address_masked (addr);
11134 p += hexnumstr (p, addr);
11135 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11136
11137 if (supports_evaluation_of_breakpoint_conditions ())
11138 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11139
11140 if (can_run_breakpoint_commands ())
11141 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11142
11143 putpkt (rs->buf);
11144 getpkt (&rs->buf);
11145
11146 switch ((m_features.packet_ok (rs->buf, PACKET_Z0)).status ())
11147 {
11148 case PACKET_ERROR:
11149 return -1;
11150 case PACKET_OK:
11151 return 0;
11152 case PACKET_UNKNOWN:
11153 break;
11154 }
11155 }
11156
11157 /* If this breakpoint has target-side commands but this stub doesn't
11158 support Z0 packets, throw error. */
11159 if (!bp_tgt->tcommands.empty ())
11160 throw_error (NOT_SUPPORTED_ERROR, _("\
11161Target doesn't support breakpoints that have target side commands."));
11162
11163 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
11164}
11165
11166int
11167remote_target::remove_breakpoint (struct gdbarch *gdbarch,
11168 struct bp_target_info *bp_tgt,
11169 enum remove_bp_reason reason)
11170{
11171 CORE_ADDR addr = bp_tgt->placed_address;
11172 struct remote_state *rs = get_remote_state ();
11173
11174 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11175 {
11176 char *p = rs->buf.data ();
11177 char *endbuf = p + get_remote_packet_size ();
11178
11179 /* Make sure the remote is pointing at the right process, if
11180 necessary. */
11181 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11182 set_general_process ();
11183
11184 *(p++) = 'z';
11185 *(p++) = '0';
11186 *(p++) = ',';
11187
11188 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
11189 p += hexnumstr (p, addr);
11190 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11191
11192 putpkt (rs->buf);
11193 getpkt (&rs->buf);
11194
11195 return (rs->buf[0] == 'E');
11196 }
11197
11198 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
11199}
11200
11201static enum Z_packet_type
11202watchpoint_to_Z_packet (int type)
11203{
11204 switch (type)
11205 {
11206 case hw_write:
11207 return Z_PACKET_WRITE_WP;
11208 break;
11209 case hw_read:
11210 return Z_PACKET_READ_WP;
11211 break;
11212 case hw_access:
11213 return Z_PACKET_ACCESS_WP;
11214 break;
11215 default:
11216 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
11217 }
11218}
11219
11220int
11221remote_target::insert_watchpoint (CORE_ADDR addr, int len,
11222 enum target_hw_bp_type type, struct expression *cond)
11223{
11224 struct remote_state *rs = get_remote_state ();
11225 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11226 char *p;
11227 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11228
11229 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11230 + to_underlying (packet))) == PACKET_DISABLE)
11231 return 1;
11232
11233 /* Make sure the remote is pointing at the right process, if
11234 necessary. */
11235 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11236 set_general_process ();
11237
11238 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11239 p = strchr (rs->buf.data (), '\0');
11240 addr = remote_address_masked (addr);
11241 p += hexnumstr (p, (ULONGEST) addr);
11242 xsnprintf (p, endbuf - p, ",%x", len);
11243
11244 putpkt (rs->buf);
11245 getpkt (&rs->buf);
11246
11247 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11248 + to_underlying (packet)))).status ())
11249 {
11250 case PACKET_ERROR:
11251 return -1;
11252 case PACKET_UNKNOWN:
11253 return 1;
11254 case PACKET_OK:
11255 return 0;
11256 }
11257 internal_error (_("remote_insert_watchpoint: reached end of function"));
11258}
11259
11260bool
11261remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11262 CORE_ADDR start, int length)
11263{
11264 CORE_ADDR diff = remote_address_masked (addr - start);
11265
11266 return diff < length;
11267}
11268
11269
11270int
11271remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11272 enum target_hw_bp_type type, struct expression *cond)
11273{
11274 struct remote_state *rs = get_remote_state ();
11275 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11276 char *p;
11277 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11278
11279 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11280 + to_underlying (packet))) == PACKET_DISABLE)
11281 return -1;
11282
11283 /* Make sure the remote is pointing at the right process, if
11284 necessary. */
11285 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11286 set_general_process ();
11287
11288 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11289 p = strchr (rs->buf.data (), '\0');
11290 addr = remote_address_masked (addr);
11291 p += hexnumstr (p, (ULONGEST) addr);
11292 xsnprintf (p, endbuf - p, ",%x", len);
11293 putpkt (rs->buf);
11294 getpkt (&rs->buf);
11295
11296 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11297 + to_underlying (packet)))).status ())
11298 {
11299 case PACKET_ERROR:
11300 case PACKET_UNKNOWN:
11301 return -1;
11302 case PACKET_OK:
11303 return 0;
11304 }
11305 internal_error (_("remote_remove_watchpoint: reached end of function"));
11306}
11307
11308
11309static int remote_hw_watchpoint_limit = -1;
11310static int remote_hw_watchpoint_length_limit = -1;
11311static int remote_hw_breakpoint_limit = -1;
11312
11313int
11314remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11315{
11316 if (remote_hw_watchpoint_length_limit == 0)
11317 return 0;
11318 else if (remote_hw_watchpoint_length_limit < 0)
11319 return 1;
11320 else if (len <= remote_hw_watchpoint_length_limit)
11321 return 1;
11322 else
11323 return 0;
11324}
11325
11326int
11327remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11328{
11329 if (type == bp_hardware_breakpoint)
11330 {
11331 if (remote_hw_breakpoint_limit == 0)
11332 return 0;
11333 else if (remote_hw_breakpoint_limit < 0)
11334 return 1;
11335 else if (cnt <= remote_hw_breakpoint_limit)
11336 return 1;
11337 }
11338 else
11339 {
11340 if (remote_hw_watchpoint_limit == 0)
11341 return 0;
11342 else if (remote_hw_watchpoint_limit < 0)
11343 return 1;
11344 else if (ot)
11345 return -1;
11346 else if (cnt <= remote_hw_watchpoint_limit)
11347 return 1;
11348 }
11349 return -1;
11350}
11351
11352/* The to_stopped_by_sw_breakpoint method of target remote. */
11353
11354bool
11355remote_target::stopped_by_sw_breakpoint ()
11356{
11357 struct thread_info *thread = inferior_thread ();
11358
11359 return (thread->priv != NULL
11360 && (get_remote_thread_info (thread)->stop_reason
11361 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11362}
11363
11364/* The to_supports_stopped_by_sw_breakpoint method of target
11365 remote. */
11366
11367bool
11368remote_target::supports_stopped_by_sw_breakpoint ()
11369{
11370 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11371}
11372
11373/* The to_stopped_by_hw_breakpoint method of target remote. */
11374
11375bool
11376remote_target::stopped_by_hw_breakpoint ()
11377{
11378 struct thread_info *thread = inferior_thread ();
11379
11380 return (thread->priv != NULL
11381 && (get_remote_thread_info (thread)->stop_reason
11382 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11383}
11384
11385/* The to_supports_stopped_by_hw_breakpoint method of target
11386 remote. */
11387
11388bool
11389remote_target::supports_stopped_by_hw_breakpoint ()
11390{
11391 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11392}
11393
11394bool
11395remote_target::stopped_by_watchpoint ()
11396{
11397 struct thread_info *thread = inferior_thread ();
11398
11399 return (thread->priv != NULL
11400 && (get_remote_thread_info (thread)->stop_reason
11401 == TARGET_STOPPED_BY_WATCHPOINT));
11402}
11403
11404bool
11405remote_target::stopped_data_address (CORE_ADDR *addr_p)
11406{
11407 struct thread_info *thread = inferior_thread ();
11408
11409 if (thread->priv != NULL
11410 && (get_remote_thread_info (thread)->stop_reason
11411 == TARGET_STOPPED_BY_WATCHPOINT))
11412 {
11413 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11414 return true;
11415 }
11416
11417 return false;
11418}
11419
11420
11421int
11422remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11423 struct bp_target_info *bp_tgt)
11424{
11425 CORE_ADDR addr = bp_tgt->reqstd_address;
11426 struct remote_state *rs;
11427 char *p, *endbuf;
11428
11429 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11430 return -1;
11431
11432 /* Make sure the remote is pointing at the right process, if
11433 necessary. */
11434 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11435 set_general_process ();
11436
11437 rs = get_remote_state ();
11438 p = rs->buf.data ();
11439 endbuf = p + get_remote_packet_size ();
11440
11441 *(p++) = 'Z';
11442 *(p++) = '1';
11443 *(p++) = ',';
11444
11445 addr = remote_address_masked (addr);
11446 p += hexnumstr (p, (ULONGEST) addr);
11447 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11448
11449 if (supports_evaluation_of_breakpoint_conditions ())
11450 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11451
11452 if (can_run_breakpoint_commands ())
11453 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11454
11455 putpkt (rs->buf);
11456 getpkt (&rs->buf);
11457
11458 packet_result result = m_features.packet_ok (rs->buf, PACKET_Z1);
11459 switch (result.status ())
11460 {
11461 case PACKET_ERROR:
11462 error (_("Remote failure reply: %s"), result.err_msg ());
11463 case PACKET_UNKNOWN:
11464 return -1;
11465 case PACKET_OK:
11466 return 0;
11467 }
11468 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11469}
11470
11471
11472int
11473remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11474 struct bp_target_info *bp_tgt)
11475{
11476 CORE_ADDR addr;
11477 struct remote_state *rs = get_remote_state ();
11478 char *p = rs->buf.data ();
11479 char *endbuf = p + get_remote_packet_size ();
11480
11481 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11482 return -1;
11483
11484 /* Make sure the remote is pointing at the right process, if
11485 necessary. */
11486 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11487 set_general_process ();
11488
11489 *(p++) = 'z';
11490 *(p++) = '1';
11491 *(p++) = ',';
11492
11493 addr = remote_address_masked (bp_tgt->placed_address);
11494 p += hexnumstr (p, (ULONGEST) addr);
11495 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11496
11497 putpkt (rs->buf);
11498 getpkt (&rs->buf);
11499
11500 switch ((m_features.packet_ok (rs->buf, PACKET_Z1)).status ())
11501 {
11502 case PACKET_ERROR:
11503 case PACKET_UNKNOWN:
11504 return -1;
11505 case PACKET_OK:
11506 return 0;
11507 }
11508 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11509}
11510
11511/* Verify memory using the "qCRC:" request. */
11512
11513int
11514remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11515{
11516 struct remote_state *rs = get_remote_state ();
11517 unsigned long host_crc, target_crc;
11518 char *tmp;
11519
11520 /* It doesn't make sense to use qCRC if the remote target is
11521 connected but not running. */
11522 if (target_has_execution ()
11523 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11524 {
11525 enum packet_status status;
11526
11527 /* Make sure the remote is pointing at the right process. */
11528 set_general_process ();
11529
11530 /* FIXME: assumes lma can fit into long. */
11531 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11532 (long) lma, (long) size);
11533 putpkt (rs->buf);
11534
11535 /* Be clever; compute the host_crc before waiting for target
11536 reply. */
11537 host_crc = xcrc32 (data, size, 0xffffffff);
11538
11539 getpkt (&rs->buf);
11540
11541 status = (m_features.packet_ok (rs->buf, PACKET_qCRC)).status ();
11542 if (status == PACKET_ERROR)
11543 return -1;
11544 else if (status == PACKET_OK)
11545 {
11546 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11547 target_crc = target_crc * 16 + fromhex (*tmp);
11548
11549 return (host_crc == target_crc);
11550 }
11551 }
11552
11553 return simple_verify_memory (this, data, lma, size);
11554}
11555
11556/* compare-sections command
11557
11558 With no arguments, compares each loadable section in the exec bfd
11559 with the same memory range on the target, and reports mismatches.
11560 Useful for verifying the image on the target against the exec file. */
11561
11562static void
11563compare_sections_command (const char *args, int from_tty)
11564{
11565 asection *s;
11566 const char *sectname;
11567 bfd_size_type size;
11568 bfd_vma lma;
11569 int matched = 0;
11570 int mismatched = 0;
11571 int res;
11572 int read_only = 0;
11573
11574 if (!current_program_space->exec_bfd ())
11575 error (_("command cannot be used without an exec file"));
11576
11577 if (args != NULL && strcmp (args, "-r") == 0)
11578 {
11579 read_only = 1;
11580 args = NULL;
11581 }
11582
11583 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11584 {
11585 if (!(s->flags & SEC_LOAD))
11586 continue; /* Skip non-loadable section. */
11587
11588 if (read_only && (s->flags & SEC_READONLY) == 0)
11589 continue; /* Skip writeable sections */
11590
11591 size = bfd_section_size (s);
11592 if (size == 0)
11593 continue; /* Skip zero-length section. */
11594
11595 sectname = bfd_section_name (s);
11596 if (args && strcmp (args, sectname) != 0)
11597 continue; /* Not the section selected by user. */
11598
11599 matched = 1; /* Do this section. */
11600 lma = s->lma;
11601
11602 gdb::byte_vector sectdata (size);
11603 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11604 sectdata.data (), 0, size);
11605
11606 res = target_verify_memory (sectdata.data (), lma, size);
11607
11608 if (res == -1)
11609 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11610 paddress (current_inferior ()->arch (), lma),
11611 paddress (current_inferior ()->arch (), lma + size));
11612
11613 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11614 paddress (current_inferior ()->arch (), lma),
11615 paddress (current_inferior ()->arch (), lma + size));
11616 if (res)
11617 gdb_printf ("matched.\n");
11618 else
11619 {
11620 gdb_printf ("MIS-MATCHED!\n");
11621 mismatched++;
11622 }
11623 }
11624 if (mismatched > 0)
11625 warning (_("One or more sections of the target image does "
11626 "not match the loaded file"));
11627 if (args && !matched)
11628 gdb_printf (_("No loaded section named '%s'.\n"), args);
11629}
11630
11631/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11632 into remote target. The number of bytes written to the remote
11633 target is returned, or -1 for error. */
11634
11635target_xfer_status
11636remote_target::remote_write_qxfer (const char *object_name,
11637 const char *annex, const gdb_byte *writebuf,
11638 ULONGEST offset, LONGEST len,
11639 ULONGEST *xfered_len,
11640 const unsigned int which_packet)
11641{
11642 int i, buf_len;
11643 ULONGEST n;
11644 struct remote_state *rs = get_remote_state ();
11645 int max_size = get_memory_write_packet_size ();
11646
11647 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11648 return TARGET_XFER_E_IO;
11649
11650 /* Insert header. */
11651 i = snprintf (rs->buf.data (), max_size,
11652 "qXfer:%s:write:%s:%s:",
11653 object_name, annex ? annex : "",
11654 phex_nz (offset));
11655 max_size -= (i + 1);
11656
11657 /* Escape as much data as fits into rs->buf. */
11658 buf_len = remote_escape_output
11659 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11660
11661 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11662 || getpkt (&rs->buf) < 0
11663 || (m_features.packet_ok (rs->buf, which_packet)).status () != PACKET_OK)
11664 return TARGET_XFER_E_IO;
11665
11666 unpack_varlen_hex (rs->buf.data (), &n);
11667
11668 *xfered_len = n;
11669 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11670}
11671
11672/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11673 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11674 number of bytes read is returned, or 0 for EOF, or -1 for error.
11675 The number of bytes read may be less than LEN without indicating an
11676 EOF. PACKET is checked and updated to indicate whether the remote
11677 target supports this object. */
11678
11679target_xfer_status
11680remote_target::remote_read_qxfer (const char *object_name,
11681 const char *annex,
11682 gdb_byte *readbuf, ULONGEST offset,
11683 LONGEST len,
11684 ULONGEST *xfered_len,
11685 const unsigned int which_packet)
11686{
11687 struct remote_state *rs = get_remote_state ();
11688 LONGEST i, n, packet_len;
11689
11690 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11691 return TARGET_XFER_E_IO;
11692
11693 /* Check whether we've cached an end-of-object packet that matches
11694 this request. */
11695 if (rs->finished_object)
11696 {
11697 if (strcmp (object_name, rs->finished_object) == 0
11698 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11699 && offset == rs->finished_offset)
11700 return TARGET_XFER_EOF;
11701
11702
11703 /* Otherwise, we're now reading something different. Discard
11704 the cache. */
11705 xfree (rs->finished_object);
11706 xfree (rs->finished_annex);
11707 rs->finished_object = NULL;
11708 rs->finished_annex = NULL;
11709 }
11710
11711 /* Request only enough to fit in a single packet. The actual data
11712 may not, since we don't know how much of it will need to be escaped;
11713 the target is free to respond with slightly less data. We subtract
11714 five to account for the response type and the protocol frame. */
11715 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11716 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11717 "qXfer:%s:read:%s:%s,%s",
11718 object_name, annex ? annex : "",
11719 phex_nz (offset),
11720 phex_nz (n));
11721 i = putpkt (rs->buf);
11722 if (i < 0)
11723 return TARGET_XFER_E_IO;
11724
11725 rs->buf[0] = '\0';
11726 packet_len = getpkt (&rs->buf);
11727 if (packet_len < 0
11728 || m_features.packet_ok (rs->buf, which_packet).status () != PACKET_OK)
11729 return TARGET_XFER_E_IO;
11730
11731 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11732 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11733
11734 /* 'm' means there is (or at least might be) more data after this
11735 batch. That does not make sense unless there's at least one byte
11736 of data in this reply. */
11737 if (rs->buf[0] == 'm' && packet_len == 1)
11738 error (_("Remote qXfer reply contained no data."));
11739
11740 /* Got some data. */
11741 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11742 packet_len - 1, readbuf, n);
11743
11744 /* 'l' is an EOF marker, possibly including a final block of data,
11745 or possibly empty. If we have the final block of a non-empty
11746 object, record this fact to bypass a subsequent partial read. */
11747 if (rs->buf[0] == 'l' && offset + i > 0)
11748 {
11749 rs->finished_object = xstrdup (object_name);
11750 rs->finished_annex = xstrdup (annex ? annex : "");
11751 rs->finished_offset = offset + i;
11752 }
11753
11754 if (i == 0)
11755 return TARGET_XFER_EOF;
11756 else
11757 {
11758 *xfered_len = i;
11759 return TARGET_XFER_OK;
11760 }
11761}
11762
11763enum target_xfer_status
11764remote_target::xfer_partial (enum target_object object,
11765 const char *annex, gdb_byte *readbuf,
11766 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11767 ULONGEST *xfered_len)
11768{
11769 struct remote_state *rs;
11770 int i;
11771 char *p2;
11772 char query_type;
11773 int unit_size
11774 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11775
11776 set_remote_traceframe ();
11777 set_general_thread (inferior_ptid);
11778
11779 rs = get_remote_state ();
11780
11781 /* Handle memory using the standard memory routines. */
11782 if (object == TARGET_OBJECT_MEMORY)
11783 {
11784 /* If the remote target is connected but not running, we should
11785 pass this request down to a lower stratum (e.g. the executable
11786 file). */
11787 if (!target_has_execution ())
11788 return TARGET_XFER_EOF;
11789
11790 if (writebuf != NULL)
11791 return remote_write_bytes (offset, writebuf, len, unit_size,
11792 xfered_len);
11793 else
11794 return remote_read_bytes (offset, readbuf, len, unit_size,
11795 xfered_len);
11796 }
11797
11798 /* Handle extra signal info using qxfer packets. */
11799 if (object == TARGET_OBJECT_SIGNAL_INFO)
11800 {
11801 if (readbuf)
11802 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11803 xfered_len, PACKET_qXfer_siginfo_read);
11804 else
11805 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11806 xfered_len, PACKET_qXfer_siginfo_write);
11807 }
11808
11809 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11810 {
11811 if (readbuf)
11812 return remote_read_qxfer ("statictrace", annex,
11813 readbuf, offset, len, xfered_len,
11814 PACKET_qXfer_statictrace_read);
11815 else
11816 return TARGET_XFER_E_IO;
11817 }
11818
11819 /* Only handle flash writes. */
11820 if (writebuf != NULL)
11821 {
11822 switch (object)
11823 {
11824 case TARGET_OBJECT_FLASH:
11825 return remote_flash_write (offset, len, xfered_len,
11826 writebuf);
11827
11828 default:
11829 return TARGET_XFER_E_IO;
11830 }
11831 }
11832
11833 /* Map pre-existing objects onto letters. DO NOT do this for new
11834 objects!!! Instead specify new query packets. */
11835 switch (object)
11836 {
11837 case TARGET_OBJECT_AVR:
11838 query_type = 'R';
11839 break;
11840
11841 case TARGET_OBJECT_AUXV:
11842 gdb_assert (annex == NULL);
11843 return remote_read_qxfer
11844 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11845
11846 case TARGET_OBJECT_AVAILABLE_FEATURES:
11847 return remote_read_qxfer
11848 ("features", annex, readbuf, offset, len, xfered_len,
11849 PACKET_qXfer_features);
11850
11851 case TARGET_OBJECT_LIBRARIES:
11852 return remote_read_qxfer
11853 ("libraries", annex, readbuf, offset, len, xfered_len,
11854 PACKET_qXfer_libraries);
11855
11856 case TARGET_OBJECT_LIBRARIES_SVR4:
11857 return remote_read_qxfer
11858 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11859 PACKET_qXfer_libraries_svr4);
11860
11861 case TARGET_OBJECT_MEMORY_MAP:
11862 gdb_assert (annex == NULL);
11863 return remote_read_qxfer
11864 ("memory-map", annex, readbuf, offset, len, xfered_len,
11865 PACKET_qXfer_memory_map);
11866
11867 case TARGET_OBJECT_OSDATA:
11868 /* Should only get here if we're connected. */
11869 gdb_assert (rs->remote_desc);
11870 return remote_read_qxfer
11871 ("osdata", annex, readbuf, offset, len, xfered_len,
11872 PACKET_qXfer_osdata);
11873
11874 case TARGET_OBJECT_THREADS:
11875 gdb_assert (annex == NULL);
11876 return remote_read_qxfer
11877 ("threads", annex, readbuf, offset, len, xfered_len,
11878 PACKET_qXfer_threads);
11879
11880 case TARGET_OBJECT_TRACEFRAME_INFO:
11881 gdb_assert (annex == NULL);
11882 return remote_read_qxfer
11883 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11884 PACKET_qXfer_traceframe_info);
11885
11886 case TARGET_OBJECT_FDPIC:
11887 return remote_read_qxfer
11888 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11889
11890 case TARGET_OBJECT_OPENVMS_UIB:
11891 return remote_read_qxfer
11892 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11893
11894 case TARGET_OBJECT_BTRACE:
11895 return remote_read_qxfer
11896 ("btrace", annex, readbuf, offset, len, xfered_len,
11897 PACKET_qXfer_btrace);
11898
11899 case TARGET_OBJECT_BTRACE_CONF:
11900 return remote_read_qxfer
11901 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11902 PACKET_qXfer_btrace_conf);
11903
11904 case TARGET_OBJECT_EXEC_FILE:
11905 return remote_read_qxfer
11906 ("exec-file", annex, readbuf, offset, len, xfered_len,
11907 PACKET_qXfer_exec_file);
11908
11909 default:
11910 return TARGET_XFER_E_IO;
11911 }
11912
11913 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11914 large enough let the caller deal with it. */
11915 if (len < get_remote_packet_size ())
11916 return TARGET_XFER_E_IO;
11917 len = get_remote_packet_size ();
11918
11919 /* Except for querying the minimum buffer size, target must be open. */
11920 if (!rs->remote_desc)
11921 error (_("remote query is only available after target open"));
11922
11923 gdb_assert (annex != NULL);
11924 gdb_assert (readbuf != NULL);
11925
11926 p2 = rs->buf.data ();
11927 *p2++ = 'q';
11928 *p2++ = query_type;
11929
11930 /* We used one buffer char for the remote protocol q command and
11931 another for the query type. As the remote protocol encapsulation
11932 uses 4 chars plus one extra in case we are debugging
11933 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11934 string. */
11935 i = 0;
11936 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11937 {
11938 /* Bad caller may have sent forbidden characters. */
11939 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11940 *p2++ = annex[i];
11941 i++;
11942 }
11943 *p2 = '\0';
11944 gdb_assert (annex[i] == '\0');
11945
11946 i = putpkt (rs->buf);
11947 if (i < 0)
11948 return TARGET_XFER_E_IO;
11949
11950 getpkt (&rs->buf);
11951 strcpy ((char *) readbuf, rs->buf.data ());
11952
11953 *xfered_len = strlen ((char *) readbuf);
11954 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11955}
11956
11957/* Implementation of to_get_memory_xfer_limit. */
11958
11959ULONGEST
11960remote_target::get_memory_xfer_limit ()
11961{
11962 return get_memory_write_packet_size ();
11963}
11964
11965int
11966remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11967 const gdb_byte *pattern, ULONGEST pattern_len,
11968 CORE_ADDR *found_addrp)
11969{
11970 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11971 struct remote_state *rs = get_remote_state ();
11972 int max_size = get_memory_write_packet_size ();
11973
11974 /* Number of packet bytes used to encode the pattern;
11975 this could be more than PATTERN_LEN due to escape characters. */
11976 int escaped_pattern_len;
11977 /* Amount of pattern that was encodable in the packet. */
11978 int used_pattern_len;
11979 int i;
11980 int found;
11981 ULONGEST found_addr;
11982
11983 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11984 {
11985 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11986 == len);
11987 };
11988
11989 /* Don't go to the target if we don't have to. This is done before
11990 checking packet_support to avoid the possibility that a success for this
11991 edge case means the facility works in general. */
11992 if (pattern_len > search_space_len)
11993 return 0;
11994 if (pattern_len == 0)
11995 {
11996 *found_addrp = start_addr;
11997 return 1;
11998 }
11999
12000 /* If we already know the packet isn't supported, fall back to the simple
12001 way of searching memory. */
12002
12003 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
12004 {
12005 /* Target doesn't provided special support, fall back and use the
12006 standard support (copy memory and do the search here). */
12007 return simple_search_memory (read_memory, start_addr, search_space_len,
12008 pattern, pattern_len, found_addrp);
12009 }
12010
12011 /* Make sure the remote is pointing at the right process. */
12012 set_general_process ();
12013
12014 /* Insert header. */
12015 i = snprintf (rs->buf.data (), max_size,
12016 "qSearch:memory:%s;%s;",
12017 phex_nz (start_addr, addr_size),
12018 phex_nz (search_space_len));
12019 max_size -= (i + 1);
12020
12021 /* Escape as much data as fits into rs->buf. */
12022 escaped_pattern_len =
12023 remote_escape_output (pattern, pattern_len, 1,
12024 (gdb_byte *) rs->buf.data () + i,
12025 &used_pattern_len, max_size);
12026
12027 /* Bail if the pattern is too large. */
12028 if (used_pattern_len != pattern_len)
12029 error (_("Pattern is too large to transmit to remote target."));
12030
12031 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
12032 || getpkt (&rs->buf) < 0
12033 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory).status ()
12034 != PACKET_OK)
12035 {
12036 /* The request may not have worked because the command is not
12037 supported. If so, fall back to the simple way. */
12038 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
12039 {
12040 return simple_search_memory (read_memory, start_addr, search_space_len,
12041 pattern, pattern_len, found_addrp);
12042 }
12043 return -1;
12044 }
12045
12046 if (rs->buf[0] == '0')
12047 found = 0;
12048 else if (rs->buf[0] == '1')
12049 {
12050 found = 1;
12051 if (rs->buf[1] != ',')
12052 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
12053 unpack_varlen_hex (&rs->buf[2], &found_addr);
12054 *found_addrp = found_addr;
12055 }
12056 else
12057 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
12058
12059 return found;
12060}
12061
12062void
12063remote_target::rcmd (const char *command, struct ui_file *outbuf)
12064{
12065 struct remote_state *rs = get_remote_state ();
12066 char *p = rs->buf.data ();
12067
12068 if (!rs->remote_desc)
12069 error (_("remote rcmd is only available after target open"));
12070
12071 /* Send a NULL command across as an empty command. */
12072 if (command == NULL)
12073 command = "";
12074
12075 /* It might be important for this command to know the current thread. */
12076 set_general_thread (inferior_ptid);
12077
12078 /* The query prefix. */
12079 strcpy (rs->buf.data (), "qRcmd,");
12080 p = strchr (rs->buf.data (), '\0');
12081
12082 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
12083 > get_remote_packet_size ())
12084 error (_("\"monitor\" command ``%s'' is too long."), command);
12085
12086 /* Encode the actual command. */
12087 bin2hex ((const gdb_byte *) command, p, strlen (command));
12088
12089 if (putpkt (rs->buf) < 0)
12090 error (_("Communication problem with target."));
12091
12092 /* get/display the response */
12093 while (1)
12094 {
12095 char *buf;
12096
12097 /* XXX - see also remote_get_noisy_reply(). */
12098 QUIT; /* Allow user to bail out with ^C. */
12099 rs->buf[0] = '\0';
12100 if (getpkt (&rs->buf) == -1)
12101 {
12102 /* Timeout. Continue to (try to) read responses.
12103 This is better than stopping with an error, assuming the stub
12104 is still executing the (long) monitor command.
12105 If needed, the user can interrupt gdb using C-c, obtaining
12106 an effect similar to stop on timeout. */
12107 continue;
12108 }
12109 buf = rs->buf.data ();
12110 if (buf[0] == 'O' && buf[1] != 'K')
12111 {
12112 /* 'O' message from stub. */
12113 remote_console_output (buf + 1, outbuf);
12114 continue;
12115 }
12116 packet_result result = packet_check_result (buf);
12117 switch (result.status ())
12118 {
12119 case PACKET_UNKNOWN:
12120 error (_("Target does not support this command."));
12121 case PACKET_ERROR:
12122 error (_("Protocol error with Rcmd: %s."), result.err_msg ());
12123 case PACKET_OK:
12124 break;
12125 }
12126
12127 if (strcmp (buf, "OK") != 0)
12128 {
12129 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
12130 {
12131 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
12132 gdb_putc (c, outbuf);
12133 }
12134 }
12135 break;
12136 }
12137}
12138
12139std::vector<mem_region>
12140remote_target::memory_map ()
12141{
12142 std::vector<mem_region> result;
12143 std::optional<gdb::char_vector> text
12144 = target_read_stralloc (current_inferior ()->top_target (),
12145 TARGET_OBJECT_MEMORY_MAP, NULL);
12146
12147 if (text)
12148 result = parse_memory_map (text->data ());
12149
12150 return result;
12151}
12152
12153/* Set of callbacks used to implement the 'maint packet' command. */
12154
12155struct cli_packet_command_callbacks : public send_remote_packet_callbacks
12156{
12157 /* Called before the packet is sent. BUF is the packet content before
12158 the protocol specific prefix, suffix, and escaping is added. */
12159
12160 void sending (gdb::array_view<const char> &buf) override
12161 {
12162 gdb_puts ("sending: ");
12163 print_packet (buf);
12164 gdb_puts ("\n");
12165 }
12166
12167 /* Called with BUF, the reply from the remote target. */
12168
12169 void received (gdb::array_view<const char> &buf) override
12170 {
12171 gdb_puts ("received: \"");
12172 print_packet (buf);
12173 gdb_puts ("\"\n");
12174 }
12175
12176private:
12177
12178 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
12179 '\x??' with '??' replaced by the hexadecimal value of the byte. */
12180
12181 static void
12182 print_packet (gdb::array_view<const char> &buf)
12183 {
12184 string_file stb;
12185
12186 for (int i = 0; i < buf.size (); ++i)
12187 {
12188 gdb_byte c = buf[i];
12189 if (isprint (c))
12190 gdb_putc (c, &stb);
12191 else
12192 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
12193 }
12194
12195 gdb_puts (stb.string ().c_str ());
12196 }
12197};
12198
12199/* See remote.h. */
12200
12201void
12202send_remote_packet (gdb::array_view<const char> &buf,
12203 send_remote_packet_callbacks *callbacks)
12204{
12205 if (buf.size () == 0 || buf.data ()[0] == '\0')
12206 error (_("a remote packet must not be empty"));
12207
12208 remote_target *remote = get_current_remote_target ();
12209 if (remote == nullptr)
12210 error (_("packets can only be sent to a remote target"));
12211
12212 callbacks->sending (buf);
12213
12214 remote->putpkt_binary (buf.data (), buf.size ());
12215 remote_state *rs = remote->get_remote_state ();
12216 int bytes = remote->getpkt (&rs->buf);
12217
12218 if (bytes < 0)
12219 error (_("error while fetching packet from remote target"));
12220
12221 gdb::array_view<const char> view (&rs->buf[0], bytes);
12222 callbacks->received (view);
12223}
12224
12225/* Entry point for the 'maint packet' command. */
12226
12227static void
12228cli_packet_command (const char *args, int from_tty)
12229{
12230 cli_packet_command_callbacks cb;
12231 gdb::array_view<const char> view
12232 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
12233 send_remote_packet (view, &cb);
12234}
12235
12236#if 0
12237/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12238
12239static void display_thread_info (struct gdb_ext_thread_info *info);
12240
12241static void threadset_test_cmd (char *cmd, int tty);
12242
12243static void threadalive_test (char *cmd, int tty);
12244
12245static void threadlist_test_cmd (char *cmd, int tty);
12246
12247int get_and_display_threadinfo (threadref *ref);
12248
12249static void threadinfo_test_cmd (char *cmd, int tty);
12250
12251static int thread_display_step (threadref *ref, void *context);
12252
12253static void threadlist_update_test_cmd (char *cmd, int tty);
12254
12255static void init_remote_threadtests (void);
12256
12257#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12258
12259static void
12260threadset_test_cmd (const char *cmd, int tty)
12261{
12262 int sample_thread = SAMPLE_THREAD;
12263
12264 gdb_printf (_("Remote threadset test\n"));
12265 set_general_thread (sample_thread);
12266}
12267
12268
12269static void
12270threadalive_test (const char *cmd, int tty)
12271{
12272 int sample_thread = SAMPLE_THREAD;
12273 int pid = inferior_ptid.pid ();
12274 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12275
12276 if (remote_thread_alive (ptid))
12277 gdb_printf ("PASS: Thread alive test\n");
12278 else
12279 gdb_printf ("FAIL: Thread alive test\n");
12280}
12281
12282void output_threadid (char *title, threadref *ref);
12283
12284void
12285output_threadid (char *title, threadref *ref)
12286{
12287 char hexid[20];
12288
12289 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12290 hexid[16] = 0;
12291 gdb_printf ("%s %s\n", title, (&hexid[0]));
12292}
12293
12294static void
12295threadlist_test_cmd (const char *cmd, int tty)
12296{
12297 int startflag = 1;
12298 threadref nextthread;
12299 int done, result_count;
12300 threadref threadlist[3];
12301
12302 gdb_printf ("Remote Threadlist test\n");
12303 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12304 &result_count, &threadlist[0]))
12305 gdb_printf ("FAIL: threadlist test\n");
12306 else
12307 {
12308 threadref *scan = threadlist;
12309 threadref *limit = scan + result_count;
12310
12311 while (scan < limit)
12312 output_threadid (" thread ", scan++);
12313 }
12314}
12315
12316void
12317display_thread_info (struct gdb_ext_thread_info *info)
12318{
12319 output_threadid ("Threadid: ", &info->threadid);
12320 gdb_printf ("Name: %s\n ", info->shortname);
12321 gdb_printf ("State: %s\n", info->display);
12322 gdb_printf ("other: %s\n\n", info->more_display);
12323}
12324
12325int
12326get_and_display_threadinfo (threadref *ref)
12327{
12328 int result;
12329 int set;
12330 struct gdb_ext_thread_info threadinfo;
12331
12332 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12333 | TAG_MOREDISPLAY | TAG_DISPLAY;
12334 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12335 display_thread_info (&threadinfo);
12336 return result;
12337}
12338
12339static void
12340threadinfo_test_cmd (const char *cmd, int tty)
12341{
12342 int athread = SAMPLE_THREAD;
12343 threadref thread;
12344 int set;
12345
12346 int_to_threadref (&thread, athread);
12347 gdb_printf ("Remote Threadinfo test\n");
12348 if (!get_and_display_threadinfo (&thread))
12349 gdb_printf ("FAIL cannot get thread info\n");
12350}
12351
12352static int
12353thread_display_step (threadref *ref, void *context)
12354{
12355 /* output_threadid(" threadstep ",ref); *//* simple test */
12356 return get_and_display_threadinfo (ref);
12357}
12358
12359static void
12360threadlist_update_test_cmd (const char *cmd, int tty)
12361{
12362 gdb_printf ("Remote Threadlist update test\n");
12363 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12364}
12365
12366static void
12367init_remote_threadtests (void)
12368{
12369 add_com ("tlist", class_obscure, threadlist_test_cmd,
12370 _("Fetch and print the remote list of "
12371 "thread identifiers, one pkt only."));
12372 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12373 _("Fetch and display info about one thread."));
12374 add_com ("tset", class_obscure, threadset_test_cmd,
12375 _("Test setting to a different thread."));
12376 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12377 _("Iterate through updating all remote thread info."));
12378 add_com ("talive", class_obscure, threadalive_test,
12379 _("Remote thread alive test."));
12380}
12381
12382#endif /* 0 */
12383
12384/* Convert a thread ID to a string. */
12385
12386std::string
12387remote_target::pid_to_str (ptid_t ptid)
12388{
12389 if (ptid == null_ptid)
12390 return normal_pid_to_str (ptid);
12391 else if (ptid.is_pid ())
12392 {
12393 /* Printing an inferior target id. */
12394
12395 /* When multi-process extensions are off, there's no way in the
12396 remote protocol to know the remote process id, if there's any
12397 at all. There's one exception --- when we're connected with
12398 target extended-remote, and we manually attached to a process
12399 with "attach PID". We don't record anywhere a flag that
12400 allows us to distinguish that case from the case of
12401 connecting with extended-remote and the stub already being
12402 attached to a process, and reporting yes to qAttached, hence
12403 no smart special casing here. */
12404 if (!m_features.remote_multi_process_p ())
12405 return "Remote target";
12406
12407 return normal_pid_to_str (ptid);
12408 }
12409 else
12410 {
12411 if (magic_null_ptid == ptid)
12412 return "Thread <main>";
12413
12414 thread_info *thread = this->find_thread (ptid);
12415 if ((thread != nullptr) && (thread->priv != nullptr))
12416 {
12417 remote_thread_info *priv = get_remote_thread_info (thread);
12418 if (!priv->id_str.empty ())
12419 return priv->id_str;
12420 }
12421
12422 if (m_features.remote_multi_process_p ())
12423 if (ptid.lwp () == 0)
12424 return normal_pid_to_str (ptid);
12425 else
12426 return string_printf ("Thread %d.%ld",
12427 ptid.pid (), ptid.lwp ());
12428 else
12429 return string_printf ("Thread %ld", ptid.lwp ());
12430 }
12431}
12432
12433/* Get the address of the thread local variable in OBJFILE which is
12434 stored at OFFSET within the thread local storage for thread PTID. */
12435
12436CORE_ADDR
12437remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12438 CORE_ADDR offset)
12439{
12440 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12441 {
12442 struct remote_state *rs = get_remote_state ();
12443 char *p = rs->buf.data ();
12444 char *endp = p + get_remote_packet_size ();
12445
12446 strcpy (p, "qGetTLSAddr:");
12447 p += strlen (p);
12448 p = write_ptid (p, endp, ptid);
12449 *p++ = ',';
12450 p += hexnumstr (p, offset);
12451 *p++ = ',';
12452 p += hexnumstr (p, lm);
12453 *p++ = '\0';
12454
12455 putpkt (rs->buf);
12456 getpkt (&rs->buf);
12457 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12458 if (result.status () == PACKET_OK)
12459 {
12460 ULONGEST addr;
12461
12462 unpack_varlen_hex (rs->buf.data (), &addr);
12463 return addr;
12464 }
12465 else if (result.status () == PACKET_UNKNOWN)
12466 throw_error (TLS_GENERIC_ERROR,
12467 _("Remote target doesn't support qGetTLSAddr packet"));
12468 else
12469 throw_error (TLS_GENERIC_ERROR,
12470 _("Remote target failed to process qGetTLSAddr request"));
12471 }
12472 else
12473 throw_error (TLS_GENERIC_ERROR,
12474 _("TLS not supported or disabled on this target"));
12475 /* Not reached. */
12476 return 0;
12477}
12478
12479bool
12480remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12481{
12482 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12483 {
12484 struct remote_state *rs = get_remote_state ();
12485 char *p = rs->buf.data ();
12486 char *endp = p + get_remote_packet_size ();
12487
12488 strcpy (p, "qGetTIBAddr:");
12489 p += strlen (p);
12490 p = write_ptid (p, endp, ptid);
12491 *p++ = '\0';
12492
12493 putpkt (rs->buf);
12494 getpkt (&rs->buf);
12495 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12496 if (result.status () == PACKET_OK)
12497 {
12498 ULONGEST val;
12499 unpack_varlen_hex (rs->buf.data (), &val);
12500 if (addr)
12501 *addr = (CORE_ADDR) val;
12502 return true;
12503 }
12504 else if (result.status () == PACKET_UNKNOWN)
12505 return false;
12506 else
12507 error (_("Remote target failed to process qGetTIBAddr request, %s"),
12508 result.err_msg ());
12509 }
12510
12511 return false;
12512}
12513
12514/* Support for inferring a target description based on the current
12515 architecture and the size of a 'g' packet. While the 'g' packet
12516 can have any size (since optional registers can be left off the
12517 end), some sizes are easily recognizable given knowledge of the
12518 approximate architecture. */
12519
12520struct remote_g_packet_guess
12521{
12522 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12523 : bytes (bytes_),
12524 tdesc (tdesc_)
12525 {
12526 }
12527
12528 int bytes;
12529 const struct target_desc *tdesc;
12530};
12531
12532struct remote_g_packet_data
12533{
12534 std::vector<remote_g_packet_guess> guesses;
12535};
12536
12537static const registry<gdbarch>::key<struct remote_g_packet_data>
12538 remote_g_packet_data_handle;
12539
12540static struct remote_g_packet_data *
12541get_g_packet_data (struct gdbarch *gdbarch)
12542{
12543 struct remote_g_packet_data *data
12544 = remote_g_packet_data_handle.get (gdbarch);
12545 if (data == nullptr)
12546 data = remote_g_packet_data_handle.emplace (gdbarch);
12547 return data;
12548}
12549
12550void
12551register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12552 const struct target_desc *tdesc)
12553{
12554 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12555
12556 gdb_assert (tdesc != NULL);
12557
12558 for (const remote_g_packet_guess &guess : data->guesses)
12559 if (guess.bytes == bytes)
12560 internal_error (_("Duplicate g packet description added for size %d"),
12561 bytes);
12562
12563 data->guesses.emplace_back (bytes, tdesc);
12564}
12565
12566/* Return true if remote_read_description would do anything on this target
12567 and architecture, false otherwise. */
12568
12569static bool
12570remote_read_description_p (struct target_ops *target)
12571{
12572 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12573
12574 return !data->guesses.empty ();
12575}
12576
12577const struct target_desc *
12578remote_target::read_description ()
12579{
12580 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12581
12582 /* Do not try this during initial connection, when we do not know
12583 whether there is a running but stopped thread. */
12584 if (!target_has_execution () || inferior_ptid == null_ptid)
12585 return beneath ()->read_description ();
12586
12587 if (!data->guesses.empty ())
12588 {
12589 int bytes = send_g_packet ();
12590
12591 for (const remote_g_packet_guess &guess : data->guesses)
12592 if (guess.bytes == bytes)
12593 return guess.tdesc;
12594
12595 /* We discard the g packet. A minor optimization would be to
12596 hold on to it, and fill the register cache once we have selected
12597 an architecture, but it's too tricky to do safely. */
12598 }
12599
12600 return beneath ()->read_description ();
12601}
12602
12603/* Remote file transfer support. This is host-initiated I/O, not
12604 target-initiated; for target-initiated, see remote-fileio.c. */
12605
12606/* If *LEFT is at least the length of STRING, copy STRING to
12607 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12608 decrease *LEFT. Otherwise raise an error. */
12609
12610static void
12611remote_buffer_add_string (char **buffer, int *left, const char *string)
12612{
12613 int len = strlen (string);
12614
12615 if (len > *left)
12616 error (_("Packet too long for target."));
12617
12618 memcpy (*buffer, string, len);
12619 *buffer += len;
12620 *left -= len;
12621
12622 /* NUL-terminate the buffer as a convenience, if there is
12623 room. */
12624 if (*left)
12625 **buffer = '\0';
12626}
12627
12628/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12629 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12630 decrease *LEFT. Otherwise raise an error. */
12631
12632static void
12633remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12634 int len)
12635{
12636 if (2 * len > *left)
12637 error (_("Packet too long for target."));
12638
12639 bin2hex (bytes, *buffer, len);
12640 *buffer += 2 * len;
12641 *left -= 2 * len;
12642
12643 /* NUL-terminate the buffer as a convenience, if there is
12644 room. */
12645 if (*left)
12646 **buffer = '\0';
12647}
12648
12649/* If *LEFT is large enough, convert VALUE to hex and add it to
12650 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12651 decrease *LEFT. Otherwise raise an error. */
12652
12653static void
12654remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12655{
12656 int len = hexnumlen (value);
12657
12658 if (len > *left)
12659 error (_("Packet too long for target."));
12660
12661 hexnumstr (*buffer, value);
12662 *buffer += len;
12663 *left -= len;
12664
12665 /* NUL-terminate the buffer as a convenience, if there is
12666 room. */
12667 if (*left)
12668 **buffer = '\0';
12669}
12670
12671/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12672 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12673 was included, and *ATTACHMENT to point to the start of the annex
12674 if any. The length of the packet isn't needed here; there may
12675 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12676
12677 Return 0 if the packet could be parsed, -1 if it could not. If
12678 -1 is returned, the other variables may not be initialized. */
12679
12680static int
12681remote_hostio_parse_result (const char *buffer, int *retcode,
12682 fileio_error *remote_errno, const char **attachment)
12683{
12684 char *p, *p2;
12685
12686 *remote_errno = FILEIO_SUCCESS;
12687 *attachment = NULL;
12688
12689 if (buffer[0] != 'F')
12690 return -1;
12691
12692 errno = 0;
12693 *retcode = strtol (&buffer[1], &p, 16);
12694 if (errno != 0 || p == &buffer[1])
12695 return -1;
12696
12697 /* Check for ",errno". */
12698 if (*p == ',')
12699 {
12700 errno = 0;
12701 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12702 if (errno != 0 || p + 1 == p2)
12703 return -1;
12704 p = p2;
12705 }
12706
12707 /* Check for ";attachment". If there is no attachment, the
12708 packet should end here. */
12709 if (*p == ';')
12710 {
12711 *attachment = p + 1;
12712 return 0;
12713 }
12714 else if (*p == '\0')
12715 return 0;
12716 else
12717 return -1;
12718}
12719
12720/* Send a prepared I/O packet to the target and read its response.
12721 The prepared packet is in the global RS->BUF before this function
12722 is called, and the answer is there when we return.
12723
12724 COMMAND_BYTES is the length of the request to send, which may include
12725 binary data. WHICH_PACKET is the packet configuration to check
12726 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12727 is set to the error number and -1 is returned. Otherwise the value
12728 returned by the function is returned.
12729
12730 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12731 attachment is expected; an error will be reported if there's a
12732 mismatch. If one is found, *ATTACHMENT will be set to point into
12733 the packet buffer and *ATTACHMENT_LEN will be set to the
12734 attachment's length. */
12735
12736int
12737remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12738 fileio_error *remote_errno, const char **attachment,
12739 int *attachment_len)
12740{
12741 struct remote_state *rs = get_remote_state ();
12742 int ret, bytes_read;
12743 const char *attachment_tmp;
12744
12745 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12746 {
12747 *remote_errno = FILEIO_ENOSYS;
12748 return -1;
12749 }
12750
12751 putpkt_binary (rs->buf.data (), command_bytes);
12752 bytes_read = getpkt (&rs->buf);
12753
12754 /* If it timed out, something is wrong. Don't try to parse the
12755 buffer. */
12756 if (bytes_read < 0)
12757 {
12758 *remote_errno = FILEIO_EINVAL;
12759 return -1;
12760 }
12761
12762 switch (m_features.packet_ok (rs->buf, which_packet).status ())
12763 {
12764 case PACKET_ERROR:
12765 *remote_errno = FILEIO_EINVAL;
12766 return -1;
12767 case PACKET_UNKNOWN:
12768 *remote_errno = FILEIO_ENOSYS;
12769 return -1;
12770 case PACKET_OK:
12771 break;
12772 }
12773
12774 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12775 &attachment_tmp))
12776 {
12777 *remote_errno = FILEIO_EINVAL;
12778 return -1;
12779 }
12780
12781 if (*remote_errno != FILEIO_SUCCESS)
12782 return -1;
12783
12784 /* Make sure we saw an attachment if and only if we expected one. */
12785 if ((attachment_tmp == NULL && attachment != NULL)
12786 || (attachment_tmp != NULL && attachment == NULL))
12787 {
12788 *remote_errno = FILEIO_EINVAL;
12789 return -1;
12790 }
12791
12792 /* If an attachment was found, it must point into the packet buffer;
12793 work out how many bytes there were. */
12794 if (attachment_tmp != NULL)
12795 {
12796 *attachment = attachment_tmp;
12797 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12798 }
12799
12800 return ret;
12801}
12802
12803/* See declaration.h. */
12804
12805void
12806readahead_cache::invalidate ()
12807{
12808 this->fd = -1;
12809}
12810
12811/* See declaration.h. */
12812
12813void
12814readahead_cache::invalidate_fd (int fd)
12815{
12816 if (this->fd == fd)
12817 this->fd = -1;
12818}
12819
12820/* Set the filesystem remote_hostio functions that take FILENAME
12821 arguments will use. Return 0 on success, or -1 if an error
12822 occurs (and set *REMOTE_ERRNO). */
12823
12824int
12825remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12826 fileio_error *remote_errno)
12827{
12828 struct remote_state *rs = get_remote_state ();
12829 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12830 char *p = rs->buf.data ();
12831 int left = get_remote_packet_size () - 1;
12832 char arg[9];
12833 int ret;
12834
12835 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12836 return 0;
12837
12838 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12839 return 0;
12840
12841 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12842
12843 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12844 remote_buffer_add_string (&p, &left, arg);
12845
12846 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12847 remote_errno, NULL, NULL);
12848
12849 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12850 return 0;
12851
12852 if (ret == 0)
12853 rs->fs_pid = required_pid;
12854
12855 return ret;
12856}
12857
12858/* Implementation of to_fileio_open. */
12859
12860int
12861remote_target::remote_hostio_open (inferior *inf, const char *filename,
12862 int flags, int mode, int warn_if_slow,
12863 fileio_error *remote_errno)
12864{
12865 struct remote_state *rs = get_remote_state ();
12866 char *p = rs->buf.data ();
12867 int left = get_remote_packet_size () - 1;
12868
12869 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12870 return -1;
12871
12872 remote_buffer_add_string (&p, &left, "vFile:open:");
12873
12874 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12875 strlen (filename));
12876 remote_buffer_add_string (&p, &left, ",");
12877
12878 remote_buffer_add_int (&p, &left, flags);
12879 remote_buffer_add_string (&p, &left, ",");
12880
12881 remote_buffer_add_int (&p, &left, mode);
12882
12883 int res = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12884 remote_errno, nullptr, nullptr);
12885
12886 if (warn_if_slow && res != -1)
12887 {
12888 static int warning_issued = 0;
12889
12890 gdb_printf (_("Reading %ps from remote target...\n"),
12891 styled_string (file_name_style.style (), filename));
12892
12893 if (!warning_issued)
12894 {
12895 warning (_("File transfers from remote targets can be slow."
12896 " Use \"%ps\" to access files locally"
12897 " instead."),
12898 styled_string (command_style.style (), "set sysroot"));
12899 warning_issued = 1;
12900 }
12901 }
12902
12903 return res;
12904}
12905
12906int
12907remote_target::fileio_open (struct inferior *inf, const char *filename,
12908 int flags, int mode, int warn_if_slow,
12909 fileio_error *remote_errno)
12910{
12911 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12912 remote_errno);
12913}
12914
12915/* Implementation of to_fileio_pwrite. */
12916
12917int
12918remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12919 ULONGEST offset, fileio_error *remote_errno)
12920{
12921 struct remote_state *rs = get_remote_state ();
12922 char *p = rs->buf.data ();
12923 int left = get_remote_packet_size ();
12924 int out_len;
12925
12926 rs->readahead_cache.invalidate_fd (fd);
12927
12928 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12929
12930 remote_buffer_add_int (&p, &left, fd);
12931 remote_buffer_add_string (&p, &left, ",");
12932
12933 remote_buffer_add_int (&p, &left, offset);
12934 remote_buffer_add_string (&p, &left, ",");
12935
12936 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12937 (get_remote_packet_size ()
12938 - (p - rs->buf.data ())));
12939
12940 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12941 remote_errno, NULL, NULL);
12942}
12943
12944int
12945remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12946 ULONGEST offset, fileio_error *remote_errno)
12947{
12948 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12949}
12950
12951/* Helper for the implementation of to_fileio_pread. Read the file
12952 from the remote side with vFile:pread. */
12953
12954int
12955remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12956 ULONGEST offset, fileio_error *remote_errno)
12957{
12958 struct remote_state *rs = get_remote_state ();
12959 char *p = rs->buf.data ();
12960 const char *attachment;
12961 int left = get_remote_packet_size ();
12962 int ret, attachment_len;
12963 int read_len;
12964
12965 remote_buffer_add_string (&p, &left, "vFile:pread:");
12966
12967 remote_buffer_add_int (&p, &left, fd);
12968 remote_buffer_add_string (&p, &left, ",");
12969
12970 remote_buffer_add_int (&p, &left, len);
12971 remote_buffer_add_string (&p, &left, ",");
12972
12973 remote_buffer_add_int (&p, &left, offset);
12974
12975 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12976 remote_errno, &attachment,
12977 &attachment_len);
12978
12979 if (ret < 0)
12980 return ret;
12981
12982 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12983 read_buf, len);
12984 if (read_len != ret)
12985 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12986
12987 return ret;
12988}
12989
12990/* See declaration.h. */
12991
12992int
12993readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12994 ULONGEST offset)
12995{
12996 if (this->fd == fd
12997 && this->offset <= offset
12998 && offset < this->offset + this->buf.size ())
12999 {
13000 ULONGEST max = this->offset + this->buf.size ();
13001
13002 if (offset + len > max)
13003 len = max - offset;
13004
13005 memcpy (read_buf, &this->buf[offset - this->offset], len);
13006 return len;
13007 }
13008
13009 return 0;
13010}
13011
13012/* Implementation of to_fileio_pread. */
13013
13014int
13015remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
13016 ULONGEST offset, fileio_error *remote_errno)
13017{
13018 int ret;
13019 struct remote_state *rs = get_remote_state ();
13020 readahead_cache *cache = &rs->readahead_cache;
13021
13022 ret = cache->pread (fd, read_buf, len, offset);
13023 if (ret > 0)
13024 {
13025 cache->hit_count++;
13026
13027 remote_debug_printf ("readahead cache hit %s",
13028 pulongest (cache->hit_count));
13029 return ret;
13030 }
13031
13032 cache->miss_count++;
13033
13034 remote_debug_printf ("readahead cache miss %s",
13035 pulongest (cache->miss_count));
13036
13037 cache->fd = fd;
13038 cache->offset = offset;
13039 cache->buf.resize (get_remote_packet_size ());
13040
13041 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
13042 cache->buf.size (),
13043 cache->offset, remote_errno);
13044 if (ret <= 0)
13045 {
13046 cache->invalidate_fd (fd);
13047 return ret;
13048 }
13049
13050 cache->buf.resize (ret);
13051 return cache->pread (fd, read_buf, len, offset);
13052}
13053
13054int
13055remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
13056 ULONGEST offset, fileio_error *remote_errno)
13057{
13058 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
13059}
13060
13061/* Implementation of to_fileio_close. */
13062
13063int
13064remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
13065{
13066 struct remote_state *rs = get_remote_state ();
13067 char *p = rs->buf.data ();
13068 int left = get_remote_packet_size () - 1;
13069
13070 rs->readahead_cache.invalidate_fd (fd);
13071
13072 remote_buffer_add_string (&p, &left, "vFile:close:");
13073
13074 remote_buffer_add_int (&p, &left, fd);
13075
13076 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
13077 remote_errno, NULL, NULL);
13078}
13079
13080int
13081remote_target::fileio_close (int fd, fileio_error *remote_errno)
13082{
13083 return remote_hostio_close (fd, remote_errno);
13084}
13085
13086/* Implementation of to_fileio_unlink. */
13087
13088int
13089remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
13090 fileio_error *remote_errno)
13091{
13092 struct remote_state *rs = get_remote_state ();
13093 char *p = rs->buf.data ();
13094 int left = get_remote_packet_size () - 1;
13095
13096 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13097 return -1;
13098
13099 remote_buffer_add_string (&p, &left, "vFile:unlink:");
13100
13101 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13102 strlen (filename));
13103
13104 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
13105 remote_errno, NULL, NULL);
13106}
13107
13108int
13109remote_target::fileio_unlink (struct inferior *inf, const char *filename,
13110 fileio_error *remote_errno)
13111{
13112 return remote_hostio_unlink (inf, filename, remote_errno);
13113}
13114
13115/* Implementation of to_fileio_readlink. */
13116
13117std::optional<std::string>
13118remote_target::fileio_readlink (struct inferior *inf, const char *filename,
13119 fileio_error *remote_errno)
13120{
13121 struct remote_state *rs = get_remote_state ();
13122 char *p = rs->buf.data ();
13123 const char *attachment;
13124 int left = get_remote_packet_size ();
13125 int len, attachment_len;
13126 int read_len;
13127
13128 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13129 return {};
13130
13131 remote_buffer_add_string (&p, &left, "vFile:readlink:");
13132
13133 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13134 strlen (filename));
13135
13136 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
13137 remote_errno, &attachment,
13138 &attachment_len);
13139
13140 if (len < 0)
13141 return {};
13142
13143 std::string ret (len, '\0');
13144
13145 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13146 (gdb_byte *) &ret[0], len);
13147 if (read_len != len)
13148 error (_("Readlink returned %d, but %d bytes."), len, read_len);
13149
13150 return ret;
13151}
13152
13153/* Helper function to handle ::fileio_fstat and ::fileio_lstat result
13154 processing. When this function is called the remote syscall has been
13155 performed and we know we didn't get an error back.
13156
13157 ATTACHMENT and ATTACHMENT_LEN are the attachment data extracted from the
13158 remote syscall reply. EXPECTED_LEN is the length returned from the
13159 fstat or stat call, this the length of the returned data (in ATTACHMENT)
13160 once it has been decoded. The fstat/stat result (from the ATTACHMENT
13161 data) is to be placed in ST. */
13162
13163static int
13164fileio_process_fstat_and_lstat_reply (const char *attachment,
13165 int attachment_len,
13166 int expected_len,
13167 struct stat *st)
13168{
13169 struct fio_stat fst;
13170
13171 int read_len
13172 = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13173 (gdb_byte *) &fst, sizeof (fst));
13174
13175 if (read_len != expected_len)
13176 error (_("vFile:fstat returned %d, but %d bytes."),
13177 expected_len, read_len);
13178
13179 if (read_len != sizeof (fst))
13180 error (_("vFile:fstat returned %d bytes, but expecting %d."),
13181 read_len, (int) sizeof (fst));
13182
13183 remote_fileio_to_host_stat (&fst, st);
13184
13185 return 0;
13186}
13187
13188/* Implementation of to_fileio_fstat. */
13189
13190int
13191remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
13192{
13193 struct remote_state *rs = get_remote_state ();
13194 char *p = rs->buf.data ();
13195 int left = get_remote_packet_size ();
13196 int attachment_len, ret;
13197 const char *attachment;
13198
13199 remote_buffer_add_string (&p, &left, "vFile:fstat:");
13200
13201 remote_buffer_add_int (&p, &left, fd);
13202
13203 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
13204 remote_errno, &attachment,
13205 &attachment_len);
13206 if (ret < 0)
13207 {
13208 if (*remote_errno != FILEIO_ENOSYS)
13209 return ret;
13210
13211 /* Strictly we should return -1, ENOSYS here, but when
13212 "set sysroot remote:" was implemented in August 2008
13213 BFD's need for a stat function was sidestepped with
13214 this hack. This was not remedied until March 2015
13215 so we retain the previous behavior to avoid breaking
13216 compatibility.
13217
13218 Note that the memset is a March 2015 addition; older
13219 GDBs set st_size *and nothing else* so the structure
13220 would have garbage in all other fields. This might
13221 break something but retaining the previous behavior
13222 here would be just too wrong. */
13223
13224 memset (st, 0, sizeof (struct stat));
13225 st->st_size = INT_MAX;
13226 return 0;
13227 }
13228
13229 return fileio_process_fstat_and_lstat_reply (attachment, attachment_len,
13230 ret, st);
13231}
13232
13233/* Implementation of to_fileio_lstat. */
13234
13235int
13236remote_target::fileio_lstat (struct inferior *inf, const char *filename,
13237 struct stat *st, fileio_error *remote_errno)
13238{
13239 struct remote_state *rs = get_remote_state ();
13240 char *p = rs->buf.data ();
13241 int left = get_remote_packet_size () - 1;
13242
13243 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13244 return {};
13245
13246 remote_buffer_add_string (&p, &left, "vFile:lstat:");
13247
13248 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13249 strlen (filename));
13250
13251 int attachment_len;
13252 const char *attachment;
13253 int ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_lstat,
13254 remote_errno, &attachment,
13255 &attachment_len);
13256
13257 /* Unlike ::fileio_fstat, the stat fileio call was added later on, and
13258 has none of the legacy bfd issues, so we can just return the error. */
13259 if (ret < 0)
13260 return ret;
13261
13262 return fileio_process_fstat_and_lstat_reply (attachment, attachment_len,
13263 ret, st);
13264}
13265
13266/* Implementation of to_filesystem_is_local. */
13267
13268bool
13269remote_target::filesystem_is_local ()
13270{
13271 /* Valgrind GDB presents itself as a remote target but works
13272 on the local filesystem: it does not implement remote get
13273 and users are not expected to set a sysroot. To handle
13274 this case we treat the remote filesystem as local if the
13275 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
13276 does not support vFile:open. */
13277 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
13278 {
13279 packet_support ps = m_features.packet_support (PACKET_vFile_open);
13280
13281 if (ps == PACKET_SUPPORT_UNKNOWN)
13282 {
13283 int fd;
13284 fileio_error remote_errno;
13285
13286 /* Try opening a file to probe support. The supplied
13287 filename is irrelevant, we only care about whether
13288 the stub recognizes the packet or not. */
13289 fd = remote_hostio_open (NULL, "just probing",
13290 FILEIO_O_RDONLY, 0700, 0,
13291 &remote_errno);
13292
13293 if (fd >= 0)
13294 remote_hostio_close (fd, &remote_errno);
13295
13296 ps = m_features.packet_support (PACKET_vFile_open);
13297 }
13298
13299 if (ps == PACKET_DISABLE)
13300 {
13301 static int warning_issued = 0;
13302
13303 if (!warning_issued)
13304 {
13305 warning (_("remote target does not support file"
13306 " transfer, attempting to access files"
13307 " from local filesystem."));
13308 warning_issued = 1;
13309 }
13310
13311 return true;
13312 }
13313 }
13314
13315 return false;
13316}
13317
13318static char *
13319remote_hostio_error (fileio_error errnum)
13320{
13321 int host_error = fileio_error_to_host (errnum);
13322
13323 if (host_error == -1)
13324 error (_("Unknown remote I/O error %d"), errnum);
13325 else
13326 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13327}
13328
13329/* A RAII wrapper around a remote file descriptor. */
13330
13331class scoped_remote_fd
13332{
13333public:
13334 scoped_remote_fd (remote_target *remote, int fd)
13335 : m_remote (remote), m_fd (fd)
13336 {
13337 }
13338
13339 ~scoped_remote_fd ()
13340 {
13341 if (m_fd != -1)
13342 {
13343 try
13344 {
13345 fileio_error remote_errno;
13346 m_remote->remote_hostio_close (m_fd, &remote_errno);
13347 }
13348 catch (const gdb_exception_quit &ex)
13349 {
13350 /* We can't throw from a destructor, so re-set the quit flag
13351 for later QUIT checking. */
13352 set_quit_flag ();
13353 }
13354 catch (const gdb_exception_forced_quit &ex)
13355 {
13356 /* Like above, but (eventually) cause GDB to terminate by
13357 setting sync_quit_force_run. */
13358 set_force_quit_flag ();
13359 }
13360 catch (...)
13361 {
13362 /* Swallow exception before it escapes the dtor. If
13363 something goes wrong, likely the connection is gone,
13364 and there's nothing else that can be done. */
13365 }
13366 }
13367 }
13368
13369 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13370
13371 /* Release ownership of the file descriptor, and return it. */
13372 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13373 {
13374 int fd = m_fd;
13375 m_fd = -1;
13376 return fd;
13377 }
13378
13379 /* Return the owned file descriptor. */
13380 int get () const noexcept
13381 {
13382 return m_fd;
13383 }
13384
13385private:
13386 /* The remote target. */
13387 remote_target *m_remote;
13388
13389 /* The owned remote I/O file descriptor. */
13390 int m_fd;
13391};
13392
13393void
13394remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13395{
13396 remote_target *remote = get_current_remote_target ();
13397
13398 if (remote == nullptr)
13399 error (_("command can only be used with remote target"));
13400
13401 remote->remote_file_put (local_file, remote_file, from_tty);
13402}
13403
13404void
13405remote_target::remote_file_put (const char *local_file, const char *remote_file,
13406 int from_tty)
13407{
13408 int retcode, bytes, io_size;
13409 fileio_error remote_errno;
13410 int bytes_in_buffer;
13411 int saw_eof;
13412 ULONGEST offset;
13413
13414 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13415 if (file == NULL)
13416 perror_with_name (local_file);
13417
13418 scoped_remote_fd fd
13419 (this, remote_hostio_open (NULL,
13420 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13421 | FILEIO_O_TRUNC),
13422 0700, 0, &remote_errno));
13423 if (fd.get () == -1)
13424 remote_hostio_error (remote_errno);
13425
13426 /* Send up to this many bytes at once. They won't all fit in the
13427 remote packet limit, so we'll transfer slightly fewer. */
13428 io_size = get_remote_packet_size ();
13429 gdb::byte_vector buffer (io_size);
13430
13431 bytes_in_buffer = 0;
13432 saw_eof = 0;
13433 offset = 0;
13434 while (bytes_in_buffer || !saw_eof)
13435 {
13436 if (!saw_eof)
13437 {
13438 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13439 io_size - bytes_in_buffer,
13440 file.get ());
13441 if (bytes == 0)
13442 {
13443 if (ferror (file.get ()))
13444 error (_("Error reading %s."), local_file);
13445 else
13446 {
13447 /* EOF. Unless there is something still in the
13448 buffer from the last iteration, we are done. */
13449 saw_eof = 1;
13450 if (bytes_in_buffer == 0)
13451 break;
13452 }
13453 }
13454 }
13455 else
13456 bytes = 0;
13457
13458 bytes += bytes_in_buffer;
13459 bytes_in_buffer = 0;
13460
13461 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13462 offset, &remote_errno);
13463
13464 if (retcode < 0)
13465 remote_hostio_error (remote_errno);
13466 else if (retcode == 0)
13467 error (_("Remote write of %d bytes returned 0!"), bytes);
13468 else if (retcode < bytes)
13469 {
13470 /* Short write. Save the rest of the read data for the next
13471 write. */
13472 bytes_in_buffer = bytes - retcode;
13473 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13474 }
13475
13476 offset += retcode;
13477 }
13478
13479 if (remote_hostio_close (fd.release (), &remote_errno))
13480 remote_hostio_error (remote_errno);
13481
13482 if (from_tty)
13483 gdb_printf (_("Successfully sent file \"%ps\".\n"),
13484 styled_string (file_name_style.style (), local_file));
13485}
13486
13487void
13488remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13489{
13490 remote_target *remote = get_current_remote_target ();
13491
13492 if (remote == nullptr)
13493 error (_("command can only be used with remote target"));
13494
13495 remote->remote_file_get (remote_file, local_file, from_tty);
13496}
13497
13498void
13499remote_target::remote_file_get (const char *remote_file, const char *local_file,
13500 int from_tty)
13501{
13502 fileio_error remote_errno;
13503 int bytes, io_size;
13504 ULONGEST offset;
13505
13506 scoped_remote_fd fd
13507 (this, remote_hostio_open (NULL,
13508 remote_file, FILEIO_O_RDONLY, 0, 0,
13509 &remote_errno));
13510 if (fd.get () == -1)
13511 remote_hostio_error (remote_errno);
13512
13513 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13514 if (file == NULL)
13515 perror_with_name (local_file);
13516
13517 /* Send up to this many bytes at once. They won't all fit in the
13518 remote packet limit, so we'll transfer slightly fewer. */
13519 io_size = get_remote_packet_size ();
13520 gdb::byte_vector buffer (io_size);
13521
13522 offset = 0;
13523 while (1)
13524 {
13525 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13526 &remote_errno);
13527 if (bytes == 0)
13528 /* Success, but no bytes, means end-of-file. */
13529 break;
13530 if (bytes == -1)
13531 remote_hostio_error (remote_errno);
13532
13533 offset += bytes;
13534
13535 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13536 if (bytes == 0)
13537 perror_with_name (local_file);
13538 }
13539
13540 if (remote_hostio_close (fd.release (), &remote_errno))
13541 remote_hostio_error (remote_errno);
13542
13543 if (from_tty)
13544 gdb_printf (_("Successfully fetched file \"%ps\".\n"),
13545 styled_string (file_name_style.style (), remote_file));
13546}
13547
13548void
13549remote_file_delete (const char *remote_file, int from_tty)
13550{
13551 remote_target *remote = get_current_remote_target ();
13552
13553 if (remote == nullptr)
13554 error (_("command can only be used with remote target"));
13555
13556 remote->remote_file_delete (remote_file, from_tty);
13557}
13558
13559void
13560remote_target::remote_file_delete (const char *remote_file, int from_tty)
13561{
13562 int retcode;
13563 fileio_error remote_errno;
13564
13565 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13566 if (retcode == -1)
13567 remote_hostio_error (remote_errno);
13568
13569 if (from_tty)
13570 gdb_printf (_("Successfully deleted file \"%ps\".\n"),
13571 styled_string (file_name_style.style (), remote_file));
13572}
13573
13574static void
13575remote_put_command (const char *args, int from_tty)
13576{
13577 if (args == NULL)
13578 error_no_arg (_("file to put"));
13579
13580 gdb_argv argv (args);
13581 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13582 error (_("Invalid parameters to remote put"));
13583
13584 remote_file_put (argv[0], argv[1], from_tty);
13585}
13586
13587static void
13588remote_get_command (const char *args, int from_tty)
13589{
13590 if (args == NULL)
13591 error_no_arg (_("file to get"));
13592
13593 gdb_argv argv (args);
13594 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13595 error (_("Invalid parameters to remote get"));
13596
13597 remote_file_get (argv[0], argv[1], from_tty);
13598}
13599
13600static void
13601remote_delete_command (const char *args, int from_tty)
13602{
13603 if (args == NULL)
13604 error_no_arg (_("file to delete"));
13605
13606 gdb_argv argv (args);
13607 if (argv[0] == NULL || argv[1] != NULL)
13608 error (_("Invalid parameters to remote delete"));
13609
13610 remote_file_delete (argv[0], from_tty);
13611}
13612
13613bool
13614remote_target::can_execute_reverse ()
13615{
13616 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13617 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13618 return true;
13619 else
13620 return false;
13621}
13622
13623bool
13624remote_target::supports_non_stop ()
13625{
13626 return true;
13627}
13628
13629bool
13630remote_target::supports_disable_randomization ()
13631{
13632 /* Only supported in extended mode. */
13633 return false;
13634}
13635
13636bool
13637remote_target::supports_multi_process ()
13638{
13639 return m_features.remote_multi_process_p ();
13640}
13641
13642int
13643remote_target::remote_supports_cond_tracepoints ()
13644{
13645 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13646 == PACKET_ENABLE);
13647}
13648
13649bool
13650remote_target::supports_evaluation_of_breakpoint_conditions ()
13651{
13652 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13653 == PACKET_ENABLE);
13654}
13655
13656int
13657remote_target::remote_supports_fast_tracepoints ()
13658{
13659 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13660}
13661
13662int
13663remote_target::remote_supports_static_tracepoints ()
13664{
13665 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13666}
13667
13668int
13669remote_target::remote_supports_install_in_trace ()
13670{
13671 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13672}
13673
13674bool
13675remote_target::supports_enable_disable_tracepoint ()
13676{
13677 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13678 == PACKET_ENABLE);
13679}
13680
13681bool
13682remote_target::supports_string_tracing ()
13683{
13684 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13685}
13686
13687bool
13688remote_target::can_run_breakpoint_commands ()
13689{
13690 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13691}
13692
13693void
13694remote_target::trace_init ()
13695{
13696 struct remote_state *rs = get_remote_state ();
13697
13698 putpkt ("QTinit");
13699 remote_get_noisy_reply ();
13700 if (strcmp (rs->buf.data (), "OK") != 0)
13701 error (_("Target does not support this command."));
13702}
13703
13704/* Recursive routine to walk through command list including loops, and
13705 download packets for each command. */
13706
13707void
13708remote_target::remote_download_command_source (int num, ULONGEST addr,
13709 struct command_line *cmds)
13710{
13711 struct remote_state *rs = get_remote_state ();
13712 struct command_line *cmd;
13713
13714 for (cmd = cmds; cmd; cmd = cmd->next)
13715 {
13716 QUIT; /* Allow user to bail out with ^C. */
13717 strcpy (rs->buf.data (), "QTDPsrc:");
13718 encode_source_string (num, addr, "cmd", cmd->line,
13719 rs->buf.data () + strlen (rs->buf.data ()),
13720 rs->buf.size () - strlen (rs->buf.data ()));
13721 putpkt (rs->buf);
13722 remote_get_noisy_reply ();
13723 if (strcmp (rs->buf.data (), "OK"))
13724 warning (_("Target does not support source download."));
13725
13726 if (cmd->control_type == while_control
13727 || cmd->control_type == while_stepping_control)
13728 {
13729 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13730
13731 QUIT; /* Allow user to bail out with ^C. */
13732 strcpy (rs->buf.data (), "QTDPsrc:");
13733 encode_source_string (num, addr, "cmd", "end",
13734 rs->buf.data () + strlen (rs->buf.data ()),
13735 rs->buf.size () - strlen (rs->buf.data ()));
13736 putpkt (rs->buf);
13737 remote_get_noisy_reply ();
13738 if (strcmp (rs->buf.data (), "OK"))
13739 warning (_("Target does not support source download."));
13740 }
13741 }
13742}
13743
13744void
13745remote_target::download_tracepoint (struct bp_location *loc)
13746{
13747 CORE_ADDR tpaddr;
13748 char addrbuf[40];
13749 std::vector<std::string> tdp_actions;
13750 std::vector<std::string> stepping_actions;
13751 char *pkt;
13752 struct breakpoint *b = loc->owner;
13753 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13754 struct remote_state *rs = get_remote_state ();
13755 int ret;
13756 const char *err_msg = _("Tracepoint packet too large for target.");
13757 size_t size_left;
13758
13759 /* We use a buffer other than rs->buf because we'll build strings
13760 across multiple statements, and other statements in between could
13761 modify rs->buf. */
13762 gdb::char_vector buf (get_remote_packet_size ());
13763
13764 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13765
13766 tpaddr = loc->address;
13767 strcpy (addrbuf, phex (tpaddr));
13768 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13769 b->number, addrbuf, /* address */
13770 (b->enable_state == bp_enabled ? 'E' : 'D'),
13771 t->step_count, t->pass_count);
13772
13773 if (ret < 0 || ret >= buf.size ())
13774 error ("%s", err_msg);
13775
13776 /* Fast tracepoints are mostly handled by the target, but we can
13777 tell the target how big of an instruction block should be moved
13778 around. */
13779 if (b->type == bp_fast_tracepoint)
13780 {
13781 /* Only test for support at download time; we may not know
13782 target capabilities at definition time. */
13783 if (remote_supports_fast_tracepoints ())
13784 {
13785 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13786 NULL))
13787 {
13788 size_left = buf.size () - strlen (buf.data ());
13789 ret = snprintf (buf.data () + strlen (buf.data ()),
13790 size_left, ":F%x",
13791 gdb_insn_length (loc->gdbarch, tpaddr));
13792
13793 if (ret < 0 || ret >= size_left)
13794 error ("%s", err_msg);
13795 }
13796 else
13797 /* If it passed validation at definition but fails now,
13798 something is very wrong. */
13799 internal_error (_("Fast tracepoint not valid during download"));
13800 }
13801 else
13802 /* Fast tracepoints are functionally identical to regular
13803 tracepoints, so don't take lack of support as a reason to
13804 give up on the trace run. */
13805 warning (_("Target does not support fast tracepoints, "
13806 "downloading %d as regular tracepoint"), b->number);
13807 }
13808 else if (b->type == bp_static_tracepoint
13809 || b->type == bp_static_marker_tracepoint)
13810 {
13811 /* Only test for support at download time; we may not know
13812 target capabilities at definition time. */
13813 if (remote_supports_static_tracepoints ())
13814 {
13815 struct static_tracepoint_marker marker;
13816
13817 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13818 {
13819 size_left = buf.size () - strlen (buf.data ());
13820 ret = snprintf (buf.data () + strlen (buf.data ()),
13821 size_left, ":S");
13822
13823 if (ret < 0 || ret >= size_left)
13824 error ("%s", err_msg);
13825 }
13826 else
13827 error (_("Static tracepoint not valid during download"));
13828 }
13829 else
13830 /* Fast tracepoints are functionally identical to regular
13831 tracepoints, so don't take lack of support as a reason
13832 to give up on the trace run. */
13833 error (_("Target does not support static tracepoints"));
13834 }
13835 /* If the tracepoint has a conditional, make it into an agent
13836 expression and append to the definition. */
13837 if (loc->cond)
13838 {
13839 /* Only test support at download time, we may not know target
13840 capabilities at definition time. */
13841 if (remote_supports_cond_tracepoints ())
13842 {
13843 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13844 loc->cond.get ());
13845
13846 size_left = buf.size () - strlen (buf.data ());
13847
13848 ret = snprintf (buf.data () + strlen (buf.data ()),
13849 size_left, ":X%x,", (int) aexpr->buf.size ());
13850
13851 if (ret < 0 || ret >= size_left)
13852 error ("%s", err_msg);
13853
13854 size_left = buf.size () - strlen (buf.data ());
13855
13856 /* Two bytes to encode each aexpr byte, plus the terminating
13857 null byte. */
13858 if (aexpr->buf.size () * 2 + 1 > size_left)
13859 error ("%s", err_msg);
13860
13861 pkt = buf.data () + strlen (buf.data ());
13862
13863 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13864 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13865 *pkt = '\0';
13866 }
13867 else
13868 warning (_("Target does not support conditional tracepoints, "
13869 "ignoring tp %d cond"), b->number);
13870 }
13871
13872 if (b->commands || !default_collect.empty ())
13873 {
13874 size_left = buf.size () - strlen (buf.data ());
13875
13876 ret = snprintf (buf.data () + strlen (buf.data ()),
13877 size_left, "-");
13878
13879 if (ret < 0 || ret >= size_left)
13880 error ("%s", err_msg);
13881 }
13882
13883 putpkt (buf.data ());
13884 remote_get_noisy_reply ();
13885 if (strcmp (rs->buf.data (), "OK"))
13886 error (_("Target does not support tracepoints."));
13887
13888 /* do_single_steps (t); */
13889 for (auto action_it = tdp_actions.begin ();
13890 action_it != tdp_actions.end (); action_it++)
13891 {
13892 QUIT; /* Allow user to bail out with ^C. */
13893
13894 bool has_more = ((action_it + 1) != tdp_actions.end ()
13895 || !stepping_actions.empty ());
13896
13897 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13898 b->number, addrbuf, /* address */
13899 action_it->c_str (),
13900 has_more ? '-' : 0);
13901
13902 if (ret < 0 || ret >= buf.size ())
13903 error ("%s", err_msg);
13904
13905 putpkt (buf.data ());
13906 remote_get_noisy_reply ();
13907 if (strcmp (rs->buf.data (), "OK"))
13908 error (_("Error on target while setting tracepoints."));
13909 }
13910
13911 for (auto action_it = stepping_actions.begin ();
13912 action_it != stepping_actions.end (); action_it++)
13913 {
13914 QUIT; /* Allow user to bail out with ^C. */
13915
13916 bool is_first = action_it == stepping_actions.begin ();
13917 bool has_more = (action_it + 1) != stepping_actions.end ();
13918
13919 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13920 b->number, addrbuf, /* address */
13921 is_first ? "S" : "",
13922 action_it->c_str (),
13923 has_more ? "-" : "");
13924
13925 if (ret < 0 || ret >= buf.size ())
13926 error ("%s", err_msg);
13927
13928 putpkt (buf.data ());
13929 remote_get_noisy_reply ();
13930 if (strcmp (rs->buf.data (), "OK"))
13931 error (_("Error on target while setting tracepoints."));
13932 }
13933
13934 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13935 {
13936 if (b->locspec != nullptr)
13937 {
13938 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13939
13940 if (ret < 0 || ret >= buf.size ())
13941 error ("%s", err_msg);
13942
13943 const char *str = b->locspec->to_string ();
13944 encode_source_string (b->number, loc->address, "at", str,
13945 buf.data () + strlen (buf.data ()),
13946 buf.size () - strlen (buf.data ()));
13947 putpkt (buf.data ());
13948 remote_get_noisy_reply ();
13949 if (strcmp (rs->buf.data (), "OK"))
13950 warning (_("Target does not support source download."));
13951 }
13952 if (b->cond_string)
13953 {
13954 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13955
13956 if (ret < 0 || ret >= buf.size ())
13957 error ("%s", err_msg);
13958
13959 encode_source_string (b->number, loc->address,
13960 "cond", b->cond_string.get (),
13961 buf.data () + strlen (buf.data ()),
13962 buf.size () - strlen (buf.data ()));
13963 putpkt (buf.data ());
13964 remote_get_noisy_reply ();
13965 if (strcmp (rs->buf.data (), "OK"))
13966 warning (_("Target does not support source download."));
13967 }
13968 remote_download_command_source (b->number, loc->address,
13969 breakpoint_commands (b));
13970 }
13971}
13972
13973bool
13974remote_target::can_download_tracepoint ()
13975{
13976 struct remote_state *rs = get_remote_state ();
13977 struct trace_status *ts;
13978 int status;
13979
13980 /* Don't try to install tracepoints until we've relocated our
13981 symbols, and fetched and merged the target's tracepoint list with
13982 ours. */
13983 if (rs->starting_up)
13984 return false;
13985
13986 ts = current_trace_status ();
13987 status = get_trace_status (ts);
13988
13989 if (status == -1 || !ts->running_known || !ts->running)
13990 return false;
13991
13992 /* If we are in a tracing experiment, but remote stub doesn't support
13993 installing tracepoint in trace, we have to return. */
13994 if (!remote_supports_install_in_trace ())
13995 return false;
13996
13997 return true;
13998}
13999
14000
14001void
14002remote_target::download_trace_state_variable (const trace_state_variable &tsv)
14003{
14004 struct remote_state *rs = get_remote_state ();
14005 char *p;
14006
14007 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
14008 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
14009 tsv.builtin);
14010 p = rs->buf.data () + strlen (rs->buf.data ());
14011 if ((p - rs->buf.data ()) + tsv.name.length () * 2
14012 >= get_remote_packet_size ())
14013 error (_("Trace state variable name too long for tsv definition packet"));
14014 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
14015 *p++ = '\0';
14016 putpkt (rs->buf);
14017 remote_get_noisy_reply ();
14018 if (rs->buf[0] == '\0')
14019 error (_("Target does not support this command."));
14020 if (strcmp (rs->buf.data (), "OK") != 0)
14021 error (_("Error on target while downloading trace state variable."));
14022}
14023
14024void
14025remote_target::enable_tracepoint (struct bp_location *location)
14026{
14027 struct remote_state *rs = get_remote_state ();
14028
14029 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
14030 location->owner->number,
14031 phex (location->address));
14032 putpkt (rs->buf);
14033 remote_get_noisy_reply ();
14034 if (rs->buf[0] == '\0')
14035 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
14036 if (strcmp (rs->buf.data (), "OK") != 0)
14037 error (_("Error on target while enabling tracepoint."));
14038}
14039
14040void
14041remote_target::disable_tracepoint (struct bp_location *location)
14042{
14043 struct remote_state *rs = get_remote_state ();
14044
14045 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
14046 location->owner->number,
14047 phex (location->address));
14048 putpkt (rs->buf);
14049 remote_get_noisy_reply ();
14050 if (rs->buf[0] == '\0')
14051 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
14052 if (strcmp (rs->buf.data (), "OK") != 0)
14053 error (_("Error on target while disabling tracepoint."));
14054}
14055
14056void
14057remote_target::trace_set_readonly_regions ()
14058{
14059 asection *s;
14060 bfd_size_type size;
14061 bfd_vma vma;
14062 int anysecs = 0;
14063 int offset = 0;
14064 bfd *abfd = current_program_space->exec_bfd ();
14065
14066 if (!abfd)
14067 return; /* No information to give. */
14068
14069 struct remote_state *rs = get_remote_state ();
14070
14071 strcpy (rs->buf.data (), "QTro");
14072 offset = strlen (rs->buf.data ());
14073 for (s = abfd->sections; s; s = s->next)
14074 {
14075 char tmp1[40], tmp2[40];
14076 int sec_length;
14077
14078 if ((s->flags & SEC_LOAD) == 0
14079 /* || (s->flags & SEC_CODE) == 0 */
14080 || (s->flags & SEC_READONLY) == 0)
14081 continue;
14082
14083 anysecs = 1;
14084 vma = bfd_section_vma (s);
14085 size = bfd_section_size (s);
14086 bfd_sprintf_vma (abfd, tmp1, vma);
14087 bfd_sprintf_vma (abfd, tmp2, vma + size);
14088 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
14089 if (offset + sec_length + 1 > rs->buf.size ())
14090 {
14091 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
14092 != PACKET_ENABLE)
14093 warning (_("\
14094Too many sections for read-only sections definition packet."));
14095 break;
14096 }
14097 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
14098 tmp1, tmp2);
14099 offset += sec_length;
14100 }
14101 if (anysecs)
14102 {
14103 putpkt (rs->buf);
14104 getpkt (&rs->buf);
14105 }
14106}
14107
14108void
14109remote_target::trace_start ()
14110{
14111 struct remote_state *rs = get_remote_state ();
14112
14113 putpkt ("QTStart");
14114 remote_get_noisy_reply ();
14115 if (rs->buf[0] == '\0')
14116 error (_("Target does not support this command."));
14117 if (strcmp (rs->buf.data (), "OK") != 0)
14118 error (_("Bogus reply from target: %s"), rs->buf.data ());
14119}
14120
14121int
14122remote_target::get_trace_status (struct trace_status *ts)
14123{
14124 /* Initialize it just to avoid a GCC false warning. */
14125 char *p = NULL;
14126 struct remote_state *rs = get_remote_state ();
14127
14128 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
14129 return -1;
14130
14131 /* FIXME we need to get register block size some other way. */
14132 trace_regblock_size
14133 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
14134
14135 putpkt ("qTStatus");
14136
14137 try
14138 {
14139 p = remote_get_noisy_reply ();
14140 }
14141 catch (const gdb_exception_error &ex)
14142 {
14143 if (ex.error != TARGET_CLOSE_ERROR)
14144 {
14145 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
14146 return -1;
14147 }
14148 throw;
14149 }
14150
14151 packet_result result = m_features.packet_ok (p, PACKET_qTStatus);
14152
14153 switch (result.status ())
14154 {
14155 case PACKET_ERROR:
14156 error (_("Remote failure reply: %s"), result.err_msg ());
14157 /* If the remote target doesn't do tracing, flag it. */
14158 case PACKET_UNKNOWN:
14159 return -1;
14160 }
14161
14162 /* We're working with a live target. */
14163 ts->filename = NULL;
14164
14165 if (*p++ != 'T')
14166 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
14167
14168 /* Function 'parse_trace_status' sets default value of each field of
14169 'ts' at first, so we don't have to do it here. */
14170 parse_trace_status (p, ts);
14171
14172 return ts->running;
14173}
14174
14175void
14176remote_target::get_tracepoint_status (tracepoint *tp,
14177 struct uploaded_tp *utp)
14178{
14179 struct remote_state *rs = get_remote_state ();
14180 char *reply;
14181 size_t size = get_remote_packet_size ();
14182
14183 if (tp)
14184 {
14185 tp->hit_count = 0;
14186 tp->traceframe_usage = 0;
14187 for (bp_location &loc : tp->locations ())
14188 {
14189 /* If the tracepoint was never downloaded, don't go asking for
14190 any status. */
14191 if (tp->number_on_target == 0)
14192 continue;
14193 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
14194 phex_nz (loc.address, 0));
14195 putpkt (rs->buf);
14196 reply = remote_get_noisy_reply ();
14197 if (reply && *reply)
14198 {
14199 if (*reply == 'V')
14200 parse_tracepoint_status (reply + 1, tp, utp);
14201 }
14202 }
14203 }
14204 else if (utp)
14205 {
14206 utp->hit_count = 0;
14207 utp->traceframe_usage = 0;
14208 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
14209 phex_nz (utp->addr, 0));
14210 putpkt (rs->buf);
14211 reply = remote_get_noisy_reply ();
14212 if (reply && *reply)
14213 {
14214 if (*reply == 'V')
14215 parse_tracepoint_status (reply + 1, tp, utp);
14216 }
14217 }
14218}
14219
14220void
14221remote_target::trace_stop ()
14222{
14223 struct remote_state *rs = get_remote_state ();
14224
14225 putpkt ("QTStop");
14226 remote_get_noisy_reply ();
14227 if (rs->buf[0] == '\0')
14228 error (_("Target does not support this command."));
14229 if (strcmp (rs->buf.data (), "OK") != 0)
14230 error (_("Bogus reply from target: %s"), rs->buf.data ());
14231}
14232
14233int
14234remote_target::trace_find (enum trace_find_type type, int num,
14235 CORE_ADDR addr1, CORE_ADDR addr2,
14236 int *tpp)
14237{
14238 struct remote_state *rs = get_remote_state ();
14239 char *endbuf = rs->buf.data () + get_remote_packet_size ();
14240 char *p, *reply;
14241 int target_frameno = -1, target_tracept = -1;
14242
14243 /* Lookups other than by absolute frame number depend on the current
14244 trace selected, so make sure it is correct on the remote end
14245 first. */
14246 if (type != tfind_number)
14247 set_remote_traceframe ();
14248
14249 p = rs->buf.data ();
14250 strcpy (p, "QTFrame:");
14251 p = strchr (p, '\0');
14252 switch (type)
14253 {
14254 case tfind_number:
14255 xsnprintf (p, endbuf - p, "%x", num);
14256 break;
14257 case tfind_pc:
14258 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
14259 break;
14260 case tfind_tp:
14261 xsnprintf (p, endbuf - p, "tdp:%x", num);
14262 break;
14263 case tfind_range:
14264 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
14265 phex_nz (addr2, 0));
14266 break;
14267 case tfind_outside:
14268 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
14269 phex_nz (addr2, 0));
14270 break;
14271 default:
14272 error (_("Unknown trace find type %d"), type);
14273 }
14274
14275 putpkt (rs->buf);
14276 reply = remote_get_noisy_reply ();
14277 if (*reply == '\0')
14278 error (_("Target does not support this command."));
14279
14280 while (reply && *reply)
14281 switch (*reply)
14282 {
14283 case 'F':
14284 p = ++reply;
14285 target_frameno = (int) strtol (p, &reply, 16);
14286 if (reply == p)
14287 error (_("Unable to parse trace frame number"));
14288 /* Don't update our remote traceframe number cache on failure
14289 to select a remote traceframe. */
14290 if (target_frameno == -1)
14291 return -1;
14292 break;
14293 case 'T':
14294 p = ++reply;
14295 target_tracept = (int) strtol (p, &reply, 16);
14296 if (reply == p)
14297 error (_("Unable to parse tracepoint number"));
14298 break;
14299 case 'O': /* "OK"? */
14300 if (reply[1] == 'K' && reply[2] == '\0')
14301 reply += 2;
14302 else
14303 error (_("Bogus reply from target: %s"), reply);
14304 break;
14305 default:
14306 error (_("Bogus reply from target: %s"), reply);
14307 }
14308 if (tpp)
14309 *tpp = target_tracept;
14310
14311 rs->remote_traceframe_number = target_frameno;
14312 return target_frameno;
14313}
14314
14315bool
14316remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
14317{
14318 struct remote_state *rs = get_remote_state ();
14319 char *reply;
14320 ULONGEST uval;
14321
14322 set_remote_traceframe ();
14323
14324 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
14325 putpkt (rs->buf);
14326 reply = remote_get_noisy_reply ();
14327 if (reply && *reply)
14328 {
14329 if (*reply == 'V')
14330 {
14331 unpack_varlen_hex (reply + 1, &uval);
14332 *val = (LONGEST) uval;
14333 return true;
14334 }
14335 }
14336 return false;
14337}
14338
14339int
14340remote_target::save_trace_data (const char *filename)
14341{
14342 struct remote_state *rs = get_remote_state ();
14343 char *p, *reply;
14344
14345 p = rs->buf.data ();
14346 strcpy (p, "QTSave:");
14347 p += strlen (p);
14348 if ((p - rs->buf.data ()) + strlen (filename) * 2
14349 >= get_remote_packet_size ())
14350 error (_("Remote file name too long for trace save packet"));
14351 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14352 *p++ = '\0';
14353 putpkt (rs->buf);
14354 reply = remote_get_noisy_reply ();
14355 if (*reply == '\0')
14356 error (_("Target does not support this command."));
14357 if (strcmp (reply, "OK") != 0)
14358 error (_("Bogus reply from target: %s"), reply);
14359 return 0;
14360}
14361
14362/* This is basically a memory transfer, but needs to be its own packet
14363 because we don't know how the target actually organizes its trace
14364 memory, plus we want to be able to ask for as much as possible, but
14365 not be unhappy if we don't get as much as we ask for. */
14366
14367LONGEST
14368remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14369{
14370 struct remote_state *rs = get_remote_state ();
14371 char *reply;
14372 char *p;
14373 int rslt;
14374
14375 p = rs->buf.data ();
14376 strcpy (p, "qTBuffer:");
14377 p += strlen (p);
14378 p += hexnumstr (p, offset);
14379 *p++ = ',';
14380 p += hexnumstr (p, len);
14381 *p++ = '\0';
14382
14383 putpkt (rs->buf);
14384 reply = remote_get_noisy_reply ();
14385 if (reply && *reply)
14386 {
14387 /* 'l' by itself means we're at the end of the buffer and
14388 there is nothing more to get. */
14389 if (*reply == 'l')
14390 return 0;
14391
14392 /* Convert the reply into binary. Limit the number of bytes to
14393 convert according to our passed-in buffer size, rather than
14394 what was returned in the packet; if the target is
14395 unexpectedly generous and gives us a bigger reply than we
14396 asked for, we don't want to crash. */
14397 rslt = hex2bin (reply, buf, len);
14398 return rslt;
14399 }
14400
14401 /* Something went wrong, flag as an error. */
14402 return -1;
14403}
14404
14405void
14406remote_target::set_disconnected_tracing (int val)
14407{
14408 struct remote_state *rs = get_remote_state ();
14409
14410 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14411 == PACKET_ENABLE)
14412 {
14413 char *reply;
14414
14415 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14416 "QTDisconnected:%x", val);
14417 putpkt (rs->buf);
14418 reply = remote_get_noisy_reply ();
14419 if (*reply == '\0')
14420 error (_("Target does not support this command."));
14421 if (strcmp (reply, "OK") != 0)
14422 error (_("Bogus reply from target: %s"), reply);
14423 }
14424 else if (val)
14425 warning (_("Target does not support disconnected tracing."));
14426}
14427
14428int
14429remote_target::core_of_thread (ptid_t ptid)
14430{
14431 thread_info *info = this->find_thread (ptid);
14432
14433 if (info != NULL && info->priv != NULL)
14434 return get_remote_thread_info (info)->core;
14435
14436 return -1;
14437}
14438
14439void
14440remote_target::set_circular_trace_buffer (int val)
14441{
14442 struct remote_state *rs = get_remote_state ();
14443 char *reply;
14444
14445 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14446 "QTBuffer:circular:%x", val);
14447 putpkt (rs->buf);
14448 reply = remote_get_noisy_reply ();
14449 if (*reply == '\0')
14450 error (_("Target does not support this command."));
14451 if (strcmp (reply, "OK") != 0)
14452 error (_("Bogus reply from target: %s"), reply);
14453}
14454
14455traceframe_info_up
14456remote_target::traceframe_info ()
14457{
14458 std::optional<gdb::char_vector> text
14459 = target_read_stralloc (current_inferior ()->top_target (),
14460 TARGET_OBJECT_TRACEFRAME_INFO,
14461 NULL);
14462 if (text)
14463 return parse_traceframe_info (text->data ());
14464
14465 return NULL;
14466}
14467
14468/* Handle the qTMinFTPILen packet. Returns the minimum length of
14469 instruction on which a fast tracepoint may be placed. Returns -1
14470 if the packet is not supported, and 0 if the minimum instruction
14471 length is unknown. */
14472
14473int
14474remote_target::get_min_fast_tracepoint_insn_len ()
14475{
14476 struct remote_state *rs = get_remote_state ();
14477 char *reply;
14478
14479 /* If we're not debugging a process yet, the IPA can't be
14480 loaded. */
14481 if (!target_has_execution ())
14482 return 0;
14483
14484 /* Make sure the remote is pointing at the right process. */
14485 set_general_process ();
14486
14487 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14488 putpkt (rs->buf);
14489 reply = remote_get_noisy_reply ();
14490 if (*reply == '\0')
14491 return -1;
14492 else
14493 {
14494 ULONGEST min_insn_len;
14495
14496 unpack_varlen_hex (reply, &min_insn_len);
14497
14498 return (int) min_insn_len;
14499 }
14500}
14501
14502void
14503remote_target::set_trace_buffer_size (LONGEST val)
14504{
14505 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14506 {
14507 struct remote_state *rs = get_remote_state ();
14508 char *buf = rs->buf.data ();
14509 char *endbuf = buf + get_remote_packet_size ();
14510
14511 gdb_assert (val >= 0 || val == -1);
14512 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14513 /* Send -1 as literal "-1" to avoid host size dependency. */
14514 if (val < 0)
14515 {
14516 *buf++ = '-';
14517 buf += hexnumstr (buf, (ULONGEST) -val);
14518 }
14519 else
14520 buf += hexnumstr (buf, (ULONGEST) val);
14521
14522 putpkt (rs->buf);
14523 remote_get_noisy_reply ();
14524 packet_result result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14525 switch (result.status ())
14526 {
14527 case PACKET_ERROR:
14528 warning (_("Error reply from target: %s"), result.err_msg ());
14529 break;
14530 case PACKET_UNKNOWN:
14531 warning (_("Remote target failed to process the request "));
14532 }
14533 }
14534}
14535
14536bool
14537remote_target::set_trace_notes (const char *user, const char *notes,
14538 const char *stop_notes)
14539{
14540 struct remote_state *rs = get_remote_state ();
14541 char *reply;
14542 char *buf = rs->buf.data ();
14543 char *endbuf = buf + get_remote_packet_size ();
14544 int nbytes;
14545
14546 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14547 if (user)
14548 {
14549 buf += xsnprintf (buf, endbuf - buf, "user:");
14550 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14551 buf += 2 * nbytes;
14552 *buf++ = ';';
14553 }
14554 if (notes)
14555 {
14556 buf += xsnprintf (buf, endbuf - buf, "notes:");
14557 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14558 buf += 2 * nbytes;
14559 *buf++ = ';';
14560 }
14561 if (stop_notes)
14562 {
14563 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14564 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14565 buf += 2 * nbytes;
14566 *buf++ = ';';
14567 }
14568 /* Ensure the buffer is terminated. */
14569 *buf = '\0';
14570
14571 putpkt (rs->buf);
14572 reply = remote_get_noisy_reply ();
14573 if (*reply == '\0')
14574 return false;
14575
14576 if (strcmp (reply, "OK") != 0)
14577 error (_("Bogus reply from target: %s"), reply);
14578
14579 return true;
14580}
14581
14582bool
14583remote_target::use_agent (bool use)
14584{
14585 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14586 {
14587 struct remote_state *rs = get_remote_state ();
14588
14589 /* If the stub supports QAgent. */
14590 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14591 putpkt (rs->buf);
14592 getpkt (&rs->buf);
14593
14594 if (strcmp (rs->buf.data (), "OK") == 0)
14595 {
14596 ::use_agent = use;
14597 return true;
14598 }
14599 }
14600
14601 return false;
14602}
14603
14604bool
14605remote_target::can_use_agent ()
14606{
14607 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14608}
14609
14610#if defined (HAVE_LIBEXPAT)
14611
14612/* Check the btrace document version. */
14613
14614static void
14615check_xml_btrace_version (struct gdb_xml_parser *parser,
14616 const struct gdb_xml_element *element,
14617 void *user_data,
14618 std::vector<gdb_xml_value> &attributes)
14619{
14620 const char *version
14621 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14622
14623 if (strcmp (version, "1.0") != 0)
14624 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14625}
14626
14627/* Parse a btrace "block" xml record. */
14628
14629static void
14630parse_xml_btrace_block (struct gdb_xml_parser *parser,
14631 const struct gdb_xml_element *element,
14632 void *user_data,
14633 std::vector<gdb_xml_value> &attributes)
14634{
14635 struct btrace_data *btrace;
14636 ULONGEST *begin, *end;
14637
14638 btrace = (struct btrace_data *) user_data;
14639
14640 switch (btrace->format)
14641 {
14642 case BTRACE_FORMAT_BTS:
14643 break;
14644
14645 case BTRACE_FORMAT_NONE:
14646 btrace->format = BTRACE_FORMAT_BTS;
14647 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14648 break;
14649
14650 default:
14651 gdb_xml_error (parser, _("Btrace format error."));
14652 }
14653
14654 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14655 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14656 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14657}
14658
14659/* Parse a "raw" xml record. */
14660
14661static void
14662parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14663 gdb_byte **pdata, size_t *psize)
14664{
14665 gdb_byte *bin;
14666 size_t len, size;
14667
14668 len = strlen (body_text);
14669 if (len % 2 != 0)
14670 gdb_xml_error (parser, _("Bad raw data size."));
14671
14672 size = len / 2;
14673
14674 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14675 bin = data.get ();
14676
14677 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14678 while (len > 0)
14679 {
14680 char hi, lo;
14681
14682 hi = *body_text++;
14683 lo = *body_text++;
14684
14685 if (hi == 0 || lo == 0)
14686 gdb_xml_error (parser, _("Bad hex encoding."));
14687
14688 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14689 len -= 2;
14690 }
14691
14692 *pdata = data.release ();
14693 *psize = size;
14694}
14695
14696/* Parse a btrace pt-config "cpu" xml record. */
14697
14698static void
14699parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14700 const struct gdb_xml_element *element,
14701 void *user_data,
14702 std::vector<gdb_xml_value> &attributes)
14703{
14704 struct btrace_data *btrace;
14705 const char *vendor;
14706 ULONGEST *family, *model, *stepping;
14707
14708 vendor
14709 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14710 family
14711 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14712 model
14713 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14714 stepping
14715 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14716
14717 btrace = (struct btrace_data *) user_data;
14718
14719 if (strcmp (vendor, "GenuineIntel") == 0)
14720 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14721
14722 btrace->variant.pt.config.cpu.family = *family;
14723 btrace->variant.pt.config.cpu.model = *model;
14724 btrace->variant.pt.config.cpu.stepping = *stepping;
14725}
14726
14727/* Parse a btrace pt "raw" xml record. */
14728
14729static void
14730parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14731 const struct gdb_xml_element *element,
14732 void *user_data, const char *body_text)
14733{
14734 struct btrace_data *btrace;
14735
14736 btrace = (struct btrace_data *) user_data;
14737 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14738 &btrace->variant.pt.size);
14739}
14740
14741/* Parse a btrace "pt" xml record. */
14742
14743static void
14744parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14745 const struct gdb_xml_element *element,
14746 void *user_data,
14747 std::vector<gdb_xml_value> &attributes)
14748{
14749 struct btrace_data *btrace;
14750
14751 btrace = (struct btrace_data *) user_data;
14752 btrace->format = BTRACE_FORMAT_PT;
14753 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14754 btrace->variant.pt.data = NULL;
14755 btrace->variant.pt.size = 0;
14756}
14757
14758static const struct gdb_xml_attribute block_attributes[] = {
14759 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14760 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14761 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14762};
14763
14764static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14765 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14766 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14767 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14768 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14769 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14770};
14771
14772static const struct gdb_xml_element btrace_pt_config_children[] = {
14773 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14774 parse_xml_btrace_pt_config_cpu, NULL },
14775 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14776};
14777
14778static const struct gdb_xml_element btrace_pt_children[] = {
14779 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14780 NULL },
14781 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14782 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14783};
14784
14785static const struct gdb_xml_attribute btrace_attributes[] = {
14786 { "version", GDB_XML_AF_NONE, NULL, NULL },
14787 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14788};
14789
14790static const struct gdb_xml_element btrace_children[] = {
14791 { "block", block_attributes, NULL,
14792 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14793 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14794 NULL },
14795 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14796};
14797
14798static const struct gdb_xml_element btrace_elements[] = {
14799 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14800 check_xml_btrace_version, NULL },
14801 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14802};
14803
14804#endif /* defined (HAVE_LIBEXPAT) */
14805
14806/* Parse a branch trace xml document XML into DATA. */
14807
14808static void
14809parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14810{
14811#if defined (HAVE_LIBEXPAT)
14812
14813 int errcode;
14814 btrace_data result;
14815 result.format = BTRACE_FORMAT_NONE;
14816
14817 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14818 buffer, &result);
14819 if (errcode != 0)
14820 error (_("Error parsing branch trace."));
14821
14822 /* Keep parse results. */
14823 *btrace = std::move (result);
14824
14825#else /* !defined (HAVE_LIBEXPAT) */
14826
14827 error (_("Cannot process branch trace. XML support was disabled at "
14828 "compile time."));
14829
14830#endif /* !defined (HAVE_LIBEXPAT) */
14831}
14832
14833#if defined (HAVE_LIBEXPAT)
14834
14835/* Parse a btrace-conf "bts" xml record. */
14836
14837static void
14838parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14839 const struct gdb_xml_element *element,
14840 void *user_data,
14841 std::vector<gdb_xml_value> &attributes)
14842{
14843 struct btrace_config *conf;
14844 struct gdb_xml_value *size;
14845
14846 conf = (struct btrace_config *) user_data;
14847 conf->format = BTRACE_FORMAT_BTS;
14848 conf->bts.size = 0;
14849
14850 size = xml_find_attribute (attributes, "size");
14851 if (size != NULL)
14852 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14853}
14854
14855/* Parse a btrace-conf "pt" xml record. */
14856
14857static void
14858parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14859 const struct gdb_xml_element *element,
14860 void *user_data,
14861 std::vector<gdb_xml_value> &attributes)
14862{
14863 struct btrace_config *conf;
14864 struct gdb_xml_value *size, *ptwrite, *event_tracing;
14865
14866 conf = (struct btrace_config *) user_data;
14867 conf->format = BTRACE_FORMAT_PT;
14868 conf->pt.size = 0;
14869
14870 size = xml_find_attribute (attributes, "size");
14871 if (size != NULL)
14872 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14873
14874 ptwrite = xml_find_attribute (attributes, "ptwrite");
14875 if (ptwrite != nullptr)
14876 conf->pt.ptwrite = (bool) *(ULONGEST *) ptwrite->value.get ();
14877
14878 event_tracing = xml_find_attribute (attributes, "event-tracing");
14879 if (event_tracing != nullptr)
14880 conf->pt.event_tracing = (bool) *(ULONGEST *) event_tracing->value.get ();
14881}
14882
14883static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14884 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14885 { "ptwrite", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_enum,
14886 gdb_xml_enums_boolean },
14887 { "event-tracing", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_enum,
14888 gdb_xml_enums_boolean },
14889 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14890};
14891
14892static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14893 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14894 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14895};
14896
14897static const struct gdb_xml_element btrace_conf_children[] = {
14898 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14899 parse_xml_btrace_conf_bts, NULL },
14900 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14901 parse_xml_btrace_conf_pt, NULL },
14902 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14903};
14904
14905static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14906 { "version", GDB_XML_AF_NONE, NULL, NULL },
14907 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14908};
14909
14910static const struct gdb_xml_element btrace_conf_elements[] = {
14911 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14912 GDB_XML_EF_NONE, NULL, NULL },
14913 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14914};
14915
14916#endif /* defined (HAVE_LIBEXPAT) */
14917
14918/* Parse a branch trace configuration xml document XML into CONF. */
14919
14920static void
14921parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14922{
14923#if defined (HAVE_LIBEXPAT)
14924
14925 int errcode;
14926 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14927 btrace_conf_elements, xml, conf);
14928 if (errcode != 0)
14929 error (_("Error parsing branch trace configuration."));
14930
14931#else /* !defined (HAVE_LIBEXPAT) */
14932
14933 error (_("Cannot process the branch trace configuration. XML support "
14934 "was disabled at compile time."));
14935
14936#endif /* !defined (HAVE_LIBEXPAT) */
14937}
14938
14939/* Reset our idea of our target's btrace configuration. */
14940
14941static void
14942remote_btrace_reset (remote_state *rs)
14943{
14944 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14945}
14946
14947/* Synchronize the configuration with the target. */
14948
14949void
14950remote_target::btrace_sync_conf (const btrace_config *conf)
14951{
14952 struct remote_state *rs;
14953 char *buf, *pos, *endbuf;
14954
14955 rs = get_remote_state ();
14956 buf = rs->buf.data ();
14957 endbuf = buf + get_remote_packet_size ();
14958
14959 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14960 && conf->bts.size != rs->btrace_config.bts.size)
14961 {
14962 pos = buf;
14963 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14964 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14965 conf->bts.size);
14966
14967 putpkt (buf);
14968 getpkt (&rs->buf);
14969
14970 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size);
14971 if (result.status () == PACKET_ERROR)
14972 error (_("Failed to configure the BTS buffer size: %s"), result.err_msg ());
14973
14974 rs->btrace_config.bts.size = conf->bts.size;
14975 }
14976
14977 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14978 && conf->pt.size != rs->btrace_config.pt.size)
14979 {
14980 pos = buf;
14981 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14982 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14983 conf->pt.size);
14984
14985 putpkt (buf);
14986 getpkt (&rs->buf);
14987
14988 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size);
14989 if (result.status () == PACKET_ERROR)
14990 error (_("Failed to configure the trace buffer size: %s"), result.err_msg ());
14991
14992 rs->btrace_config.pt.size = conf->pt.size;
14993 }
14994
14995 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_ptwrite)
14996 == PACKET_ENABLE)
14997 && conf->pt.ptwrite != rs->btrace_config.pt.ptwrite)
14998 {
14999 pos = buf;
15000 const char *ptw = conf->pt.ptwrite ? "yes" : "no";
15001 const char *name
15002 = packets_descriptions[PACKET_Qbtrace_conf_pt_ptwrite].name;
15003 pos += xsnprintf (pos, endbuf - pos, "%s=\"%s\"", name, ptw);
15004
15005 putpkt (buf);
15006 getpkt (&rs->buf, 0);
15007
15008 packet_result result
15009 = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_ptwrite);
15010 if (result.status () == PACKET_ERROR)
15011 {
15012 if (buf[0] == 'E' && buf[1] == '.')
15013 error (_("Failed to sync ptwrite config: %s"), buf + 2);
15014 else
15015 error (_("Failed to sync ptwrite config."));
15016 }
15017
15018 rs->btrace_config.pt.ptwrite = conf->pt.ptwrite;
15019 }
15020
15021 /* Event tracing is a user setting, warn if it is set but the target
15022 doesn't support it. */
15023 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_event_tracing)
15024 != PACKET_ENABLE)
15025 && conf->pt.event_tracing)
15026 warning (_("Target does not support event-tracing."));
15027
15028 if ((m_features.packet_support (PACKET_Qbtrace_conf_pt_event_tracing)
15029 == PACKET_ENABLE)
15030 && conf->pt.event_tracing != rs->btrace_config.pt.event_tracing)
15031 {
15032 pos = buf;
15033 const char *event_tracing = conf->pt.event_tracing ? "yes" : "no";
15034 const char *name
15035 = packets_descriptions[PACKET_Qbtrace_conf_pt_event_tracing].name;
15036 pos += xsnprintf (pos, endbuf - pos, "%s=\"%s\"", name, event_tracing);
15037
15038 putpkt (buf);
15039 getpkt (&rs->buf, 0);
15040
15041 packet_result result
15042 = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_event_tracing);
15043 if (result.status () == PACKET_ERROR)
15044 {
15045 if (buf[0] == 'E' && buf[1] == '.')
15046 error (_("Failed to sync event-tracing config: %s"), buf + 2);
15047 else
15048 error (_("Failed to sync event-tracing config."));
15049 }
15050
15051 rs->btrace_config.pt.event_tracing = conf->pt.event_tracing;
15052 }
15053}
15054
15055/* Read TP's btrace configuration from the target and store it into CONF. */
15056
15057static void
15058btrace_read_config (thread_info *tp, btrace_config *conf)
15059{
15060 /* target_read_stralloc relies on INFERIOR_PTID. */
15061 scoped_restore_current_thread restore_thread;
15062 switch_to_thread (tp);
15063
15064 std::optional<gdb::char_vector> xml
15065 = target_read_stralloc (current_inferior ()->top_target (),
15066 TARGET_OBJECT_BTRACE_CONF, "");
15067 if (xml)
15068 parse_xml_btrace_conf (conf, xml->data ());
15069}
15070
15071/* Maybe reopen target btrace. */
15072
15073void
15074remote_target::remote_btrace_maybe_reopen ()
15075{
15076 struct remote_state *rs = get_remote_state ();
15077 int btrace_target_pushed = 0;
15078#if !defined (HAVE_LIBIPT)
15079 int warned = 0;
15080#endif
15081
15082 /* Don't bother walking the entirety of the remote thread list when
15083 we know the feature isn't supported by the remote. */
15084 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
15085 return;
15086
15087 for (thread_info *tp : all_non_exited_threads (this))
15088 {
15089 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
15090 btrace_read_config (tp, &rs->btrace_config);
15091
15092 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
15093 continue;
15094
15095#if !defined (HAVE_LIBIPT)
15096 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
15097 {
15098 if (!warned)
15099 {
15100 warned = 1;
15101 warning (_("Target is recording using Intel Processor Trace "
15102 "but support was disabled at compile time."));
15103 }
15104
15105 continue;
15106 }
15107#endif /* !defined (HAVE_LIBIPT) */
15108
15109 /* Push target, once, but before anything else happens. This way our
15110 changes to the threads will be cleaned up by unpushing the target
15111 in case btrace_read_config () throws. */
15112 if (!btrace_target_pushed)
15113 {
15114 btrace_target_pushed = 1;
15115 record_btrace_push_target ();
15116 gdb_printf (_("Target is recording using %s.\n"),
15117 btrace_format_string (rs->btrace_config.format));
15118 }
15119
15120 tp->btrace.target
15121 = new btrace_target_info { tp->ptid, rs->btrace_config };
15122 }
15123}
15124
15125/* Enable branch tracing. */
15126
15127struct btrace_target_info *
15128remote_target::enable_btrace (thread_info *tp,
15129 const struct btrace_config *conf)
15130{
15131 struct packet_config *packet = NULL;
15132 struct remote_state *rs = get_remote_state ();
15133 char *buf = rs->buf.data ();
15134 char *endbuf = buf + get_remote_packet_size ();
15135
15136 unsigned int which_packet;
15137 switch (conf->format)
15138 {
15139 case BTRACE_FORMAT_BTS:
15140 which_packet = PACKET_Qbtrace_bts;
15141 break;
15142 case BTRACE_FORMAT_PT:
15143 which_packet = PACKET_Qbtrace_pt;
15144 break;
15145 default:
15146 internal_error (_("Bad branch btrace format: %u."),
15147 (unsigned int) conf->format);
15148 }
15149
15150 packet = &m_features.m_protocol_packets[which_packet];
15151 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
15152 error (_("Target does not support branch tracing."));
15153
15154 btrace_sync_conf (conf);
15155
15156 ptid_t ptid = tp->ptid;
15157 set_general_thread (ptid);
15158
15159 buf += xsnprintf (buf, endbuf - buf, "%s",
15160 packets_descriptions[which_packet].name);
15161 putpkt (rs->buf);
15162 getpkt (&rs->buf);
15163
15164 packet_result result = m_features.packet_ok (rs->buf, which_packet);
15165 if (result.status () == PACKET_ERROR)
15166 error (_("Could not enable branch tracing for %s: %s"),
15167 target_pid_to_str (ptid).c_str (), result.err_msg ());
15168
15169 btrace_target_info *tinfo = new btrace_target_info { ptid };
15170
15171 /* If we fail to read the configuration, we lose some information, but the
15172 tracing itself is not impacted. */
15173 try
15174 {
15175 btrace_read_config (tp, &tinfo->conf);
15176 }
15177 catch (const gdb_exception_error &err)
15178 {
15179 if (err.message != NULL)
15180 warning ("%s", err.what ());
15181 }
15182
15183 return tinfo;
15184}
15185
15186/* Disable branch tracing. */
15187
15188void
15189remote_target::disable_btrace (struct btrace_target_info *tinfo)
15190{
15191 struct remote_state *rs = get_remote_state ();
15192 char *buf = rs->buf.data ();
15193 char *endbuf = buf + get_remote_packet_size ();
15194
15195 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
15196 error (_("Target does not support branch tracing."));
15197
15198 set_general_thread (tinfo->ptid);
15199
15200 buf += xsnprintf (buf, endbuf - buf, "%s",
15201 packets_descriptions[PACKET_Qbtrace_off].name);
15202 putpkt (rs->buf);
15203 getpkt (&rs->buf);
15204
15205 packet_result result = m_features.packet_ok (rs->buf, PACKET_Qbtrace_off);
15206 if (result.status () == PACKET_ERROR)
15207 error (_("Could not disable branch tracing for %s: %s"),
15208 target_pid_to_str (tinfo->ptid).c_str (), result.err_msg ());
15209
15210 delete tinfo;
15211}
15212
15213/* Teardown branch tracing. */
15214
15215void
15216remote_target::teardown_btrace (struct btrace_target_info *tinfo)
15217{
15218 /* We must not talk to the target during teardown. */
15219 delete tinfo;
15220}
15221
15222/* Read the branch trace. */
15223
15224enum btrace_error
15225remote_target::read_btrace (struct btrace_data *btrace,
15226 struct btrace_target_info *tinfo,
15227 enum btrace_read_type type)
15228{
15229 const char *annex;
15230
15231 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
15232 error (_("Target does not support branch tracing."));
15233
15234#if !defined(HAVE_LIBEXPAT)
15235 error (_("Cannot process branch tracing result. XML parsing not supported."));
15236#endif
15237
15238 switch (type)
15239 {
15240 case BTRACE_READ_ALL:
15241 annex = "all";
15242 break;
15243 case BTRACE_READ_NEW:
15244 annex = "new";
15245 break;
15246 case BTRACE_READ_DELTA:
15247 annex = "delta";
15248 break;
15249 default:
15250 internal_error (_("Bad branch tracing read type: %u."),
15251 (unsigned int) type);
15252 }
15253
15254 std::optional<gdb::char_vector> xml
15255 = target_read_stralloc (current_inferior ()->top_target (),
15256 TARGET_OBJECT_BTRACE, annex);
15257 if (!xml)
15258 return BTRACE_ERR_UNKNOWN;
15259
15260 parse_xml_btrace (btrace, xml->data ());
15261
15262 return BTRACE_ERR_NONE;
15263}
15264
15265const struct btrace_config *
15266remote_target::btrace_conf (const struct btrace_target_info *tinfo)
15267{
15268 return &tinfo->conf;
15269}
15270
15271bool
15272remote_target::augmented_libraries_svr4_read ()
15273{
15274 return
15275 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
15276 == PACKET_ENABLE);
15277}
15278
15279/* Implementation of to_load. */
15280
15281void
15282remote_target::load (const char *name, int from_tty)
15283{
15284 generic_load (name, from_tty);
15285}
15286
15287/* Accepts an integer PID; returns a string representing a file that
15288 can be opened on the remote side to get the symbols for the child
15289 process. Returns NULL if the operation is not supported. */
15290
15291const char *
15292remote_target::pid_to_exec_file (int pid)
15293{
15294 static std::optional<gdb::char_vector> filename;
15295 char *annex = NULL;
15296
15297 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
15298 return NULL;
15299
15300 inferior *inf = find_inferior_pid (this, pid);
15301 if (inf == NULL)
15302 internal_error (_("not currently attached to process %d"), pid);
15303
15304 if (!inf->fake_pid_p)
15305 {
15306 const int annex_size = 9;
15307
15308 annex = (char *) alloca (annex_size);
15309 xsnprintf (annex, annex_size, "%x", pid);
15310 }
15311
15312 filename = target_read_stralloc (current_inferior ()->top_target (),
15313 TARGET_OBJECT_EXEC_FILE, annex);
15314
15315 return filename ? filename->data () : nullptr;
15316}
15317
15318/* Implement the to_can_do_single_step target_ops method. */
15319
15320int
15321remote_target::can_do_single_step ()
15322{
15323 /* We can only tell whether target supports single step or not by
15324 supported s and S vCont actions if the stub supports vContSupported
15325 feature. If the stub doesn't support vContSupported feature,
15326 we have conservatively to think target doesn't supports single
15327 step. */
15328 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
15329 {
15330 struct remote_state *rs = get_remote_state ();
15331
15332 return rs->supports_vCont.s && rs->supports_vCont.S;
15333 }
15334 else
15335 return 0;
15336}
15337
15338/* Implementation of the to_execution_direction method for the remote
15339 target. */
15340
15341enum exec_direction_kind
15342remote_target::execution_direction ()
15343{
15344 struct remote_state *rs = get_remote_state ();
15345
15346 return rs->last_resume_exec_dir;
15347}
15348
15349/* Return pointer to the thread_info struct which corresponds to
15350 THREAD_HANDLE (having length HANDLE_LEN). */
15351
15352thread_info *
15353remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
15354 int handle_len,
15355 inferior *inf)
15356{
15357 for (thread_info *tp : all_non_exited_threads (this))
15358 {
15359 remote_thread_info *priv = get_remote_thread_info (tp);
15360
15361 if (tp->inf == inf && priv != NULL)
15362 {
15363 if (handle_len != priv->thread_handle.size ())
15364 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15365 handle_len, priv->thread_handle.size ());
15366 if (memcmp (thread_handle, priv->thread_handle.data (),
15367 handle_len) == 0)
15368 return tp;
15369 }
15370 }
15371
15372 return NULL;
15373}
15374
15375gdb::array_view<const gdb_byte>
15376remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15377{
15378 remote_thread_info *priv = get_remote_thread_info (tp);
15379 return priv->thread_handle;
15380}
15381
15382bool
15383remote_target::can_async_p ()
15384{
15385 /* This flag should be checked in the common target.c code. */
15386 gdb_assert (target_async_permitted);
15387
15388 /* We're async whenever the serial device can. */
15389 return get_remote_state ()->can_async_p ();
15390}
15391
15392bool
15393remote_target::is_async_p ()
15394{
15395 /* We're async whenever the serial device is. */
15396 return get_remote_state ()->is_async_p ();
15397}
15398
15399/* Pass the SERIAL event on and up to the client. One day this code
15400 will be able to delay notifying the client of an event until the
15401 point where an entire packet has been received. */
15402
15403static serial_event_ftype remote_async_serial_handler;
15404
15405static void
15406remote_async_serial_handler (struct serial *scb, void *context)
15407{
15408 /* Don't propagate error information up to the client. Instead let
15409 the client find out about the error by querying the target. */
15410 inferior_event_handler (INF_REG_EVENT);
15411}
15412
15413int
15414remote_target::async_wait_fd ()
15415{
15416 struct remote_state *rs = get_remote_state ();
15417 return rs->remote_desc->fd;
15418}
15419
15420void
15421remote_target::async (bool enable)
15422{
15423 struct remote_state *rs = get_remote_state ();
15424
15425 if (enable)
15426 {
15427 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15428
15429 /* If there are pending events in the stop reply queue tell the
15430 event loop to process them. */
15431 if (!rs->stop_reply_queue.empty ())
15432 rs->mark_async_event_handler ();
15433
15434 /* For simplicity, below we clear the pending events token
15435 without remembering whether it is marked, so here we always
15436 mark it. If there's actually no pending notification to
15437 process, this ends up being a no-op (other than a spurious
15438 event-loop wakeup). */
15439 if (target_is_non_stop_p ())
15440 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15441 }
15442 else
15443 {
15444 serial_async (rs->remote_desc, NULL, NULL);
15445 /* If the core is disabling async, it doesn't want to be
15446 disturbed with target events. Clear all async event sources
15447 too. */
15448 rs->clear_async_event_handler ();
15449
15450 if (target_is_non_stop_p ())
15451 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15452 }
15453}
15454
15455/* Implementation of the to_thread_events method. */
15456
15457void
15458remote_target::thread_events (bool enable)
15459{
15460 struct remote_state *rs = get_remote_state ();
15461 size_t size = get_remote_packet_size ();
15462
15463 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15464 return;
15465
15466 if (rs->last_thread_events == enable)
15467 return;
15468
15469 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15470 putpkt (rs->buf);
15471 getpkt (&rs->buf);
15472
15473 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadEvents);
15474 switch (result.status ())
15475 {
15476 case PACKET_OK:
15477 if (strcmp (rs->buf.data (), "OK") != 0)
15478 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15479 rs->last_thread_events = enable;
15480 break;
15481 case PACKET_ERROR:
15482 warning (_("Remote failure reply: %s"), result.err_msg ());
15483 break;
15484 case PACKET_UNKNOWN:
15485 break;
15486 }
15487}
15488
15489/* Implementation of the supports_set_thread_options target
15490 method. */
15491
15492bool
15493remote_target::supports_set_thread_options (gdb_thread_options options)
15494{
15495 remote_state *rs = get_remote_state ();
15496 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15497 && (rs->supported_thread_options & options) == options);
15498}
15499
15500/* For coalescing reasons, actually sending the options to the target
15501 happens at resume time, via this function. See target_resume for
15502 all-stop, and target_commit_resumed for non-stop. */
15503
15504void
15505remote_target::commit_requested_thread_options ()
15506{
15507 struct remote_state *rs = get_remote_state ();
15508
15509 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15510 return;
15511
15512 char *p = rs->buf.data ();
15513 char *endp = p + get_remote_packet_size ();
15514
15515 /* Clear options for all threads by default. Note that unlike
15516 vCont, the rightmost options that match a thread apply, so we
15517 don't have to worry about whether we can use wildcard ptids. */
15518 strcpy (p, "QThreadOptions;0");
15519 p += strlen (p);
15520
15521 /* Send the QThreadOptions packet stored in P. */
15522 auto flush = [&] ()
15523 {
15524 *p++ = '\0';
15525
15526 putpkt (rs->buf);
15527 getpkt (&rs->buf, 0);
15528
15529 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadOptions);
15530 switch (result.status ())
15531 {
15532 case PACKET_OK:
15533 if (strcmp (rs->buf.data (), "OK") != 0)
15534 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15535 break;
15536 case PACKET_ERROR:
15537 error (_("Remote failure reply: %s"), result.err_msg ());
15538 case PACKET_UNKNOWN:
15539 gdb_assert_not_reached ("PACKET_UNKNOWN");
15540 break;
15541 }
15542 };
15543
15544 /* Prepare P for another QThreadOptions packet. */
15545 auto restart = [&] ()
15546 {
15547 p = rs->buf.data ();
15548 strcpy (p, "QThreadOptions");
15549 p += strlen (p);
15550 };
15551
15552 /* Now set non-zero options for threads that need them. We don't
15553 bother with the case of all threads of a process wanting the same
15554 non-zero options as that's not an expected scenario. */
15555 for (thread_info *tp : all_non_exited_threads (this))
15556 {
15557 gdb_thread_options options = tp->thread_options ();
15558
15559 if (options == 0)
15560 continue;
15561
15562 /* It might be possible to we have more threads with options
15563 than can fit a single QThreadOptions packet. So build each
15564 options/thread pair in this separate buffer to make sure it
15565 fits. */
15566 constexpr size_t max_options_size = 100;
15567 char obuf[max_options_size];
15568 char *obuf_p = obuf;
15569 char *obuf_endp = obuf + max_options_size;
15570
15571 *obuf_p++ = ';';
15572 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15573 phex_nz (options));
15574 if (tp->ptid != magic_null_ptid)
15575 {
15576 *obuf_p++ = ':';
15577 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15578 }
15579
15580 size_t osize = obuf_p - obuf;
15581 if (osize > endp - p)
15582 {
15583 /* This new options/thread pair doesn't fit the packet
15584 buffer. Send what we have already. */
15585 flush ();
15586 restart ();
15587
15588 /* Should now fit. */
15589 gdb_assert (osize <= endp - p);
15590 }
15591
15592 memcpy (p, obuf, osize);
15593 p += osize;
15594 }
15595
15596 flush ();
15597}
15598
15599static void
15600show_remote_cmd (const char *args, int from_tty)
15601{
15602 /* We can't just use cmd_show_list here, because we want to skip
15603 the redundant "show remote Z-packet" and the legacy aliases. */
15604 struct cmd_list_element *list = remote_show_cmdlist;
15605 struct ui_out *uiout = current_uiout;
15606
15607 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15608 const ui_file_style cmd_style = command_style.style ();
15609 for (; list != NULL; list = list->next)
15610 if (strcmp (list->name, "Z-packet") == 0)
15611 continue;
15612 else if (list->type == not_set_cmd)
15613 /* Alias commands are exactly like the original, except they
15614 don't have the normal type. */
15615 continue;
15616 else
15617 {
15618 ui_out_emit_tuple option_emitter (uiout, "option");
15619
15620 uiout->field_string ("name", list->name, cmd_style);
15621 uiout->text (": ");
15622 if (list->type == show_cmd)
15623 do_show_command (NULL, from_tty, list);
15624 else
15625 cmd_func (list, NULL, from_tty);
15626 }
15627}
15628
15629/* Some change happened in PSPACE's objfile list (obfiles added or removed),
15630 offer all inferiors using that program space a change to look up symbols. */
15631
15632static void
15633remote_objfile_changed_check_symbols (program_space *pspace)
15634{
15635 /* The affected program space is possibly shared by multiple inferiors.
15636 Consider sending a qSymbol packet for each of the inferiors using that
15637 program space. */
15638 for (inferior *inf : all_inferiors ())
15639 {
15640 if (inf->pspace != pspace)
15641 continue;
15642
15643 /* Check whether the inferior's process target is a remote target. */
15644 remote_target *remote = as_remote_target (inf->process_target ());
15645 if (remote == nullptr)
15646 continue;
15647
15648 /* When we are attaching or handling a fork child and the shared library
15649 subsystem reads the list of loaded libraries, we receive new objfile
15650 events in between each found library. The libraries are read in an
15651 undefined order, so if we gave the remote side a chance to look up
15652 symbols between each objfile, we might give it an inconsistent picture
15653 of the inferior. It could appear that a library A appears loaded but
15654 a library B does not, even though library A requires library B. That
15655 would present a state that couldn't normally exist in the inferior.
15656
15657 So, skip these events, we'll give the remote a chance to look up
15658 symbols once all the loaded libraries and their symbols are known to
15659 GDB. */
15660 if (inf->in_initial_library_scan)
15661 continue;
15662
15663 if (!remote->has_execution (inf))
15664 continue;
15665
15666 /* Need to switch to a specific thread, because remote_check_symbols will
15667 set the general thread using INFERIOR_PTID.
15668
15669 It's possible to have inferiors with no thread here, because we are
15670 called very early in the connection process, while the inferior is
15671 being set up, before threads are added. Just skip it, start_remote_1
15672 also calls remote_check_symbols when it's done setting things up. */
15673 thread_info *thread = any_thread_of_inferior (inf);
15674 if (thread != nullptr)
15675 {
15676 scoped_restore_current_thread restore_thread;
15677 switch_to_thread (thread);
15678 remote->remote_check_symbols ();
15679 }
15680 }
15681}
15682
15683/* Function to be called whenever a new objfile (shlib) is detected. */
15684
15685static void
15686remote_new_objfile (struct objfile *objfile)
15687{
15688 remote_objfile_changed_check_symbols (objfile->pspace ());
15689}
15690
15691/* Pull all the tracepoints defined on the target and create local
15692 data structures representing them. We don't want to create real
15693 tracepoints yet, we don't want to mess up the user's existing
15694 collection. */
15695
15696int
15697remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15698{
15699 struct remote_state *rs = get_remote_state ();
15700 char *p;
15701
15702 /* Ask for a first packet of tracepoint definition. */
15703 putpkt ("qTfP");
15704 getpkt (&rs->buf);
15705 p = rs->buf.data ();
15706 while (*p && *p != 'l')
15707 {
15708 parse_tracepoint_definition (p, utpp);
15709 /* Ask for another packet of tracepoint definition. */
15710 putpkt ("qTsP");
15711 getpkt (&rs->buf);
15712 p = rs->buf.data ();
15713 }
15714 return 0;
15715}
15716
15717int
15718remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15719{
15720 struct remote_state *rs = get_remote_state ();
15721 char *p;
15722
15723 /* Ask for a first packet of variable definition. */
15724 putpkt ("qTfV");
15725 getpkt (&rs->buf);
15726 p = rs->buf.data ();
15727 while (*p && *p != 'l')
15728 {
15729 parse_tsv_definition (p, utsvp);
15730 /* Ask for another packet of variable definition. */
15731 putpkt ("qTsV");
15732 getpkt (&rs->buf);
15733 p = rs->buf.data ();
15734 }
15735 return 0;
15736}
15737
15738/* The "set/show range-stepping" show hook. */
15739
15740static void
15741show_range_stepping (struct ui_file *file, int from_tty,
15742 struct cmd_list_element *c,
15743 const char *value)
15744{
15745 gdb_printf (file,
15746 _("Debugger's willingness to use range stepping "
15747 "is %s.\n"), value);
15748}
15749
15750/* Return true if the vCont;r action is supported by the remote
15751 stub. */
15752
15753bool
15754remote_target::vcont_r_supported ()
15755{
15756 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15757 && get_remote_state ()->supports_vCont.r);
15758}
15759
15760/* The "set/show range-stepping" set hook. */
15761
15762static void
15763set_range_stepping (const char *ignore_args, int from_tty,
15764 struct cmd_list_element *c)
15765{
15766 /* When enabling, check whether range stepping is actually supported
15767 by the target, and warn if not. */
15768 if (use_range_stepping)
15769 {
15770 remote_target *remote = get_current_remote_target ();
15771 if (remote == NULL
15772 || !remote->vcont_r_supported ())
15773 warning (_("Range stepping is not supported by the current target"));
15774 }
15775}
15776
15777static void
15778show_remote_debug (struct ui_file *file, int from_tty,
15779 struct cmd_list_element *c, const char *value)
15780{
15781 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15782 value);
15783}
15784
15785static void
15786show_remote_timeout (struct ui_file *file, int from_tty,
15787 struct cmd_list_element *c, const char *value)
15788{
15789 gdb_printf (file,
15790 _("Timeout limit to wait for target to respond is %s.\n"),
15791 value);
15792}
15793
15794/* Implement the "supports_memory_tagging" target_ops method. */
15795
15796bool
15797remote_target::supports_memory_tagging ()
15798{
15799 return m_features.remote_memory_tagging_p ();
15800}
15801
15802/* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15803
15804static void
15805create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15806 size_t len, int type)
15807{
15808 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15809
15810 std::string request = string_printf ("qMemTags:%s,%s:%s",
15811 phex_nz (address, addr_size),
15812 phex_nz (len),
15813 phex_nz (type));
15814
15815 strcpy (packet.data (), request.c_str ());
15816}
15817
15818/* Parse the qMemTags packet reply into TAGS.
15819
15820 Return true if successful, false otherwise. */
15821
15822static bool
15823parse_fetch_memtags_reply (const gdb::char_vector &reply,
15824 gdb::byte_vector &tags)
15825{
15826 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15827 return false;
15828
15829 /* Copy the tag data. */
15830 tags = hex2bin (reply.data () + 1);
15831
15832 return true;
15833}
15834
15835/* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15836
15837static void
15838create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15839 size_t len, int type,
15840 const gdb::byte_vector &tags)
15841{
15842 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15843
15844 /* Put together the main packet, address and length. */
15845 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15846 phex_nz (address, addr_size),
15847 phex_nz (len),
15848 phex_nz (type));
15849 request += bin2hex (tags.data (), tags.size ());
15850
15851 /* Check if we have exceeded the maximum packet size. */
15852 if (packet.size () < request.length ())
15853 error (_("Contents too big for packet QMemTags."));
15854
15855 strcpy (packet.data (), request.c_str ());
15856}
15857
15858static void
15859create_is_address_tagged_request (gdbarch *gdbarch, gdb::char_vector &packet,
15860 CORE_ADDR address)
15861{
15862 int addr_size;
15863 std::string request;
15864
15865 addr_size = gdbarch_addr_bit (gdbarch) / 8;
15866 request = string_printf ("qIsAddressTagged:%s", phex_nz (address, addr_size));
15867
15868 if (packet.size () < request.length () + 1)
15869 error (_("Contents too big for packet qIsAddressTagged."));
15870
15871 strcpy (packet.data (), request.c_str ());
15872}
15873
15874static bool
15875check_is_address_tagged_reply (remote_target *remote, gdb::char_vector &packet,
15876 bool &tagged)
15877{
15878 gdb_assert (remote != nullptr);
15879 /* Check reply and disable qIsAddressTagged usage if it's not supported. */
15880 packet_result result = remote->m_features.packet_ok (packet,
15881 PACKET_qIsAddressTagged);
15882
15883 /* Return false on error (Exx), empty reply (packet not supported), or reply
15884 size doesn't match 2 hex digits. */
15885 if ((result.status () != PACKET_OK) || (strlen (packet.data ()) != 2))
15886 return false;
15887
15888 gdb_byte reply;
15889 /* Convert only 2 hex digits, i.e. 1 byte in hex format. */
15890 hex2bin (packet.data (), &reply, 1);
15891
15892 if (reply == 0x00 || reply == 0x01)
15893 {
15894 tagged = !!reply;
15895 return true;
15896 }
15897
15898 /* Invalid reply. */
15899 return false;
15900}
15901
15902/* Implement the "fetch_memtags" target_ops method. */
15903
15904bool
15905remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15906 gdb::byte_vector &tags, int type)
15907{
15908 /* Make sure the qMemTags packet is supported. */
15909 if (!m_features.remote_memory_tagging_p ())
15910 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15911
15912 struct remote_state *rs = get_remote_state ();
15913
15914 create_fetch_memtags_request (rs->buf, address, len, type);
15915
15916 putpkt (rs->buf);
15917 getpkt (&rs->buf);
15918
15919 return parse_fetch_memtags_reply (rs->buf, tags);
15920}
15921
15922/* Implement the "store_memtags" target_ops method. */
15923
15924bool
15925remote_target::store_memtags (CORE_ADDR address, size_t len,
15926 const gdb::byte_vector &tags, int type)
15927{
15928 /* Make sure the QMemTags packet is supported. */
15929 if (!m_features.remote_memory_tagging_p ())
15930 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15931
15932 struct remote_state *rs = get_remote_state ();
15933
15934 create_store_memtags_request (rs->buf, address, len, type, tags);
15935
15936 putpkt (rs->buf);
15937 getpkt (&rs->buf);
15938
15939 /* Verify if the request was successful. */
15940 return packet_check_result (rs->buf).status () == PACKET_OK;
15941}
15942
15943/* Implement the "is_address_tagged" target_ops method. */
15944
15945bool
15946remote_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
15947{
15948 /* Firstly, attempt to check the address using the qIsAddressTagged
15949 packet. */
15950 if (m_features.packet_support (PACKET_qIsAddressTagged) != PACKET_DISABLE)
15951 {
15952 remote_target *remote = get_current_remote_target ();
15953 struct remote_state *rs = get_remote_state ();
15954 bool is_addr_tagged;
15955
15956 create_is_address_tagged_request (gdbarch, rs->buf, address);
15957
15958 putpkt (rs->buf);
15959 getpkt (&rs->buf);
15960
15961 /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
15962 set to PACKET_DISABLE so no further attempt is made to check addresses
15963 using this packet and the fallback mechanism below will be used
15964 instead. Also, if the check fails due to an error (Exx reply) the
15965 fallback is used too. Otherwise, the qIsAddressTagged query succeeded
15966 and is_addr_tagged is valid. */
15967 if (check_is_address_tagged_reply (remote, rs->buf, is_addr_tagged))
15968 return is_addr_tagged;
15969 }
15970
15971 /* Fallback to arch-specific method of checking whether an address is tagged
15972 in case check via qIsAddressTagged fails. */
15973 return gdbarch_tagged_address_p (gdbarch, address);
15974}
15975
15976/* Return true if remote target T is non-stop. */
15977
15978bool
15979remote_target_is_non_stop_p (remote_target *t)
15980{
15981 scoped_restore_current_thread restore_thread;
15982 switch_to_target_no_thread (t);
15983
15984 return target_is_non_stop_p ();
15985}
15986
15987#if GDB_SELF_TEST
15988
15989namespace selftests {
15990
15991static void
15992test_memory_tagging_functions ()
15993{
15994 remote_target remote;
15995
15996 struct packet_config *config
15997 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15998
15999 scoped_restore restore_memtag_support_
16000 = make_scoped_restore (&config->support);
16001
16002 struct gdbarch *gdbarch = current_inferior ()->arch ();
16003
16004 /* Test memory tagging packet support. */
16005 config->support = PACKET_SUPPORT_UNKNOWN;
16006 SELF_CHECK (remote.supports_memory_tagging () == false);
16007 config->support = PACKET_DISABLE;
16008 SELF_CHECK (remote.supports_memory_tagging () == false);
16009 config->support = PACKET_ENABLE;
16010 SELF_CHECK (remote.supports_memory_tagging () == true);
16011
16012 /* Setup testing. */
16013 gdb::char_vector packet;
16014 gdb::byte_vector tags, bv;
16015 std::string expected, reply;
16016 packet.resize (32000);
16017
16018 /* Test creating a qMemTags request. */
16019
16020 expected = "qMemTags:0,0:0";
16021 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
16022 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
16023
16024 expected = "qMemTags:deadbeef,10:1";
16025 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
16026 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
16027
16028 /* Test parsing a qMemTags reply. */
16029
16030 /* Error reply, tags vector unmodified. */
16031 reply = "E00";
16032 strcpy (packet.data (), reply.c_str ());
16033 tags.resize (0);
16034 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
16035 SELF_CHECK (tags.size () == 0);
16036
16037 /* Valid reply, tags vector updated. */
16038 tags.resize (0);
16039 bv.resize (0);
16040
16041 for (int i = 0; i < 5; i++)
16042 bv.push_back (i);
16043
16044 reply = "m" + bin2hex (bv.data (), bv.size ());
16045 strcpy (packet.data (), reply.c_str ());
16046
16047 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
16048 SELF_CHECK (tags.size () == 5);
16049
16050 for (int i = 0; i < 5; i++)
16051 SELF_CHECK (tags[i] == i);
16052
16053 /* Test creating a QMemTags request. */
16054
16055 /* Empty tag data. */
16056 tags.resize (0);
16057 expected = "QMemTags:0,0:0:";
16058 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
16059 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
16060 expected.length ()) == 0);
16061
16062 /* Non-empty tag data. */
16063 tags.resize (0);
16064 for (int i = 0; i < 5; i++)
16065 tags.push_back (i);
16066 expected = "QMemTags:deadbeef,ff:1:0001020304";
16067 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
16068 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
16069 expected.length ()) == 0);
16070
16071 /* Test creating a qIsAddressTagged request. */
16072 expected = "qIsAddressTagged:deadbeef";
16073 create_is_address_tagged_request (gdbarch, packet, 0xdeadbeef);
16074 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
16075
16076 /* Test error reply on qIsAddressTagged request. */
16077 reply = "E00";
16078 strcpy (packet.data (), reply.c_str ());
16079 /* is_tagged must not change, hence it's tested too. */
16080 bool is_tagged = false;
16081 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16082 false);
16083 SELF_CHECK (is_tagged == false);
16084
16085 /* Test 'tagged' as reply. */
16086 reply = "01";
16087 strcpy (packet.data (), reply.c_str ());
16088 /* Because the byte is 01, is_tagged should be set to true. */
16089 is_tagged = false;
16090 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16091 true);
16092 SELF_CHECK (is_tagged == true);
16093
16094 /* Test 'not tagged' as reply. */
16095 reply = "00";
16096 strcpy (packet.data (), reply.c_str ());
16097 /* Because the byte is 00, is_tagged should be set to false. */
16098 is_tagged = true;
16099 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16100 true);
16101 SELF_CHECK (is_tagged == false);
16102
16103 /* Test an invalid reply (neither 00 nor 01). */
16104 reply = "04";
16105 strcpy (packet.data (), reply.c_str ());
16106 /* Because the byte is invalid is_tagged must not change. */
16107 is_tagged = false;
16108 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16109 false);
16110 SELF_CHECK (is_tagged == false);
16111
16112 /* Test malformed reply of incorrect length. */
16113 reply = "0104A590001234006";
16114 strcpy (packet.data (), reply.c_str ());
16115 /* Because this is a malformed reply is_tagged must not change. */
16116 is_tagged = false;
16117 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16118 false);
16119 SELF_CHECK (is_tagged == false);
16120
16121 /* Test empty reply. */
16122 reply = "";
16123 strcpy (packet.data (), reply.c_str ());
16124 /* is_tagged must not change, hence it's tested too. */
16125 is_tagged = true;
16126 /* On the previous tests, qIsAddressTagged packet was auto detected and set
16127 as supported. But an empty reply means the packet is unsupported, so for
16128 testing the empty reply the support is reset to unknown state, otherwise
16129 packet_ok will complain. */
16130 remote.m_features.m_protocol_packets[PACKET_qIsAddressTagged].support =
16131 PACKET_SUPPORT_UNKNOWN;
16132 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
16133 false);
16134 SELF_CHECK (is_tagged == true);
16135}
16136
16137static void
16138test_packet_check_result ()
16139{
16140 std::string buf = "E.msg";
16141 packet_result result = packet_check_result (buf.data ());
16142
16143 SELF_CHECK (result.status () == PACKET_ERROR);
16144 SELF_CHECK (strcmp(result.err_msg (), "msg") == 0);
16145
16146 result = packet_check_result ("E01");
16147 SELF_CHECK (result.status () == PACKET_ERROR);
16148 SELF_CHECK (strcmp(result.err_msg (), "01") == 0);
16149
16150 SELF_CHECK (packet_check_result ("E1").status () == PACKET_OK);
16151
16152 SELF_CHECK (packet_check_result ("E000").status () == PACKET_OK);
16153
16154 result = packet_check_result ("E.");
16155 SELF_CHECK (result.status () == PACKET_ERROR);
16156 SELF_CHECK (strcmp(result.err_msg (), "no error provided") == 0);
16157
16158 SELF_CHECK (packet_check_result ("some response").status () == PACKET_OK);
16159
16160 SELF_CHECK (packet_check_result ("").status () == PACKET_UNKNOWN);
16161}
16162} /* namespace selftests */
16163#endif /* GDB_SELF_TEST */
16164
16165INIT_GDB_FILE (remote)
16166{
16167 add_target (remote_target_info, remote_target::open);
16168 add_target (extended_remote_target_info, extended_remote_target::open);
16169
16170 /* Hook into new objfile notification. */
16171 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
16172 gdb::observers::all_objfiles_removed.attach
16173 (remote_objfile_changed_check_symbols, "remote");
16174
16175#if 0
16176 init_remote_threadtests ();
16177#endif
16178
16179 /* set/show remote ... */
16180
16181 add_basic_prefix_cmd ("remote", class_maintenance, _("\
16182Remote protocol specific variables.\n\
16183Configure various remote-protocol specific variables such as\n\
16184the packets being used."),
16185 &remote_set_cmdlist,
16186 0 /* allow-unknown */, &setlist);
16187 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
16188Remote protocol specific variables.\n\
16189Configure various remote-protocol specific variables such as\n\
16190the packets being used."),
16191 &remote_show_cmdlist,
16192 0 /* allow-unknown */, &showlist);
16193
16194 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
16195Compare section data on target to the exec file.\n\
16196Argument is a single section name (default: all loaded sections).\n\
16197To compare only read-only loaded sections, specify the -r option."),
16198 &cmdlist);
16199
16200 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
16201Send an arbitrary packet to a remote target.\n\
16202 maintenance packet TEXT\n\
16203If GDB is talking to an inferior via the GDB serial protocol, then\n\
16204this command sends the string TEXT to the inferior, and displays the\n\
16205response packet. GDB supplies the initial `$' character, and the\n\
16206terminating `#' character and checksum."),
16207 &maintenancelist);
16208
16209 set_show_commands remotebreak_cmds
16210 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
16211Set whether to send break if interrupted."), _("\
16212Show whether to send break if interrupted."), _("\
16213If set, a break, instead of a cntrl-c, is sent to the remote target."),
16214 set_remotebreak, show_remotebreak,
16215 &setlist, &showlist);
16216 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
16217 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
16218
16219 add_setshow_enum_cmd ("interrupt-sequence", class_support,
16220 interrupt_sequence_modes, &interrupt_sequence_mode,
16221 _("\
16222Set interrupt sequence to remote target."), _("\
16223Show interrupt sequence to remote target."), _("\
16224Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
16225 NULL, show_interrupt_sequence,
16226 &remote_set_cmdlist,
16227 &remote_show_cmdlist);
16228
16229 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
16230 &interrupt_on_connect, _("\
16231Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16232Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
16233If set, interrupt sequence is sent to remote target."),
16234 NULL, NULL,
16235 &remote_set_cmdlist, &remote_show_cmdlist);
16236
16237 /* Install commands for configuring memory read/write packets. */
16238
16239 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
16240Set the maximum number of bytes per memory write packet (deprecated)."),
16241 &setlist);
16242 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
16243Show the maximum number of bytes per memory write packet (deprecated)."),
16244 &showlist);
16245 add_cmd ("memory-write-packet-size", no_class,
16246 set_memory_write_packet_size, _("\
16247Set the maximum number of bytes per memory-write packet.\n\
16248Specify the number of bytes in a packet or 0 (zero) for the\n\
16249default packet size. The actual limit is further reduced\n\
16250dependent on the target. Specify \"fixed\" to disable the\n\
16251further restriction and \"limit\" to enable that restriction."),
16252 &remote_set_cmdlist);
16253 add_cmd ("memory-read-packet-size", no_class,
16254 set_memory_read_packet_size, _("\
16255Set the maximum number of bytes per memory-read packet.\n\
16256Specify the number of bytes in a packet or 0 (zero) for the\n\
16257default packet size. The actual limit is further reduced\n\
16258dependent on the target. Specify \"fixed\" to disable the\n\
16259further restriction and \"limit\" to enable that restriction."),
16260 &remote_set_cmdlist);
16261 add_cmd ("memory-write-packet-size", no_class,
16262 show_memory_write_packet_size,
16263 _("Show the maximum number of bytes per memory-write packet."),
16264 &remote_show_cmdlist);
16265 add_cmd ("memory-read-packet-size", no_class,
16266 show_memory_read_packet_size,
16267 _("Show the maximum number of bytes per memory-read packet."),
16268 &remote_show_cmdlist);
16269
16270 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
16271 &remote_hw_watchpoint_limit, _("\
16272Set the maximum number of target hardware watchpoints."), _("\
16273Show the maximum number of target hardware watchpoints."), _("\
16274Specify \"unlimited\" for unlimited hardware watchpoints."),
16275 NULL, show_hardware_watchpoint_limit,
16276 &remote_set_cmdlist,
16277 &remote_show_cmdlist);
16278 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
16279 no_class,
16280 &remote_hw_watchpoint_length_limit, _("\
16281Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
16282Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
16283Specify \"unlimited\" to allow watchpoints of unlimited size."),
16284 NULL, show_hardware_watchpoint_length_limit,
16285 &remote_set_cmdlist, &remote_show_cmdlist);
16286 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
16287 &remote_hw_breakpoint_limit, _("\
16288Set the maximum number of target hardware breakpoints."), _("\
16289Show the maximum number of target hardware breakpoints."), _("\
16290Specify \"unlimited\" for unlimited hardware breakpoints."),
16291 NULL, show_hardware_breakpoint_limit,
16292 &remote_set_cmdlist, &remote_show_cmdlist);
16293
16294 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
16295 &remote_address_size, _("\
16296Set the maximum size of the address (in bits) in a memory packet."), _("\
16297Show the maximum size of the address (in bits) in a memory packet."), NULL,
16298 NULL,
16299 NULL, /* FIXME: i18n: */
16300 &setlist, &showlist);
16301
16302 init_all_packet_configs ();
16303
16304 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
16305
16306 add_packet_config_cmd (PACKET_x, "x", "binary-upload", 0);
16307
16308 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
16309
16310 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
16311 0);
16312
16313 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
16314 "catch-syscalls", 0);
16315
16316 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
16317 "program-signals", 0);
16318
16319 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
16320 "set-working-dir", 0);
16321
16322 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
16323 "startup-with-shell", 0);
16324
16325 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
16326 "environment-hex-encoded", 0);
16327
16328 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
16329 "environment-reset", 0);
16330
16331 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
16332 "environment-unset", 0);
16333
16334 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
16335
16336 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
16337
16338 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
16339
16340 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
16341
16342 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
16343
16344 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
16345
16346 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
16347
16348 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
16349
16350 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
16351 "read-aux-vector", 0);
16352
16353 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
16354 "pid-to-exec-file", 0);
16355
16356 add_packet_config_cmd (PACKET_qXfer_features,
16357 "qXfer:features:read", "target-features", 0);
16358
16359 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
16360 "library-info", 0);
16361
16362 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
16363 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
16364
16365 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
16366 "memory-map", 0);
16367
16368 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
16369
16370 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
16371 0);
16372
16373 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
16374 "read-siginfo-object", 0);
16375
16376 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
16377 "write-siginfo-object", 0);
16378
16379 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
16380 "qXfer:traceframe-info:read", "traceframe-info", 0);
16381
16382 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
16383 "unwind-info-block", 0);
16384
16385 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
16386 "get-thread-local-storage-address", 0);
16387
16388 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
16389 "get-thread-information-block-address", 0);
16390
16391 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
16392
16393 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
16394
16395 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
16396 0);
16397
16398 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
16399 "search-memory", 0);
16400
16401 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
16402
16403 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
16404
16405 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
16406
16407 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
16408
16409 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
16410 0);
16411
16412 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
16413
16414 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
16415 0);
16416
16417 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
16418 "hostio-readlink", 0);
16419
16420 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
16421
16422 add_packet_config_cmd (PACKET_vFile_stat, "vFile:stat", "hostio-stat", 0);
16423
16424 add_packet_config_cmd (PACKET_vFile_lstat, "vFile:lstat", "hostio-lstat", 0);
16425
16426 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
16427
16428 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
16429
16430 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
16431
16432 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
16433
16434 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
16435
16436 add_packet_config_cmd (PACKET_ConditionalTracepoints,
16437 "ConditionalTracepoints", "conditional-tracepoints",
16438 0);
16439
16440 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
16441 "ConditionalBreakpoints", "conditional-breakpoints",
16442 0);
16443
16444 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
16445 "breakpoint-commands", 0);
16446
16447 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
16448 "fast-tracepoints", 0);
16449
16450 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
16451 "TracepointSource", 0);
16452
16453 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
16454
16455 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
16456 "static-tracepoints", 0);
16457
16458 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
16459 "install-in-trace", 0);
16460
16461 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
16462 "qXfer:statictrace:read", "read-sdata-object", 0);
16463
16464 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
16465 "read-fdpic-loadmap", 0);
16466
16467 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
16468 "disable-randomization", 0);
16469
16470 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
16471
16472 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
16473 "trace-buffer-size", 0);
16474
16475 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
16476 0);
16477
16478 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
16479 0);
16480
16481 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
16482 0);
16483
16484 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
16485
16486 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
16487 "read-btrace-conf", 0);
16488
16489 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
16490 "btrace-conf-bts-size", 0);
16491
16492 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
16493 "multiprocess-feature", 0);
16494
16495 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
16496 "swbreak-feature", 0);
16497
16498 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
16499 "hwbreak-feature", 0);
16500
16501 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
16502 "fork-event-feature", 0);
16503
16504 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
16505 "vfork-event-feature", 0);
16506
16507 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
16508 "btrace-conf-pt-size", 0);
16509
16510 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_ptwrite, "Qbtrace-conf:pt:ptwrite",
16511 "btrace-conf-pt-ptwrite", 0);
16512
16513 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_event_tracing,
16514 "Qbtrace-conf:pt:event-tracing",
16515 "btrace-conf-pt-event-tracing", 0);
16516
16517 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
16518 "verbose-resume-supported", 0);
16519
16520 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
16521 "exec-event-feature", 0);
16522
16523 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
16524
16525 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
16526 0);
16527
16528 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
16529 "thread-options", 0);
16530
16531 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
16532 "no-resumed-stop-reply", 0);
16533
16534 add_packet_config_cmd (PACKET_memory_tagging_feature,
16535 "memory-tagging-feature", "memory-tagging-feature", 0);
16536
16537 add_packet_config_cmd (PACKET_qIsAddressTagged,
16538 "qIsAddressTagged", "memory-tagging-address-check", 0);
16539
16540 add_packet_config_cmd (PACKET_accept_error_message,
16541 "error-message", "error-message", 0);
16542
16543 /* Assert that we've registered "set remote foo-packet" commands
16544 for all packet configs. */
16545 {
16546 int i;
16547
16548 for (i = 0; i < PACKET_MAX; i++)
16549 {
16550 /* Ideally all configs would have a command associated. Some
16551 still don't though. */
16552 int excepted;
16553
16554 switch (i)
16555 {
16556 case PACKET_QNonStop:
16557 case PACKET_EnableDisableTracepoints_feature:
16558 case PACKET_tracenz_feature:
16559 case PACKET_DisconnectedTracing_feature:
16560 case PACKET_augmented_libraries_svr4_read_feature:
16561 case PACKET_qCRC:
16562 /* Additions to this list need to be well justified:
16563 pre-existing packets are OK; new packets are not. */
16564 excepted = 1;
16565 break;
16566 default:
16567 excepted = 0;
16568 break;
16569 }
16570
16571 /* This catches both forgetting to add a config command, and
16572 forgetting to remove a packet from the exception list. */
16573 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16574 }
16575 }
16576
16577 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16578 Z sub-packet has its own set and show commands, but users may
16579 have sets to this variable in their .gdbinit files (or in their
16580 documentation). */
16581 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16582 &remote_Z_packet_detect, _("\
16583Set use of remote protocol `Z' packets."), _("\
16584Show use of remote protocol `Z' packets."), _("\
16585When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16586packets."),
16587 set_remote_protocol_Z_packet_cmd,
16588 show_remote_protocol_Z_packet_cmd,
16589 /* FIXME: i18n: Use of remote protocol
16590 `Z' packets is %s. */
16591 &remote_set_cmdlist, &remote_show_cmdlist);
16592
16593 add_basic_prefix_cmd ("remote", class_files, _("\
16594Manipulate files on the remote system.\n\
16595Transfer files to and from the remote target system."),
16596 &remote_cmdlist,
16597 0 /* allow-unknown */, &cmdlist);
16598
16599 add_cmd ("put", class_files, remote_put_command,
16600 _("Copy a local file to the remote system."),
16601 &remote_cmdlist);
16602
16603 add_cmd ("get", class_files, remote_get_command,
16604 _("Copy a remote file to the local system."),
16605 &remote_cmdlist);
16606
16607 add_cmd ("delete", class_files, remote_delete_command,
16608 _("Delete a remote file."),
16609 &remote_cmdlist);
16610
16611 add_setshow_string_noescape_cmd ("exec-file", class_files,
16612 &remote_exec_file_var, _("\
16613Set the remote pathname for \"run\"."), _("\
16614Show the remote pathname for \"run\"."), NULL,
16615 set_remote_exec_file,
16616 show_remote_exec_file,
16617 &remote_set_cmdlist,
16618 &remote_show_cmdlist);
16619
16620 add_setshow_boolean_cmd ("range-stepping", class_run,
16621 &use_range_stepping, _("\
16622Enable or disable range stepping."), _("\
16623Show whether target-assisted range stepping is enabled."), _("\
16624If on, and the target supports it, when stepping a source line, GDB\n\
16625tells the target to step the corresponding range of addresses itself instead\n\
16626of issuing multiple single-steps. This speeds up source level\n\
16627stepping. If off, GDB always issues single-steps, even if range\n\
16628stepping is supported by the target. The default is on."),
16629 set_range_stepping,
16630 show_range_stepping,
16631 &setlist,
16632 &showlist);
16633
16634 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16635Set watchdog timer."), _("\
16636Show watchdog timer."), _("\
16637When non-zero, this timeout is used instead of waiting forever for a target\n\
16638to finish a low-level step or continue operation. If the specified amount\n\
16639of time passes without a response from the target, an error occurs."),
16640 NULL,
16641 show_watchdog,
16642 &setlist, &showlist);
16643
16644 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16645 &remote_packet_max_chars, _("\
16646Set the maximum number of characters to display for each remote packet."), _("\
16647Show the maximum number of characters to display for each remote packet."), _("\
16648Specify \"unlimited\" to display all the characters."),
16649 NULL, show_remote_packet_max_chars,
16650 &setdebuglist, &showdebuglist);
16651
16652 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16653 _("Set debugging of remote protocol."),
16654 _("Show debugging of remote protocol."),
16655 _("\
16656When enabled, each packet sent or received with the remote target\n\
16657is displayed."),
16658 NULL,
16659 show_remote_debug,
16660 &setdebuglist, &showdebuglist);
16661
16662 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16663 &remote_timeout, _("\
16664Set timeout limit to wait for target to respond."), _("\
16665Show timeout limit to wait for target to respond."), _("\
16666This value is used to set the time limit for gdb to wait for a response\n\
16667from the target."),
16668 NULL,
16669 show_remote_timeout,
16670 &setlist, &showlist);
16671
16672 /* Eventually initialize fileio. See fileio.c */
16673 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16674
16675#if GDB_SELF_TEST
16676 selftests::register_test ("remote_memory_tagging",
16677 selftests::test_memory_tagging_functions);
16678 selftests::register_test ("packet_check_result",
16679 selftests::test_packet_check_result);
16680#endif
16681}