]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2024 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 "inferior.h"
25 #include "infrun.h"
26 #include "bfd.h"
27 #include "symfile.h"
28 #include "target.h"
29 #include "process-stratum-target.h"
30 #include "cli/cli-cmds.h"
31 #include "objfiles.h"
32 #include "gdbthread.h"
33 #include "remote.h"
34 #include "remote-notif.h"
35 #include "regcache.h"
36 #include "value.h"
37 #include "observable.h"
38 #include "solib.h"
39 #include "cli/cli-decode.h"
40 #include "cli/cli-setshow.h"
41 #include "target-descriptions.h"
42 #include "gdb_bfd.h"
43 #include "gdbsupport/filestuff.h"
44 #include "gdbsupport/rsp-low.h"
45 #include "disasm.h"
46 #include "location.h"
47
48 #include "gdbsupport/gdb_sys_time.h"
49
50 #include "gdbsupport/event-loop.h"
51 #include "event-top.h"
52 #include "inf-loop.h"
53
54 #include <signal.h>
55 #include "serial.h"
56
57 #include "gdbcore.h"
58
59 #include "remote-fileio.h"
60 #include "gdbsupport/fileio.h"
61 #include <sys/stat.h>
62 #include "xml-support.h"
63
64 #include "memory-map.h"
65
66 #include "tracepoint.h"
67 #include "ax.h"
68 #include "ax-gdb.h"
69 #include "gdbsupport/agent.h"
70 #include "btrace.h"
71 #include "record-btrace.h"
72 #include "gdbsupport/scoped_restore.h"
73 #include "gdbsupport/environ.h"
74 #include "gdbsupport/byte-vector.h"
75 #include "gdbsupport/search.h"
76 #include <algorithm>
77 #include <iterator>
78 #include <unordered_map>
79 #include "async-event.h"
80 #include "gdbsupport/selftest.h"
81
82 /* The remote target. */
83
84 static const char remote_doc[] = N_("\
85 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
86 Specify the serial device it is connected to\n\
87 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
88
89 /* See remote.h */
90
91 bool remote_debug = false;
92
93 #define OPAQUETHREADBYTES 8
94
95 /* a 64 bit opaque identifier */
96 typedef unsigned char threadref[OPAQUETHREADBYTES];
97
98 struct gdb_ext_thread_info;
99 struct threads_listing_context;
100 typedef int (*rmt_thread_action) (threadref *ref, void *context);
101 struct protocol_feature;
102 struct packet_reg;
103
104 struct stop_reply;
105 typedef std::unique_ptr<stop_reply> stop_reply_up;
106
107 /* Generic configuration support for packets the stub optionally
108 supports. Allows the user to specify the use of the packet as well
109 as allowing GDB to auto-detect support in the remote stub. */
110
111 enum packet_support
112 {
113 PACKET_SUPPORT_UNKNOWN = 0,
114 PACKET_ENABLE,
115 PACKET_DISABLE
116 };
117
118 /* Convert the packet support auto_boolean to a name used for gdb printing. */
119
120 static const char *
121 get_packet_support_name (auto_boolean support)
122 {
123 switch (support)
124 {
125 case AUTO_BOOLEAN_TRUE:
126 return "on";
127 case AUTO_BOOLEAN_FALSE:
128 return "off";
129 case AUTO_BOOLEAN_AUTO:
130 return "auto";
131 default:
132 gdb_assert_not_reached ("invalid var_auto_boolean");
133 }
134 }
135
136 /* Convert the target type (future remote target or currently connected target)
137 to a name used for gdb printing. */
138
139 static const char *
140 get_target_type_name (bool target_connected)
141 {
142 if (target_connected)
143 return _("on the current remote target");
144 else
145 return _("on future remote targets");
146 }
147
148 /* Analyze a packet's return value and update the packet config
149 accordingly. */
150
151 enum packet_status
152 {
153 PACKET_ERROR,
154 PACKET_OK,
155 PACKET_UNKNOWN
156 };
157
158 /* Keeps packet's return value. If packet's return value is PACKET_ERROR,
159 err_msg contains an error message string from E.string or the number
160 stored as a string from E.num. */
161 class packet_result
162 {
163 private:
164 /* Private ctors for internal use. Clients should use the public
165 factory static methods instead. */
166
167 /* Construct a PACKET_ERROR packet_result. */
168 packet_result (const char *err_msg, bool textual_err_msg)
169 : m_status (PACKET_ERROR),
170 m_err_msg (err_msg),
171 m_textual_err_msg (textual_err_msg)
172 {}
173
174 /* Construct an PACKET_OK/PACKET_UNKNOWN packet_result. */
175 explicit packet_result (enum packet_status status)
176 : m_status (status)
177 {
178 gdb_assert (status != PACKET_ERROR);
179 }
180
181 public:
182 enum packet_status status () const
183 {
184 return this->m_status;
185 }
186
187 const char *err_msg () const
188 {
189 gdb_assert (this->m_status == PACKET_ERROR);
190 return this->m_err_msg.c_str ();
191 }
192
193 bool textual_err_msg () const
194 {
195 gdb_assert (this->m_status == PACKET_ERROR);
196 return this->m_textual_err_msg;
197 }
198
199 static packet_result make_numeric_error (const char *err_msg)
200 {
201 return packet_result (err_msg, false);
202 }
203
204 static packet_result make_textual_error (const char *err_msg)
205 {
206 return packet_result (err_msg, true);
207 }
208
209 static packet_result make_ok ()
210 {
211 return packet_result (PACKET_OK);
212 }
213
214 static packet_result make_unknown ()
215 {
216 return packet_result (PACKET_UNKNOWN);
217 }
218
219 private:
220 enum packet_status m_status;
221 std::string m_err_msg;
222
223 /* True if we have a textual error message, from an "E.MESSAGE"
224 response. */
225 bool m_textual_err_msg = false;
226 };
227
228 /* Enumeration of packets for a remote target. */
229
230 enum {
231 PACKET_vCont = 0,
232 PACKET_X,
233 PACKET_qSymbol,
234 PACKET_P,
235 PACKET_p,
236 PACKET_Z0,
237 PACKET_Z1,
238 PACKET_Z2,
239 PACKET_Z3,
240 PACKET_Z4,
241 PACKET_vFile_setfs,
242 PACKET_vFile_open,
243 PACKET_vFile_pread,
244 PACKET_vFile_pwrite,
245 PACKET_vFile_close,
246 PACKET_vFile_unlink,
247 PACKET_vFile_readlink,
248 PACKET_vFile_fstat,
249 PACKET_qXfer_auxv,
250 PACKET_qXfer_features,
251 PACKET_qXfer_exec_file,
252 PACKET_qXfer_libraries,
253 PACKET_qXfer_libraries_svr4,
254 PACKET_qXfer_memory_map,
255 PACKET_qXfer_osdata,
256 PACKET_qXfer_threads,
257 PACKET_qXfer_statictrace_read,
258 PACKET_qXfer_traceframe_info,
259 PACKET_qXfer_uib,
260 PACKET_qGetTIBAddr,
261 PACKET_qGetTLSAddr,
262 PACKET_qSupported,
263 PACKET_qTStatus,
264 PACKET_QPassSignals,
265 PACKET_QCatchSyscalls,
266 PACKET_QProgramSignals,
267 PACKET_QSetWorkingDir,
268 PACKET_QStartupWithShell,
269 PACKET_QEnvironmentHexEncoded,
270 PACKET_QEnvironmentReset,
271 PACKET_QEnvironmentUnset,
272 PACKET_qCRC,
273 PACKET_qSearch_memory,
274 PACKET_vAttach,
275 PACKET_vRun,
276 PACKET_QStartNoAckMode,
277 PACKET_vKill,
278 PACKET_qXfer_siginfo_read,
279 PACKET_qXfer_siginfo_write,
280 PACKET_qAttached,
281
282 /* Support for conditional tracepoints. */
283 PACKET_ConditionalTracepoints,
284
285 /* Support for target-side breakpoint conditions. */
286 PACKET_ConditionalBreakpoints,
287
288 /* Support for target-side breakpoint commands. */
289 PACKET_BreakpointCommands,
290
291 /* Support for fast tracepoints. */
292 PACKET_FastTracepoints,
293
294 /* Support for static tracepoints. */
295 PACKET_StaticTracepoints,
296
297 /* Support for installing tracepoints while a trace experiment is
298 running. */
299 PACKET_InstallInTrace,
300
301 PACKET_bc,
302 PACKET_bs,
303 PACKET_TracepointSource,
304 PACKET_QAllow,
305 PACKET_qXfer_fdpic,
306 PACKET_QDisableRandomization,
307 PACKET_QAgent,
308 PACKET_QTBuffer_size,
309 PACKET_Qbtrace_off,
310 PACKET_Qbtrace_bts,
311 PACKET_Qbtrace_pt,
312 PACKET_qXfer_btrace,
313
314 /* Support for the QNonStop packet. */
315 PACKET_QNonStop,
316
317 /* Support for the QThreadEvents packet. */
318 PACKET_QThreadEvents,
319
320 /* Support for the QThreadOptions packet. */
321 PACKET_QThreadOptions,
322
323 /* Support for multi-process extensions. */
324 PACKET_multiprocess_feature,
325
326 /* Support for enabling and disabling tracepoints while a trace
327 experiment is running. */
328 PACKET_EnableDisableTracepoints_feature,
329
330 /* Support for collecting strings using the tracenz bytecode. */
331 PACKET_tracenz_feature,
332
333 /* Support for continuing to run a trace experiment while GDB is
334 disconnected. */
335 PACKET_DisconnectedTracing_feature,
336
337 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
338 PACKET_augmented_libraries_svr4_read_feature,
339
340 /* Support for the qXfer:btrace-conf:read packet. */
341 PACKET_qXfer_btrace_conf,
342
343 /* Support for the Qbtrace-conf:bts:size packet. */
344 PACKET_Qbtrace_conf_bts_size,
345
346 /* Support for swbreak+ feature. */
347 PACKET_swbreak_feature,
348
349 /* Support for hwbreak+ feature. */
350 PACKET_hwbreak_feature,
351
352 /* Support for fork events. */
353 PACKET_fork_event_feature,
354
355 /* Support for vfork events. */
356 PACKET_vfork_event_feature,
357
358 /* Support for the Qbtrace-conf:pt:size packet. */
359 PACKET_Qbtrace_conf_pt_size,
360
361 /* Support for exec events. */
362 PACKET_exec_event_feature,
363
364 /* Support for query supported vCont actions. */
365 PACKET_vContSupported,
366
367 /* Support remote CTRL-C. */
368 PACKET_vCtrlC,
369
370 /* Support TARGET_WAITKIND_NO_RESUMED. */
371 PACKET_no_resumed,
372
373 /* Support for memory tagging, allocation tag fetch/store
374 packets and the tag violation stop replies. */
375 PACKET_memory_tagging_feature,
376
377 /* Support for the qIsAddressTagged packet. */
378 PACKET_qIsAddressTagged,
379
380 PACKET_MAX
381 };
382
383 struct threads_listing_context;
384
385 /* Stub vCont actions support.
386
387 Each field is a boolean flag indicating whether the stub reports
388 support for the corresponding action. */
389
390 struct vCont_action_support
391 {
392 /* vCont;t */
393 bool t = false;
394
395 /* vCont;r */
396 bool r = false;
397
398 /* vCont;s */
399 bool s = false;
400
401 /* vCont;S */
402 bool S = false;
403 };
404
405 /* About this many threadids fit in a packet. */
406
407 #define MAXTHREADLISTRESULTS 32
408
409 /* Data for the vFile:pread readahead cache. */
410
411 struct readahead_cache
412 {
413 /* Invalidate the readahead cache. */
414 void invalidate ();
415
416 /* Invalidate the readahead cache if it is holding data for FD. */
417 void invalidate_fd (int fd);
418
419 /* Serve pread from the readahead cache. Returns number of bytes
420 read, or 0 if the request can't be served from the cache. */
421 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
422
423 /* The file descriptor for the file that is being cached. -1 if the
424 cache is invalid. */
425 int fd = -1;
426
427 /* The offset into the file that the cache buffer corresponds
428 to. */
429 ULONGEST offset = 0;
430
431 /* The buffer holding the cache contents. */
432 gdb::byte_vector buf;
433
434 /* Cache hit and miss counters. */
435 ULONGEST hit_count = 0;
436 ULONGEST miss_count = 0;
437 };
438
439 /* Description of the remote protocol for a given architecture. */
440
441 struct packet_reg
442 {
443 long offset; /* Offset into G packet. */
444 long regnum; /* GDB's internal register number. */
445 LONGEST pnum; /* Remote protocol register number. */
446 int in_g_packet; /* Always part of G packet. */
447 /* long size in bytes; == register_size (arch, regnum);
448 at present. */
449 /* char *name; == gdbarch_register_name (arch, regnum);
450 at present. */
451 };
452
453 struct remote_arch_state
454 {
455 explicit remote_arch_state (struct gdbarch *gdbarch);
456
457 /* Description of the remote protocol registers. */
458 long sizeof_g_packet;
459
460 /* Description of the remote protocol registers indexed by REGNUM
461 (making an array gdbarch_num_regs in size). */
462 std::unique_ptr<packet_reg[]> regs;
463
464 /* This is the size (in chars) of the first response to the ``g''
465 packet. It is used as a heuristic when determining the maximum
466 size of memory-read and memory-write packets. A target will
467 typically only reserve a buffer large enough to hold the ``g''
468 packet. The size does not include packet overhead (headers and
469 trailers). */
470 long actual_register_packet_size;
471
472 /* This is the maximum size (in chars) of a non read/write packet.
473 It is also used as a cap on the size of read/write packets. */
474 long remote_packet_size;
475 };
476
477 /* Description of the remote protocol state for the currently
478 connected target. This is per-target state, and independent of the
479 selected architecture. */
480
481 class remote_state
482 {
483 public:
484
485 remote_state ();
486 ~remote_state ();
487
488 /* Get the remote arch state for GDBARCH. */
489 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
490
491 void create_async_event_handler ()
492 {
493 gdb_assert (m_async_event_handler_token == nullptr);
494 m_async_event_handler_token
495 = ::create_async_event_handler ([] (gdb_client_data data)
496 {
497 inferior_event_handler (INF_REG_EVENT);
498 },
499 nullptr, "remote");
500 }
501
502 void mark_async_event_handler ()
503 {
504 gdb_assert (this->is_async_p ());
505 ::mark_async_event_handler (m_async_event_handler_token);
506 }
507
508 void clear_async_event_handler ()
509 { ::clear_async_event_handler (m_async_event_handler_token); }
510
511 bool async_event_handler_marked () const
512 { return ::async_event_handler_marked (m_async_event_handler_token); }
513
514 void delete_async_event_handler ()
515 {
516 if (m_async_event_handler_token != nullptr)
517 ::delete_async_event_handler (&m_async_event_handler_token);
518 }
519
520 bool is_async_p () const
521 {
522 /* We're async whenever the serial device is. */
523 gdb_assert (this->remote_desc != nullptr);
524 return serial_is_async_p (this->remote_desc);
525 }
526
527 bool can_async_p () const
528 {
529 /* We can async whenever the serial device can. */
530 gdb_assert (this->remote_desc != nullptr);
531 return serial_can_async_p (this->remote_desc);
532 }
533
534 public: /* data */
535
536 /* A buffer to use for incoming packets, and its current size. The
537 buffer is grown dynamically for larger incoming packets.
538 Outgoing packets may also be constructed in this buffer.
539 The size of the buffer is always at least REMOTE_PACKET_SIZE;
540 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
541 packets. */
542 gdb::char_vector buf;
543
544 /* True if we're going through initial connection setup (finding out
545 about the remote side's threads, relocating symbols, etc.). */
546 bool starting_up = false;
547
548 /* If we negotiated packet size explicitly (and thus can bypass
549 heuristics for the largest packet size that will not overflow
550 a buffer in the stub), this will be set to that packet size.
551 Otherwise zero, meaning to use the guessed size. */
552 long explicit_packet_size = 0;
553
554 /* True, if in no ack mode. That is, neither GDB nor the stub will
555 expect acks from each other. The connection is assumed to be
556 reliable. */
557 bool noack_mode = false;
558
559 /* True if we're connected in extended remote mode. */
560 bool extended = false;
561
562 /* True if we resumed the target and we're waiting for the target to
563 stop. In the mean time, we can't start another command/query.
564 The remote server wouldn't be ready to process it, so we'd
565 timeout waiting for a reply that would never come and eventually
566 we'd close the connection. This can happen in asynchronous mode
567 because we allow GDB commands while the target is running. */
568 bool waiting_for_stop_reply = false;
569
570 /* The status of the stub support for the various vCont actions. */
571 vCont_action_support supports_vCont;
572
573 /* True if the user has pressed Ctrl-C, but the target hasn't
574 responded to that. */
575 bool ctrlc_pending_p = false;
576
577 /* True if we saw a Ctrl-C while reading or writing from/to the
578 remote descriptor. At that point it is not safe to send a remote
579 interrupt packet, so we instead remember we saw the Ctrl-C and
580 process it once we're done with sending/receiving the current
581 packet, which should be shortly. If however that takes too long,
582 and the user presses Ctrl-C again, we offer to disconnect. */
583 bool got_ctrlc_during_io = false;
584
585 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
586 remote_open knows that we don't have a file open when the program
587 starts. */
588 struct serial *remote_desc = nullptr;
589
590 /* These are the threads which we last sent to the remote system. The
591 TID member will be -1 for all or -2 for not sent yet. */
592 ptid_t general_thread = null_ptid;
593 ptid_t continue_thread = null_ptid;
594
595 /* This is the traceframe which we last selected on the remote system.
596 It will be -1 if no traceframe is selected. */
597 int remote_traceframe_number = -1;
598
599 char *last_pass_packet = nullptr;
600
601 /* The last QProgramSignals packet sent to the target. We bypass
602 sending a new program signals list down to the target if the new
603 packet is exactly the same as the last we sent. IOW, we only let
604 the target know about program signals list changes. */
605 char *last_program_signals_packet = nullptr;
606
607 /* Similarly, the last QThreadEvents state we sent to the
608 target. */
609 bool last_thread_events = false;
610
611 gdb_signal last_sent_signal = GDB_SIGNAL_0;
612
613 bool last_sent_step = false;
614
615 /* The execution direction of the last resume we got. */
616 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
617
618 char *finished_object = nullptr;
619 char *finished_annex = nullptr;
620 ULONGEST finished_offset = 0;
621
622 /* Should we try the 'ThreadInfo' query packet?
623
624 This variable (NOT available to the user: auto-detect only!)
625 determines whether GDB will use the new, simpler "ThreadInfo"
626 query or the older, more complex syntax for thread queries.
627 This is an auto-detect variable (set to true at each connect,
628 and set to false when the target fails to recognize it). */
629 bool use_threadinfo_query = false;
630 bool use_threadextra_query = false;
631
632 threadref echo_nextthread {};
633 threadref nextthread {};
634 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
635
636 /* The state of remote notification. */
637 struct remote_notif_state *notif_state = nullptr;
638
639 /* The branch trace configuration. */
640 struct btrace_config btrace_config {};
641
642 /* The argument to the last "vFile:setfs:" packet we sent, used
643 to avoid sending repeated unnecessary "vFile:setfs:" packets.
644 Initialized to -1 to indicate that no "vFile:setfs:" packet
645 has yet been sent. */
646 int fs_pid = -1;
647
648 /* A readahead cache for vFile:pread. Often, reading a binary
649 involves a sequence of small reads. E.g., when parsing an ELF
650 file. A readahead cache helps mostly the case of remote
651 debugging on a connection with higher latency, due to the
652 request/reply nature of the RSP. We only cache data for a single
653 file descriptor at a time. */
654 struct readahead_cache readahead_cache;
655
656 /* The list of already fetched and acknowledged stop events. This
657 queue is used for notification Stop, and other notifications
658 don't need queue for their events, because the notification
659 events of Stop can't be consumed immediately, so that events
660 should be queued first, and be consumed by remote_wait_{ns,as}
661 one per time. Other notifications can consume their events
662 immediately, so queue is not needed for them. */
663 std::vector<stop_reply_up> stop_reply_queue;
664
665 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
666 ``forever'' still use the normal timeout mechanism. This is
667 currently used by the ASYNC code to guarentee that target reads
668 during the initial connect always time-out. Once getpkt has been
669 modified to return a timeout indication and, in turn
670 remote_wait()/wait_for_inferior() have gained a timeout parameter
671 this can go away. */
672 bool wait_forever_enabled_p = true;
673
674 /* The set of thread options the target reported it supports, via
675 qSupported. */
676 gdb_thread_options supported_thread_options = 0;
677
678 private:
679 /* Asynchronous signal handle registered as event loop source for
680 when we have pending events ready to be passed to the core. */
681 async_event_handler *m_async_event_handler_token = nullptr;
682
683 /* Mapping of remote protocol data for each gdbarch. Usually there
684 is only one entry here, though we may see more with stubs that
685 support multi-process. */
686 std::unordered_map<struct gdbarch *, remote_arch_state>
687 m_arch_states;
688 };
689
690 static const target_info remote_target_info = {
691 "remote",
692 N_("Remote target using gdb-specific protocol"),
693 remote_doc
694 };
695
696 /* Description of a remote packet. */
697
698 struct packet_description
699 {
700 /* Name of the packet used for gdb output. */
701 const char *name;
702
703 /* Title of the packet, used by the set/show remote name-packet
704 commands to identify the individual packages and gdb output. */
705 const char *title;
706 };
707
708 /* Configuration of a remote packet. */
709
710 struct packet_config
711 {
712 /* If auto, GDB auto-detects support for this packet or feature,
713 either through qSupported, or by trying the packet and looking
714 at the response. If true, GDB assumes the target supports this
715 packet. If false, the packet is disabled. Configs that don't
716 have an associated command always have this set to auto. */
717 enum auto_boolean detect;
718
719 /* Does the target support this packet? */
720 enum packet_support support;
721 };
722
723 /* User configurable variables for the number of characters in a
724 memory read/write packet. MIN (rsa->remote_packet_size,
725 rsa->sizeof_g_packet) is the default. Some targets need smaller
726 values (fifo overruns, et.al.) and some users need larger values
727 (speed up transfers). The variables ``preferred_*'' (the user
728 request), ``current_*'' (what was actually set) and ``forced_*''
729 (Positive - a soft limit, negative - a hard limit). */
730
731 struct memory_packet_config
732 {
733 const char *name;
734 long size;
735 int fixed_p;
736 };
737
738 /* These global variables contain the default configuration for every new
739 remote_feature object. */
740 static memory_packet_config memory_read_packet_config =
741 {
742 "memory-read-packet-size",
743 };
744 static memory_packet_config memory_write_packet_config =
745 {
746 "memory-write-packet-size",
747 };
748
749 /* This global array contains packet descriptions (name and title). */
750 static packet_description packets_descriptions[PACKET_MAX];
751 /* This global array contains the default configuration for every new
752 per-remote target array. */
753 static packet_config remote_protocol_packets[PACKET_MAX];
754
755 /* Description of a remote target's features. It stores the configuration
756 and provides functions to determine supported features of the target. */
757
758 struct remote_features
759 {
760 remote_features ()
761 {
762 m_memory_read_packet_config = memory_read_packet_config;
763 m_memory_write_packet_config = memory_write_packet_config;
764
765 std::copy (std::begin (remote_protocol_packets),
766 std::end (remote_protocol_packets),
767 std::begin (m_protocol_packets));
768 }
769 ~remote_features () = default;
770
771 DISABLE_COPY_AND_ASSIGN (remote_features);
772
773 /* Returns whether a given packet defined by its enum value is supported. */
774 enum packet_support packet_support (int) const;
775
776 /* Returns the packet's corresponding "set remote foo-packet" command
777 state. See struct packet_config for more details. */
778 enum auto_boolean packet_set_cmd_state (int packet) const
779 { return m_protocol_packets[packet].detect; }
780
781 /* Returns true if the multi-process extensions are in effect. */
782 int remote_multi_process_p () const
783 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
784
785 /* Returns true if fork events are supported. */
786 int remote_fork_event_p () const
787 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
788
789 /* Returns true if vfork events are supported. */
790 int remote_vfork_event_p () const
791 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
792
793 /* Returns true if exec events are supported. */
794 int remote_exec_event_p () const
795 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
796
797 /* Returns true if memory tagging is supported, false otherwise. */
798 bool remote_memory_tagging_p () const
799 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
800
801 /* Reset all packets back to "unknown support". Called when opening a
802 new connection to a remote target. */
803 void reset_all_packet_configs_support ();
804
805 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
806 support configuration accordingly. */
807 packet_result packet_ok (const char *buf, const int which_packet);
808 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
809
810 /* Configuration of a remote target's memory read packet. */
811 memory_packet_config m_memory_read_packet_config;
812 /* Configuration of a remote target's memory write packet. */
813 memory_packet_config m_memory_write_packet_config;
814
815 /* The per-remote target array which stores a remote's packet
816 configurations. */
817 packet_config m_protocol_packets[PACKET_MAX];
818 };
819
820 class remote_target : public process_stratum_target
821 {
822 public:
823 remote_target () = default;
824 ~remote_target () override;
825
826 const target_info &info () const override
827 { return remote_target_info; }
828
829 const char *connection_string () override;
830
831 thread_control_capabilities get_thread_control_capabilities () override
832 { return tc_schedlock; }
833
834 /* Open a remote connection. */
835 static void open (const char *, int);
836
837 void close () override;
838
839 void detach (inferior *, int) override;
840 void disconnect (const char *, int) override;
841
842 void commit_requested_thread_options ();
843
844 void commit_resumed () override;
845 void resume (ptid_t, int, enum gdb_signal) override;
846 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
847 bool has_pending_events () override;
848
849 void fetch_registers (struct regcache *, int) override;
850 void store_registers (struct regcache *, int) override;
851 void prepare_to_store (struct regcache *) override;
852
853 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
854
855 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
856 enum remove_bp_reason) override;
857
858
859 bool stopped_by_sw_breakpoint () override;
860 bool supports_stopped_by_sw_breakpoint () override;
861
862 bool stopped_by_hw_breakpoint () override;
863
864 bool supports_stopped_by_hw_breakpoint () override;
865
866 bool stopped_by_watchpoint () override;
867
868 bool stopped_data_address (CORE_ADDR *) override;
869
870 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
871
872 int can_use_hw_breakpoint (enum bptype, int, int) override;
873
874 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
875
876 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
877
878 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
879
880 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
881 struct expression *) override;
882
883 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
884 struct expression *) override;
885
886 void kill () override;
887
888 void load (const char *, int) override;
889
890 void mourn_inferior () override;
891
892 void pass_signals (gdb::array_view<const unsigned char>) override;
893
894 int set_syscall_catchpoint (int, bool, int,
895 gdb::array_view<const int>) override;
896
897 void program_signals (gdb::array_view<const unsigned char>) override;
898
899 bool thread_alive (ptid_t ptid) override;
900
901 const char *thread_name (struct thread_info *) override;
902
903 void update_thread_list () override;
904
905 std::string pid_to_str (ptid_t) override;
906
907 const char *extra_thread_info (struct thread_info *) override;
908
909 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
910
911 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
912 int handle_len,
913 inferior *inf) override;
914
915 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
916 override;
917
918 void stop (ptid_t) override;
919
920 void interrupt () override;
921
922 void pass_ctrlc () override;
923
924 enum target_xfer_status xfer_partial (enum target_object object,
925 const char *annex,
926 gdb_byte *readbuf,
927 const gdb_byte *writebuf,
928 ULONGEST offset, ULONGEST len,
929 ULONGEST *xfered_len) override;
930
931 ULONGEST get_memory_xfer_limit () override;
932
933 void rcmd (const char *command, struct ui_file *output) override;
934
935 const char *pid_to_exec_file (int pid) override;
936
937 void log_command (const char *cmd) override
938 {
939 serial_log_command (this, cmd);
940 }
941
942 CORE_ADDR get_thread_local_address (ptid_t ptid,
943 CORE_ADDR load_module_addr,
944 CORE_ADDR offset) override;
945
946 bool can_execute_reverse () override;
947
948 std::vector<mem_region> memory_map () override;
949
950 void flash_erase (ULONGEST address, LONGEST length) override;
951
952 void flash_done () override;
953
954 const struct target_desc *read_description () override;
955
956 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
957 const gdb_byte *pattern, ULONGEST pattern_len,
958 CORE_ADDR *found_addrp) override;
959
960 bool can_async_p () override;
961
962 bool is_async_p () override;
963
964 void async (bool) override;
965
966 int async_wait_fd () override;
967
968 void thread_events (int) override;
969
970 bool supports_set_thread_options (gdb_thread_options) override;
971
972 int can_do_single_step () override;
973
974 void terminal_inferior () override;
975
976 void terminal_ours () override;
977
978 bool supports_non_stop () override;
979
980 bool supports_multi_process () override;
981
982 bool supports_disable_randomization () override;
983
984 bool filesystem_is_local () override;
985
986
987 int fileio_open (struct inferior *inf, const char *filename,
988 int flags, int mode, int warn_if_slow,
989 fileio_error *target_errno) override;
990
991 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
992 ULONGEST offset, fileio_error *target_errno) override;
993
994 int fileio_pread (int fd, gdb_byte *read_buf, int len,
995 ULONGEST offset, fileio_error *target_errno) override;
996
997 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
998
999 int fileio_close (int fd, fileio_error *target_errno) override;
1000
1001 int fileio_unlink (struct inferior *inf,
1002 const char *filename,
1003 fileio_error *target_errno) override;
1004
1005 std::optional<std::string>
1006 fileio_readlink (struct inferior *inf,
1007 const char *filename,
1008 fileio_error *target_errno) override;
1009
1010 bool supports_enable_disable_tracepoint () override;
1011
1012 bool supports_string_tracing () override;
1013
1014 int remote_supports_cond_tracepoints ();
1015
1016 bool supports_evaluation_of_breakpoint_conditions () override;
1017
1018 int remote_supports_fast_tracepoints ();
1019
1020 int remote_supports_static_tracepoints ();
1021
1022 int remote_supports_install_in_trace ();
1023
1024 bool can_run_breakpoint_commands () override;
1025
1026 void trace_init () override;
1027
1028 void download_tracepoint (struct bp_location *location) override;
1029
1030 bool can_download_tracepoint () override;
1031
1032 void download_trace_state_variable (const trace_state_variable &tsv) override;
1033
1034 void enable_tracepoint (struct bp_location *location) override;
1035
1036 void disable_tracepoint (struct bp_location *location) override;
1037
1038 void trace_set_readonly_regions () override;
1039
1040 void trace_start () override;
1041
1042 int get_trace_status (struct trace_status *ts) override;
1043
1044 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
1045 override;
1046
1047 void trace_stop () override;
1048
1049 int trace_find (enum trace_find_type type, int num,
1050 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
1051
1052 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
1053
1054 int save_trace_data (const char *filename) override;
1055
1056 int upload_tracepoints (struct uploaded_tp **utpp) override;
1057
1058 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
1059
1060 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
1061
1062 int get_min_fast_tracepoint_insn_len () override;
1063
1064 void set_disconnected_tracing (int val) override;
1065
1066 void set_circular_trace_buffer (int val) override;
1067
1068 void set_trace_buffer_size (LONGEST val) override;
1069
1070 bool set_trace_notes (const char *user, const char *notes,
1071 const char *stopnotes) override;
1072
1073 int core_of_thread (ptid_t ptid) override;
1074
1075 int verify_memory (const gdb_byte *data,
1076 CORE_ADDR memaddr, ULONGEST size) override;
1077
1078
1079 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
1080
1081 void set_permissions () override;
1082
1083 bool static_tracepoint_marker_at (CORE_ADDR,
1084 struct static_tracepoint_marker *marker)
1085 override;
1086
1087 std::vector<static_tracepoint_marker>
1088 static_tracepoint_markers_by_strid (const char *id) override;
1089
1090 traceframe_info_up traceframe_info () override;
1091
1092 bool use_agent (bool use) override;
1093 bool can_use_agent () override;
1094
1095 struct btrace_target_info *
1096 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1097
1098 void disable_btrace (struct btrace_target_info *tinfo) override;
1099
1100 void teardown_btrace (struct btrace_target_info *tinfo) override;
1101
1102 enum btrace_error read_btrace (struct btrace_data *data,
1103 struct btrace_target_info *btinfo,
1104 enum btrace_read_type type) override;
1105
1106 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1107 bool augmented_libraries_svr4_read () override;
1108 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1109 void follow_clone (ptid_t child_ptid) override;
1110 void follow_exec (inferior *, ptid_t, const char *) override;
1111 int insert_fork_catchpoint (int) override;
1112 int remove_fork_catchpoint (int) override;
1113 int insert_vfork_catchpoint (int) override;
1114 int remove_vfork_catchpoint (int) override;
1115 int insert_exec_catchpoint (int) override;
1116 int remove_exec_catchpoint (int) override;
1117 enum exec_direction_kind execution_direction () override;
1118
1119 bool supports_memory_tagging () override;
1120
1121 bool fetch_memtags (CORE_ADDR address, size_t len,
1122 gdb::byte_vector &tags, int type) override;
1123
1124 bool store_memtags (CORE_ADDR address, size_t len,
1125 const gdb::byte_vector &tags, int type) override;
1126
1127 bool is_address_tagged (gdbarch *gdbarch, CORE_ADDR address) override;
1128
1129 public: /* Remote specific methods. */
1130
1131 void remote_download_command_source (int num, ULONGEST addr,
1132 struct command_line *cmds);
1133
1134 void remote_file_put (const char *local_file, const char *remote_file,
1135 int from_tty);
1136 void remote_file_get (const char *remote_file, const char *local_file,
1137 int from_tty);
1138 void remote_file_delete (const char *remote_file, int from_tty);
1139
1140 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1141 ULONGEST offset, fileio_error *remote_errno);
1142 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1143 ULONGEST offset, fileio_error *remote_errno);
1144 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1145 ULONGEST offset, fileio_error *remote_errno);
1146
1147 int remote_hostio_send_command (int command_bytes, int which_packet,
1148 fileio_error *remote_errno, const char **attachment,
1149 int *attachment_len);
1150 int remote_hostio_set_filesystem (struct inferior *inf,
1151 fileio_error *remote_errno);
1152 /* We should get rid of this and use fileio_open directly. */
1153 int remote_hostio_open (struct inferior *inf, const char *filename,
1154 int flags, int mode, int warn_if_slow,
1155 fileio_error *remote_errno);
1156 int remote_hostio_close (int fd, fileio_error *remote_errno);
1157
1158 int remote_hostio_unlink (inferior *inf, const char *filename,
1159 fileio_error *remote_errno);
1160
1161 struct remote_state *get_remote_state ();
1162
1163 long get_remote_packet_size (void);
1164 long get_memory_packet_size (struct memory_packet_config *config);
1165
1166 long get_memory_write_packet_size ();
1167 long get_memory_read_packet_size ();
1168
1169 char *append_pending_thread_resumptions (char *p, char *endp,
1170 ptid_t ptid);
1171 static void open_1 (const char *name, int from_tty, int extended_p);
1172 void start_remote (int from_tty, int extended_p);
1173 void remote_detach_1 (struct inferior *inf, int from_tty);
1174
1175 char *append_resumption (char *p, char *endp,
1176 ptid_t ptid, int step, gdb_signal siggnal);
1177 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1178 gdb_signal siggnal);
1179
1180 thread_info *add_current_inferior_and_thread (const char *wait_status);
1181
1182 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1183 target_wait_flags options);
1184 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1185 target_wait_flags options);
1186
1187 ptid_t process_stop_reply (stop_reply_up stop_reply,
1188 target_waitstatus *status);
1189
1190 ptid_t select_thread_for_ambiguous_stop_reply
1191 (const struct target_waitstatus &status);
1192
1193 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1194
1195 void print_one_stopped_thread (thread_info *thread);
1196 void process_initial_stop_replies (int from_tty);
1197
1198 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1199 bool silent_p);
1200
1201 void btrace_sync_conf (const btrace_config *conf);
1202
1203 void remote_btrace_maybe_reopen ();
1204
1205 void remove_new_children (threads_listing_context *context);
1206 void kill_new_fork_children (inferior *inf);
1207 void discard_pending_stop_replies (struct inferior *inf);
1208 int stop_reply_queue_length ();
1209
1210 void check_pending_events_prevent_wildcard_vcont
1211 (bool *may_global_wildcard_vcont);
1212
1213 void discard_pending_stop_replies_in_queue ();
1214 stop_reply_up remote_notif_remove_queued_reply (ptid_t ptid);
1215 stop_reply_up queued_stop_reply (ptid_t ptid);
1216 int peek_stop_reply (ptid_t ptid);
1217 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1218
1219 void remote_stop_ns (ptid_t ptid);
1220 void remote_interrupt_as ();
1221 void remote_interrupt_ns ();
1222
1223 char *remote_get_noisy_reply ();
1224 int remote_query_attached (int pid);
1225 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1226 int try_open_exec);
1227
1228 ptid_t remote_current_thread (ptid_t oldpid);
1229 ptid_t get_current_thread (const char *wait_status);
1230
1231 void set_thread (ptid_t ptid, int gen);
1232 void set_general_thread (ptid_t ptid);
1233 void set_continue_thread (ptid_t ptid);
1234 void set_general_process ();
1235
1236 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1237
1238 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1239 gdb_ext_thread_info *info);
1240 int remote_get_threadinfo (threadref *threadid, int fieldset,
1241 gdb_ext_thread_info *info);
1242
1243 int parse_threadlist_response (const char *pkt, int result_limit,
1244 threadref *original_echo,
1245 threadref *resultlist,
1246 int *doneflag);
1247 int remote_get_threadlist (int startflag, threadref *nextthread,
1248 int result_limit, int *done, int *result_count,
1249 threadref *threadlist);
1250
1251 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1252 void *context, int looplimit);
1253
1254 int remote_get_threads_with_ql (threads_listing_context *context);
1255 int remote_get_threads_with_qxfer (threads_listing_context *context);
1256 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1257
1258 void extended_remote_restart ();
1259
1260 void get_offsets ();
1261
1262 void remote_check_symbols ();
1263
1264 void remote_supported_packet (const struct protocol_feature *feature,
1265 enum packet_support support,
1266 const char *argument);
1267
1268 void remote_query_supported ();
1269
1270 void remote_packet_size (const protocol_feature *feature,
1271 packet_support support, const char *value);
1272 void remote_supported_thread_options (const protocol_feature *feature,
1273 enum packet_support support,
1274 const char *value);
1275
1276 void remote_serial_quit_handler ();
1277
1278 void remote_detach_pid (int pid);
1279
1280 void remote_vcont_probe ();
1281
1282 void remote_resume_with_hc (ptid_t ptid, int step,
1283 gdb_signal siggnal);
1284
1285 void send_interrupt_sequence ();
1286 void interrupt_query ();
1287
1288 void remote_notif_get_pending_events (const notif_client *nc);
1289
1290 int fetch_register_using_p (struct regcache *regcache,
1291 packet_reg *reg);
1292 int send_g_packet ();
1293 void process_g_packet (struct regcache *regcache);
1294 void fetch_registers_using_g (struct regcache *regcache);
1295 int store_register_using_P (const struct regcache *regcache,
1296 packet_reg *reg);
1297 void store_registers_using_G (const struct regcache *regcache);
1298
1299 void set_remote_traceframe ();
1300
1301 void check_binary_download (CORE_ADDR addr);
1302
1303 target_xfer_status remote_write_bytes_aux (const char *header,
1304 CORE_ADDR memaddr,
1305 const gdb_byte *myaddr,
1306 ULONGEST len_units,
1307 int unit_size,
1308 ULONGEST *xfered_len_units,
1309 char packet_format,
1310 int use_length);
1311
1312 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1313 const gdb_byte *myaddr, ULONGEST len,
1314 int unit_size, ULONGEST *xfered_len);
1315
1316 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1317 ULONGEST len_units,
1318 int unit_size, ULONGEST *xfered_len_units);
1319
1320 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1321 ULONGEST memaddr,
1322 ULONGEST len,
1323 int unit_size,
1324 ULONGEST *xfered_len);
1325
1326 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1327 gdb_byte *myaddr, ULONGEST len,
1328 int unit_size,
1329 ULONGEST *xfered_len);
1330
1331 packet_status remote_send_printf (const char *format, ...)
1332 ATTRIBUTE_PRINTF (2, 3);
1333
1334 target_xfer_status remote_flash_write (ULONGEST address,
1335 ULONGEST length, ULONGEST *xfered_len,
1336 const gdb_byte *data);
1337
1338 int readchar (int timeout);
1339
1340 void remote_serial_write (const char *str, int len);
1341 void remote_serial_send_break ();
1342
1343 int putpkt (const char *buf);
1344 int putpkt_binary (const char *buf, int cnt);
1345
1346 int putpkt (const gdb::char_vector &buf)
1347 {
1348 return putpkt (buf.data ());
1349 }
1350
1351 void skip_frame ();
1352 long read_frame (gdb::char_vector *buf_p);
1353 int getpkt (gdb::char_vector *buf, bool forever = false,
1354 bool *is_notif = nullptr);
1355 int remote_vkill (int pid);
1356 void remote_kill_k ();
1357
1358 void extended_remote_disable_randomization (int val);
1359 int extended_remote_run (const std::string &args);
1360
1361 void send_environment_packet (const char *action,
1362 const char *packet,
1363 const char *value);
1364
1365 void extended_remote_environment_support ();
1366 void extended_remote_set_inferior_cwd ();
1367
1368 target_xfer_status remote_write_qxfer (const char *object_name,
1369 const char *annex,
1370 const gdb_byte *writebuf,
1371 ULONGEST offset, LONGEST len,
1372 ULONGEST *xfered_len,
1373 const unsigned int which_packet);
1374
1375 target_xfer_status remote_read_qxfer (const char *object_name,
1376 const char *annex,
1377 gdb_byte *readbuf, ULONGEST offset,
1378 LONGEST len,
1379 ULONGEST *xfered_len,
1380 const unsigned int which_packet);
1381
1382 void push_stop_reply (stop_reply_up new_event);
1383
1384 bool vcont_r_supported ();
1385
1386 remote_features m_features;
1387
1388 private:
1389
1390 bool start_remote_1 (int from_tty, int extended_p);
1391
1392 /* The remote state. Don't reference this directly. Use the
1393 get_remote_state method instead. */
1394 remote_state m_remote_state;
1395 };
1396
1397 static const target_info extended_remote_target_info = {
1398 "extended-remote",
1399 N_("Extended remote target using gdb-specific protocol"),
1400 remote_doc
1401 };
1402
1403 /* Set up the extended remote target by extending the standard remote
1404 target and adding to it. */
1405
1406 class extended_remote_target final : public remote_target
1407 {
1408 public:
1409 const target_info &info () const override
1410 { return extended_remote_target_info; }
1411
1412 /* Open an extended-remote connection. */
1413 static void open (const char *, int);
1414
1415 bool can_create_inferior () override { return true; }
1416 void create_inferior (const char *, const std::string &,
1417 char **, int) override;
1418
1419 void detach (inferior *, int) override;
1420
1421 bool can_attach () override { return true; }
1422 void attach (const char *, int) override;
1423
1424 void post_attach (int) override;
1425 bool supports_disable_randomization () override;
1426 };
1427
1428 struct stop_reply : public notif_event
1429 {
1430 /* The identifier of the thread about this event */
1431 ptid_t ptid;
1432
1433 /* The remote state this event is associated with. When the remote
1434 connection, represented by a remote_state object, is closed,
1435 all the associated stop_reply events should be released. */
1436 struct remote_state *rs;
1437
1438 struct target_waitstatus ws;
1439
1440 /* The architecture associated with the expedited registers. */
1441 gdbarch *arch;
1442
1443 /* Expedited registers. This makes remote debugging a bit more
1444 efficient for those targets that provide critical registers as
1445 part of their normal status mechanism (as another roundtrip to
1446 fetch them is avoided). */
1447 std::vector<cached_reg_t> regcache;
1448
1449 enum target_stop_reason stop_reason;
1450
1451 CORE_ADDR watch_data_address;
1452
1453 int core;
1454 };
1455
1456 /* Return TARGET as a remote_target if it is one, else nullptr. */
1457
1458 static remote_target *
1459 as_remote_target (process_stratum_target *target)
1460 {
1461 return dynamic_cast<remote_target *> (target);
1462 }
1463
1464 /* See remote.h. */
1465
1466 bool
1467 is_remote_target (process_stratum_target *target)
1468 {
1469 return as_remote_target (target) != nullptr;
1470 }
1471
1472 /* Per-program-space data key. */
1473 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1474 remote_pspace_data;
1475
1476 /* The variable registered as the control variable used by the
1477 remote exec-file commands. While the remote exec-file setting is
1478 per-program-space, the set/show machinery uses this as the
1479 location of the remote exec-file value. */
1480 static std::string remote_exec_file_var;
1481
1482 /* The size to align memory write packets, when practical. The protocol
1483 does not guarantee any alignment, and gdb will generate short
1484 writes and unaligned writes, but even as a best-effort attempt this
1485 can improve bulk transfers. For instance, if a write is misaligned
1486 relative to the target's data bus, the stub may need to make an extra
1487 round trip fetching data from the target. This doesn't make a
1488 huge difference, but it's easy to do, so we try to be helpful.
1489
1490 The alignment chosen is arbitrary; usually data bus width is
1491 important here, not the possibly larger cache line size. */
1492 enum { REMOTE_ALIGN_WRITES = 16 };
1493
1494 /* Prototypes for local functions. */
1495
1496 static int hexnumlen (ULONGEST num);
1497
1498 static int stubhex (int ch);
1499
1500 static int hexnumstr (char *, ULONGEST);
1501
1502 static int hexnumnstr (char *, ULONGEST, int);
1503
1504 static CORE_ADDR remote_address_masked (CORE_ADDR);
1505
1506 static int stub_unpack_int (const char *buff, int fieldlength);
1507
1508 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1509 cmd_list_element *c);
1510
1511 static void show_packet_config_cmd (ui_file *file,
1512 const unsigned int which_packet,
1513 remote_target *remote);
1514
1515 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1516 int from_tty,
1517 struct cmd_list_element *c,
1518 const char *value);
1519
1520 static ptid_t read_ptid (const char *buf, const char **obuf);
1521
1522 static bool remote_read_description_p (struct target_ops *target);
1523
1524 static void remote_console_output (const char *msg, ui_file *stream);
1525
1526 static void remote_btrace_reset (remote_state *rs);
1527
1528 static void remote_unpush_and_throw (remote_target *target);
1529
1530 /* For "remote". */
1531
1532 static struct cmd_list_element *remote_cmdlist;
1533
1534 /* For "set remote" and "show remote". */
1535
1536 static struct cmd_list_element *remote_set_cmdlist;
1537 static struct cmd_list_element *remote_show_cmdlist;
1538
1539 /* Controls whether GDB is willing to use range stepping. */
1540
1541 static bool use_range_stepping = true;
1542
1543 /* From the remote target's point of view, each thread is in one of these three
1544 states. */
1545 enum class resume_state
1546 {
1547 /* Not resumed - we haven't been asked to resume this thread. */
1548 NOT_RESUMED,
1549
1550 /* We have been asked to resume this thread, but haven't sent a vCont action
1551 for it yet. We'll need to consider it next time commit_resume is
1552 called. */
1553 RESUMED_PENDING_VCONT,
1554
1555 /* We have been asked to resume this thread, and we have sent a vCont action
1556 for it. */
1557 RESUMED,
1558 };
1559
1560 /* Information about a thread's pending vCont-resume. Used when a thread is in
1561 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1562 stores this information which is then picked up by
1563 remote_target::commit_resume to know which is the proper action for this
1564 thread to include in the vCont packet. */
1565 struct resumed_pending_vcont_info
1566 {
1567 /* True if the last resume call for this thread was a step request, false
1568 if a continue request. */
1569 bool step;
1570
1571 /* The signal specified in the last resume call for this thread. */
1572 gdb_signal sig;
1573 };
1574
1575 /* Private data that we'll store in (struct thread_info)->priv. */
1576 struct remote_thread_info : public private_thread_info
1577 {
1578 std::string extra;
1579 std::string name;
1580 int core = -1;
1581
1582 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1583 sequence of bytes. */
1584 gdb::byte_vector thread_handle;
1585
1586 /* Whether the target stopped for a breakpoint/watchpoint. */
1587 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1588
1589 /* This is set to the data address of the access causing the target
1590 to stop for a watchpoint. */
1591 CORE_ADDR watch_data_address = 0;
1592
1593 /* Get the thread's resume state. */
1594 enum resume_state get_resume_state () const
1595 {
1596 return m_resume_state;
1597 }
1598
1599 /* Put the thread in the NOT_RESUMED state. */
1600 void set_not_resumed ()
1601 {
1602 m_resume_state = resume_state::NOT_RESUMED;
1603 }
1604
1605 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1606 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1607 {
1608 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1609 m_resumed_pending_vcont_info.step = step;
1610 m_resumed_pending_vcont_info.sig = sig;
1611 }
1612
1613 /* Get the information this thread's pending vCont-resumption.
1614
1615 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1616 state. */
1617 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1618 {
1619 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1620
1621 return m_resumed_pending_vcont_info;
1622 }
1623
1624 /* Put the thread in the VCONT_RESUMED state. */
1625 void set_resumed ()
1626 {
1627 m_resume_state = resume_state::RESUMED;
1628 }
1629
1630 private:
1631 /* Resume state for this thread. This is used to implement vCont action
1632 coalescing (only when the target operates in non-stop mode).
1633
1634 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1635 which notes that this thread must be considered in the next commit_resume
1636 call.
1637
1638 remote_target::commit_resume sends a vCont packet with actions for the
1639 threads in the RESUMED_PENDING_VCONT state and moves them to the
1640 VCONT_RESUMED state.
1641
1642 When reporting a stop to the core for a thread, that thread is moved back
1643 to the NOT_RESUMED state. */
1644 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1645
1646 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1647 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1648 };
1649
1650 remote_state::remote_state ()
1651 : buf (400)
1652 {
1653 }
1654
1655 remote_state::~remote_state ()
1656 {
1657 xfree (this->last_pass_packet);
1658 xfree (this->last_program_signals_packet);
1659 xfree (this->finished_object);
1660 xfree (this->finished_annex);
1661 }
1662
1663 /* Utility: generate error from an incoming stub packet. */
1664 static void
1665 trace_error (char *buf)
1666 {
1667 if (*buf++ != 'E')
1668 return; /* not an error msg */
1669 switch (*buf)
1670 {
1671 case '1': /* malformed packet error */
1672 if (*++buf == '0') /* general case: */
1673 error (_("remote.c: error in outgoing packet."));
1674 else
1675 error (_("remote.c: error in outgoing packet at field #%ld."),
1676 strtol (buf, NULL, 16));
1677 default:
1678 error (_("Target returns error code '%s'."), buf);
1679 }
1680 }
1681
1682 /* Utility: wait for reply from stub, while accepting "O" packets. */
1683
1684 char *
1685 remote_target::remote_get_noisy_reply ()
1686 {
1687 struct remote_state *rs = get_remote_state ();
1688
1689 do /* Loop on reply from remote stub. */
1690 {
1691 char *buf;
1692
1693 QUIT; /* Allow user to bail out with ^C. */
1694 getpkt (&rs->buf);
1695 buf = rs->buf.data ();
1696 if (buf[0] == 'E')
1697 trace_error (buf);
1698 else if (startswith (buf, "qRelocInsn:"))
1699 {
1700 ULONGEST ul;
1701 CORE_ADDR from, to, org_to;
1702 const char *p, *pp;
1703 int adjusted_size = 0;
1704 int relocated = 0;
1705
1706 p = buf + strlen ("qRelocInsn:");
1707 pp = unpack_varlen_hex (p, &ul);
1708 if (*pp != ';')
1709 error (_("invalid qRelocInsn packet: %s"), buf);
1710 from = ul;
1711
1712 p = pp + 1;
1713 unpack_varlen_hex (p, &ul);
1714 to = ul;
1715
1716 org_to = to;
1717
1718 try
1719 {
1720 gdbarch_relocate_instruction (current_inferior ()->arch (),
1721 &to, from);
1722 relocated = 1;
1723 }
1724 catch (const gdb_exception &ex)
1725 {
1726 if (ex.error == MEMORY_ERROR)
1727 {
1728 /* Propagate memory errors silently back to the
1729 target. The stub may have limited the range of
1730 addresses we can write to, for example. */
1731 }
1732 else
1733 {
1734 /* Something unexpectedly bad happened. Be verbose
1735 so we can tell what, and propagate the error back
1736 to the stub, so it doesn't get stuck waiting for
1737 a response. */
1738 exception_fprintf (gdb_stderr, ex,
1739 _("warning: relocating instruction: "));
1740 }
1741 putpkt ("E01");
1742 }
1743
1744 if (relocated)
1745 {
1746 adjusted_size = to - org_to;
1747
1748 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1749 putpkt (buf);
1750 }
1751 }
1752 else if (buf[0] == 'O' && buf[1] != 'K')
1753 {
1754 /* 'O' message from stub */
1755 remote_console_output (buf + 1, gdb_stdtarg);
1756 }
1757 else
1758 return buf; /* Here's the actual reply. */
1759 }
1760 while (1);
1761 }
1762
1763 struct remote_arch_state *
1764 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1765 {
1766 remote_arch_state *rsa;
1767
1768 auto it = this->m_arch_states.find (gdbarch);
1769 if (it == this->m_arch_states.end ())
1770 {
1771 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1772 std::forward_as_tuple (gdbarch),
1773 std::forward_as_tuple (gdbarch));
1774 rsa = &p.first->second;
1775
1776 /* Make sure that the packet buffer is plenty big enough for
1777 this architecture. */
1778 if (this->buf.size () < rsa->remote_packet_size)
1779 this->buf.resize (2 * rsa->remote_packet_size);
1780 }
1781 else
1782 rsa = &it->second;
1783
1784 return rsa;
1785 }
1786
1787 /* Fetch the global remote target state. */
1788
1789 remote_state *
1790 remote_target::get_remote_state ()
1791 {
1792 /* Make sure that the remote architecture state has been
1793 initialized, because doing so might reallocate rs->buf. Any
1794 function which calls getpkt also needs to be mindful of changes
1795 to rs->buf, but this call limits the number of places which run
1796 into trouble. */
1797 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1798
1799 return &m_remote_state;
1800 }
1801
1802 /* Fetch the remote exec-file from the current program space. */
1803
1804 static const char *
1805 get_remote_exec_file (void)
1806 {
1807 char *remote_exec_file;
1808
1809 remote_exec_file = remote_pspace_data.get (current_program_space);
1810 if (remote_exec_file == NULL)
1811 return "";
1812
1813 return remote_exec_file;
1814 }
1815
1816 /* Set the remote exec file for PSPACE. */
1817
1818 static void
1819 set_pspace_remote_exec_file (struct program_space *pspace,
1820 const char *remote_exec_file)
1821 {
1822 char *old_file = remote_pspace_data.get (pspace);
1823
1824 xfree (old_file);
1825 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1826 }
1827
1828 /* The "set/show remote exec-file" set command hook. */
1829
1830 static void
1831 set_remote_exec_file (const char *ignored, int from_tty,
1832 struct cmd_list_element *c)
1833 {
1834 set_pspace_remote_exec_file (current_program_space,
1835 remote_exec_file_var.c_str ());
1836 }
1837
1838 /* The "set/show remote exec-file" show command hook. */
1839
1840 static void
1841 show_remote_exec_file (struct ui_file *file, int from_tty,
1842 struct cmd_list_element *cmd, const char *value)
1843 {
1844 gdb_printf (file, "%s\n", get_remote_exec_file ());
1845 }
1846
1847 static int
1848 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1849 {
1850 int regnum, num_remote_regs, offset;
1851 struct packet_reg **remote_regs;
1852
1853 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1854 {
1855 struct packet_reg *r = &regs[regnum];
1856
1857 if (register_size (gdbarch, regnum) == 0)
1858 /* Do not try to fetch zero-sized (placeholder) registers. */
1859 r->pnum = -1;
1860 else
1861 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1862
1863 r->regnum = regnum;
1864 }
1865
1866 /* Define the g/G packet format as the contents of each register
1867 with a remote protocol number, in order of ascending protocol
1868 number. */
1869
1870 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1871 for (num_remote_regs = 0, regnum = 0;
1872 regnum < gdbarch_num_regs (gdbarch);
1873 regnum++)
1874 if (regs[regnum].pnum != -1)
1875 remote_regs[num_remote_regs++] = &regs[regnum];
1876
1877 std::sort (remote_regs, remote_regs + num_remote_regs,
1878 [] (const packet_reg *a, const packet_reg *b)
1879 { return a->pnum < b->pnum; });
1880
1881 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1882 {
1883 remote_regs[regnum]->in_g_packet = 1;
1884 remote_regs[regnum]->offset = offset;
1885 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1886 }
1887
1888 return offset;
1889 }
1890
1891 /* Given the architecture described by GDBARCH, return the remote
1892 protocol register's number and the register's offset in the g/G
1893 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1894 If the target does not have a mapping for REGNUM, return false,
1895 otherwise, return true. */
1896
1897 int
1898 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1899 int *pnum, int *poffset)
1900 {
1901 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1902
1903 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1904
1905 map_regcache_remote_table (gdbarch, regs.data ());
1906
1907 *pnum = regs[regnum].pnum;
1908 *poffset = regs[regnum].offset;
1909
1910 return *pnum != -1;
1911 }
1912
1913 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1914 {
1915 /* Use the architecture to build a regnum<->pnum table, which will be
1916 1:1 unless a feature set specifies otherwise. */
1917 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1918
1919 /* Record the maximum possible size of the g packet - it may turn out
1920 to be smaller. */
1921 this->sizeof_g_packet
1922 = map_regcache_remote_table (gdbarch, this->regs.get ());
1923
1924 /* Default maximum number of characters in a packet body. Many
1925 remote stubs have a hardwired buffer size of 400 bytes
1926 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1927 as the maximum packet-size to ensure that the packet and an extra
1928 NUL character can always fit in the buffer. This stops GDB
1929 trashing stubs that try to squeeze an extra NUL into what is
1930 already a full buffer (As of 1999-12-04 that was most stubs). */
1931 this->remote_packet_size = 400 - 1;
1932
1933 /* This one is filled in when a ``g'' packet is received. */
1934 this->actual_register_packet_size = 0;
1935
1936 /* Should rsa->sizeof_g_packet needs more space than the
1937 default, adjust the size accordingly. Remember that each byte is
1938 encoded as two characters. 32 is the overhead for the packet
1939 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1940 (``$NN:G...#NN'') is a better guess, the below has been padded a
1941 little. */
1942 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1943 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1944 }
1945
1946 /* Get a pointer to the current remote target. If not connected to a
1947 remote target, return NULL. */
1948
1949 static remote_target *
1950 get_current_remote_target ()
1951 {
1952 target_ops *proc_target = current_inferior ()->process_target ();
1953 return dynamic_cast<remote_target *> (proc_target);
1954 }
1955
1956 /* Return the current allowed size of a remote packet. This is
1957 inferred from the current architecture, and should be used to
1958 limit the length of outgoing packets. */
1959 long
1960 remote_target::get_remote_packet_size ()
1961 {
1962 struct remote_state *rs = get_remote_state ();
1963 remote_arch_state *rsa
1964 = rs->get_remote_arch_state (current_inferior ()->arch ());
1965
1966 if (rs->explicit_packet_size)
1967 return rs->explicit_packet_size;
1968
1969 return rsa->remote_packet_size;
1970 }
1971
1972 static struct packet_reg *
1973 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1974 long regnum)
1975 {
1976 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1977 return NULL;
1978 else
1979 {
1980 struct packet_reg *r = &rsa->regs[regnum];
1981
1982 gdb_assert (r->regnum == regnum);
1983 return r;
1984 }
1985 }
1986
1987 static struct packet_reg *
1988 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1989 LONGEST pnum)
1990 {
1991 int i;
1992
1993 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1994 {
1995 struct packet_reg *r = &rsa->regs[i];
1996
1997 if (r->pnum == pnum)
1998 return r;
1999 }
2000 return NULL;
2001 }
2002
2003 /* Allow the user to specify what sequence to send to the remote
2004 when he requests a program interruption: Although ^C is usually
2005 what remote systems expect (this is the default, here), it is
2006 sometimes preferable to send a break. On other systems such
2007 as the Linux kernel, a break followed by g, which is Magic SysRq g
2008 is required in order to interrupt the execution. */
2009 const char interrupt_sequence_control_c[] = "Ctrl-C";
2010 const char interrupt_sequence_break[] = "BREAK";
2011 const char interrupt_sequence_break_g[] = "BREAK-g";
2012 static const char *const interrupt_sequence_modes[] =
2013 {
2014 interrupt_sequence_control_c,
2015 interrupt_sequence_break,
2016 interrupt_sequence_break_g,
2017 NULL
2018 };
2019 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
2020
2021 static void
2022 show_interrupt_sequence (struct ui_file *file, int from_tty,
2023 struct cmd_list_element *c,
2024 const char *value)
2025 {
2026 if (interrupt_sequence_mode == interrupt_sequence_control_c)
2027 gdb_printf (file,
2028 _("Send the ASCII ETX character (Ctrl-c) "
2029 "to the remote target to interrupt the "
2030 "execution of the program.\n"));
2031 else if (interrupt_sequence_mode == interrupt_sequence_break)
2032 gdb_printf (file,
2033 _("send a break signal to the remote target "
2034 "to interrupt the execution of the program.\n"));
2035 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
2036 gdb_printf (file,
2037 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
2038 "the remote target to interrupt the execution "
2039 "of Linux kernel.\n"));
2040 else
2041 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
2042 interrupt_sequence_mode);
2043 }
2044
2045 /* This boolean variable specifies whether interrupt_sequence is sent
2046 to the remote target when gdb connects to it.
2047 This is mostly needed when you debug the Linux kernel: The Linux kernel
2048 expects BREAK g which is Magic SysRq g for connecting gdb. */
2049 static bool interrupt_on_connect = false;
2050
2051 /* This variable is used to implement the "set/show remotebreak" commands.
2052 Since these commands are now deprecated in favor of "set/show remote
2053 interrupt-sequence", it no longer has any effect on the code. */
2054 static bool remote_break;
2055
2056 static void
2057 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
2058 {
2059 if (remote_break)
2060 interrupt_sequence_mode = interrupt_sequence_break;
2061 else
2062 interrupt_sequence_mode = interrupt_sequence_control_c;
2063 }
2064
2065 static void
2066 show_remotebreak (struct ui_file *file, int from_tty,
2067 struct cmd_list_element *c,
2068 const char *value)
2069 {
2070 }
2071
2072 /* This variable sets the number of bits in an address that are to be
2073 sent in a memory ("M" or "m") packet. Normally, after stripping
2074 leading zeros, the entire address would be sent. This variable
2075 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2076 initial implementation of remote.c restricted the address sent in
2077 memory packets to ``host::sizeof long'' bytes - (typically 32
2078 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2079 address was never sent. Since fixing this bug may cause a break in
2080 some remote targets this variable is principally provided to
2081 facilitate backward compatibility. */
2082
2083 static unsigned int remote_address_size;
2084
2085 \f
2086 /* The default max memory-write-packet-size, when the setting is
2087 "fixed". The 16k is historical. (It came from older GDB's using
2088 alloca for buffers and the knowledge (folklore?) that some hosts
2089 don't cope very well with large alloca calls.) */
2090 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2091
2092 /* The minimum remote packet size for memory transfers. Ensures we
2093 can write at least one byte. */
2094 #define MIN_MEMORY_PACKET_SIZE 20
2095
2096 /* Get the memory packet size, assuming it is fixed. */
2097
2098 static long
2099 get_fixed_memory_packet_size (struct memory_packet_config *config)
2100 {
2101 gdb_assert (config->fixed_p);
2102
2103 if (config->size <= 0)
2104 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2105 else
2106 return config->size;
2107 }
2108
2109 /* Compute the current size of a read/write packet. Since this makes
2110 use of ``actual_register_packet_size'' the computation is dynamic. */
2111
2112 long
2113 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2114 {
2115 struct remote_state *rs = get_remote_state ();
2116 remote_arch_state *rsa
2117 = rs->get_remote_arch_state (current_inferior ()->arch ());
2118
2119 long what_they_get;
2120 if (config->fixed_p)
2121 what_they_get = get_fixed_memory_packet_size (config);
2122 else
2123 {
2124 what_they_get = get_remote_packet_size ();
2125 /* Limit the packet to the size specified by the user. */
2126 if (config->size > 0
2127 && what_they_get > config->size)
2128 what_they_get = config->size;
2129
2130 /* Limit it to the size of the targets ``g'' response unless we have
2131 permission from the stub to use a larger packet size. */
2132 if (rs->explicit_packet_size == 0
2133 && rsa->actual_register_packet_size > 0
2134 && what_they_get > rsa->actual_register_packet_size)
2135 what_they_get = rsa->actual_register_packet_size;
2136 }
2137 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2138 what_they_get = MIN_MEMORY_PACKET_SIZE;
2139
2140 /* Make sure there is room in the global buffer for this packet
2141 (including its trailing NUL byte). */
2142 if (rs->buf.size () < what_they_get + 1)
2143 rs->buf.resize (2 * what_they_get);
2144
2145 return what_they_get;
2146 }
2147
2148 /* Update the size of a read/write packet. If they user wants
2149 something really big then do a sanity check. */
2150
2151 static void
2152 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2153 bool target_connected)
2154 {
2155 int fixed_p = config->fixed_p;
2156 long size = config->size;
2157
2158 if (args == NULL)
2159 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2160 else if (strcmp (args, "hard") == 0
2161 || strcmp (args, "fixed") == 0)
2162 fixed_p = 1;
2163 else if (strcmp (args, "soft") == 0
2164 || strcmp (args, "limit") == 0)
2165 fixed_p = 0;
2166 else
2167 {
2168 char *end;
2169
2170 size = strtoul (args, &end, 0);
2171 if (args == end)
2172 error (_("Invalid %s (bad syntax)."), config->name);
2173
2174 /* Instead of explicitly capping the size of a packet to or
2175 disallowing it, the user is allowed to set the size to
2176 something arbitrarily large. */
2177 }
2178
2179 /* Extra checks? */
2180 if (fixed_p && !config->fixed_p)
2181 {
2182 /* So that the query shows the correct value. */
2183 long query_size = (size <= 0
2184 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2185 : size);
2186
2187 if (target_connected
2188 && !query (_("The target may not be able to correctly handle a %s\n"
2189 "of %ld bytes. Change the packet size? "),
2190 config->name, query_size))
2191 error (_("Packet size not changed."));
2192 else if (!target_connected
2193 && !query (_("Future remote targets may not be able to "
2194 "correctly handle a %s\nof %ld bytes. Change the "
2195 "packet size for future remote targets? "),
2196 config->name, query_size))
2197 error (_("Packet size not changed."));
2198 }
2199 /* Update the config. */
2200 config->fixed_p = fixed_p;
2201 config->size = size;
2202
2203 const char *target_type = get_target_type_name (target_connected);
2204 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2205 args);
2206
2207 }
2208
2209 /* Show the memory-read or write-packet size configuration CONFIG of the
2210 target REMOTE. If REMOTE is nullptr, the default configuration for future
2211 remote targets should be passed in CONFIG. */
2212
2213 static void
2214 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2215 {
2216 const char *target_type = get_target_type_name (remote != nullptr);
2217
2218 if (config->size == 0)
2219 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2220 else
2221 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2222 config->size);
2223
2224 if (config->fixed_p)
2225 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2226 get_fixed_memory_packet_size (config));
2227 else
2228 {
2229 if (remote != nullptr)
2230 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2231 remote->get_memory_packet_size (config));
2232 else
2233 gdb_puts ("The actual limit will be further reduced "
2234 "dependent on the target.\n");
2235 }
2236 }
2237
2238 /* Configure the memory-write-packet size of the currently selected target. If
2239 no target is available, the default configuration for future remote targets
2240 is configured. */
2241
2242 static void
2243 set_memory_write_packet_size (const char *args, int from_tty)
2244 {
2245 remote_target *remote = get_current_remote_target ();
2246 if (remote != nullptr)
2247 {
2248 set_memory_packet_size
2249 (args, &remote->m_features.m_memory_write_packet_config, true);
2250 }
2251 else
2252 {
2253 memory_packet_config* config = &memory_write_packet_config;
2254 set_memory_packet_size (args, config, false);
2255 }
2256 }
2257
2258 /* Display the memory-write-packet size of the currently selected target. If
2259 no target is available, the default configuration for future remote targets
2260 is shown. */
2261
2262 static void
2263 show_memory_write_packet_size (const char *args, int from_tty)
2264 {
2265 remote_target *remote = get_current_remote_target ();
2266 if (remote != nullptr)
2267 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2268 remote);
2269 else
2270 show_memory_packet_size (&memory_write_packet_config, nullptr);
2271 }
2272
2273 /* Show the number of hardware watchpoints that can be used. */
2274
2275 static void
2276 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2277 struct cmd_list_element *c,
2278 const char *value)
2279 {
2280 gdb_printf (file, _("The maximum number of target hardware "
2281 "watchpoints is %s.\n"), value);
2282 }
2283
2284 /* Show the length limit (in bytes) for hardware watchpoints. */
2285
2286 static void
2287 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2288 struct cmd_list_element *c,
2289 const char *value)
2290 {
2291 gdb_printf (file, _("The maximum length (in bytes) of a target "
2292 "hardware watchpoint is %s.\n"), value);
2293 }
2294
2295 /* Show the number of hardware breakpoints that can be used. */
2296
2297 static void
2298 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2299 struct cmd_list_element *c,
2300 const char *value)
2301 {
2302 gdb_printf (file, _("The maximum number of target hardware "
2303 "breakpoints is %s.\n"), value);
2304 }
2305
2306 /* Controls the maximum number of characters to display in the debug output
2307 for each remote packet. The remaining characters are omitted. */
2308
2309 static int remote_packet_max_chars = 512;
2310
2311 /* Show the maximum number of characters to display for each remote packet
2312 when remote debugging is enabled. */
2313
2314 static void
2315 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2316 struct cmd_list_element *c,
2317 const char *value)
2318 {
2319 gdb_printf (file, _("Number of remote packet characters to "
2320 "display is %s.\n"), value);
2321 }
2322
2323 long
2324 remote_target::get_memory_write_packet_size ()
2325 {
2326 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2327 }
2328
2329 /* Configure the memory-read-packet size of the currently selected target. If
2330 no target is available, the default configuration for future remote targets
2331 is adapted. */
2332
2333 static void
2334 set_memory_read_packet_size (const char *args, int from_tty)
2335 {
2336 remote_target *remote = get_current_remote_target ();
2337 if (remote != nullptr)
2338 set_memory_packet_size
2339 (args, &remote->m_features.m_memory_read_packet_config, true);
2340 else
2341 {
2342 memory_packet_config* config = &memory_read_packet_config;
2343 set_memory_packet_size (args, config, false);
2344 }
2345
2346 }
2347
2348 /* Display the memory-read-packet size of the currently selected target. If
2349 no target is available, the default configuration for future remote targets
2350 is shown. */
2351
2352 static void
2353 show_memory_read_packet_size (const char *args, int from_tty)
2354 {
2355 remote_target *remote = get_current_remote_target ();
2356 if (remote != nullptr)
2357 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2358 remote);
2359 else
2360 show_memory_packet_size (&memory_read_packet_config, nullptr);
2361 }
2362
2363 long
2364 remote_target::get_memory_read_packet_size ()
2365 {
2366 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2367
2368 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2369 extra buffer size argument before the memory read size can be
2370 increased beyond this. */
2371 if (size > get_remote_packet_size ())
2372 size = get_remote_packet_size ();
2373 return size;
2374 }
2375
2376 static enum packet_support packet_config_support (const packet_config *config);
2377
2378
2379 static void
2380 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2381 cmd_list_element *c)
2382 {
2383 remote_target *remote = get_current_remote_target ();
2384 gdb_assert (c->var.has_value ());
2385
2386 auto *default_config = static_cast<packet_config *> (c->context ());
2387 const int packet_idx = std::distance (remote_protocol_packets,
2388 default_config);
2389
2390 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2391 {
2392 const char *name = packets_descriptions[packet_idx].name;
2393 const auto_boolean value = c->var->get<auto_boolean> ();
2394 const char *support = get_packet_support_name (value);
2395 const char *target_type = get_target_type_name (remote != nullptr);
2396
2397 if (remote != nullptr)
2398 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2399 else
2400 remote_protocol_packets[packet_idx].detect = value;
2401
2402 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2403 target_type, support);
2404 return;
2405 }
2406
2407 internal_error (_("Could not find config for %s"), c->name);
2408 }
2409
2410 static void
2411 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2412 remote_target *remote)
2413 {
2414 const char *support = "internal-error";
2415 const char *target_type = get_target_type_name (remote != nullptr);
2416
2417 packet_config *config;
2418 if (remote != nullptr)
2419 config = &remote->m_features.m_protocol_packets[which_packet];
2420 else
2421 config = &remote_protocol_packets[which_packet];
2422
2423 switch (packet_config_support (config))
2424 {
2425 case PACKET_ENABLE:
2426 support = "enabled";
2427 break;
2428 case PACKET_DISABLE:
2429 support = "disabled";
2430 break;
2431 case PACKET_SUPPORT_UNKNOWN:
2432 support = "unknown";
2433 break;
2434 }
2435 switch (config->detect)
2436 {
2437 case AUTO_BOOLEAN_AUTO:
2438 gdb_printf (file,
2439 _("Support for the '%s' packet %s is \"auto\", "
2440 "currently %s.\n"),
2441 packets_descriptions[which_packet].name, target_type,
2442 support);
2443 break;
2444 case AUTO_BOOLEAN_TRUE:
2445 case AUTO_BOOLEAN_FALSE:
2446 gdb_printf (file,
2447 _("Support for the '%s' packet %s is \"%s\".\n"),
2448 packets_descriptions[which_packet].name, target_type,
2449 get_packet_support_name (config->detect));
2450 break;
2451 }
2452 }
2453
2454 static void
2455 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2456 const char *title, int legacy)
2457 {
2458 packets_descriptions[which_packet].name = name;
2459 packets_descriptions[which_packet].title = title;
2460
2461 packet_config *config = &remote_protocol_packets[which_packet];
2462
2463 gdb::unique_xmalloc_ptr<char> set_doc
2464 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2465 name, title);
2466 gdb::unique_xmalloc_ptr<char> show_doc
2467 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2468 name, title);
2469 /* set/show TITLE-packet {auto,on,off} */
2470 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2471 set_show_commands cmds
2472 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2473 &config->detect, set_doc.get (),
2474 show_doc.get (), NULL, /* help_doc */
2475 set_remote_protocol_packet_cmd,
2476 show_remote_protocol_packet_cmd,
2477 &remote_set_cmdlist, &remote_show_cmdlist);
2478 cmds.show->set_context (config);
2479 cmds.set->set_context (config);
2480
2481 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2482 if (legacy)
2483 {
2484 /* It's not clear who should take ownership of the LEGACY_NAME string
2485 created below, so, for now, place the string into a static vector
2486 which ensures the strings is released when GDB exits. */
2487 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2488 gdb::unique_xmalloc_ptr<char> legacy_name
2489 = xstrprintf ("%s-packet", name);
2490 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2491 &remote_set_cmdlist);
2492 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2493 &remote_show_cmdlist);
2494 legacy_names.emplace_back (std::move (legacy_name));
2495 }
2496 }
2497
2498 /* Check GDBserver's reply packet. Return packet_result structure
2499 which contains the packet_status enum and an error message for the
2500 PACKET_ERROR case.
2501
2502 An error packet can always take the form Exx (where xx is a hex
2503 code). When ACCEPT_MSG is true error messages can also take the
2504 form E.msg (where msg is any arbitrary string). */
2505 static packet_result
2506 packet_check_result (const char *buf, bool accept_msg)
2507 {
2508 if (buf[0] != '\0')
2509 {
2510 /* The stub recognized the packet request. Check that the
2511 operation succeeded. */
2512 if (buf[0] == 'E'
2513 && isxdigit (buf[1]) && isxdigit (buf[2])
2514 && buf[3] == '\0')
2515 /* "Enn" - definitely an error. */
2516 return packet_result::make_numeric_error (buf + 1);
2517
2518 /* Not every request accepts an error in a E.msg form.
2519 Some packets accepts only Enn, in this case E. is not
2520 defined and E. is treated as PACKET_OK. */
2521 if (accept_msg)
2522 {
2523 /* Always treat "E." as an error. This will be used for
2524 more verbose error messages, such as E.memtypes. */
2525 if (buf[0] == 'E' && buf[1] == '.')
2526 {
2527 if (buf[2] != '\0')
2528 return packet_result::make_textual_error (buf + 2);
2529 else
2530 return packet_result::make_textual_error ("no error provided");
2531 }
2532 }
2533
2534 /* The packet may or may not be OK. Just assume it is. */
2535 return packet_result::make_ok ();
2536 }
2537 else
2538 {
2539 /* The stub does not support the packet. */
2540 return packet_result::make_unknown ();
2541 }
2542 }
2543
2544 static packet_result
2545 packet_check_result (const gdb::char_vector &buf, bool accept_msg)
2546 {
2547 return packet_check_result (buf.data (), accept_msg);
2548 }
2549
2550 packet_result
2551 remote_features::packet_ok (const char *buf, const int which_packet)
2552 {
2553 packet_config *config = &m_protocol_packets[which_packet];
2554 packet_description *descr = &packets_descriptions[which_packet];
2555
2556 if (config->detect != AUTO_BOOLEAN_TRUE
2557 && config->support == PACKET_DISABLE)
2558 internal_error (_("packet_ok: attempt to use a disabled packet"));
2559
2560 packet_result result = packet_check_result (buf, true);
2561 switch (result.status ())
2562 {
2563 case PACKET_OK:
2564 case PACKET_ERROR:
2565 /* The stub recognized the packet request. */
2566 if (config->support == PACKET_SUPPORT_UNKNOWN)
2567 {
2568 remote_debug_printf ("Packet %s (%s) is supported",
2569 descr->name, descr->title);
2570 config->support = PACKET_ENABLE;
2571 }
2572 break;
2573 case PACKET_UNKNOWN:
2574 /* The stub does not support the packet. */
2575 if (config->detect == AUTO_BOOLEAN_AUTO
2576 && config->support == PACKET_ENABLE)
2577 {
2578 /* If the stub previously indicated that the packet was
2579 supported then there is a protocol error. */
2580 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2581 descr->name, descr->title);
2582 }
2583 else if (config->detect == AUTO_BOOLEAN_TRUE)
2584 {
2585 /* The user set it wrong. */
2586 error (_("Enabled packet %s (%s) not recognized by stub"),
2587 descr->name, descr->title);
2588 }
2589
2590 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2591 descr->title);
2592 config->support = PACKET_DISABLE;
2593 break;
2594 }
2595
2596 return result;
2597 }
2598
2599 packet_result
2600 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2601 {
2602 return packet_ok (buf.data (), which_packet);
2603 }
2604
2605 /* Returns whether a given packet or feature is supported. This takes
2606 into account the state of the corresponding "set remote foo-packet"
2607 command, which may be used to bypass auto-detection. */
2608
2609 static enum packet_support
2610 packet_config_support (const packet_config *config)
2611 {
2612 switch (config->detect)
2613 {
2614 case AUTO_BOOLEAN_TRUE:
2615 return PACKET_ENABLE;
2616 case AUTO_BOOLEAN_FALSE:
2617 return PACKET_DISABLE;
2618 case AUTO_BOOLEAN_AUTO:
2619 return config->support;
2620 default:
2621 gdb_assert_not_reached ("bad switch");
2622 }
2623 }
2624
2625 packet_support
2626 remote_features::packet_support (int packet) const
2627 {
2628 const packet_config *config = &m_protocol_packets[packet];
2629 return packet_config_support (config);
2630 }
2631
2632 static void
2633 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2634 struct cmd_list_element *c,
2635 const char *value)
2636 {
2637 remote_target *remote = get_current_remote_target ();
2638 gdb_assert (c->var.has_value ());
2639
2640 auto *default_config = static_cast<packet_config *> (c->context ());
2641 const int packet_idx = std::distance (remote_protocol_packets,
2642 default_config);
2643
2644 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2645 {
2646 show_packet_config_cmd (file, packet_idx, remote);
2647 return;
2648 }
2649 internal_error (_("Could not find config for %s"), c->name);
2650 }
2651
2652 /* Should we try one of the 'Z' requests? */
2653
2654 enum Z_packet_type
2655 {
2656 Z_PACKET_SOFTWARE_BP,
2657 Z_PACKET_HARDWARE_BP,
2658 Z_PACKET_WRITE_WP,
2659 Z_PACKET_READ_WP,
2660 Z_PACKET_ACCESS_WP,
2661 NR_Z_PACKET_TYPES
2662 };
2663
2664 /* For compatibility with older distributions. Provide a ``set remote
2665 Z-packet ...'' command that updates all the Z packet types. */
2666
2667 static enum auto_boolean remote_Z_packet_detect;
2668
2669 static void
2670 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2671 struct cmd_list_element *c)
2672 {
2673 remote_target *remote = get_current_remote_target ();
2674 int i;
2675
2676 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2677 {
2678 if (remote != nullptr)
2679 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2680 = remote_Z_packet_detect;
2681 else
2682 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2683 }
2684
2685 const char *support = get_packet_support_name (remote_Z_packet_detect);
2686 const char *target_type = get_target_type_name (remote != nullptr);
2687 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2688 support);
2689
2690 }
2691
2692 static void
2693 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2694 struct cmd_list_element *c,
2695 const char *value)
2696 {
2697 remote_target *remote = get_current_remote_target ();
2698 int i;
2699
2700 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2701 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2702 }
2703
2704 /* Insert fork catchpoint target routine. If fork events are enabled
2705 then return success, nothing more to do. */
2706
2707 int
2708 remote_target::insert_fork_catchpoint (int pid)
2709 {
2710 return !m_features.remote_fork_event_p ();
2711 }
2712
2713 /* Remove fork catchpoint target routine. Nothing to do, just
2714 return success. */
2715
2716 int
2717 remote_target::remove_fork_catchpoint (int pid)
2718 {
2719 return 0;
2720 }
2721
2722 /* Insert vfork catchpoint target routine. If vfork events are enabled
2723 then return success, nothing more to do. */
2724
2725 int
2726 remote_target::insert_vfork_catchpoint (int pid)
2727 {
2728 return !m_features.remote_vfork_event_p ();
2729 }
2730
2731 /* Remove vfork catchpoint target routine. Nothing to do, just
2732 return success. */
2733
2734 int
2735 remote_target::remove_vfork_catchpoint (int pid)
2736 {
2737 return 0;
2738 }
2739
2740 /* Insert exec catchpoint target routine. If exec events are
2741 enabled, just return success. */
2742
2743 int
2744 remote_target::insert_exec_catchpoint (int pid)
2745 {
2746 return !m_features.remote_exec_event_p ();
2747 }
2748
2749 /* Remove exec catchpoint target routine. Nothing to do, just
2750 return success. */
2751
2752 int
2753 remote_target::remove_exec_catchpoint (int pid)
2754 {
2755 return 0;
2756 }
2757
2758 \f
2759
2760 /* Take advantage of the fact that the TID field is not used, to tag
2761 special ptids with it set to != 0. */
2762 static const ptid_t magic_null_ptid (42000, -1, 1);
2763 static const ptid_t not_sent_ptid (42000, -2, 1);
2764 static const ptid_t any_thread_ptid (42000, 0, 1);
2765
2766 /* Find out if the stub attached to PID (and hence GDB should offer to
2767 detach instead of killing it when bailing out). */
2768
2769 int
2770 remote_target::remote_query_attached (int pid)
2771 {
2772 struct remote_state *rs = get_remote_state ();
2773 size_t size = get_remote_packet_size ();
2774
2775 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2776 return 0;
2777
2778 if (m_features.remote_multi_process_p ())
2779 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2780 else
2781 xsnprintf (rs->buf.data (), size, "qAttached");
2782
2783 putpkt (rs->buf);
2784 getpkt (&rs->buf);
2785
2786 packet_result result = m_features.packet_ok (rs->buf, PACKET_qAttached);
2787 switch (result.status ())
2788 {
2789 case PACKET_OK:
2790 if (strcmp (rs->buf.data (), "1") == 0)
2791 return 1;
2792 break;
2793 case PACKET_ERROR:
2794 warning (_("Remote failure reply: %s"), result.err_msg ());
2795 break;
2796 case PACKET_UNKNOWN:
2797 break;
2798 }
2799
2800 return 0;
2801 }
2802
2803 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2804 has been invented by GDB, instead of reported by the target. Since
2805 we can be connected to a remote system before before knowing about
2806 any inferior, mark the target with execution when we find the first
2807 inferior. If ATTACHED is 1, then we had just attached to this
2808 inferior. If it is 0, then we just created this inferior. If it
2809 is -1, then try querying the remote stub to find out if it had
2810 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2811 attempt to open this inferior's executable as the main executable
2812 if no main executable is open already. */
2813
2814 inferior *
2815 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2816 int try_open_exec)
2817 {
2818 struct inferior *inf;
2819
2820 /* Check whether this process we're learning about is to be
2821 considered attached, or if is to be considered to have been
2822 spawned by the stub. */
2823 if (attached == -1)
2824 attached = remote_query_attached (pid);
2825
2826 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2827 {
2828 /* If the target shares code across all inferiors, then every
2829 attach adds a new inferior. */
2830 inf = add_inferior (pid);
2831
2832 /* ... and every inferior is bound to the same program space.
2833 However, each inferior may still have its own address
2834 space. */
2835 inf->aspace = maybe_new_address_space ();
2836 inf->pspace = current_program_space;
2837 }
2838 else
2839 {
2840 /* In the traditional debugging scenario, there's a 1-1 match
2841 between program/address spaces. We simply bind the inferior
2842 to the program space's address space. */
2843 inf = current_inferior ();
2844
2845 /* However, if the current inferior is already bound to a
2846 process, find some other empty inferior. */
2847 if (inf->pid != 0)
2848 {
2849 inf = nullptr;
2850 for (inferior *it : all_inferiors ())
2851 if (it->pid == 0)
2852 {
2853 inf = it;
2854 break;
2855 }
2856 }
2857 if (inf == nullptr)
2858 {
2859 /* Since all inferiors were already bound to a process, add
2860 a new inferior. */
2861 inf = add_inferior_with_spaces ();
2862 }
2863 switch_to_inferior_no_thread (inf);
2864 inf->push_target (this);
2865 inferior_appeared (inf, pid);
2866 }
2867
2868 inf->attach_flag = attached;
2869 inf->fake_pid_p = fake_pid_p;
2870
2871 /* If no main executable is currently open then attempt to
2872 open the file that was executed to create this inferior. */
2873 if (try_open_exec && get_exec_file (0) == NULL)
2874 exec_file_locate_attach (pid, 0, 1);
2875
2876 /* Check for exec file mismatch, and let the user solve it. */
2877 validate_exec_file (1);
2878
2879 return inf;
2880 }
2881
2882 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2883 static remote_thread_info *get_remote_thread_info (remote_target *target,
2884 ptid_t ptid);
2885
2886 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2887 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2888 remote_state::starting_up flag) is true then the new thread is added
2889 silently, otherwise the new thread will be announced to the user. */
2890
2891 thread_info *
2892 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2893 bool silent_p)
2894 {
2895 struct remote_state *rs = get_remote_state ();
2896 struct thread_info *thread;
2897
2898 /* GDB historically didn't pull threads in the initial connection
2899 setup. If the remote target doesn't even have a concept of
2900 threads (e.g., a bare-metal target), even if internally we
2901 consider that a single-threaded target, mentioning a new thread
2902 might be confusing to the user. Be silent then, preserving the
2903 age old behavior. */
2904 if (rs->starting_up || silent_p)
2905 thread = add_thread_silent (this, ptid);
2906 else
2907 thread = add_thread (this, ptid);
2908
2909 if (executing)
2910 get_remote_thread_info (thread)->set_resumed ();
2911 set_executing (this, ptid, executing);
2912 set_running (this, ptid, running);
2913
2914 return thread;
2915 }
2916
2917 /* Come here when we learn about a thread id from the remote target.
2918 It may be the first time we hear about such thread, so take the
2919 opportunity to add it to GDB's thread list. In case this is the
2920 first time we're noticing its corresponding inferior, add it to
2921 GDB's inferior list as well. EXECUTING indicates whether the
2922 thread is (internally) executing or stopped. */
2923
2924 void
2925 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2926 {
2927 /* In non-stop mode, we assume new found threads are (externally)
2928 running until proven otherwise with a stop reply. In all-stop,
2929 we can only get here if all threads are stopped. */
2930 bool running = target_is_non_stop_p ();
2931
2932 /* If this is a new thread, add it to GDB's thread list.
2933 If we leave it up to WFI to do this, bad things will happen. */
2934
2935 thread_info *tp = this->find_thread (currthread);
2936 if (tp != NULL && tp->state == THREAD_EXITED)
2937 {
2938 /* We're seeing an event on a thread id we knew had exited.
2939 This has to be a new thread reusing the old id. Add it. */
2940 remote_add_thread (currthread, running, executing, false);
2941 return;
2942 }
2943
2944 if (!in_thread_list (this, currthread))
2945 {
2946 struct inferior *inf = NULL;
2947 int pid = currthread.pid ();
2948
2949 if (inferior_ptid.is_pid ()
2950 && pid == inferior_ptid.pid ())
2951 {
2952 /* inferior_ptid has no thread member yet. This can happen
2953 with the vAttach -> remote_wait,"TAAthread:" path if the
2954 stub doesn't support qC. This is the first stop reported
2955 after an attach, so this is the main thread. Update the
2956 ptid in the thread list. */
2957 if (in_thread_list (this, ptid_t (pid)))
2958 thread_change_ptid (this, inferior_ptid, currthread);
2959 else
2960 {
2961 thread_info *thr
2962 = remote_add_thread (currthread, running, executing, false);
2963 switch_to_thread (thr);
2964 }
2965 return;
2966 }
2967
2968 if (magic_null_ptid == inferior_ptid)
2969 {
2970 /* inferior_ptid is not set yet. This can happen with the
2971 vRun -> remote_wait,"TAAthread:" path if the stub
2972 doesn't support qC. This is the first stop reported
2973 after an attach, so this is the main thread. Update the
2974 ptid in the thread list. */
2975 thread_change_ptid (this, inferior_ptid, currthread);
2976 return;
2977 }
2978
2979 /* When connecting to a target remote, or to a target
2980 extended-remote which already was debugging an inferior, we
2981 may not know about it yet. Add it before adding its child
2982 thread, so notifications are emitted in a sensible order. */
2983 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2984 {
2985 bool fake_pid_p = !m_features.remote_multi_process_p ();
2986
2987 inf = remote_add_inferior (fake_pid_p,
2988 currthread.pid (), -1, 1);
2989 }
2990
2991 /* This is really a new thread. Add it. */
2992 thread_info *new_thr
2993 = remote_add_thread (currthread, running, executing, false);
2994
2995 /* If we found a new inferior, let the common code do whatever
2996 it needs to with it (e.g., read shared libraries, insert
2997 breakpoints), unless we're just setting up an all-stop
2998 connection. */
2999 if (inf != NULL)
3000 {
3001 struct remote_state *rs = get_remote_state ();
3002
3003 if (!rs->starting_up)
3004 notice_new_inferior (new_thr, executing, 0);
3005 }
3006 }
3007 }
3008
3009 /* Return THREAD's private thread data, creating it if necessary. */
3010
3011 static remote_thread_info *
3012 get_remote_thread_info (thread_info *thread)
3013 {
3014 gdb_assert (thread != NULL);
3015
3016 if (thread->priv == NULL)
3017 thread->priv.reset (new remote_thread_info);
3018
3019 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
3020 }
3021
3022 /* Return PTID's private thread data, creating it if necessary. */
3023
3024 static remote_thread_info *
3025 get_remote_thread_info (remote_target *target, ptid_t ptid)
3026 {
3027 thread_info *thr = target->find_thread (ptid);
3028 return get_remote_thread_info (thr);
3029 }
3030
3031 /* Call this function as a result of
3032 1) A halt indication (T packet) containing a thread id
3033 2) A direct query of currthread
3034 3) Successful execution of set thread */
3035
3036 static void
3037 record_currthread (struct remote_state *rs, ptid_t currthread)
3038 {
3039 rs->general_thread = currthread;
3040 }
3041
3042 /* If 'QPassSignals' is supported, tell the remote stub what signals
3043 it can simply pass through to the inferior without reporting. */
3044
3045 void
3046 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
3047 {
3048 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
3049 {
3050 char *pass_packet, *p;
3051 int count = 0;
3052 struct remote_state *rs = get_remote_state ();
3053
3054 gdb_assert (pass_signals.size () < 256);
3055 for (size_t i = 0; i < pass_signals.size (); i++)
3056 {
3057 if (pass_signals[i])
3058 count++;
3059 }
3060 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
3061 strcpy (pass_packet, "QPassSignals:");
3062 p = pass_packet + strlen (pass_packet);
3063 for (size_t i = 0; i < pass_signals.size (); i++)
3064 {
3065 if (pass_signals[i])
3066 {
3067 if (i >= 16)
3068 *p++ = tohex (i >> 4);
3069 *p++ = tohex (i & 15);
3070 if (count)
3071 *p++ = ';';
3072 else
3073 break;
3074 count--;
3075 }
3076 }
3077 *p = 0;
3078 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
3079 {
3080 putpkt (pass_packet);
3081 getpkt (&rs->buf);
3082 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
3083 xfree (rs->last_pass_packet);
3084 rs->last_pass_packet = pass_packet;
3085 }
3086 else
3087 xfree (pass_packet);
3088 }
3089 }
3090
3091 /* If 'QCatchSyscalls' is supported, tell the remote stub
3092 to report syscalls to GDB. */
3093
3094 int
3095 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3096 gdb::array_view<const int> syscall_counts)
3097 {
3098 const char *catch_packet;
3099 int n_sysno = 0;
3100
3101 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3102 {
3103 /* Not supported. */
3104 return 1;
3105 }
3106
3107 if (needed && any_count == 0)
3108 {
3109 /* Count how many syscalls are to be caught. */
3110 for (size_t i = 0; i < syscall_counts.size (); i++)
3111 {
3112 if (syscall_counts[i] != 0)
3113 n_sysno++;
3114 }
3115 }
3116
3117 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3118 pid, needed, any_count, n_sysno);
3119
3120 std::string built_packet;
3121 if (needed)
3122 {
3123 /* Prepare a packet with the sysno list, assuming max 8+1
3124 characters for a sysno. If the resulting packet size is too
3125 big, fallback on the non-selective packet. */
3126 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3127 built_packet.reserve (maxpktsz);
3128 built_packet = "QCatchSyscalls:1";
3129 if (any_count == 0)
3130 {
3131 /* Add in each syscall to be caught. */
3132 for (size_t i = 0; i < syscall_counts.size (); i++)
3133 {
3134 if (syscall_counts[i] != 0)
3135 string_appendf (built_packet, ";%zx", i);
3136 }
3137 }
3138 if (built_packet.size () > get_remote_packet_size ())
3139 {
3140 /* catch_packet too big. Fallback to less efficient
3141 non selective mode, with GDB doing the filtering. */
3142 catch_packet = "QCatchSyscalls:1";
3143 }
3144 else
3145 catch_packet = built_packet.c_str ();
3146 }
3147 else
3148 catch_packet = "QCatchSyscalls:0";
3149
3150 struct remote_state *rs = get_remote_state ();
3151
3152 putpkt (catch_packet);
3153 getpkt (&rs->buf);
3154 packet_result result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3155 if (result.status () == PACKET_OK)
3156 return 0;
3157 else
3158 return -1;
3159 }
3160
3161 /* If 'QProgramSignals' is supported, tell the remote stub what
3162 signals it should pass through to the inferior when detaching. */
3163
3164 void
3165 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3166 {
3167 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3168 {
3169 char *packet, *p;
3170 int count = 0;
3171 struct remote_state *rs = get_remote_state ();
3172
3173 gdb_assert (signals.size () < 256);
3174 for (size_t i = 0; i < signals.size (); i++)
3175 {
3176 if (signals[i])
3177 count++;
3178 }
3179 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3180 strcpy (packet, "QProgramSignals:");
3181 p = packet + strlen (packet);
3182 for (size_t i = 0; i < signals.size (); i++)
3183 {
3184 if (signal_pass_state (i))
3185 {
3186 if (i >= 16)
3187 *p++ = tohex (i >> 4);
3188 *p++ = tohex (i & 15);
3189 if (count)
3190 *p++ = ';';
3191 else
3192 break;
3193 count--;
3194 }
3195 }
3196 *p = 0;
3197 if (!rs->last_program_signals_packet
3198 || strcmp (rs->last_program_signals_packet, packet) != 0)
3199 {
3200 putpkt (packet);
3201 getpkt (&rs->buf);
3202 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3203 xfree (rs->last_program_signals_packet);
3204 rs->last_program_signals_packet = packet;
3205 }
3206 else
3207 xfree (packet);
3208 }
3209 }
3210
3211 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3212 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3213 thread. If GEN is set, set the general thread, if not, then set
3214 the step/continue thread. */
3215 void
3216 remote_target::set_thread (ptid_t ptid, int gen)
3217 {
3218 struct remote_state *rs = get_remote_state ();
3219 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3220 char *buf = rs->buf.data ();
3221 char *endbuf = buf + get_remote_packet_size ();
3222
3223 if (state == ptid)
3224 return;
3225
3226 *buf++ = 'H';
3227 *buf++ = gen ? 'g' : 'c';
3228 if (ptid == magic_null_ptid)
3229 xsnprintf (buf, endbuf - buf, "0");
3230 else if (ptid == any_thread_ptid)
3231 xsnprintf (buf, endbuf - buf, "0");
3232 else if (ptid == minus_one_ptid)
3233 xsnprintf (buf, endbuf - buf, "-1");
3234 else
3235 write_ptid (buf, endbuf, ptid);
3236 putpkt (rs->buf);
3237 getpkt (&rs->buf);
3238 if (gen)
3239 rs->general_thread = ptid;
3240 else
3241 rs->continue_thread = ptid;
3242 }
3243
3244 void
3245 remote_target::set_general_thread (ptid_t ptid)
3246 {
3247 set_thread (ptid, 1);
3248 }
3249
3250 void
3251 remote_target::set_continue_thread (ptid_t ptid)
3252 {
3253 set_thread (ptid, 0);
3254 }
3255
3256 /* Change the remote current process. Which thread within the process
3257 ends up selected isn't important, as long as it is the same process
3258 as what INFERIOR_PTID points to.
3259
3260 This comes from that fact that there is no explicit notion of
3261 "selected process" in the protocol. The selected process for
3262 general operations is the process the selected general thread
3263 belongs to. */
3264
3265 void
3266 remote_target::set_general_process ()
3267 {
3268 /* If the remote can't handle multiple processes, don't bother. */
3269 if (!m_features.remote_multi_process_p ())
3270 return;
3271
3272 remote_state *rs = get_remote_state ();
3273
3274 /* We only need to change the remote current thread if it's pointing
3275 at some other process. */
3276 if (rs->general_thread.pid () != inferior_ptid.pid ())
3277 set_general_thread (inferior_ptid);
3278 }
3279
3280 \f
3281 /* Return nonzero if this is the main thread that we made up ourselves
3282 to model non-threaded targets as single-threaded. */
3283
3284 static int
3285 remote_thread_always_alive (ptid_t ptid)
3286 {
3287 if (ptid == magic_null_ptid)
3288 /* The main thread is always alive. */
3289 return 1;
3290
3291 if (ptid.pid () != 0 && ptid.lwp () == 0)
3292 /* The main thread is always alive. This can happen after a
3293 vAttach, if the remote side doesn't support
3294 multi-threading. */
3295 return 1;
3296
3297 return 0;
3298 }
3299
3300 /* Return nonzero if the thread PTID is still alive on the remote
3301 system. */
3302
3303 bool
3304 remote_target::thread_alive (ptid_t ptid)
3305 {
3306 struct remote_state *rs = get_remote_state ();
3307 char *p, *endp;
3308
3309 /* Check if this is a thread that we made up ourselves to model
3310 non-threaded targets as single-threaded. */
3311 if (remote_thread_always_alive (ptid))
3312 return 1;
3313
3314 p = rs->buf.data ();
3315 endp = p + get_remote_packet_size ();
3316
3317 *p++ = 'T';
3318 write_ptid (p, endp, ptid);
3319
3320 putpkt (rs->buf);
3321 getpkt (&rs->buf);
3322 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3323 }
3324
3325 /* Return a pointer to a thread name if we know it and NULL otherwise.
3326 The thread_info object owns the memory for the name. */
3327
3328 const char *
3329 remote_target::thread_name (struct thread_info *info)
3330 {
3331 if (info->priv != NULL)
3332 {
3333 const std::string &name = get_remote_thread_info (info)->name;
3334 return !name.empty () ? name.c_str () : NULL;
3335 }
3336
3337 return NULL;
3338 }
3339
3340 /* About these extended threadlist and threadinfo packets. They are
3341 variable length packets but, the fields within them are often fixed
3342 length. They are redundant enough to send over UDP as is the
3343 remote protocol in general. There is a matching unit test module
3344 in libstub. */
3345
3346 /* WARNING: This threadref data structure comes from the remote O.S.,
3347 libstub protocol encoding, and remote.c. It is not particularly
3348 changeable. */
3349
3350 /* Right now, the internal structure is int. We want it to be bigger.
3351 Plan to fix this. */
3352
3353 typedef int gdb_threadref; /* Internal GDB thread reference. */
3354
3355 /* gdb_ext_thread_info is an internal GDB data structure which is
3356 equivalent to the reply of the remote threadinfo packet. */
3357
3358 struct gdb_ext_thread_info
3359 {
3360 threadref threadid; /* External form of thread reference. */
3361 int active; /* Has state interesting to GDB?
3362 regs, stack. */
3363 char display[256]; /* Brief state display, name,
3364 blocked/suspended. */
3365 char shortname[32]; /* To be used to name threads. */
3366 char more_display[256]; /* Long info, statistics, queue depth,
3367 whatever. */
3368 };
3369
3370 /* The volume of remote transfers can be limited by submitting
3371 a mask containing bits specifying the desired information.
3372 Use a union of these values as the 'selection' parameter to
3373 get_thread_info. FIXME: Make these TAG names more thread specific. */
3374
3375 #define TAG_THREADID 1
3376 #define TAG_EXISTS 2
3377 #define TAG_DISPLAY 4
3378 #define TAG_THREADNAME 8
3379 #define TAG_MOREDISPLAY 16
3380
3381 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3382
3383 static const char *unpack_nibble (const char *buf, int *val);
3384
3385 static const char *unpack_byte (const char *buf, int *value);
3386
3387 static char *pack_int (char *buf, int value);
3388
3389 static const char *unpack_int (const char *buf, int *value);
3390
3391 static const char *unpack_string (const char *src, char *dest, int length);
3392
3393 static char *pack_threadid (char *pkt, threadref *id);
3394
3395 static const char *unpack_threadid (const char *inbuf, threadref *id);
3396
3397 void int_to_threadref (threadref *id, int value);
3398
3399 static int threadref_to_int (threadref *ref);
3400
3401 static void copy_threadref (threadref *dest, threadref *src);
3402
3403 static int threadmatch (threadref *dest, threadref *src);
3404
3405 static char *pack_threadinfo_request (char *pkt, int mode,
3406 threadref *id);
3407
3408 static char *pack_threadlist_request (char *pkt, int startflag,
3409 int threadcount,
3410 threadref *nextthread);
3411
3412 static int remote_newthread_step (threadref *ref, void *context);
3413
3414
3415 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3416 buffer we're allowed to write to. Returns
3417 BUF+CHARACTERS_WRITTEN. */
3418
3419 char *
3420 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3421 {
3422 int pid, tid;
3423
3424 if (m_features.remote_multi_process_p ())
3425 {
3426 pid = ptid.pid ();
3427 if (pid < 0)
3428 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3429 else
3430 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3431 }
3432 tid = ptid.lwp ();
3433 if (tid < 0)
3434 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3435 else
3436 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3437
3438 return buf;
3439 }
3440
3441 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3442 last parsed char. Returns null_ptid if no thread id is found, and
3443 throws an error if the thread id has an invalid format. */
3444
3445 static ptid_t
3446 read_ptid (const char *buf, const char **obuf)
3447 {
3448 const char *p = buf;
3449 const char *pp;
3450 ULONGEST pid = 0, tid = 0;
3451
3452 if (*p == 'p')
3453 {
3454 /* Multi-process ptid. */
3455 pp = unpack_varlen_hex (p + 1, &pid);
3456 if (*pp != '.')
3457 error (_("invalid remote ptid: %s"), p);
3458
3459 p = pp;
3460 pp = unpack_varlen_hex (p + 1, &tid);
3461 if (obuf)
3462 *obuf = pp;
3463 return ptid_t (pid, tid);
3464 }
3465
3466 /* No multi-process. Just a tid. */
3467 pp = unpack_varlen_hex (p, &tid);
3468
3469 /* Return null_ptid when no thread id is found. */
3470 if (p == pp)
3471 {
3472 if (obuf)
3473 *obuf = pp;
3474 return null_ptid;
3475 }
3476
3477 /* Since the stub is not sending a process id, default to what's
3478 current_inferior, unless it doesn't have a PID yet. If so,
3479 then since there's no way to know the pid of the reported
3480 threads, use the magic number. */
3481 inferior *inf = current_inferior ();
3482 if (inf->pid == 0)
3483 pid = magic_null_ptid.pid ();
3484 else
3485 pid = inf->pid;
3486
3487 if (obuf)
3488 *obuf = pp;
3489 return ptid_t (pid, tid);
3490 }
3491
3492 static int
3493 stubhex (int ch)
3494 {
3495 if (ch >= 'a' && ch <= 'f')
3496 return ch - 'a' + 10;
3497 if (ch >= '0' && ch <= '9')
3498 return ch - '0';
3499 if (ch >= 'A' && ch <= 'F')
3500 return ch - 'A' + 10;
3501 return -1;
3502 }
3503
3504 static int
3505 stub_unpack_int (const char *buff, int fieldlength)
3506 {
3507 int nibble;
3508 int retval = 0;
3509
3510 while (fieldlength)
3511 {
3512 nibble = stubhex (*buff++);
3513 retval |= nibble;
3514 fieldlength--;
3515 if (fieldlength)
3516 retval = retval << 4;
3517 }
3518 return retval;
3519 }
3520
3521 static const char *
3522 unpack_nibble (const char *buf, int *val)
3523 {
3524 *val = fromhex (*buf++);
3525 return buf;
3526 }
3527
3528 static const char *
3529 unpack_byte (const char *buf, int *value)
3530 {
3531 *value = stub_unpack_int (buf, 2);
3532 return buf + 2;
3533 }
3534
3535 static char *
3536 pack_int (char *buf, int value)
3537 {
3538 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3539 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3540 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3541 buf = pack_hex_byte (buf, (value & 0xff));
3542 return buf;
3543 }
3544
3545 static const char *
3546 unpack_int (const char *buf, int *value)
3547 {
3548 *value = stub_unpack_int (buf, 8);
3549 return buf + 8;
3550 }
3551
3552 #if 0 /* Currently unused, uncomment when needed. */
3553 static char *pack_string (char *pkt, char *string);
3554
3555 static char *
3556 pack_string (char *pkt, char *string)
3557 {
3558 char ch;
3559 int len;
3560
3561 len = strlen (string);
3562 if (len > 200)
3563 len = 200; /* Bigger than most GDB packets, junk??? */
3564 pkt = pack_hex_byte (pkt, len);
3565 while (len-- > 0)
3566 {
3567 ch = *string++;
3568 if ((ch == '\0') || (ch == '#'))
3569 ch = '*'; /* Protect encapsulation. */
3570 *pkt++ = ch;
3571 }
3572 return pkt;
3573 }
3574 #endif /* 0 (unused) */
3575
3576 static const char *
3577 unpack_string (const char *src, char *dest, int length)
3578 {
3579 while (length--)
3580 *dest++ = *src++;
3581 *dest = '\0';
3582 return src;
3583 }
3584
3585 static char *
3586 pack_threadid (char *pkt, threadref *id)
3587 {
3588 char *limit;
3589 unsigned char *altid;
3590
3591 altid = (unsigned char *) id;
3592 limit = pkt + BUF_THREAD_ID_SIZE;
3593 while (pkt < limit)
3594 pkt = pack_hex_byte (pkt, *altid++);
3595 return pkt;
3596 }
3597
3598
3599 static const char *
3600 unpack_threadid (const char *inbuf, threadref *id)
3601 {
3602 char *altref;
3603 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3604 int x, y;
3605
3606 altref = (char *) id;
3607
3608 while (inbuf < limit)
3609 {
3610 x = stubhex (*inbuf++);
3611 y = stubhex (*inbuf++);
3612 *altref++ = (x << 4) | y;
3613 }
3614 return inbuf;
3615 }
3616
3617 /* Externally, threadrefs are 64 bits but internally, they are still
3618 ints. This is due to a mismatch of specifications. We would like
3619 to use 64bit thread references internally. This is an adapter
3620 function. */
3621
3622 void
3623 int_to_threadref (threadref *id, int value)
3624 {
3625 unsigned char *scan;
3626
3627 scan = (unsigned char *) id;
3628 {
3629 int i = 4;
3630 while (i--)
3631 *scan++ = 0;
3632 }
3633 *scan++ = (value >> 24) & 0xff;
3634 *scan++ = (value >> 16) & 0xff;
3635 *scan++ = (value >> 8) & 0xff;
3636 *scan++ = (value & 0xff);
3637 }
3638
3639 static int
3640 threadref_to_int (threadref *ref)
3641 {
3642 int i, value = 0;
3643 unsigned char *scan;
3644
3645 scan = *ref;
3646 scan += 4;
3647 i = 4;
3648 while (i-- > 0)
3649 value = (value << 8) | ((*scan++) & 0xff);
3650 return value;
3651 }
3652
3653 static void
3654 copy_threadref (threadref *dest, threadref *src)
3655 {
3656 int i;
3657 unsigned char *csrc, *cdest;
3658
3659 csrc = (unsigned char *) src;
3660 cdest = (unsigned char *) dest;
3661 i = 8;
3662 while (i--)
3663 *cdest++ = *csrc++;
3664 }
3665
3666 static int
3667 threadmatch (threadref *dest, threadref *src)
3668 {
3669 /* Things are broken right now, so just assume we got a match. */
3670 #if 0
3671 unsigned char *srcp, *destp;
3672 int i, result;
3673 srcp = (char *) src;
3674 destp = (char *) dest;
3675
3676 result = 1;
3677 while (i-- > 0)
3678 result &= (*srcp++ == *destp++) ? 1 : 0;
3679 return result;
3680 #endif
3681 return 1;
3682 }
3683
3684 /*
3685 threadid:1, # always request threadid
3686 context_exists:2,
3687 display:4,
3688 unique_name:8,
3689 more_display:16
3690 */
3691
3692 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3693
3694 static char *
3695 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3696 {
3697 *pkt++ = 'q'; /* Info Query */
3698 *pkt++ = 'P'; /* process or thread info */
3699 pkt = pack_int (pkt, mode); /* mode */
3700 pkt = pack_threadid (pkt, id); /* threadid */
3701 *pkt = '\0'; /* terminate */
3702 return pkt;
3703 }
3704
3705 /* These values tag the fields in a thread info response packet. */
3706 /* Tagging the fields allows us to request specific fields and to
3707 add more fields as time goes by. */
3708
3709 #define TAG_THREADID 1 /* Echo the thread identifier. */
3710 #define TAG_EXISTS 2 /* Is this process defined enough to
3711 fetch registers and its stack? */
3712 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3713 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3714 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3715 the process. */
3716
3717 int
3718 remote_target::remote_unpack_thread_info_response (const char *pkt,
3719 threadref *expectedref,
3720 gdb_ext_thread_info *info)
3721 {
3722 struct remote_state *rs = get_remote_state ();
3723 int mask, length;
3724 int tag;
3725 threadref ref;
3726 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3727 int retval = 1;
3728
3729 /* info->threadid = 0; FIXME: implement zero_threadref. */
3730 info->active = 0;
3731 info->display[0] = '\0';
3732 info->shortname[0] = '\0';
3733 info->more_display[0] = '\0';
3734
3735 /* Assume the characters indicating the packet type have been
3736 stripped. */
3737 pkt = unpack_int (pkt, &mask); /* arg mask */
3738 pkt = unpack_threadid (pkt, &ref);
3739
3740 if (mask == 0)
3741 warning (_("Incomplete response to threadinfo request."));
3742 if (!threadmatch (&ref, expectedref))
3743 { /* This is an answer to a different request. */
3744 warning (_("ERROR RMT Thread info mismatch."));
3745 return 0;
3746 }
3747 copy_threadref (&info->threadid, &ref);
3748
3749 /* Loop on tagged fields , try to bail if something goes wrong. */
3750
3751 /* Packets are terminated with nulls. */
3752 while ((pkt < limit) && mask && *pkt)
3753 {
3754 pkt = unpack_int (pkt, &tag); /* tag */
3755 pkt = unpack_byte (pkt, &length); /* length */
3756 if (!(tag & mask)) /* Tags out of synch with mask. */
3757 {
3758 warning (_("ERROR RMT: threadinfo tag mismatch."));
3759 retval = 0;
3760 break;
3761 }
3762 if (tag == TAG_THREADID)
3763 {
3764 if (length != 16)
3765 {
3766 warning (_("ERROR RMT: length of threadid is not 16."));
3767 retval = 0;
3768 break;
3769 }
3770 pkt = unpack_threadid (pkt, &ref);
3771 mask = mask & ~TAG_THREADID;
3772 continue;
3773 }
3774 if (tag == TAG_EXISTS)
3775 {
3776 info->active = stub_unpack_int (pkt, length);
3777 pkt += length;
3778 mask = mask & ~(TAG_EXISTS);
3779 if (length > 8)
3780 {
3781 warning (_("ERROR RMT: 'exists' length too long."));
3782 retval = 0;
3783 break;
3784 }
3785 continue;
3786 }
3787 if (tag == TAG_THREADNAME)
3788 {
3789 pkt = unpack_string (pkt, &info->shortname[0], length);
3790 mask = mask & ~TAG_THREADNAME;
3791 continue;
3792 }
3793 if (tag == TAG_DISPLAY)
3794 {
3795 pkt = unpack_string (pkt, &info->display[0], length);
3796 mask = mask & ~TAG_DISPLAY;
3797 continue;
3798 }
3799 if (tag == TAG_MOREDISPLAY)
3800 {
3801 pkt = unpack_string (pkt, &info->more_display[0], length);
3802 mask = mask & ~TAG_MOREDISPLAY;
3803 continue;
3804 }
3805 warning (_("ERROR RMT: unknown thread info tag."));
3806 break; /* Not a tag we know about. */
3807 }
3808 return retval;
3809 }
3810
3811 int
3812 remote_target::remote_get_threadinfo (threadref *threadid,
3813 int fieldset,
3814 gdb_ext_thread_info *info)
3815 {
3816 struct remote_state *rs = get_remote_state ();
3817 int result;
3818
3819 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3820 putpkt (rs->buf);
3821 getpkt (&rs->buf);
3822
3823 if (rs->buf[0] == '\0')
3824 return 0;
3825
3826 result = remote_unpack_thread_info_response (&rs->buf[2],
3827 threadid, info);
3828 return result;
3829 }
3830
3831 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3832
3833 static char *
3834 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3835 threadref *nextthread)
3836 {
3837 *pkt++ = 'q'; /* info query packet */
3838 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3839 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3840 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3841 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3842 *pkt = '\0';
3843 return pkt;
3844 }
3845
3846 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3847
3848 int
3849 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3850 threadref *original_echo,
3851 threadref *resultlist,
3852 int *doneflag)
3853 {
3854 struct remote_state *rs = get_remote_state ();
3855 int count, resultcount, done;
3856
3857 resultcount = 0;
3858 /* Assume the 'q' and 'M chars have been stripped. */
3859 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3860 /* done parse past here */
3861 pkt = unpack_byte (pkt, &count); /* count field */
3862 pkt = unpack_nibble (pkt, &done);
3863 /* The first threadid is the argument threadid. */
3864 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3865 while ((count-- > 0) && (pkt < limit))
3866 {
3867 pkt = unpack_threadid (pkt, resultlist++);
3868 if (resultcount++ >= result_limit)
3869 break;
3870 }
3871 if (doneflag)
3872 *doneflag = done;
3873 return resultcount;
3874 }
3875
3876 /* Fetch the next batch of threads from the remote. Returns -1 if the
3877 qL packet is not supported, 0 on error and 1 on success. */
3878
3879 int
3880 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3881 int result_limit, int *done, int *result_count,
3882 threadref *threadlist)
3883 {
3884 struct remote_state *rs = get_remote_state ();
3885 int result = 1;
3886
3887 /* Truncate result limit to be smaller than the packet size. */
3888 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3889 >= get_remote_packet_size ())
3890 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3891
3892 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3893 nextthread);
3894 putpkt (rs->buf);
3895 getpkt (&rs->buf);
3896 if (rs->buf[0] == '\0')
3897 {
3898 /* Packet not supported. */
3899 return -1;
3900 }
3901
3902 *result_count =
3903 parse_threadlist_response (&rs->buf[2], result_limit,
3904 &rs->echo_nextthread, threadlist, done);
3905
3906 if (!threadmatch (&rs->echo_nextthread, nextthread))
3907 {
3908 /* FIXME: This is a good reason to drop the packet. */
3909 /* Possibly, there is a duplicate response. */
3910 /* Possibilities :
3911 retransmit immediatly - race conditions
3912 retransmit after timeout - yes
3913 exit
3914 wait for packet, then exit
3915 */
3916 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3917 return 0; /* I choose simply exiting. */
3918 }
3919 if (*result_count <= 0)
3920 {
3921 if (*done != 1)
3922 {
3923 warning (_("RMT ERROR : failed to get remote thread list."));
3924 result = 0;
3925 }
3926 return result; /* break; */
3927 }
3928 if (*result_count > result_limit)
3929 {
3930 *result_count = 0;
3931 warning (_("RMT ERROR: threadlist response longer than requested."));
3932 return 0;
3933 }
3934 return result;
3935 }
3936
3937 /* Fetch the list of remote threads, with the qL packet, and call
3938 STEPFUNCTION for each thread found. Stops iterating and returns 1
3939 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3940 STEPFUNCTION returns false. If the packet is not supported,
3941 returns -1. */
3942
3943 int
3944 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3945 void *context, int looplimit)
3946 {
3947 struct remote_state *rs = get_remote_state ();
3948 int done, i, result_count;
3949 int startflag = 1;
3950 int result = 1;
3951 int loopcount = 0;
3952
3953 done = 0;
3954 while (!done)
3955 {
3956 if (loopcount++ > looplimit)
3957 {
3958 result = 0;
3959 warning (_("Remote fetch threadlist -infinite loop-."));
3960 break;
3961 }
3962 result = remote_get_threadlist (startflag, &rs->nextthread,
3963 MAXTHREADLISTRESULTS,
3964 &done, &result_count,
3965 rs->resultthreadlist);
3966 if (result <= 0)
3967 break;
3968 /* Clear for later iterations. */
3969 startflag = 0;
3970 /* Setup to resume next batch of thread references, set nextthread. */
3971 if (result_count >= 1)
3972 copy_threadref (&rs->nextthread,
3973 &rs->resultthreadlist[result_count - 1]);
3974 i = 0;
3975 while (result_count--)
3976 {
3977 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3978 {
3979 result = 0;
3980 break;
3981 }
3982 }
3983 }
3984 return result;
3985 }
3986
3987 /* A thread found on the remote target. */
3988
3989 struct thread_item
3990 {
3991 explicit thread_item (ptid_t ptid_)
3992 : ptid (ptid_)
3993 {}
3994
3995 thread_item (thread_item &&other) = default;
3996 thread_item &operator= (thread_item &&other) = default;
3997
3998 DISABLE_COPY_AND_ASSIGN (thread_item);
3999
4000 /* The thread's PTID. */
4001 ptid_t ptid;
4002
4003 /* The thread's extra info. */
4004 std::string extra;
4005
4006 /* The thread's name. */
4007 std::string name;
4008
4009 /* The core the thread was running on. -1 if not known. */
4010 int core = -1;
4011
4012 /* The thread handle associated with the thread. */
4013 gdb::byte_vector thread_handle;
4014 };
4015
4016 /* Context passed around to the various methods listing remote
4017 threads. As new threads are found, they're added to the ITEMS
4018 vector. */
4019
4020 struct threads_listing_context
4021 {
4022 /* Return true if this object contains an entry for a thread with ptid
4023 PTID. */
4024
4025 bool contains_thread (ptid_t ptid) const
4026 {
4027 auto match_ptid = [&] (const thread_item &item)
4028 {
4029 return item.ptid == ptid;
4030 };
4031
4032 auto it = std::find_if (this->items.begin (),
4033 this->items.end (),
4034 match_ptid);
4035
4036 return it != this->items.end ();
4037 }
4038
4039 /* Remove the thread with ptid PTID. */
4040
4041 void remove_thread (ptid_t ptid)
4042 {
4043 auto match_ptid = [&] (const thread_item &item)
4044 {
4045 return item.ptid == ptid;
4046 };
4047
4048 auto it = std::remove_if (this->items.begin (),
4049 this->items.end (),
4050 match_ptid);
4051
4052 if (it != this->items.end ())
4053 this->items.erase (it);
4054 }
4055
4056 /* The threads found on the remote target. */
4057 std::vector<thread_item> items;
4058 };
4059
4060 static int
4061 remote_newthread_step (threadref *ref, void *data)
4062 {
4063 struct threads_listing_context *context
4064 = (struct threads_listing_context *) data;
4065 int pid = inferior_ptid.pid ();
4066 int lwp = threadref_to_int (ref);
4067 ptid_t ptid (pid, lwp);
4068
4069 context->items.emplace_back (ptid);
4070
4071 return 1; /* continue iterator */
4072 }
4073
4074 #define CRAZY_MAX_THREADS 1000
4075
4076 ptid_t
4077 remote_target::remote_current_thread (ptid_t oldpid)
4078 {
4079 struct remote_state *rs = get_remote_state ();
4080
4081 putpkt ("qC");
4082 getpkt (&rs->buf);
4083 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
4084 {
4085 const char *obuf;
4086 ptid_t result;
4087
4088 result = read_ptid (&rs->buf[2], &obuf);
4089 if (*obuf != '\0')
4090 remote_debug_printf ("warning: garbage in qC reply");
4091
4092 return result;
4093 }
4094 else
4095 return oldpid;
4096 }
4097
4098 /* List remote threads using the deprecated qL packet. */
4099
4100 int
4101 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4102 {
4103 if (remote_threadlist_iterator (remote_newthread_step, context,
4104 CRAZY_MAX_THREADS) >= 0)
4105 return 1;
4106
4107 return 0;
4108 }
4109
4110 #if defined(HAVE_LIBEXPAT)
4111
4112 static void
4113 start_thread (struct gdb_xml_parser *parser,
4114 const struct gdb_xml_element *element,
4115 void *user_data,
4116 std::vector<gdb_xml_value> &attributes)
4117 {
4118 struct threads_listing_context *data
4119 = (struct threads_listing_context *) user_data;
4120 struct gdb_xml_value *attr;
4121
4122 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4123 ptid_t ptid = read_ptid (id, NULL);
4124
4125 thread_item &item = data->items.emplace_back (ptid);
4126
4127 attr = xml_find_attribute (attributes, "core");
4128 if (attr != NULL)
4129 item.core = *(ULONGEST *) attr->value.get ();
4130
4131 attr = xml_find_attribute (attributes, "name");
4132 if (attr != NULL)
4133 item.name = (const char *) attr->value.get ();
4134
4135 attr = xml_find_attribute (attributes, "handle");
4136 if (attr != NULL)
4137 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4138 }
4139
4140 static void
4141 end_thread (struct gdb_xml_parser *parser,
4142 const struct gdb_xml_element *element,
4143 void *user_data, const char *body_text)
4144 {
4145 struct threads_listing_context *data
4146 = (struct threads_listing_context *) user_data;
4147
4148 if (body_text != NULL && *body_text != '\0')
4149 data->items.back ().extra = body_text;
4150 }
4151
4152 const struct gdb_xml_attribute thread_attributes[] = {
4153 { "id", GDB_XML_AF_NONE, NULL, NULL },
4154 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4155 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4156 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4157 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4158 };
4159
4160 const struct gdb_xml_element thread_children[] = {
4161 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4162 };
4163
4164 const struct gdb_xml_element threads_children[] = {
4165 { "thread", thread_attributes, thread_children,
4166 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4167 start_thread, end_thread },
4168 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4169 };
4170
4171 const struct gdb_xml_element threads_elements[] = {
4172 { "threads", NULL, threads_children,
4173 GDB_XML_EF_NONE, NULL, NULL },
4174 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4175 };
4176
4177 #endif
4178
4179 /* List remote threads using qXfer:threads:read. */
4180
4181 int
4182 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4183 {
4184 #if defined(HAVE_LIBEXPAT)
4185 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4186 {
4187 std::optional<gdb::char_vector> xml
4188 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4189
4190 if (xml && (*xml)[0] != '\0')
4191 {
4192 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4193 threads_elements, xml->data (), context);
4194 }
4195
4196 return 1;
4197 }
4198 #endif
4199
4200 return 0;
4201 }
4202
4203 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4204
4205 int
4206 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4207 {
4208 struct remote_state *rs = get_remote_state ();
4209
4210 if (rs->use_threadinfo_query)
4211 {
4212 const char *bufp;
4213
4214 putpkt ("qfThreadInfo");
4215 getpkt (&rs->buf);
4216 bufp = rs->buf.data ();
4217 if (bufp[0] != '\0') /* q packet recognized */
4218 {
4219 while (*bufp++ == 'm') /* reply contains one or more TID */
4220 {
4221 do
4222 {
4223 ptid_t ptid = read_ptid (bufp, &bufp);
4224 context->items.emplace_back (ptid);
4225 }
4226 while (*bufp++ == ','); /* comma-separated list */
4227 putpkt ("qsThreadInfo");
4228 getpkt (&rs->buf);
4229 bufp = rs->buf.data ();
4230 }
4231 return 1;
4232 }
4233 else
4234 {
4235 /* Packet not recognized. */
4236 rs->use_threadinfo_query = 0;
4237 }
4238 }
4239
4240 return 0;
4241 }
4242
4243 /* Return true if INF only has one non-exited thread. */
4244
4245 static bool
4246 has_single_non_exited_thread (inferior *inf)
4247 {
4248 int count = 0;
4249 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4250 if (++count > 1)
4251 break;
4252 return count == 1;
4253 }
4254
4255 /* Implement the to_update_thread_list function for the remote
4256 targets. */
4257
4258 void
4259 remote_target::update_thread_list ()
4260 {
4261 struct threads_listing_context context;
4262 int got_list = 0;
4263
4264 /* We have a few different mechanisms to fetch the thread list. Try
4265 them all, starting with the most preferred one first, falling
4266 back to older methods. */
4267 if (remote_get_threads_with_qxfer (&context)
4268 || remote_get_threads_with_qthreadinfo (&context)
4269 || remote_get_threads_with_ql (&context))
4270 {
4271 got_list = 1;
4272
4273 if (context.items.empty ()
4274 && remote_thread_always_alive (inferior_ptid))
4275 {
4276 /* Some targets don't really support threads, but still
4277 reply an (empty) thread list in response to the thread
4278 listing packets, instead of replying "packet not
4279 supported". Exit early so we don't delete the main
4280 thread. */
4281 return;
4282 }
4283
4284 /* CONTEXT now holds the current thread list on the remote
4285 target end. Delete GDB-side threads no longer found on the
4286 target. */
4287 for (thread_info *tp : all_threads_safe ())
4288 {
4289 if (tp->inf->process_target () != this)
4290 continue;
4291
4292 if (!context.contains_thread (tp->ptid))
4293 {
4294 /* Do not remove the thread if it is the last thread in
4295 the inferior. This situation happens when we have a
4296 pending exit process status to process. Otherwise we
4297 may end up with a seemingly live inferior (i.e. pid
4298 != 0) that has no threads. */
4299 if (has_single_non_exited_thread (tp->inf))
4300 continue;
4301
4302 /* Do not remove the thread if we've requested to be
4303 notified of its exit. For example, the thread may be
4304 displaced stepping, infrun will need to handle the
4305 exit event, and displaced stepping info is recorded
4306 in the thread object. If we deleted the thread now,
4307 we'd lose that info. */
4308 if ((tp->thread_options () & GDB_THREAD_OPTION_EXIT) != 0)
4309 continue;
4310
4311 /* Not found. */
4312 delete_thread (tp);
4313 }
4314 }
4315
4316 /* Remove any unreported fork/vfork/clone child threads from
4317 CONTEXT so that we don't interfere with follow
4318 fork/vfork/clone, which is where creation of such threads is
4319 handled. */
4320 remove_new_children (&context);
4321
4322 /* And now add threads we don't know about yet to our list. */
4323 for (thread_item &item : context.items)
4324 {
4325 if (item.ptid != null_ptid)
4326 {
4327 /* In non-stop mode, we assume new found threads are
4328 executing until proven otherwise with a stop reply.
4329 In all-stop, we can only get here if all threads are
4330 stopped. */
4331 bool executing = target_is_non_stop_p ();
4332
4333 remote_notice_new_inferior (item.ptid, executing);
4334
4335 thread_info *tp = this->find_thread (item.ptid);
4336 remote_thread_info *info = get_remote_thread_info (tp);
4337 info->core = item.core;
4338 info->extra = std::move (item.extra);
4339 info->name = std::move (item.name);
4340 info->thread_handle = std::move (item.thread_handle);
4341 }
4342 }
4343 }
4344
4345 if (!got_list)
4346 {
4347 /* If no thread listing method is supported, then query whether
4348 each known thread is alive, one by one, with the T packet.
4349 If the target doesn't support threads at all, then this is a
4350 no-op. See remote_thread_alive. */
4351 prune_threads ();
4352 }
4353 }
4354
4355 /*
4356 * Collect a descriptive string about the given thread.
4357 * The target may say anything it wants to about the thread
4358 * (typically info about its blocked / runnable state, name, etc.).
4359 * This string will appear in the info threads display.
4360 *
4361 * Optional: targets are not required to implement this function.
4362 */
4363
4364 const char *
4365 remote_target::extra_thread_info (thread_info *tp)
4366 {
4367 struct remote_state *rs = get_remote_state ();
4368 int set;
4369 threadref id;
4370 struct gdb_ext_thread_info threadinfo;
4371
4372 if (rs->remote_desc == 0) /* paranoia */
4373 internal_error (_("remote_threads_extra_info"));
4374
4375 if (tp->ptid == magic_null_ptid
4376 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4377 /* This is the main thread which was added by GDB. The remote
4378 server doesn't know about it. */
4379 return NULL;
4380
4381 std::string &extra = get_remote_thread_info (tp)->extra;
4382
4383 /* If already have cached info, use it. */
4384 if (!extra.empty ())
4385 return extra.c_str ();
4386
4387 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4388 {
4389 /* If we're using qXfer:threads:read, then the extra info is
4390 included in the XML. So if we didn't have anything cached,
4391 it's because there's really no extra info. */
4392 return NULL;
4393 }
4394
4395 if (rs->use_threadextra_query)
4396 {
4397 char *b = rs->buf.data ();
4398 char *endb = b + get_remote_packet_size ();
4399
4400 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4401 b += strlen (b);
4402 write_ptid (b, endb, tp->ptid);
4403
4404 putpkt (rs->buf);
4405 getpkt (&rs->buf);
4406 if (rs->buf[0] != 0)
4407 {
4408 extra.resize (strlen (rs->buf.data ()) / 2);
4409 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4410 return extra.c_str ();
4411 }
4412 }
4413
4414 /* If the above query fails, fall back to the old method. */
4415 rs->use_threadextra_query = 0;
4416 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4417 | TAG_MOREDISPLAY | TAG_DISPLAY;
4418 int_to_threadref (&id, tp->ptid.lwp ());
4419 if (remote_get_threadinfo (&id, set, &threadinfo))
4420 if (threadinfo.active)
4421 {
4422 if (*threadinfo.shortname)
4423 string_appendf (extra, " Name: %s", threadinfo.shortname);
4424 if (*threadinfo.display)
4425 {
4426 if (!extra.empty ())
4427 extra += ',';
4428 string_appendf (extra, " State: %s", threadinfo.display);
4429 }
4430 if (*threadinfo.more_display)
4431 {
4432 if (!extra.empty ())
4433 extra += ',';
4434 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4435 }
4436 return extra.c_str ();
4437 }
4438 return NULL;
4439 }
4440 \f
4441
4442 bool
4443 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4444 struct static_tracepoint_marker *marker)
4445 {
4446 struct remote_state *rs = get_remote_state ();
4447 char *p = rs->buf.data ();
4448
4449 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4450 p += strlen (p);
4451 p += hexnumstr (p, addr);
4452 putpkt (rs->buf);
4453 getpkt (&rs->buf);
4454 p = rs->buf.data ();
4455
4456 if (*p == 'E')
4457 error (_("Remote failure reply: %s"), p);
4458
4459 if (*p++ == 'm')
4460 {
4461 parse_static_tracepoint_marker_definition (p, NULL, marker);
4462 return true;
4463 }
4464
4465 return false;
4466 }
4467
4468 std::vector<static_tracepoint_marker>
4469 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4470 {
4471 struct remote_state *rs = get_remote_state ();
4472 std::vector<static_tracepoint_marker> markers;
4473 const char *p;
4474 static_tracepoint_marker marker;
4475
4476 /* Ask for a first packet of static tracepoint marker
4477 definition. */
4478 putpkt ("qTfSTM");
4479 getpkt (&rs->buf);
4480 p = rs->buf.data ();
4481 if (*p == 'E')
4482 error (_("Remote failure reply: %s"), p);
4483
4484 while (*p++ == 'm')
4485 {
4486 do
4487 {
4488 parse_static_tracepoint_marker_definition (p, &p, &marker);
4489
4490 if (strid == NULL || marker.str_id == strid)
4491 markers.push_back (std::move (marker));
4492 }
4493 while (*p++ == ','); /* comma-separated list */
4494 /* Ask for another packet of static tracepoint definition. */
4495 putpkt ("qTsSTM");
4496 getpkt (&rs->buf);
4497 p = rs->buf.data ();
4498 }
4499
4500 return markers;
4501 }
4502
4503 \f
4504 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4505
4506 ptid_t
4507 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4508 {
4509 return ptid_t (inferior_ptid.pid (), lwp);
4510 }
4511 \f
4512
4513 /* Restart the remote side; this is an extended protocol operation. */
4514
4515 void
4516 remote_target::extended_remote_restart ()
4517 {
4518 struct remote_state *rs = get_remote_state ();
4519
4520 /* Send the restart command; for reasons I don't understand the
4521 remote side really expects a number after the "R". */
4522 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4523 putpkt (rs->buf);
4524
4525 remote_fileio_reset ();
4526 }
4527 \f
4528 /* Clean up connection to a remote debugger. */
4529
4530 void
4531 remote_target::close ()
4532 {
4533 /* Make sure we leave stdin registered in the event loop. */
4534 terminal_ours ();
4535
4536 trace_reset_local_state ();
4537
4538 delete this;
4539 }
4540
4541 remote_target::~remote_target ()
4542 {
4543 struct remote_state *rs = get_remote_state ();
4544
4545 /* Check for NULL because we may get here with a partially
4546 constructed target/connection. */
4547 if (rs->remote_desc == nullptr)
4548 return;
4549
4550 serial_close (rs->remote_desc);
4551
4552 /* We are destroying the remote target, so we should discard
4553 everything of this target. */
4554 discard_pending_stop_replies_in_queue ();
4555
4556 rs->delete_async_event_handler ();
4557
4558 delete rs->notif_state;
4559 }
4560
4561 /* Query the remote side for the text, data and bss offsets. */
4562
4563 void
4564 remote_target::get_offsets ()
4565 {
4566 struct remote_state *rs = get_remote_state ();
4567 char *buf;
4568 char *ptr;
4569 int lose, num_segments = 0, do_sections, do_segments;
4570 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4571
4572 if (current_program_space->symfile_object_file == NULL)
4573 return;
4574
4575 putpkt ("qOffsets");
4576 getpkt (&rs->buf);
4577 buf = rs->buf.data ();
4578
4579 if (buf[0] == '\000')
4580 return; /* Return silently. Stub doesn't support
4581 this command. */
4582 if (buf[0] == 'E')
4583 {
4584 warning (_("Remote failure reply: %s"), buf);
4585 return;
4586 }
4587
4588 /* Pick up each field in turn. This used to be done with scanf, but
4589 scanf will make trouble if CORE_ADDR size doesn't match
4590 conversion directives correctly. The following code will work
4591 with any size of CORE_ADDR. */
4592 text_addr = data_addr = bss_addr = 0;
4593 ptr = buf;
4594 lose = 0;
4595
4596 if (startswith (ptr, "Text="))
4597 {
4598 ptr += 5;
4599 /* Don't use strtol, could lose on big values. */
4600 while (*ptr && *ptr != ';')
4601 text_addr = (text_addr << 4) + fromhex (*ptr++);
4602
4603 if (startswith (ptr, ";Data="))
4604 {
4605 ptr += 6;
4606 while (*ptr && *ptr != ';')
4607 data_addr = (data_addr << 4) + fromhex (*ptr++);
4608 }
4609 else
4610 lose = 1;
4611
4612 if (!lose && startswith (ptr, ";Bss="))
4613 {
4614 ptr += 5;
4615 while (*ptr && *ptr != ';')
4616 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4617
4618 if (bss_addr != data_addr)
4619 warning (_("Target reported unsupported offsets: %s"), buf);
4620 }
4621 else
4622 lose = 1;
4623 }
4624 else if (startswith (ptr, "TextSeg="))
4625 {
4626 ptr += 8;
4627 /* Don't use strtol, could lose on big values. */
4628 while (*ptr && *ptr != ';')
4629 text_addr = (text_addr << 4) + fromhex (*ptr++);
4630 num_segments = 1;
4631
4632 if (startswith (ptr, ";DataSeg="))
4633 {
4634 ptr += 9;
4635 while (*ptr && *ptr != ';')
4636 data_addr = (data_addr << 4) + fromhex (*ptr++);
4637 num_segments++;
4638 }
4639 }
4640 else
4641 lose = 1;
4642
4643 if (lose)
4644 error (_("Malformed response to offset query, %s"), buf);
4645 else if (*ptr != '\0')
4646 warning (_("Target reported unsupported offsets: %s"), buf);
4647
4648 objfile *objf = current_program_space->symfile_object_file;
4649 section_offsets offs = objf->section_offsets;
4650
4651 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4652 do_segments = (data != NULL);
4653 do_sections = num_segments == 0;
4654
4655 if (num_segments > 0)
4656 {
4657 segments[0] = text_addr;
4658 segments[1] = data_addr;
4659 }
4660 /* If we have two segments, we can still try to relocate everything
4661 by assuming that the .text and .data offsets apply to the whole
4662 text and data segments. Convert the offsets given in the packet
4663 to base addresses for symfile_map_offsets_to_segments. */
4664 else if (data != nullptr && data->segments.size () == 2)
4665 {
4666 segments[0] = data->segments[0].base + text_addr;
4667 segments[1] = data->segments[1].base + data_addr;
4668 num_segments = 2;
4669 }
4670 /* If the object file has only one segment, assume that it is text
4671 rather than data; main programs with no writable data are rare,
4672 but programs with no code are useless. Of course the code might
4673 have ended up in the data segment... to detect that we would need
4674 the permissions here. */
4675 else if (data && data->segments.size () == 1)
4676 {
4677 segments[0] = data->segments[0].base + text_addr;
4678 num_segments = 1;
4679 }
4680 /* There's no way to relocate by segment. */
4681 else
4682 do_segments = 0;
4683
4684 if (do_segments)
4685 {
4686 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4687 data.get (), offs,
4688 num_segments, segments);
4689
4690 if (ret == 0 && !do_sections)
4691 error (_("Can not handle qOffsets TextSeg "
4692 "response with this symbol file"));
4693
4694 if (ret > 0)
4695 do_sections = 0;
4696 }
4697
4698 if (do_sections)
4699 {
4700 offs[SECT_OFF_TEXT (objf)] = text_addr;
4701
4702 /* This is a temporary kludge to force data and bss to use the
4703 same offsets because that's what nlmconv does now. The real
4704 solution requires changes to the stub and remote.c that I
4705 don't have time to do right now. */
4706
4707 offs[SECT_OFF_DATA (objf)] = data_addr;
4708 offs[SECT_OFF_BSS (objf)] = data_addr;
4709 }
4710
4711 objfile_relocate (objf, offs);
4712 }
4713
4714 /* Send interrupt_sequence to remote target. */
4715
4716 void
4717 remote_target::send_interrupt_sequence ()
4718 {
4719 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4720 remote_serial_write ("\x03", 1);
4721 else if (interrupt_sequence_mode == interrupt_sequence_break)
4722 remote_serial_send_break ();
4723 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4724 {
4725 remote_serial_send_break ();
4726 remote_serial_write ("g", 1);
4727 }
4728 else
4729 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4730 interrupt_sequence_mode);
4731 }
4732
4733 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4734 and extract the PTID. Returns NULL_PTID if not found. */
4735
4736 static ptid_t
4737 stop_reply_extract_thread (const char *stop_reply)
4738 {
4739 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4740 {
4741 const char *p;
4742
4743 /* Txx r:val ; r:val (...) */
4744 p = &stop_reply[3];
4745
4746 /* Look for "register" named "thread". */
4747 while (*p != '\0')
4748 {
4749 const char *p1;
4750
4751 p1 = strchr (p, ':');
4752 if (p1 == NULL)
4753 return null_ptid;
4754
4755 if (strncmp (p, "thread", p1 - p) == 0)
4756 return read_ptid (++p1, &p);
4757
4758 p1 = strchr (p, ';');
4759 if (p1 == NULL)
4760 return null_ptid;
4761 p1++;
4762
4763 p = p1;
4764 }
4765 }
4766
4767 return null_ptid;
4768 }
4769
4770 /* Determine the remote side's current thread. If we have a stop
4771 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4772 "thread" register we can extract the current thread from. If not,
4773 ask the remote which is the current thread with qC. The former
4774 method avoids a roundtrip. */
4775
4776 ptid_t
4777 remote_target::get_current_thread (const char *wait_status)
4778 {
4779 ptid_t ptid = null_ptid;
4780
4781 /* Note we don't use remote_parse_stop_reply as that makes use of
4782 the target architecture, which we haven't yet fully determined at
4783 this point. */
4784 if (wait_status != NULL)
4785 ptid = stop_reply_extract_thread (wait_status);
4786 if (ptid == null_ptid)
4787 ptid = remote_current_thread (inferior_ptid);
4788
4789 return ptid;
4790 }
4791
4792 /* Query the remote target for which is the current thread/process,
4793 add it to our tables, and update INFERIOR_PTID. The caller is
4794 responsible for setting the state such that the remote end is ready
4795 to return the current thread.
4796
4797 This function is called after handling the '?' or 'vRun' packets,
4798 whose response is a stop reply from which we can also try
4799 extracting the thread. If the target doesn't support the explicit
4800 qC query, we infer the current thread from that stop reply, passed
4801 in in WAIT_STATUS, which may be NULL.
4802
4803 The function returns pointer to the main thread of the inferior. */
4804
4805 thread_info *
4806 remote_target::add_current_inferior_and_thread (const char *wait_status)
4807 {
4808 bool fake_pid_p = false;
4809
4810 switch_to_no_thread ();
4811
4812 /* Now, if we have thread information, update the current thread's
4813 ptid. */
4814 ptid_t curr_ptid = get_current_thread (wait_status);
4815
4816 if (curr_ptid != null_ptid)
4817 {
4818 if (!m_features.remote_multi_process_p ())
4819 fake_pid_p = true;
4820 }
4821 else
4822 {
4823 /* Without this, some commands which require an active target
4824 (such as kill) won't work. This variable serves (at least)
4825 double duty as both the pid of the target process (if it has
4826 such), and as a flag indicating that a target is active. */
4827 curr_ptid = magic_null_ptid;
4828 fake_pid_p = true;
4829 }
4830
4831 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4832
4833 /* Add the main thread and switch to it. Don't try reading
4834 registers yet, since we haven't fetched the target description
4835 yet. */
4836 thread_info *tp = add_thread_silent (this, curr_ptid);
4837 switch_to_thread_no_regs (tp);
4838
4839 return tp;
4840 }
4841
4842 /* Print info about a thread that was found already stopped on
4843 connection. */
4844
4845 void
4846 remote_target::print_one_stopped_thread (thread_info *thread)
4847 {
4848 target_waitstatus ws;
4849
4850 /* If there is a pending waitstatus, use it. If there isn't it's because
4851 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4852 and process_initial_stop_replies decided it wasn't interesting to save
4853 and report to the core. */
4854 if (thread->has_pending_waitstatus ())
4855 {
4856 ws = thread->pending_waitstatus ();
4857 thread->clear_pending_waitstatus ();
4858 }
4859 else
4860 {
4861 ws.set_stopped (GDB_SIGNAL_0);
4862 }
4863
4864 switch_to_thread (thread);
4865 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4866 set_current_sal_from_frame (get_current_frame ());
4867
4868 /* For "info program". */
4869 set_last_target_status (this, thread->ptid, ws);
4870
4871 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4872 {
4873 enum gdb_signal sig = ws.sig ();
4874
4875 if (signal_print_state (sig))
4876 notify_signal_received (sig);
4877 }
4878
4879 notify_normal_stop (nullptr, 1);
4880 }
4881
4882 /* Process all initial stop replies the remote side sent in response
4883 to the ? packet. These indicate threads that were already stopped
4884 on initial connection. We mark these threads as stopped and print
4885 their current frame before giving the user the prompt. */
4886
4887 void
4888 remote_target::process_initial_stop_replies (int from_tty)
4889 {
4890 int pending_stop_replies = stop_reply_queue_length ();
4891 struct thread_info *selected = NULL;
4892 struct thread_info *lowest_stopped = NULL;
4893 struct thread_info *first = NULL;
4894
4895 /* This is only used when the target is non-stop. */
4896 gdb_assert (target_is_non_stop_p ());
4897
4898 /* Consume the initial pending events. */
4899 while (pending_stop_replies-- > 0)
4900 {
4901 ptid_t waiton_ptid = minus_one_ptid;
4902 ptid_t event_ptid;
4903 struct target_waitstatus ws;
4904 int ignore_event = 0;
4905
4906 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4907 if (remote_debug)
4908 print_target_wait_results (waiton_ptid, event_ptid, ws);
4909
4910 switch (ws.kind ())
4911 {
4912 case TARGET_WAITKIND_IGNORE:
4913 case TARGET_WAITKIND_NO_RESUMED:
4914 case TARGET_WAITKIND_SIGNALLED:
4915 case TARGET_WAITKIND_EXITED:
4916 /* We shouldn't see these, but if we do, just ignore. */
4917 remote_debug_printf ("event ignored");
4918 ignore_event = 1;
4919 break;
4920
4921 default:
4922 break;
4923 }
4924
4925 if (ignore_event)
4926 continue;
4927
4928 thread_info *evthread = this->find_thread (event_ptid);
4929
4930 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4931 {
4932 enum gdb_signal sig = ws.sig ();
4933
4934 /* Stubs traditionally report SIGTRAP as initial signal,
4935 instead of signal 0. Suppress it. */
4936 if (sig == GDB_SIGNAL_TRAP)
4937 sig = GDB_SIGNAL_0;
4938 evthread->set_stop_signal (sig);
4939 ws.set_stopped (sig);
4940 }
4941
4942 if (ws.kind () != TARGET_WAITKIND_STOPPED
4943 || ws.sig () != GDB_SIGNAL_0)
4944 evthread->set_pending_waitstatus (ws);
4945
4946 set_executing (this, event_ptid, false);
4947 set_running (this, event_ptid, false);
4948 get_remote_thread_info (evthread)->set_not_resumed ();
4949 }
4950
4951 /* "Notice" the new inferiors before anything related to
4952 registers/memory. */
4953 for (inferior *inf : all_non_exited_inferiors (this))
4954 {
4955 inf->needs_setup = true;
4956
4957 if (non_stop)
4958 {
4959 thread_info *thread = any_live_thread_of_inferior (inf);
4960 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4961 from_tty);
4962 }
4963 }
4964
4965 /* If all-stop on top of non-stop, pause all threads. Note this
4966 records the threads' stop pc, so must be done after "noticing"
4967 the inferiors. */
4968 if (!non_stop)
4969 {
4970 {
4971 /* At this point, the remote target is not async. It needs to be for
4972 the poll in stop_all_threads to consider events from it, so enable
4973 it temporarily. */
4974 gdb_assert (!this->is_async_p ());
4975 SCOPE_EXIT { target_async (false); };
4976 target_async (true);
4977 stop_all_threads ("remote connect in all-stop");
4978 }
4979
4980 /* If all threads of an inferior were already stopped, we
4981 haven't setup the inferior yet. */
4982 for (inferior *inf : all_non_exited_inferiors (this))
4983 {
4984 if (inf->needs_setup)
4985 {
4986 thread_info *thread = any_live_thread_of_inferior (inf);
4987 switch_to_thread_no_regs (thread);
4988 setup_inferior (0);
4989 }
4990 }
4991 }
4992
4993 /* Now go over all threads that are stopped, and print their current
4994 frame. If all-stop, then if there's a signalled thread, pick
4995 that as current. */
4996 for (thread_info *thread : all_non_exited_threads (this))
4997 {
4998 if (first == NULL)
4999 first = thread;
5000
5001 if (!non_stop)
5002 thread->set_running (false);
5003 else if (thread->state != THREAD_STOPPED)
5004 continue;
5005
5006 if (selected == nullptr && thread->has_pending_waitstatus ())
5007 selected = thread;
5008
5009 if (lowest_stopped == NULL
5010 || thread->inf->num < lowest_stopped->inf->num
5011 || thread->per_inf_num < lowest_stopped->per_inf_num)
5012 lowest_stopped = thread;
5013
5014 if (non_stop)
5015 print_one_stopped_thread (thread);
5016 }
5017
5018 /* In all-stop, we only print the status of one thread, and leave
5019 others with their status pending. */
5020 if (!non_stop)
5021 {
5022 thread_info *thread = selected;
5023 if (thread == NULL)
5024 thread = lowest_stopped;
5025 if (thread == NULL)
5026 thread = first;
5027
5028 print_one_stopped_thread (thread);
5029 }
5030 }
5031
5032 /* Mark a remote_target as starting (by setting the starting_up flag within
5033 its remote_state) for the lifetime of this object. The reference count
5034 on the remote target is temporarily incremented, to prevent the target
5035 being deleted under our feet. */
5036
5037 struct scoped_mark_target_starting
5038 {
5039 /* Constructor, TARGET is the target to be marked as starting, its
5040 reference count will be incremented. */
5041 scoped_mark_target_starting (remote_target *target)
5042 : m_remote_target (remote_target_ref::new_reference (target)),
5043 m_restore_starting_up (set_starting_up_flag (target))
5044 { /* Nothing. */ }
5045
5046 private:
5047
5048 /* Helper function, set the starting_up flag on TARGET and return an
5049 object which, when it goes out of scope, will restore the previous
5050 value of the starting_up flag. */
5051 static scoped_restore_tmpl<bool>
5052 set_starting_up_flag (remote_target *target)
5053 {
5054 remote_state *rs = target->get_remote_state ();
5055 gdb_assert (!rs->starting_up);
5056 return make_scoped_restore (&rs->starting_up, true);
5057 }
5058
5059 /* A gdb::ref_ptr pointer to a remote_target. */
5060 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
5061
5062 /* A reference to the target on which we are operating. */
5063 remote_target_ref m_remote_target;
5064
5065 /* An object which restores the previous value of the starting_up flag
5066 when it goes out of scope. */
5067 scoped_restore_tmpl<bool> m_restore_starting_up;
5068 };
5069
5070 /* Transfer ownership of the stop_reply owned by EVENT to a
5071 stop_reply_up object. */
5072
5073 static stop_reply_up
5074 as_stop_reply_up (notif_event_up event)
5075 {
5076 auto *stop_reply = static_cast<struct stop_reply *> (event.release ());
5077 return stop_reply_up (stop_reply);
5078 }
5079
5080 /* Helper for remote_target::start_remote, start the remote connection and
5081 sync state. Return true if everything goes OK, otherwise, return false.
5082 This function exists so that the scoped_restore created within it will
5083 expire before we return to remote_target::start_remote. */
5084
5085 bool
5086 remote_target::start_remote_1 (int from_tty, int extended_p)
5087 {
5088 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
5089
5090 struct remote_state *rs = get_remote_state ();
5091
5092 /* Signal other parts that we're going through the initial setup,
5093 and so things may not be stable yet. E.g., we don't try to
5094 install tracepoints until we've relocated symbols. Also, a
5095 Ctrl-C before we're connected and synced up can't interrupt the
5096 target. Instead, it offers to drop the (potentially wedged)
5097 connection. */
5098 scoped_mark_target_starting target_is_starting (this);
5099
5100 QUIT;
5101
5102 if (interrupt_on_connect)
5103 send_interrupt_sequence ();
5104
5105 /* Ack any packet which the remote side has already sent. */
5106 remote_serial_write ("+", 1);
5107
5108 /* The first packet we send to the target is the optional "supported
5109 packets" request. If the target can answer this, it will tell us
5110 which later probes to skip. */
5111 remote_query_supported ();
5112
5113 /* Check vCont support and set the remote state's vCont_action_support
5114 attribute. */
5115 remote_vcont_probe ();
5116
5117 /* If the stub wants to get a QAllow, compose one and send it. */
5118 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5119 set_permissions ();
5120
5121 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5122 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5123 as a reply to known packet. For packet "vFile:setfs:" it is an
5124 invalid reply and GDB would return error in
5125 remote_hostio_set_filesystem, making remote files access impossible.
5126 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5127 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5128 {
5129 const char v_mustreplyempty[] = "vMustReplyEmpty";
5130
5131 putpkt (v_mustreplyempty);
5132 getpkt (&rs->buf);
5133 if (strcmp (rs->buf.data (), "OK") == 0)
5134 {
5135 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5136 = PACKET_DISABLE;
5137 }
5138 else if (strcmp (rs->buf.data (), "") != 0)
5139 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5140 rs->buf.data ());
5141 }
5142
5143 /* Next, we possibly activate noack mode.
5144
5145 If the QStartNoAckMode packet configuration is set to AUTO,
5146 enable noack mode if the stub reported a wish for it with
5147 qSupported.
5148
5149 If set to TRUE, then enable noack mode even if the stub didn't
5150 report it in qSupported. If the stub doesn't reply OK, the
5151 session ends with an error.
5152
5153 If FALSE, then don't activate noack mode, regardless of what the
5154 stub claimed should be the default with qSupported. */
5155
5156 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5157 {
5158 putpkt ("QStartNoAckMode");
5159 getpkt (&rs->buf);
5160 if ((m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode)).status ()
5161 == PACKET_OK)
5162 rs->noack_mode = 1;
5163 }
5164
5165 if (extended_p)
5166 {
5167 /* Tell the remote that we are using the extended protocol. */
5168 putpkt ("!");
5169 getpkt (&rs->buf);
5170 }
5171
5172 /* Let the target know which signals it is allowed to pass down to
5173 the program. */
5174 update_signals_program_target ();
5175
5176 /* Next, if the target can specify a description, read it. We do
5177 this before anything involving memory or registers. */
5178 target_find_description ();
5179
5180 /* Next, now that we know something about the target, update the
5181 address spaces in the program spaces. */
5182 update_address_spaces ();
5183
5184 /* On OSs where the list of libraries is global to all
5185 processes, we fetch them early. */
5186 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5187 solib_add (NULL, from_tty, auto_solib_add);
5188
5189 if (target_is_non_stop_p ())
5190 {
5191 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5192 error (_("Non-stop mode requested, but remote "
5193 "does not support non-stop"));
5194
5195 putpkt ("QNonStop:1");
5196 getpkt (&rs->buf);
5197
5198 if (strcmp (rs->buf.data (), "OK") != 0)
5199 error (_("Remote refused setting non-stop mode with: %s"),
5200 rs->buf.data ());
5201
5202 /* Find about threads and processes the stub is already
5203 controlling. We default to adding them in the running state.
5204 The '?' query below will then tell us about which threads are
5205 stopped. */
5206 this->update_thread_list ();
5207 }
5208 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5209 {
5210 /* Don't assume that the stub can operate in all-stop mode.
5211 Request it explicitly. */
5212 putpkt ("QNonStop:0");
5213 getpkt (&rs->buf);
5214
5215 if (strcmp (rs->buf.data (), "OK") != 0)
5216 error (_("Remote refused setting all-stop mode with: %s"),
5217 rs->buf.data ());
5218 }
5219
5220 /* Upload TSVs regardless of whether the target is running or not. The
5221 remote stub, such as GDBserver, may have some predefined or builtin
5222 TSVs, even if the target is not running. */
5223 if (get_trace_status (current_trace_status ()) != -1)
5224 {
5225 struct uploaded_tsv *uploaded_tsvs = NULL;
5226
5227 upload_trace_state_variables (&uploaded_tsvs);
5228 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5229 }
5230
5231 /* Check whether the target is running now. */
5232 putpkt ("?");
5233 getpkt (&rs->buf);
5234
5235 if (!target_is_non_stop_p ())
5236 {
5237 char *wait_status = NULL;
5238
5239 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5240 {
5241 if (!extended_p)
5242 error (_("The target is not running (try extended-remote?)"));
5243 return false;
5244 }
5245 else
5246 {
5247 /* Save the reply for later. */
5248 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5249 strcpy (wait_status, rs->buf.data ());
5250 }
5251
5252 /* Fetch thread list. */
5253 target_update_thread_list ();
5254
5255 /* Let the stub know that we want it to return the thread. */
5256 set_continue_thread (minus_one_ptid);
5257
5258 if (thread_count (this) == 0)
5259 {
5260 /* Target has no concept of threads at all. GDB treats
5261 non-threaded target as single-threaded; add a main
5262 thread. */
5263 thread_info *tp = add_current_inferior_and_thread (wait_status);
5264 get_remote_thread_info (tp)->set_resumed ();
5265 }
5266 else
5267 {
5268 /* We have thread information; select the thread the target
5269 says should be current. If we're reconnecting to a
5270 multi-threaded program, this will ideally be the thread
5271 that last reported an event before GDB disconnected. */
5272 ptid_t curr_thread = get_current_thread (wait_status);
5273 if (curr_thread == null_ptid)
5274 {
5275 /* Odd... The target was able to list threads, but not
5276 tell us which thread was current (no "thread"
5277 register in T stop reply?). Just pick the first
5278 thread in the thread list then. */
5279
5280 remote_debug_printf ("warning: couldn't determine remote "
5281 "current thread; picking first in list.");
5282
5283 for (thread_info *tp : all_non_exited_threads (this,
5284 minus_one_ptid))
5285 {
5286 switch_to_thread (tp);
5287 break;
5288 }
5289 }
5290 else
5291 switch_to_thread (this->find_thread (curr_thread));
5292
5293 get_remote_thread_info (inferior_thread ())->set_resumed ();
5294 }
5295
5296 /* init_wait_for_inferior should be called before get_offsets in order
5297 to manage `inserted' flag in bp loc in a correct state.
5298 breakpoint_init_inferior, called from init_wait_for_inferior, set
5299 `inserted' flag to 0, while before breakpoint_re_set, called from
5300 start_remote, set `inserted' flag to 1. In the initialization of
5301 inferior, breakpoint_init_inferior should be called first, and then
5302 breakpoint_re_set can be called. If this order is broken, state of
5303 `inserted' flag is wrong, and cause some problems on breakpoint
5304 manipulation. */
5305 init_wait_for_inferior ();
5306
5307 get_offsets (); /* Get text, data & bss offsets. */
5308
5309 /* If we could not find a description using qXfer, and we know
5310 how to do it some other way, try again. This is not
5311 supported for non-stop; it could be, but it is tricky if
5312 there are no stopped threads when we connect. */
5313 if (remote_read_description_p (this)
5314 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5315 {
5316 target_clear_description ();
5317 target_find_description ();
5318 }
5319
5320 /* Use the previously fetched status. */
5321 gdb_assert (wait_status != NULL);
5322 notif_event_up reply
5323 = remote_notif_parse (this, &notif_client_stop, wait_status);
5324 push_stop_reply (as_stop_reply_up (std::move (reply)));
5325
5326 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5327 }
5328 else
5329 {
5330 /* Clear WFI global state. Do this before finding about new
5331 threads and inferiors, and setting the current inferior.
5332 Otherwise we would clear the proceed status of the current
5333 inferior when we want its stop_soon state to be preserved
5334 (see notice_new_inferior). */
5335 init_wait_for_inferior ();
5336
5337 /* In non-stop, we will either get an "OK", meaning that there
5338 are no stopped threads at this time; or, a regular stop
5339 reply. In the latter case, there may be more than one thread
5340 stopped --- we pull them all out using the vStopped
5341 mechanism. */
5342 if (strcmp (rs->buf.data (), "OK") != 0)
5343 {
5344 const notif_client *notif = &notif_client_stop;
5345
5346 /* remote_notif_get_pending_replies acks this one, and gets
5347 the rest out. */
5348 rs->notif_state->pending_event[notif_client_stop.id]
5349 = remote_notif_parse (this, notif, rs->buf.data ());
5350 remote_notif_get_pending_events (notif);
5351 }
5352
5353 if (thread_count (this) == 0)
5354 {
5355 if (!extended_p)
5356 error (_("The target is not running (try extended-remote?)"));
5357 return false;
5358 }
5359
5360 /* Report all signals during attach/startup. */
5361 pass_signals ({});
5362
5363 /* If there are already stopped threads, mark them stopped and
5364 report their stops before giving the prompt to the user. */
5365 process_initial_stop_replies (from_tty);
5366
5367 if (target_can_async_p ())
5368 target_async (true);
5369 }
5370
5371 /* Give the target a chance to look up symbols. */
5372 for (inferior *inf : all_inferiors (this))
5373 {
5374 /* The inferiors that exist at this point were created from what
5375 was found already running on the remote side, so we know they
5376 have execution. */
5377 gdb_assert (this->has_execution (inf));
5378
5379 /* No use without a symbol-file. */
5380 if (inf->pspace->symfile_object_file == nullptr)
5381 continue;
5382
5383 /* Need to switch to a specific thread, because remote_check_symbols
5384 uses INFERIOR_PTID to set the general thread. */
5385 scoped_restore_current_thread restore_thread;
5386 thread_info *thread = any_thread_of_inferior (inf);
5387 switch_to_thread (thread);
5388 this->remote_check_symbols ();
5389 }
5390
5391 /* Possibly the target has been engaged in a trace run started
5392 previously; find out where things are at. */
5393 if (get_trace_status (current_trace_status ()) != -1)
5394 {
5395 struct uploaded_tp *uploaded_tps = NULL;
5396
5397 if (current_trace_status ()->running)
5398 gdb_printf (_("Trace is already running on the target.\n"));
5399
5400 upload_tracepoints (&uploaded_tps);
5401
5402 merge_uploaded_tracepoints (&uploaded_tps);
5403 }
5404
5405 /* Possibly the target has been engaged in a btrace record started
5406 previously; find out where things are at. */
5407 remote_btrace_maybe_reopen ();
5408
5409 return true;
5410 }
5411
5412 /* Start the remote connection and sync state. */
5413
5414 void
5415 remote_target::start_remote (int from_tty, int extended_p)
5416 {
5417 if (start_remote_1 (from_tty, extended_p)
5418 && breakpoints_should_be_inserted_now ())
5419 insert_breakpoints ();
5420 }
5421
5422 const char *
5423 remote_target::connection_string ()
5424 {
5425 remote_state *rs = get_remote_state ();
5426
5427 if (rs->remote_desc->name != NULL)
5428 return rs->remote_desc->name;
5429 else
5430 return NULL;
5431 }
5432
5433 /* Open a connection to a remote debugger.
5434 NAME is the filename used for communication. */
5435
5436 void
5437 remote_target::open (const char *name, int from_tty)
5438 {
5439 open_1 (name, from_tty, 0);
5440 }
5441
5442 /* Open a connection to a remote debugger using the extended
5443 remote gdb protocol. NAME is the filename used for communication. */
5444
5445 void
5446 extended_remote_target::open (const char *name, int from_tty)
5447 {
5448 open_1 (name, from_tty, 1 /*extended_p */);
5449 }
5450
5451 void
5452 remote_features::reset_all_packet_configs_support ()
5453 {
5454 int i;
5455
5456 for (i = 0; i < PACKET_MAX; i++)
5457 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5458 }
5459
5460 /* Initialize all packet configs. */
5461
5462 static void
5463 init_all_packet_configs (void)
5464 {
5465 int i;
5466
5467 for (i = 0; i < PACKET_MAX; i++)
5468 {
5469 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5470 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5471 }
5472 }
5473
5474 /* Symbol look-up. */
5475
5476 void
5477 remote_target::remote_check_symbols ()
5478 {
5479 char *tmp;
5480 int end;
5481
5482 /* It doesn't make sense to send a qSymbol packet for an inferior that
5483 doesn't have execution, because the remote side doesn't know about
5484 inferiors without execution. */
5485 gdb_assert (target_has_execution ());
5486
5487 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5488 return;
5489
5490 /* Make sure the remote is pointing at the right process. Note
5491 there's no way to select "no process". */
5492 set_general_process ();
5493
5494 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5495 because we need both at the same time. */
5496 gdb::char_vector msg (get_remote_packet_size ());
5497 gdb::char_vector reply (get_remote_packet_size ());
5498
5499 /* Invite target to request symbol lookups. */
5500
5501 putpkt ("qSymbol::");
5502 getpkt (&reply);
5503 m_features.packet_ok (reply, PACKET_qSymbol);
5504
5505 while (startswith (reply.data (), "qSymbol:"))
5506 {
5507 struct bound_minimal_symbol sym;
5508
5509 tmp = &reply[8];
5510 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5511 strlen (tmp) / 2);
5512 msg[end] = '\0';
5513 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5514 if (sym.minsym == NULL)
5515 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5516 &reply[8]);
5517 else
5518 {
5519 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5520 CORE_ADDR sym_addr = sym.value_address ();
5521
5522 /* If this is a function address, return the start of code
5523 instead of any data function descriptor. */
5524 sym_addr = gdbarch_convert_from_func_ptr_addr
5525 (current_inferior ()->arch (), sym_addr,
5526 current_inferior ()->top_target ());
5527
5528 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5529 phex_nz (sym_addr, addr_size), &reply[8]);
5530 }
5531
5532 putpkt (msg.data ());
5533 getpkt (&reply);
5534 }
5535 }
5536
5537 static struct serial *
5538 remote_serial_open (const char *name)
5539 {
5540 static int udp_warning = 0;
5541
5542 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5543 of in ser-tcp.c, because it is the remote protocol assuming that the
5544 serial connection is reliable and not the serial connection promising
5545 to be. */
5546 if (!udp_warning && startswith (name, "udp:"))
5547 {
5548 warning (_("The remote protocol may be unreliable over UDP.\n"
5549 "Some events may be lost, rendering further debugging "
5550 "impossible."));
5551 udp_warning = 1;
5552 }
5553
5554 return serial_open (name);
5555 }
5556
5557 /* Inform the target of our permission settings. The permission flags
5558 work without this, but if the target knows the settings, it can do
5559 a couple things. First, it can add its own check, to catch cases
5560 that somehow manage to get by the permissions checks in target
5561 methods. Second, if the target is wired to disallow particular
5562 settings (for instance, a system in the field that is not set up to
5563 be able to stop at a breakpoint), it can object to any unavailable
5564 permissions. */
5565
5566 void
5567 remote_target::set_permissions ()
5568 {
5569 struct remote_state *rs = get_remote_state ();
5570
5571 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5572 "WriteReg:%x;WriteMem:%x;"
5573 "InsertBreak:%x;InsertTrace:%x;"
5574 "InsertFastTrace:%x;Stop:%x",
5575 may_write_registers, may_write_memory,
5576 may_insert_breakpoints, may_insert_tracepoints,
5577 may_insert_fast_tracepoints, may_stop);
5578 putpkt (rs->buf);
5579 getpkt (&rs->buf);
5580
5581 /* If the target didn't like the packet, warn the user. Do not try
5582 to undo the user's settings, that would just be maddening. */
5583 if (strcmp (rs->buf.data (), "OK") != 0)
5584 warning (_("Remote refused setting permissions with: %s"),
5585 rs->buf.data ());
5586 }
5587
5588 /* This type describes each known response to the qSupported
5589 packet. */
5590 struct protocol_feature
5591 {
5592 /* The name of this protocol feature. */
5593 const char *name;
5594
5595 /* The default for this protocol feature. */
5596 enum packet_support default_support;
5597
5598 /* The function to call when this feature is reported, or after
5599 qSupported processing if the feature is not supported.
5600 The first argument points to this structure. The second
5601 argument indicates whether the packet requested support be
5602 enabled, disabled, or probed (or the default, if this function
5603 is being called at the end of processing and this feature was
5604 not reported). The third argument may be NULL; if not NULL, it
5605 is a NUL-terminated string taken from the packet following
5606 this feature's name and an equals sign. */
5607 void (*func) (remote_target *remote, const struct protocol_feature *,
5608 enum packet_support, const char *);
5609
5610 /* The corresponding packet for this feature. Only used if
5611 FUNC is remote_supported_packet. */
5612 int packet;
5613 };
5614
5615 static void
5616 remote_supported_packet (remote_target *remote,
5617 const struct protocol_feature *feature,
5618 enum packet_support support,
5619 const char *argument)
5620 {
5621 if (argument)
5622 {
5623 warning (_("Remote qSupported response supplied an unexpected value for"
5624 " \"%s\"."), feature->name);
5625 return;
5626 }
5627
5628 remote->m_features.m_protocol_packets[feature->packet].support = support;
5629 }
5630
5631 void
5632 remote_target::remote_packet_size (const protocol_feature *feature,
5633 enum packet_support support,
5634 const char *value)
5635 {
5636 struct remote_state *rs = get_remote_state ();
5637
5638 int packet_size;
5639 char *value_end;
5640
5641 if (support != PACKET_ENABLE)
5642 return;
5643
5644 if (value == NULL || *value == '\0')
5645 {
5646 warning (_("Remote target reported \"%s\" without a size."),
5647 feature->name);
5648 return;
5649 }
5650
5651 errno = 0;
5652 packet_size = strtol (value, &value_end, 16);
5653 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5654 {
5655 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5656 feature->name, value);
5657 return;
5658 }
5659
5660 /* Record the new maximum packet size. */
5661 rs->explicit_packet_size = packet_size;
5662 }
5663
5664 static void
5665 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5666 enum packet_support support, const char *value)
5667 {
5668 remote->remote_packet_size (feature, support, value);
5669 }
5670
5671 void
5672 remote_target::remote_supported_thread_options (const protocol_feature *feature,
5673 enum packet_support support,
5674 const char *value)
5675 {
5676 struct remote_state *rs = get_remote_state ();
5677
5678 m_features.m_protocol_packets[feature->packet].support = support;
5679
5680 if (support != PACKET_ENABLE)
5681 return;
5682
5683 if (value == nullptr || *value == '\0')
5684 {
5685 warning (_("Remote target reported \"%s\" without supported options."),
5686 feature->name);
5687 return;
5688 }
5689
5690 ULONGEST options = 0;
5691 const char *p = unpack_varlen_hex (value, &options);
5692
5693 if (*p != '\0')
5694 {
5695 warning (_("Remote target reported \"%s\" with "
5696 "bad thread options: \"%s\"."),
5697 feature->name, value);
5698 return;
5699 }
5700
5701 /* Record the set of supported options. */
5702 rs->supported_thread_options = (gdb_thread_option) options;
5703 }
5704
5705 static void
5706 remote_supported_thread_options (remote_target *remote,
5707 const protocol_feature *feature,
5708 enum packet_support support,
5709 const char *value)
5710 {
5711 remote->remote_supported_thread_options (feature, support, value);
5712 }
5713
5714 static const struct protocol_feature remote_protocol_features[] = {
5715 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5716 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5717 PACKET_qXfer_auxv },
5718 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5719 PACKET_qXfer_exec_file },
5720 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5721 PACKET_qXfer_features },
5722 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5723 PACKET_qXfer_libraries },
5724 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5725 PACKET_qXfer_libraries_svr4 },
5726 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5727 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5728 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5729 PACKET_qXfer_memory_map },
5730 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5731 PACKET_qXfer_osdata },
5732 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5733 PACKET_qXfer_threads },
5734 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5735 PACKET_qXfer_traceframe_info },
5736 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5737 PACKET_QPassSignals },
5738 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5739 PACKET_QCatchSyscalls },
5740 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5741 PACKET_QProgramSignals },
5742 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5743 PACKET_QSetWorkingDir },
5744 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5745 PACKET_QStartupWithShell },
5746 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5747 PACKET_QEnvironmentHexEncoded },
5748 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5749 PACKET_QEnvironmentReset },
5750 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5751 PACKET_QEnvironmentUnset },
5752 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5753 PACKET_QStartNoAckMode },
5754 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5755 PACKET_multiprocess_feature },
5756 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5757 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5758 PACKET_qXfer_siginfo_read },
5759 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5760 PACKET_qXfer_siginfo_write },
5761 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5762 PACKET_ConditionalTracepoints },
5763 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5764 PACKET_ConditionalBreakpoints },
5765 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5766 PACKET_BreakpointCommands },
5767 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5768 PACKET_FastTracepoints },
5769 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5770 PACKET_StaticTracepoints },
5771 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5772 PACKET_InstallInTrace},
5773 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5774 PACKET_DisconnectedTracing_feature },
5775 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5776 PACKET_bc },
5777 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5778 PACKET_bs },
5779 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5780 PACKET_TracepointSource },
5781 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5782 PACKET_QAllow },
5783 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5784 PACKET_EnableDisableTracepoints_feature },
5785 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5786 PACKET_qXfer_fdpic },
5787 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5788 PACKET_qXfer_uib },
5789 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5790 PACKET_QDisableRandomization },
5791 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5792 { "QTBuffer:size", PACKET_DISABLE,
5793 remote_supported_packet, PACKET_QTBuffer_size},
5794 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5795 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5796 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5797 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5798 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5799 PACKET_qXfer_btrace },
5800 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5801 PACKET_qXfer_btrace_conf },
5802 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5803 PACKET_Qbtrace_conf_bts_size },
5804 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5805 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5806 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5807 PACKET_fork_event_feature },
5808 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5809 PACKET_vfork_event_feature },
5810 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5811 PACKET_exec_event_feature },
5812 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5813 PACKET_Qbtrace_conf_pt_size },
5814 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5815 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5816 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5817 PACKET_QThreadOptions },
5818 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5819 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5820 PACKET_memory_tagging_feature },
5821 };
5822
5823 static char *remote_support_xml;
5824
5825 /* Register string appended to "xmlRegisters=" in qSupported query. */
5826
5827 void
5828 register_remote_support_xml (const char *xml)
5829 {
5830 #if defined(HAVE_LIBEXPAT)
5831 if (remote_support_xml == NULL)
5832 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5833 else
5834 {
5835 char *copy = xstrdup (remote_support_xml + 13);
5836 char *saveptr;
5837 char *p = strtok_r (copy, ",", &saveptr);
5838
5839 do
5840 {
5841 if (strcmp (p, xml) == 0)
5842 {
5843 /* already there */
5844 xfree (copy);
5845 return;
5846 }
5847 }
5848 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5849 xfree (copy);
5850
5851 remote_support_xml = reconcat (remote_support_xml,
5852 remote_support_xml, ",", xml,
5853 (char *) NULL);
5854 }
5855 #endif
5856 }
5857
5858 static void
5859 remote_query_supported_append (std::string *msg, const char *append)
5860 {
5861 if (!msg->empty ())
5862 msg->append (";");
5863 msg->append (append);
5864 }
5865
5866 void
5867 remote_target::remote_query_supported ()
5868 {
5869 struct remote_state *rs = get_remote_state ();
5870 char *next;
5871 int i;
5872 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5873
5874 /* The packet support flags are handled differently for this packet
5875 than for most others. We treat an error, a disabled packet, and
5876 an empty response identically: any features which must be reported
5877 to be used will be automatically disabled. An empty buffer
5878 accomplishes this, since that is also the representation for a list
5879 containing no features. */
5880
5881 rs->buf[0] = 0;
5882 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5883 {
5884 std::string q;
5885
5886 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5887 != AUTO_BOOLEAN_FALSE)
5888 remote_query_supported_append (&q, "multiprocess+");
5889
5890 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5891 != AUTO_BOOLEAN_FALSE)
5892 remote_query_supported_append (&q, "swbreak+");
5893
5894 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5895 != AUTO_BOOLEAN_FALSE)
5896 remote_query_supported_append (&q, "hwbreak+");
5897
5898 remote_query_supported_append (&q, "qRelocInsn+");
5899
5900 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5901 != AUTO_BOOLEAN_FALSE)
5902 remote_query_supported_append (&q, "fork-events+");
5903
5904 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5905 != AUTO_BOOLEAN_FALSE)
5906 remote_query_supported_append (&q, "vfork-events+");
5907
5908 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5909 != AUTO_BOOLEAN_FALSE)
5910 remote_query_supported_append (&q, "exec-events+");
5911
5912 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5913 != AUTO_BOOLEAN_FALSE)
5914 remote_query_supported_append (&q, "vContSupported+");
5915
5916 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5917 != AUTO_BOOLEAN_FALSE)
5918 remote_query_supported_append (&q, "QThreadEvents+");
5919
5920 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5921 != AUTO_BOOLEAN_FALSE)
5922 remote_query_supported_append (&q, "QThreadOptions+");
5923
5924 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5925 != AUTO_BOOLEAN_FALSE)
5926 remote_query_supported_append (&q, "no-resumed+");
5927
5928 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5929 != AUTO_BOOLEAN_FALSE)
5930 remote_query_supported_append (&q, "memory-tagging+");
5931
5932 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5933 the qSupported:xmlRegisters=i386 handling. */
5934 if (remote_support_xml != NULL
5935 && (m_features.packet_support (PACKET_qXfer_features)
5936 != PACKET_DISABLE))
5937 remote_query_supported_append (&q, remote_support_xml);
5938
5939 q = "qSupported:" + q;
5940 putpkt (q.c_str ());
5941
5942 getpkt (&rs->buf);
5943
5944 /* If an error occurred, warn, but do not return - just reset the
5945 buffer to empty and go on to disable features. */
5946 packet_result result = m_features.packet_ok (rs->buf, PACKET_qSupported);
5947 if (result.status () == PACKET_ERROR)
5948 {
5949 warning (_("Remote failure reply: %s"), result.err_msg ());
5950 rs->buf[0] = 0;
5951 }
5952 }
5953
5954 memset (seen, 0, sizeof (seen));
5955
5956 next = rs->buf.data ();
5957 while (*next)
5958 {
5959 enum packet_support is_supported;
5960 char *p, *end, *name_end, *value;
5961
5962 /* First separate out this item from the rest of the packet. If
5963 there's another item after this, we overwrite the separator
5964 (terminated strings are much easier to work with). */
5965 p = next;
5966 end = strchr (p, ';');
5967 if (end == NULL)
5968 {
5969 end = p + strlen (p);
5970 next = end;
5971 }
5972 else
5973 {
5974 *end = '\0';
5975 next = end + 1;
5976
5977 if (end == p)
5978 {
5979 warning (_("empty item in \"qSupported\" response"));
5980 continue;
5981 }
5982 }
5983
5984 name_end = strchr (p, '=');
5985 if (name_end)
5986 {
5987 /* This is a name=value entry. */
5988 is_supported = PACKET_ENABLE;
5989 value = name_end + 1;
5990 *name_end = '\0';
5991 }
5992 else
5993 {
5994 value = NULL;
5995 switch (end[-1])
5996 {
5997 case '+':
5998 is_supported = PACKET_ENABLE;
5999 break;
6000
6001 case '-':
6002 is_supported = PACKET_DISABLE;
6003 break;
6004
6005 case '?':
6006 is_supported = PACKET_SUPPORT_UNKNOWN;
6007 break;
6008
6009 default:
6010 warning (_("unrecognized item \"%s\" "
6011 "in \"qSupported\" response"), p);
6012 continue;
6013 }
6014 end[-1] = '\0';
6015 }
6016
6017 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6018 if (strcmp (remote_protocol_features[i].name, p) == 0)
6019 {
6020 const struct protocol_feature *feature;
6021
6022 seen[i] = 1;
6023 feature = &remote_protocol_features[i];
6024 feature->func (this, feature, is_supported, value);
6025 break;
6026 }
6027 }
6028
6029 /* If we increased the packet size, make sure to increase the global
6030 buffer size also. We delay this until after parsing the entire
6031 qSupported packet, because this is the same buffer we were
6032 parsing. */
6033 if (rs->buf.size () < rs->explicit_packet_size)
6034 rs->buf.resize (rs->explicit_packet_size);
6035
6036 /* Handle the defaults for unmentioned features. */
6037 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
6038 if (!seen[i])
6039 {
6040 const struct protocol_feature *feature;
6041
6042 feature = &remote_protocol_features[i];
6043 feature->func (this, feature, feature->default_support, NULL);
6044 }
6045 }
6046
6047 /* Serial QUIT handler for the remote serial descriptor.
6048
6049 Defers handling a Ctrl-C until we're done with the current
6050 command/response packet sequence, unless:
6051
6052 - We're setting up the connection. Don't send a remote interrupt
6053 request, as we're not fully synced yet. Quit immediately
6054 instead.
6055
6056 - The target has been resumed in the foreground
6057 (target_terminal::is_ours is false) with a synchronous resume
6058 packet, and we're blocked waiting for the stop reply, thus a
6059 Ctrl-C should be immediately sent to the target.
6060
6061 - We get a second Ctrl-C while still within the same serial read or
6062 write. In that case the serial is seemingly wedged --- offer to
6063 quit/disconnect.
6064
6065 - We see a second Ctrl-C without target response, after having
6066 previously interrupted the target. In that case the target/stub
6067 is probably wedged --- offer to quit/disconnect.
6068 */
6069
6070 void
6071 remote_target::remote_serial_quit_handler ()
6072 {
6073 struct remote_state *rs = get_remote_state ();
6074
6075 if (check_quit_flag ())
6076 {
6077 /* If we're starting up, we're not fully synced yet. Quit
6078 immediately. */
6079 if (rs->starting_up)
6080 quit ();
6081 else if (rs->got_ctrlc_during_io)
6082 {
6083 if (query (_("The target is not responding to GDB commands.\n"
6084 "Stop debugging it? ")))
6085 remote_unpush_and_throw (this);
6086 }
6087 /* If ^C has already been sent once, offer to disconnect. */
6088 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
6089 interrupt_query ();
6090 /* All-stop protocol, and blocked waiting for stop reply. Send
6091 an interrupt request. */
6092 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
6093 target_interrupt ();
6094 else
6095 rs->got_ctrlc_during_io = 1;
6096 }
6097 }
6098
6099 /* The remote_target that is current while the quit handler is
6100 overridden with remote_serial_quit_handler. */
6101 static remote_target *curr_quit_handler_target;
6102
6103 static void
6104 remote_serial_quit_handler ()
6105 {
6106 curr_quit_handler_target->remote_serial_quit_handler ();
6107 }
6108
6109 /* Remove the remote target from the target stack of each inferior
6110 that is using it. Upper targets depend on it so remove them
6111 first. */
6112
6113 static void
6114 remote_unpush_target (remote_target *target)
6115 {
6116 /* We have to unpush the target from all inferiors, even those that
6117 aren't running. */
6118 scoped_restore_current_inferior restore_current_inferior;
6119
6120 for (inferior *inf : all_inferiors (target))
6121 {
6122 switch_to_inferior_no_thread (inf);
6123 inf->pop_all_targets_at_and_above (process_stratum);
6124 generic_mourn_inferior ();
6125 }
6126
6127 /* Don't rely on target_close doing this when the target is popped
6128 from the last remote inferior above, because something may be
6129 holding a reference to the target higher up on the stack, meaning
6130 target_close won't be called yet. We lost the connection to the
6131 target, so clear these now, otherwise we may later throw
6132 TARGET_CLOSE_ERROR while trying to tell the remote target to
6133 close the file. */
6134 fileio_handles_invalidate_target (target);
6135 }
6136
6137 static void
6138 remote_unpush_and_throw (remote_target *target)
6139 {
6140 remote_unpush_target (target);
6141 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6142 }
6143
6144 void
6145 remote_target::open_1 (const char *name, int from_tty, int extended_p)
6146 {
6147 remote_target *curr_remote = get_current_remote_target ();
6148
6149 if (name == 0)
6150 error (_("To open a remote debug connection, you need to specify what\n"
6151 "serial device is attached to the remote system\n"
6152 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6153
6154 /* If we're connected to a running target, target_preopen will kill it.
6155 Ask this question first, before target_preopen has a chance to kill
6156 anything. */
6157 if (curr_remote != NULL && !target_has_execution ())
6158 {
6159 if (from_tty
6160 && !query (_("Already connected to a remote target. Disconnect? ")))
6161 error (_("Still connected."));
6162 }
6163
6164 /* Here the possibly existing remote target gets unpushed. */
6165 target_preopen (from_tty);
6166
6167 remote_fileio_reset ();
6168 reopen_exec_file ();
6169 reread_symbols (from_tty);
6170
6171 remote_target *remote
6172 = (extended_p ? new extended_remote_target () : new remote_target ());
6173 target_ops_up target_holder (remote);
6174
6175 remote_state *rs = remote->get_remote_state ();
6176
6177 /* See FIXME above. */
6178 if (!target_async_permitted)
6179 rs->wait_forever_enabled_p = true;
6180
6181 rs->remote_desc = remote_serial_open (name);
6182
6183 if (baud_rate != -1)
6184 {
6185 try
6186 {
6187 serial_setbaudrate (rs->remote_desc, baud_rate);
6188 }
6189 catch (const gdb_exception_error &)
6190 {
6191 /* The requested speed could not be set. Error out to
6192 top level after closing remote_desc. Take care to
6193 set remote_desc to NULL to avoid closing remote_desc
6194 more than once. */
6195 serial_close (rs->remote_desc);
6196 rs->remote_desc = NULL;
6197 throw;
6198 }
6199 }
6200
6201 serial_setparity (rs->remote_desc, serial_parity);
6202 serial_raw (rs->remote_desc);
6203
6204 /* If there is something sitting in the buffer we might take it as a
6205 response to a command, which would be bad. */
6206 serial_flush_input (rs->remote_desc);
6207
6208 if (from_tty)
6209 {
6210 gdb_puts ("Remote debugging using ");
6211 gdb_puts (name);
6212 gdb_puts ("\n");
6213 }
6214
6215 /* Switch to using the remote target now. */
6216 current_inferior ()->push_target (std::move (target_holder));
6217
6218 /* Register extra event sources in the event loop. */
6219 rs->create_async_event_handler ();
6220
6221 rs->notif_state = remote_notif_state_allocate (remote);
6222
6223 /* Reset the target state; these things will be queried either by
6224 remote_query_supported or as they are needed. */
6225 remote->m_features.reset_all_packet_configs_support ();
6226 rs->explicit_packet_size = 0;
6227 rs->noack_mode = 0;
6228 rs->extended = extended_p;
6229 rs->waiting_for_stop_reply = 0;
6230 rs->ctrlc_pending_p = 0;
6231 rs->got_ctrlc_during_io = 0;
6232
6233 rs->general_thread = not_sent_ptid;
6234 rs->continue_thread = not_sent_ptid;
6235 rs->remote_traceframe_number = -1;
6236
6237 rs->last_resume_exec_dir = EXEC_FORWARD;
6238
6239 /* Probe for ability to use "ThreadInfo" query, as required. */
6240 rs->use_threadinfo_query = 1;
6241 rs->use_threadextra_query = 1;
6242
6243 rs->readahead_cache.invalidate ();
6244
6245 if (target_async_permitted)
6246 {
6247 /* FIXME: cagney/1999-09-23: During the initial connection it is
6248 assumed that the target is already ready and able to respond to
6249 requests. Unfortunately remote_start_remote() eventually calls
6250 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6251 around this. Eventually a mechanism that allows
6252 wait_for_inferior() to expect/get timeouts will be
6253 implemented. */
6254 rs->wait_forever_enabled_p = false;
6255 }
6256
6257 /* First delete any symbols previously loaded from shared libraries. */
6258 no_shared_libraries (NULL, 0);
6259
6260 /* Start the remote connection. If error() or QUIT, discard this
6261 target (we'd otherwise be in an inconsistent state) and then
6262 propogate the error on up the exception chain. This ensures that
6263 the caller doesn't stumble along blindly assuming that the
6264 function succeeded. The CLI doesn't have this problem but other
6265 UI's, such as MI do.
6266
6267 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6268 this function should return an error indication letting the
6269 caller restore the previous state. Unfortunately the command
6270 ``target remote'' is directly wired to this function making that
6271 impossible. On a positive note, the CLI side of this problem has
6272 been fixed - the function set_cmd_context() makes it possible for
6273 all the ``target ....'' commands to share a common callback
6274 function. See cli-dump.c. */
6275 {
6276
6277 try
6278 {
6279 remote->start_remote (from_tty, extended_p);
6280 }
6281 catch (const gdb_exception &ex)
6282 {
6283 /* Pop the partially set up target - unless something else did
6284 already before throwing the exception. */
6285 if (ex.error != TARGET_CLOSE_ERROR)
6286 remote_unpush_target (remote);
6287 throw;
6288 }
6289 }
6290
6291 remote_btrace_reset (rs);
6292
6293 if (target_async_permitted)
6294 rs->wait_forever_enabled_p = true;
6295 }
6296
6297 /* Determine if WS represents a fork status. */
6298
6299 static bool
6300 is_fork_status (target_waitkind kind)
6301 {
6302 return (kind == TARGET_WAITKIND_FORKED
6303 || kind == TARGET_WAITKIND_VFORKED);
6304 }
6305
6306 /* Return a reference to the field where a pending child status, if
6307 there's one, is recorded. If there's no child event pending, the
6308 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6309
6310 static const target_waitstatus &
6311 thread_pending_status (struct thread_info *thread)
6312 {
6313 return (thread->has_pending_waitstatus ()
6314 ? thread->pending_waitstatus ()
6315 : thread->pending_follow);
6316 }
6317
6318 /* Return THREAD's pending status if it is a pending fork/vfork (but
6319 not clone) parent, else return nullptr. */
6320
6321 static const target_waitstatus *
6322 thread_pending_fork_status (struct thread_info *thread)
6323 {
6324 const target_waitstatus &ws = thread_pending_status (thread);
6325
6326 if (!is_fork_status (ws.kind ()))
6327 return nullptr;
6328
6329 return &ws;
6330 }
6331
6332 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6333 event, else return nullptr. */
6334
6335 static const target_waitstatus *
6336 thread_pending_child_status (thread_info *thread)
6337 {
6338 const target_waitstatus &ws = thread_pending_status (thread);
6339
6340 if (!is_new_child_status (ws.kind ()))
6341 return nullptr;
6342
6343 return &ws;
6344 }
6345
6346 /* Detach the specified process. */
6347
6348 void
6349 remote_target::remote_detach_pid (int pid)
6350 {
6351 struct remote_state *rs = get_remote_state ();
6352
6353 /* This should not be necessary, but the handling for D;PID in
6354 GDBserver versions prior to 8.2 incorrectly assumes that the
6355 selected process points to the same process we're detaching,
6356 leading to misbehavior (and possibly GDBserver crashing) when it
6357 does not. Since it's easy and cheap, work around it by forcing
6358 GDBserver to select GDB's current process. */
6359 set_general_process ();
6360
6361 if (m_features.remote_multi_process_p ())
6362 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6363 else
6364 strcpy (rs->buf.data (), "D");
6365
6366 putpkt (rs->buf);
6367 getpkt (&rs->buf);
6368
6369 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6370 ;
6371 else if (rs->buf[0] == '\0')
6372 error (_("Remote doesn't know how to detach"));
6373 else
6374 {
6375 /* It is possible that we have an unprocessed exit event for this
6376 pid. If this is the case then we can ignore the failure to detach
6377 and just pretend that the detach worked, as far as the user is
6378 concerned, the process exited immediately after the detach. */
6379 bool process_has_already_exited = false;
6380 remote_notif_get_pending_events (&notif_client_stop);
6381 for (stop_reply_up &reply : rs->stop_reply_queue)
6382 {
6383 if (reply->ptid.pid () != pid)
6384 continue;
6385
6386 enum target_waitkind kind = reply->ws.kind ();
6387 if (kind == TARGET_WAITKIND_EXITED
6388 || kind == TARGET_WAITKIND_SIGNALLED)
6389 {
6390 process_has_already_exited = true;
6391 remote_debug_printf
6392 ("detach failed, but process already exited");
6393 break;
6394 }
6395 }
6396
6397 if (!process_has_already_exited)
6398 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6399 }
6400 }
6401
6402 /* This detaches a program to which we previously attached, using
6403 inferior_ptid to identify the process. After this is done, GDB
6404 can be used to debug some other program. We better not have left
6405 any breakpoints in the target program or it'll die when it hits
6406 one. */
6407
6408 void
6409 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6410 {
6411 int pid = inferior_ptid.pid ();
6412 struct remote_state *rs = get_remote_state ();
6413 int is_fork_parent;
6414
6415 if (!target_has_execution ())
6416 error (_("No process to detach from."));
6417
6418 target_announce_detach (from_tty);
6419
6420 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6421 {
6422 /* If we're in breakpoints-always-inserted mode, or the inferior
6423 is running, we have to remove breakpoints before detaching.
6424 We don't do this in common code instead because not all
6425 targets support removing breakpoints while the target is
6426 running. The remote target / gdbserver does, though. */
6427 remove_breakpoints_inf (current_inferior ());
6428 }
6429
6430 /* Tell the remote target to detach. */
6431 remote_detach_pid (pid);
6432
6433 /* Exit only if this is the only active inferior. */
6434 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6435 gdb_puts (_("Ending remote debugging.\n"));
6436
6437 /* See if any thread of the inferior we are detaching has a pending fork
6438 status. In that case, we must detach from the child resulting from
6439 that fork. */
6440 for (thread_info *thread : inf->non_exited_threads ())
6441 {
6442 const target_waitstatus *ws = thread_pending_fork_status (thread);
6443
6444 if (ws == nullptr)
6445 continue;
6446
6447 remote_detach_pid (ws->child_ptid ().pid ());
6448 }
6449
6450 /* Check also for any pending fork events in the stop reply queue. */
6451 remote_notif_get_pending_events (&notif_client_stop);
6452 for (stop_reply_up &reply : rs->stop_reply_queue)
6453 {
6454 if (reply->ptid.pid () != pid)
6455 continue;
6456
6457 if (!is_fork_status (reply->ws.kind ()))
6458 continue;
6459
6460 remote_detach_pid (reply->ws.child_ptid ().pid ());
6461 }
6462
6463 thread_info *tp = this->find_thread (inferior_ptid);
6464
6465 /* Check to see if we are detaching a fork parent. Note that if we
6466 are detaching a fork child, tp == NULL. */
6467 is_fork_parent = (tp != NULL
6468 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6469
6470 /* If doing detach-on-fork, we don't mourn, because that will delete
6471 breakpoints that should be available for the followed inferior. */
6472 if (!is_fork_parent)
6473 {
6474 /* Save the pid as a string before mourning, since that will
6475 unpush the remote target, and we need the string after. */
6476 std::string infpid = target_pid_to_str (ptid_t (pid));
6477
6478 target_mourn_inferior (inferior_ptid);
6479 if (print_inferior_events)
6480 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6481 inf->num, infpid.c_str ());
6482 }
6483 else
6484 {
6485 switch_to_no_thread ();
6486 detach_inferior (current_inferior ());
6487 }
6488 }
6489
6490 void
6491 remote_target::detach (inferior *inf, int from_tty)
6492 {
6493 remote_detach_1 (inf, from_tty);
6494 }
6495
6496 void
6497 extended_remote_target::detach (inferior *inf, int from_tty)
6498 {
6499 remote_detach_1 (inf, from_tty);
6500 }
6501
6502 /* Target follow-fork function for remote targets. On entry, and
6503 at return, the current inferior is the fork parent.
6504
6505 Note that although this is currently only used for extended-remote,
6506 it is named remote_follow_fork in anticipation of using it for the
6507 remote target as well. */
6508
6509 void
6510 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6511 target_waitkind fork_kind, bool follow_child,
6512 bool detach_fork)
6513 {
6514 process_stratum_target::follow_fork (child_inf, child_ptid,
6515 fork_kind, follow_child, detach_fork);
6516
6517 if ((fork_kind == TARGET_WAITKIND_FORKED
6518 && m_features.remote_fork_event_p ())
6519 || (fork_kind == TARGET_WAITKIND_VFORKED
6520 && m_features.remote_vfork_event_p ()))
6521 {
6522 /* When following the parent and detaching the child, we detach
6523 the child here. For the case of following the child and
6524 detaching the parent, the detach is done in the target-
6525 independent follow fork code in infrun.c. We can't use
6526 target_detach when detaching an unfollowed child because
6527 the client side doesn't know anything about the child. */
6528 if (detach_fork && !follow_child)
6529 {
6530 /* Detach the fork child. */
6531 remote_detach_pid (child_ptid.pid ());
6532 }
6533 }
6534 }
6535
6536 void
6537 remote_target::follow_clone (ptid_t child_ptid)
6538 {
6539 remote_add_thread (child_ptid, false, false, false);
6540 }
6541
6542 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6543 in the program space of the new inferior. */
6544
6545 void
6546 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6547 const char *execd_pathname)
6548 {
6549 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6550
6551 /* We know that this is a target file name, so if it has the "target:"
6552 prefix we strip it off before saving it in the program space. */
6553 if (is_target_filename (execd_pathname))
6554 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6555
6556 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6557 }
6558
6559 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6560
6561 void
6562 remote_target::disconnect (const char *args, int from_tty)
6563 {
6564 if (args)
6565 error (_("Argument given to \"disconnect\" when remotely debugging."));
6566
6567 /* Make sure we unpush even the extended remote targets. Calling
6568 target_mourn_inferior won't unpush, and
6569 remote_target::mourn_inferior won't unpush if there is more than
6570 one inferior left. */
6571 remote_unpush_target (this);
6572
6573 if (from_tty)
6574 gdb_puts ("Ending remote debugging.\n");
6575 }
6576
6577 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6578 be chatty about it. */
6579
6580 void
6581 extended_remote_target::attach (const char *args, int from_tty)
6582 {
6583 struct remote_state *rs = get_remote_state ();
6584 int pid;
6585 char *wait_status = NULL;
6586
6587 pid = parse_pid_to_attach (args);
6588
6589 /* Remote PID can be freely equal to getpid, do not check it here the same
6590 way as in other targets. */
6591
6592 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6593 error (_("This target does not support attaching to a process"));
6594
6595 target_announce_attach (from_tty, pid);
6596
6597 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6598 putpkt (rs->buf);
6599 getpkt (&rs->buf);
6600
6601 packet_result result = m_features.packet_ok (rs->buf, PACKET_vAttach);
6602 switch (result.status ())
6603 {
6604 case PACKET_OK:
6605 if (!target_is_non_stop_p ())
6606 {
6607 /* Save the reply for later. */
6608 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6609 strcpy (wait_status, rs->buf.data ());
6610 }
6611 else if (strcmp (rs->buf.data (), "OK") != 0)
6612 error (_("Attaching to %s failed with: %s"),
6613 target_pid_to_str (ptid_t (pid)).c_str (),
6614 rs->buf.data ());
6615 break;
6616 case PACKET_UNKNOWN:
6617 error (_("This target does not support attaching to a process"));
6618 case PACKET_ERROR:
6619 error (_("Attaching to %s failed: %s"),
6620 target_pid_to_str (ptid_t (pid)).c_str (), result.err_msg ());
6621 }
6622
6623 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6624
6625 inferior_ptid = ptid_t (pid);
6626
6627 if (target_is_non_stop_p ())
6628 {
6629 /* Get list of threads. */
6630 update_thread_list ();
6631
6632 thread_info *thread = first_thread_of_inferior (current_inferior ());
6633 if (thread != nullptr)
6634 switch_to_thread (thread);
6635
6636 /* Invalidate our notion of the remote current thread. */
6637 record_currthread (rs, minus_one_ptid);
6638 }
6639 else
6640 {
6641 /* Now, if we have thread information, update the main thread's
6642 ptid. */
6643 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6644
6645 /* Add the main thread to the thread list. We add the thread
6646 silently in this case (the final true parameter). */
6647 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6648
6649 switch_to_thread (thr);
6650 }
6651
6652 /* Next, if the target can specify a description, read it. We do
6653 this before anything involving memory or registers. */
6654 target_find_description ();
6655
6656 if (!target_is_non_stop_p ())
6657 {
6658 /* Use the previously fetched status. */
6659 gdb_assert (wait_status != NULL);
6660
6661 notif_event_up reply
6662 = remote_notif_parse (this, &notif_client_stop, wait_status);
6663 push_stop_reply (as_stop_reply_up (std::move (reply)));
6664 }
6665 else
6666 {
6667 gdb_assert (wait_status == NULL);
6668
6669 gdb_assert (target_can_async_p ());
6670 }
6671 }
6672
6673 /* Implementation of the to_post_attach method. */
6674
6675 void
6676 extended_remote_target::post_attach (int pid)
6677 {
6678 /* Get text, data & bss offsets. */
6679 get_offsets ();
6680
6681 /* In certain cases GDB might not have had the chance to start
6682 symbol lookup up until now. This could happen if the debugged
6683 binary is not using shared libraries, the vsyscall page is not
6684 present (on Linux) and the binary itself hadn't changed since the
6685 debugging process was started. */
6686 if (current_program_space->symfile_object_file != NULL)
6687 remote_check_symbols();
6688 }
6689
6690 \f
6691 /* Check for the availability of vCont. This function should also check
6692 the response. */
6693
6694 void
6695 remote_target::remote_vcont_probe ()
6696 {
6697 remote_state *rs = get_remote_state ();
6698 char *buf;
6699
6700 strcpy (rs->buf.data (), "vCont?");
6701 putpkt (rs->buf);
6702 getpkt (&rs->buf);
6703 buf = rs->buf.data ();
6704
6705 /* Make sure that the features we assume are supported. */
6706 if (startswith (buf, "vCont"))
6707 {
6708 char *p = &buf[5];
6709 int support_c, support_C;
6710
6711 rs->supports_vCont.s = 0;
6712 rs->supports_vCont.S = 0;
6713 support_c = 0;
6714 support_C = 0;
6715 rs->supports_vCont.t = 0;
6716 rs->supports_vCont.r = 0;
6717 while (p && *p == ';')
6718 {
6719 p++;
6720 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6721 rs->supports_vCont.s = 1;
6722 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6723 rs->supports_vCont.S = 1;
6724 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6725 support_c = 1;
6726 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6727 support_C = 1;
6728 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6729 rs->supports_vCont.t = 1;
6730 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6731 rs->supports_vCont.r = 1;
6732
6733 p = strchr (p, ';');
6734 }
6735
6736 /* If c, and C are not all supported, we can't use vCont. Clearing
6737 BUF will make packet_ok disable the packet. */
6738 if (!support_c || !support_C)
6739 buf[0] = 0;
6740 }
6741
6742 m_features.packet_ok (rs->buf, PACKET_vCont);
6743 }
6744
6745 /* Helper function for building "vCont" resumptions. Write a
6746 resumption to P. ENDP points to one-passed-the-end of the buffer
6747 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6748 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6749 resumed thread should be single-stepped and/or signalled. If PTID
6750 equals minus_one_ptid, then all threads are resumed; if PTID
6751 represents a process, then all threads of the process are
6752 resumed. */
6753
6754 char *
6755 remote_target::append_resumption (char *p, char *endp,
6756 ptid_t ptid, int step, gdb_signal siggnal)
6757 {
6758 struct remote_state *rs = get_remote_state ();
6759
6760 if (step && siggnal != GDB_SIGNAL_0)
6761 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6762 else if (step
6763 /* GDB is willing to range step. */
6764 && use_range_stepping
6765 /* Target supports range stepping. */
6766 && rs->supports_vCont.r
6767 /* We don't currently support range stepping multiple
6768 threads with a wildcard (though the protocol allows it,
6769 so stubs shouldn't make an active effort to forbid
6770 it). */
6771 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6772 {
6773 struct thread_info *tp;
6774
6775 if (ptid == minus_one_ptid)
6776 {
6777 /* If we don't know about the target thread's tid, then
6778 we're resuming magic_null_ptid (see caller). */
6779 tp = this->find_thread (magic_null_ptid);
6780 }
6781 else
6782 tp = this->find_thread (ptid);
6783 gdb_assert (tp != NULL);
6784
6785 if (tp->control.may_range_step)
6786 {
6787 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6788
6789 p += xsnprintf (p, endp - p, ";r%s,%s",
6790 phex_nz (tp->control.step_range_start,
6791 addr_size),
6792 phex_nz (tp->control.step_range_end,
6793 addr_size));
6794 }
6795 else
6796 p += xsnprintf (p, endp - p, ";s");
6797 }
6798 else if (step)
6799 p += xsnprintf (p, endp - p, ";s");
6800 else if (siggnal != GDB_SIGNAL_0)
6801 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6802 else
6803 p += xsnprintf (p, endp - p, ";c");
6804
6805 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6806 {
6807 ptid_t nptid;
6808
6809 /* All (-1) threads of process. */
6810 nptid = ptid_t (ptid.pid (), -1);
6811
6812 p += xsnprintf (p, endp - p, ":");
6813 p = write_ptid (p, endp, nptid);
6814 }
6815 else if (ptid != minus_one_ptid)
6816 {
6817 p += xsnprintf (p, endp - p, ":");
6818 p = write_ptid (p, endp, ptid);
6819 }
6820
6821 return p;
6822 }
6823
6824 /* Clear the thread's private info on resume. */
6825
6826 static void
6827 resume_clear_thread_private_info (struct thread_info *thread)
6828 {
6829 if (thread->priv != NULL)
6830 {
6831 remote_thread_info *priv = get_remote_thread_info (thread);
6832
6833 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6834 priv->watch_data_address = 0;
6835 }
6836 }
6837
6838 /* Append a vCont continue-with-signal action for threads that have a
6839 non-zero stop signal. */
6840
6841 char *
6842 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6843 ptid_t ptid)
6844 {
6845 for (thread_info *thread : all_non_exited_threads (this, ptid))
6846 if (inferior_ptid != thread->ptid
6847 && thread->stop_signal () != GDB_SIGNAL_0)
6848 {
6849 p = append_resumption (p, endp, thread->ptid,
6850 0, thread->stop_signal ());
6851 thread->set_stop_signal (GDB_SIGNAL_0);
6852 resume_clear_thread_private_info (thread);
6853 }
6854
6855 return p;
6856 }
6857
6858 /* Set the target running, using the packets that use Hc
6859 (c/s/C/S). */
6860
6861 void
6862 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6863 gdb_signal siggnal)
6864 {
6865 struct remote_state *rs = get_remote_state ();
6866 char *buf;
6867
6868 rs->last_sent_signal = siggnal;
6869 rs->last_sent_step = step;
6870
6871 /* The c/s/C/S resume packets use Hc, so set the continue
6872 thread. */
6873 if (ptid == minus_one_ptid)
6874 set_continue_thread (any_thread_ptid);
6875 else
6876 set_continue_thread (ptid);
6877
6878 for (thread_info *thread : all_non_exited_threads (this))
6879 resume_clear_thread_private_info (thread);
6880
6881 buf = rs->buf.data ();
6882 if (::execution_direction == EXEC_REVERSE)
6883 {
6884 /* We don't pass signals to the target in reverse exec mode. */
6885 if (info_verbose && siggnal != GDB_SIGNAL_0)
6886 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6887 siggnal);
6888
6889 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6890 error (_("Remote reverse-step not supported."));
6891 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6892 error (_("Remote reverse-continue not supported."));
6893
6894 strcpy (buf, step ? "bs" : "bc");
6895 }
6896 else if (siggnal != GDB_SIGNAL_0)
6897 {
6898 buf[0] = step ? 'S' : 'C';
6899 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6900 buf[2] = tohex (((int) siggnal) & 0xf);
6901 buf[3] = '\0';
6902 }
6903 else
6904 strcpy (buf, step ? "s" : "c");
6905
6906 putpkt (buf);
6907 }
6908
6909 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6910 STEP, and SIGGNAL have the same meaning as in target_resume. This
6911 function returns non-zero iff it resumes the inferior.
6912
6913 This function issues a strict subset of all possible vCont commands
6914 at the moment. */
6915
6916 int
6917 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6918 enum gdb_signal siggnal)
6919 {
6920 struct remote_state *rs = get_remote_state ();
6921 char *p;
6922 char *endp;
6923
6924 /* No reverse execution actions defined for vCont. */
6925 if (::execution_direction == EXEC_REVERSE)
6926 return 0;
6927
6928 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6929 return 0;
6930
6931 p = rs->buf.data ();
6932 endp = p + get_remote_packet_size ();
6933
6934 /* If we could generate a wider range of packets, we'd have to worry
6935 about overflowing BUF. Should there be a generic
6936 "multi-part-packet" packet? */
6937
6938 p += xsnprintf (p, endp - p, "vCont");
6939
6940 if (scope_ptid == magic_null_ptid)
6941 {
6942 /* MAGIC_NULL_PTID means that we don't have any active threads,
6943 so we don't have any TID numbers the inferior will
6944 understand. Make sure to only send forms that do not specify
6945 a TID. */
6946 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6947 }
6948 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6949 {
6950 /* Resume all threads (of all processes, or of a single
6951 process), with preference for INFERIOR_PTID. This assumes
6952 inferior_ptid belongs to the set of all threads we are about
6953 to resume. */
6954 if (step || siggnal != GDB_SIGNAL_0)
6955 {
6956 /* Step inferior_ptid, with or without signal. */
6957 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6958 }
6959
6960 /* Also pass down any pending signaled resumption for other
6961 threads not the current. */
6962 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6963
6964 /* And continue others without a signal. */
6965 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6966 }
6967 else
6968 {
6969 /* Scheduler locking; resume only SCOPE_PTID. */
6970 append_resumption (p, endp, scope_ptid, step, siggnal);
6971 }
6972
6973 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6974 putpkt (rs->buf);
6975
6976 if (target_is_non_stop_p ())
6977 {
6978 /* In non-stop, the stub replies to vCont with "OK". The stop
6979 reply will be reported asynchronously by means of a `%Stop'
6980 notification. */
6981 getpkt (&rs->buf);
6982 if (strcmp (rs->buf.data (), "OK") != 0)
6983 error (_("Unexpected vCont reply in non-stop mode: %s"),
6984 rs->buf.data ());
6985 }
6986
6987 return 1;
6988 }
6989
6990 /* Tell the remote machine to resume. */
6991
6992 void
6993 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6994 {
6995 struct remote_state *rs = get_remote_state ();
6996
6997 /* When connected in non-stop mode, the core resumes threads
6998 individually. Resuming remote threads directly in target_resume
6999 would thus result in sending one packet per thread. Instead, to
7000 minimize roundtrip latency, here we just store the resume
7001 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
7002 resumption will be done in remote_target::commit_resume, where we'll be
7003 able to do vCont action coalescing. */
7004 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
7005 {
7006 remote_thread_info *remote_thr
7007 = get_remote_thread_info (inferior_thread ());
7008
7009 /* We don't expect the core to ask to resume an already resumed (from
7010 its point of view) thread. */
7011 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
7012
7013 remote_thr->set_resumed_pending_vcont (step, siggnal);
7014
7015 /* There's actually nothing that says that the core can't
7016 request a wildcard resume in non-stop mode, though. It's
7017 just that we know it doesn't currently, so we don't bother
7018 with it. */
7019 gdb_assert (scope_ptid == inferior_ptid);
7020 return;
7021 }
7022
7023 commit_requested_thread_options ();
7024
7025 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
7026 (explained in remote-notif.c:handle_notification) so
7027 remote_notif_process is not called. We need find a place where
7028 it is safe to start a 'vNotif' sequence. It is good to do it
7029 before resuming inferior, because inferior was stopped and no RSP
7030 traffic at that moment. */
7031 if (!target_is_non_stop_p ())
7032 remote_notif_process (rs->notif_state, &notif_client_stop);
7033
7034 rs->last_resume_exec_dir = ::execution_direction;
7035
7036 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
7037 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
7038 remote_resume_with_hc (scope_ptid, step, siggnal);
7039
7040 /* Update resumed state tracked by the remote target. */
7041 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
7042 get_remote_thread_info (tp)->set_resumed ();
7043
7044 /* We've just told the target to resume. The remote server will
7045 wait for the inferior to stop, and then send a stop reply. In
7046 the mean time, we can't start another command/query ourselves
7047 because the stub wouldn't be ready to process it. This applies
7048 only to the base all-stop protocol, however. In non-stop (which
7049 only supports vCont), the stub replies with an "OK", and is
7050 immediate able to process further serial input. */
7051 if (!target_is_non_stop_p ())
7052 rs->waiting_for_stop_reply = 1;
7053 }
7054
7055 /* Private per-inferior info for target remote processes. */
7056
7057 struct remote_inferior : public private_inferior
7058 {
7059 /* Whether we can send a wildcard vCont for this process. */
7060 bool may_wildcard_vcont = true;
7061 };
7062
7063 /* Get the remote private inferior data associated to INF. */
7064
7065 static remote_inferior *
7066 get_remote_inferior (inferior *inf)
7067 {
7068 if (inf->priv == NULL)
7069 inf->priv.reset (new remote_inferior);
7070
7071 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
7072 }
7073
7074 /* Class used to track the construction of a vCont packet in the
7075 outgoing packet buffer. This is used to send multiple vCont
7076 packets if we have more actions than would fit a single packet. */
7077
7078 class vcont_builder
7079 {
7080 public:
7081 explicit vcont_builder (remote_target *remote)
7082 : m_remote (remote)
7083 {
7084 restart ();
7085 }
7086
7087 void flush ();
7088 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
7089
7090 private:
7091 void restart ();
7092
7093 /* The remote target. */
7094 remote_target *m_remote;
7095
7096 /* Pointer to the first action. P points here if no action has been
7097 appended yet. */
7098 char *m_first_action;
7099
7100 /* Where the next action will be appended. */
7101 char *m_p;
7102
7103 /* The end of the buffer. Must never write past this. */
7104 char *m_endp;
7105 };
7106
7107 /* Prepare the outgoing buffer for a new vCont packet. */
7108
7109 void
7110 vcont_builder::restart ()
7111 {
7112 struct remote_state *rs = m_remote->get_remote_state ();
7113
7114 m_p = rs->buf.data ();
7115 m_endp = m_p + m_remote->get_remote_packet_size ();
7116 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7117 m_first_action = m_p;
7118 }
7119
7120 /* If the vCont packet being built has any action, send it to the
7121 remote end. */
7122
7123 void
7124 vcont_builder::flush ()
7125 {
7126 struct remote_state *rs;
7127
7128 if (m_p == m_first_action)
7129 return;
7130
7131 rs = m_remote->get_remote_state ();
7132 m_remote->putpkt (rs->buf);
7133 m_remote->getpkt (&rs->buf);
7134 if (strcmp (rs->buf.data (), "OK") != 0)
7135 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7136 }
7137
7138 /* The largest action is range-stepping, with its two addresses. This
7139 is more than sufficient. If a new, bigger action is created, it'll
7140 quickly trigger a failed assertion in append_resumption (and we'll
7141 just bump this). */
7142 #define MAX_ACTION_SIZE 200
7143
7144 /* Append a new vCont action in the outgoing packet being built. If
7145 the action doesn't fit the packet along with previous actions, push
7146 what we've got so far to the remote end and start over a new vCont
7147 packet (with the new action). */
7148
7149 void
7150 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7151 {
7152 char buf[MAX_ACTION_SIZE + 1];
7153
7154 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7155 ptid, step, siggnal);
7156
7157 /* Check whether this new action would fit in the vCont packet along
7158 with previous actions. If not, send what we've got so far and
7159 start a new vCont packet. */
7160 size_t rsize = endp - buf;
7161 if (rsize > m_endp - m_p)
7162 {
7163 flush ();
7164 restart ();
7165
7166 /* Should now fit. */
7167 gdb_assert (rsize <= m_endp - m_p);
7168 }
7169
7170 memcpy (m_p, buf, rsize);
7171 m_p += rsize;
7172 *m_p = '\0';
7173 }
7174
7175 /* to_commit_resume implementation. */
7176
7177 void
7178 remote_target::commit_resumed ()
7179 {
7180 /* If connected in all-stop mode, we'd send the remote resume
7181 request directly from remote_resume. Likewise if
7182 reverse-debugging, as there are no defined vCont actions for
7183 reverse execution. */
7184 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7185 return;
7186
7187 commit_requested_thread_options ();
7188
7189 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7190 instead of resuming all threads of each process individually.
7191 However, if any thread of a process must remain halted, we can't
7192 send wildcard resumes and must send one action per thread.
7193
7194 Care must be taken to not resume threads/processes the server
7195 side already told us are stopped, but the core doesn't know about
7196 yet, because the events are still in the vStopped notification
7197 queue. For example:
7198
7199 #1 => vCont s:p1.1;c
7200 #2 <= OK
7201 #3 <= %Stopped T05 p1.1
7202 #4 => vStopped
7203 #5 <= T05 p1.2
7204 #6 => vStopped
7205 #7 <= OK
7206 #8 (infrun handles the stop for p1.1 and continues stepping)
7207 #9 => vCont s:p1.1;c
7208
7209 The last vCont above would resume thread p1.2 by mistake, because
7210 the server has no idea that the event for p1.2 had not been
7211 handled yet.
7212
7213 The server side must similarly ignore resume actions for the
7214 thread that has a pending %Stopped notification (and any other
7215 threads with events pending), until GDB acks the notification
7216 with vStopped. Otherwise, e.g., the following case is
7217 mishandled:
7218
7219 #1 => g (or any other packet)
7220 #2 <= [registers]
7221 #3 <= %Stopped T05 p1.2
7222 #4 => vCont s:p1.1;c
7223 #5 <= OK
7224
7225 Above, the server must not resume thread p1.2. GDB can't know
7226 that p1.2 stopped until it acks the %Stopped notification, and
7227 since from GDB's perspective all threads should be running, it
7228 sends a "c" action.
7229
7230 Finally, special care must also be given to handling fork/vfork
7231 events. A (v)fork event actually tells us that two processes
7232 stopped -- the parent and the child. Until we follow the fork,
7233 we must not resume the child. Therefore, if we have a pending
7234 fork follow, we must not send a global wildcard resume action
7235 (vCont;c). We can still send process-wide wildcards though. */
7236
7237 /* Start by assuming a global wildcard (vCont;c) is possible. */
7238 bool may_global_wildcard_vcont = true;
7239
7240 /* And assume every process is individually wildcard-able too. */
7241 for (inferior *inf : all_non_exited_inferiors (this))
7242 {
7243 remote_inferior *priv = get_remote_inferior (inf);
7244
7245 priv->may_wildcard_vcont = true;
7246 }
7247
7248 /* Check for any pending events (not reported or processed yet) and
7249 disable process and global wildcard resumes appropriately. */
7250 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7251
7252 bool any_pending_vcont_resume = false;
7253
7254 for (thread_info *tp : all_non_exited_threads (this))
7255 {
7256 remote_thread_info *priv = get_remote_thread_info (tp);
7257
7258 /* If a thread of a process is not meant to be resumed, then we
7259 can't wildcard that process. */
7260 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7261 {
7262 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7263
7264 /* And if we can't wildcard a process, we can't wildcard
7265 everything either. */
7266 may_global_wildcard_vcont = false;
7267 continue;
7268 }
7269
7270 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7271 any_pending_vcont_resume = true;
7272
7273 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7274 then we can't do a global wildcard, as that would resume the
7275 pending child. */
7276 if (thread_pending_child_status (tp) != nullptr)
7277 may_global_wildcard_vcont = false;
7278 }
7279
7280 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7281 do. */
7282 if (!any_pending_vcont_resume)
7283 return;
7284
7285 /* Now let's build the vCont packet(s). Actions must be appended
7286 from narrower to wider scopes (thread -> process -> global). If
7287 we end up with too many actions for a single packet vcont_builder
7288 flushes the current vCont packet to the remote side and starts a
7289 new one. */
7290 struct vcont_builder vcont_builder (this);
7291
7292 /* Threads first. */
7293 for (thread_info *tp : all_non_exited_threads (this))
7294 {
7295 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7296
7297 /* If the thread was previously vCont-resumed, no need to send a specific
7298 action for it. If we didn't receive a resume request for it, don't
7299 send an action for it either. */
7300 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7301 continue;
7302
7303 gdb_assert (!thread_is_in_step_over_chain (tp));
7304
7305 /* We should never be commit-resuming a thread that has a stop reply.
7306 Otherwise, we would end up reporting a stop event for a thread while
7307 it is running on the remote target. */
7308 remote_state *rs = get_remote_state ();
7309 for (const auto &stop_reply : rs->stop_reply_queue)
7310 gdb_assert (stop_reply->ptid != tp->ptid);
7311
7312 const resumed_pending_vcont_info &info
7313 = remote_thr->resumed_pending_vcont_info ();
7314
7315 /* Check if we need to send a specific action for this thread. If not,
7316 it will be included in a wildcard resume instead. */
7317 if (info.step || info.sig != GDB_SIGNAL_0
7318 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7319 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7320
7321 remote_thr->set_resumed ();
7322 }
7323
7324 /* Now check whether we can send any process-wide wildcard. This is
7325 to avoid sending a global wildcard in the case nothing is
7326 supposed to be resumed. */
7327 bool any_process_wildcard = false;
7328
7329 for (inferior *inf : all_non_exited_inferiors (this))
7330 {
7331 if (get_remote_inferior (inf)->may_wildcard_vcont)
7332 {
7333 any_process_wildcard = true;
7334 break;
7335 }
7336 }
7337
7338 if (any_process_wildcard)
7339 {
7340 /* If all processes are wildcard-able, then send a single "c"
7341 action, otherwise, send an "all (-1) threads of process"
7342 continue action for each running process, if any. */
7343 if (may_global_wildcard_vcont)
7344 {
7345 vcont_builder.push_action (minus_one_ptid,
7346 false, GDB_SIGNAL_0);
7347 }
7348 else
7349 {
7350 for (inferior *inf : all_non_exited_inferiors (this))
7351 {
7352 if (get_remote_inferior (inf)->may_wildcard_vcont)
7353 {
7354 vcont_builder.push_action (ptid_t (inf->pid),
7355 false, GDB_SIGNAL_0);
7356 }
7357 }
7358 }
7359 }
7360
7361 vcont_builder.flush ();
7362 }
7363
7364 /* Implementation of target_has_pending_events. */
7365
7366 bool
7367 remote_target::has_pending_events ()
7368 {
7369 if (target_can_async_p ())
7370 {
7371 remote_state *rs = get_remote_state ();
7372
7373 if (rs->async_event_handler_marked ())
7374 return true;
7375
7376 /* Note that BUFCNT can be negative, indicating sticky
7377 error. */
7378 if (rs->remote_desc->bufcnt != 0)
7379 return true;
7380 }
7381 return false;
7382 }
7383
7384 \f
7385
7386 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7387 thread, all threads of a remote process, or all threads of all
7388 processes. */
7389
7390 void
7391 remote_target::remote_stop_ns (ptid_t ptid)
7392 {
7393 struct remote_state *rs = get_remote_state ();
7394 char *p = rs->buf.data ();
7395 char *endp = p + get_remote_packet_size ();
7396
7397 /* If any thread that needs to stop was resumed but pending a vCont
7398 resume, generate a phony stop_reply. However, first check
7399 whether the thread wasn't resumed with a signal. Generating a
7400 phony stop in that case would result in losing the signal. */
7401 bool needs_commit = false;
7402 for (thread_info *tp : all_non_exited_threads (this, ptid))
7403 {
7404 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7405
7406 if (remote_thr->get_resume_state ()
7407 == resume_state::RESUMED_PENDING_VCONT)
7408 {
7409 const resumed_pending_vcont_info &info
7410 = remote_thr->resumed_pending_vcont_info ();
7411 if (info.sig != GDB_SIGNAL_0)
7412 {
7413 /* This signal must be forwarded to the inferior. We
7414 could commit-resume just this thread, but its simpler
7415 to just commit-resume everything. */
7416 needs_commit = true;
7417 break;
7418 }
7419 }
7420 }
7421
7422 if (needs_commit)
7423 commit_resumed ();
7424 else
7425 for (thread_info *tp : all_non_exited_threads (this, ptid))
7426 {
7427 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7428
7429 if (remote_thr->get_resume_state ()
7430 == resume_state::RESUMED_PENDING_VCONT)
7431 {
7432 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7433 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7434 tp->ptid.lwp (),
7435 pulongest (tp->ptid.tid ()));
7436
7437 /* Check that the thread wasn't resumed with a signal.
7438 Generating a phony stop would result in losing the
7439 signal. */
7440 const resumed_pending_vcont_info &info
7441 = remote_thr->resumed_pending_vcont_info ();
7442 gdb_assert (info.sig == GDB_SIGNAL_0);
7443
7444 stop_reply_up sr = std::make_unique<stop_reply> ();
7445 sr->ptid = tp->ptid;
7446 sr->rs = rs;
7447 sr->ws.set_stopped (GDB_SIGNAL_0);
7448 sr->arch = tp->inf->arch ();
7449 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7450 sr->watch_data_address = 0;
7451 sr->core = 0;
7452 this->push_stop_reply (std::move (sr));
7453
7454 /* Pretend that this thread was actually resumed on the
7455 remote target, then stopped. If we leave it in the
7456 RESUMED_PENDING_VCONT state and the commit_resumed
7457 method is called while the stop reply is still in the
7458 queue, we'll end up reporting a stop event to the core
7459 for that thread while it is running on the remote
7460 target... that would be bad. */
7461 remote_thr->set_resumed ();
7462 }
7463 }
7464
7465 if (!rs->supports_vCont.t)
7466 error (_("Remote server does not support stopping threads"));
7467
7468 if (ptid == minus_one_ptid
7469 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7470 p += xsnprintf (p, endp - p, "vCont;t");
7471 else
7472 {
7473 ptid_t nptid;
7474
7475 p += xsnprintf (p, endp - p, "vCont;t:");
7476
7477 if (ptid.is_pid ())
7478 /* All (-1) threads of process. */
7479 nptid = ptid_t (ptid.pid (), -1);
7480 else
7481 {
7482 /* Small optimization: if we already have a stop reply for
7483 this thread, no use in telling the stub we want this
7484 stopped. */
7485 if (peek_stop_reply (ptid))
7486 return;
7487
7488 nptid = ptid;
7489 }
7490
7491 write_ptid (p, endp, nptid);
7492 }
7493
7494 /* In non-stop, we get an immediate OK reply. The stop reply will
7495 come in asynchronously by notification. */
7496 putpkt (rs->buf);
7497 getpkt (&rs->buf);
7498 if (strcmp (rs->buf.data (), "OK") != 0)
7499 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7500 rs->buf.data ());
7501 }
7502
7503 /* All-stop version of target_interrupt. Sends a break or a ^C to
7504 interrupt the remote target. It is undefined which thread of which
7505 process reports the interrupt. */
7506
7507 void
7508 remote_target::remote_interrupt_as ()
7509 {
7510 struct remote_state *rs = get_remote_state ();
7511
7512 rs->ctrlc_pending_p = 1;
7513
7514 /* If the inferior is stopped already, but the core didn't know
7515 about it yet, just ignore the request. The pending stop events
7516 will be collected in remote_wait. */
7517 if (stop_reply_queue_length () > 0)
7518 return;
7519
7520 /* Send interrupt_sequence to remote target. */
7521 send_interrupt_sequence ();
7522 }
7523
7524 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7525 the remote target. It is undefined which thread of which process
7526 reports the interrupt. Throws an error if the packet is not
7527 supported by the server. */
7528
7529 void
7530 remote_target::remote_interrupt_ns ()
7531 {
7532 struct remote_state *rs = get_remote_state ();
7533 char *p = rs->buf.data ();
7534 char *endp = p + get_remote_packet_size ();
7535
7536 xsnprintf (p, endp - p, "vCtrlC");
7537
7538 /* In non-stop, we get an immediate OK reply. The stop reply will
7539 come in asynchronously by notification. */
7540 putpkt (rs->buf);
7541 getpkt (&rs->buf);
7542
7543 packet_result result = m_features.packet_ok (rs->buf, PACKET_vCtrlC);
7544 switch (result.status ())
7545 {
7546 case PACKET_OK:
7547 break;
7548 case PACKET_UNKNOWN:
7549 error (_("No support for interrupting the remote target."));
7550 case PACKET_ERROR:
7551 error (_("Interrupting target failed: %s"), result.err_msg ());
7552 }
7553 }
7554
7555 /* Implement the to_stop function for the remote targets. */
7556
7557 void
7558 remote_target::stop (ptid_t ptid)
7559 {
7560 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7561
7562 if (target_is_non_stop_p ())
7563 remote_stop_ns (ptid);
7564 else
7565 {
7566 /* We don't currently have a way to transparently pause the
7567 remote target in all-stop mode. Interrupt it instead. */
7568 remote_interrupt_as ();
7569 }
7570 }
7571
7572 /* Implement the to_interrupt function for the remote targets. */
7573
7574 void
7575 remote_target::interrupt ()
7576 {
7577 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7578
7579 if (target_is_non_stop_p ())
7580 remote_interrupt_ns ();
7581 else
7582 remote_interrupt_as ();
7583 }
7584
7585 /* Implement the to_pass_ctrlc function for the remote targets. */
7586
7587 void
7588 remote_target::pass_ctrlc ()
7589 {
7590 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7591
7592 struct remote_state *rs = get_remote_state ();
7593
7594 /* If we're starting up, we're not fully synced yet. Quit
7595 immediately. */
7596 if (rs->starting_up)
7597 quit ();
7598 /* If ^C has already been sent once, offer to disconnect. */
7599 else if (rs->ctrlc_pending_p)
7600 interrupt_query ();
7601 else
7602 target_interrupt ();
7603 }
7604
7605 /* Ask the user what to do when an interrupt is received. */
7606
7607 void
7608 remote_target::interrupt_query ()
7609 {
7610 struct remote_state *rs = get_remote_state ();
7611
7612 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7613 {
7614 if (query (_("The target is not responding to interrupt requests.\n"
7615 "Stop debugging it? ")))
7616 {
7617 remote_unpush_target (this);
7618 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7619 }
7620 }
7621 else
7622 {
7623 if (query (_("Interrupted while waiting for the program.\n"
7624 "Give up waiting? ")))
7625 quit ();
7626 }
7627 }
7628
7629 /* Enable/disable target terminal ownership. Most targets can use
7630 terminal groups to control terminal ownership. Remote targets are
7631 different in that explicit transfer of ownership to/from GDB/target
7632 is required. */
7633
7634 void
7635 remote_target::terminal_inferior ()
7636 {
7637 /* NOTE: At this point we could also register our selves as the
7638 recipient of all input. Any characters typed could then be
7639 passed on down to the target. */
7640 }
7641
7642 void
7643 remote_target::terminal_ours ()
7644 {
7645 }
7646
7647 static void
7648 remote_console_output (const char *msg, ui_file *stream)
7649 {
7650 const char *p;
7651
7652 for (p = msg; p[0] && p[1]; p += 2)
7653 {
7654 char tb[2];
7655 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7656
7657 tb[0] = c;
7658 tb[1] = 0;
7659 stream->puts (tb);
7660 }
7661 stream->flush ();
7662 }
7663
7664 /* Return the length of the stop reply queue. */
7665
7666 int
7667 remote_target::stop_reply_queue_length ()
7668 {
7669 remote_state *rs = get_remote_state ();
7670 return rs->stop_reply_queue.size ();
7671 }
7672
7673 static void
7674 remote_notif_stop_parse (remote_target *remote,
7675 const notif_client *self, const char *buf,
7676 struct notif_event *event)
7677 {
7678 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7679 }
7680
7681 static void
7682 remote_notif_stop_ack (remote_target *remote,
7683 const notif_client *self, const char *buf,
7684 notif_event_up event)
7685 {
7686 stop_reply_up stop_reply = as_stop_reply_up (std::move (event));
7687
7688 /* acknowledge */
7689 putpkt (remote, self->ack_command);
7690
7691 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7692 the notification. It was left in the queue because we need to
7693 acknowledge it and pull the rest of the notifications out. */
7694 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7695 remote->push_stop_reply (std::move (stop_reply));
7696 }
7697
7698 static int
7699 remote_notif_stop_can_get_pending_events (remote_target *remote,
7700 const notif_client *self)
7701 {
7702 /* We can't get pending events in remote_notif_process for
7703 notification stop, and we have to do this in remote_wait_ns
7704 instead. If we fetch all queued events from stub, remote stub
7705 may exit and we have no chance to process them back in
7706 remote_wait_ns. */
7707 remote_state *rs = remote->get_remote_state ();
7708 rs->mark_async_event_handler ();
7709 return 0;
7710 }
7711
7712 static notif_event_up
7713 remote_notif_stop_alloc_reply ()
7714 {
7715 return notif_event_up (new struct stop_reply ());
7716 }
7717
7718 /* A client of notification Stop. */
7719
7720 const notif_client notif_client_stop =
7721 {
7722 "Stop",
7723 "vStopped",
7724 remote_notif_stop_parse,
7725 remote_notif_stop_ack,
7726 remote_notif_stop_can_get_pending_events,
7727 remote_notif_stop_alloc_reply,
7728 REMOTE_NOTIF_STOP,
7729 };
7730
7731 /* If CONTEXT contains any fork/vfork/clone child threads that have
7732 not been reported yet, remove them from the CONTEXT list. If such
7733 a thread exists it is because we are stopped at a fork/vfork/clone
7734 catchpoint and have not yet called follow_fork/follow_clone, which
7735 will set up the host-side data structures for the new child. */
7736
7737 void
7738 remote_target::remove_new_children (threads_listing_context *context)
7739 {
7740 const notif_client *notif = &notif_client_stop;
7741
7742 /* For any threads stopped at a (v)fork/clone event, remove the
7743 corresponding child threads from the CONTEXT list. */
7744 for (thread_info *thread : all_non_exited_threads (this))
7745 {
7746 const target_waitstatus *ws = thread_pending_child_status (thread);
7747
7748 if (ws == nullptr)
7749 continue;
7750
7751 context->remove_thread (ws->child_ptid ());
7752 }
7753
7754 /* Check for any pending (v)fork/clone events (not reported or
7755 processed yet) in process PID and remove those child threads from
7756 the CONTEXT list as well. */
7757 remote_notif_get_pending_events (notif);
7758 for (auto &event : get_remote_state ()->stop_reply_queue)
7759 if (is_new_child_status (event->ws.kind ()))
7760 context->remove_thread (event->ws.child_ptid ());
7761 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7762 context->remove_thread (event->ptid);
7763 }
7764
7765 /* Check whether any event pending in the vStopped queue would prevent a
7766 global or process wildcard vCont action. Set *may_global_wildcard to
7767 false if we can't do a global wildcard (vCont;c), and clear the event
7768 inferior's may_wildcard_vcont flag if we can't do a process-wide
7769 wildcard resume (vCont;c:pPID.-1). */
7770
7771 void
7772 remote_target::check_pending_events_prevent_wildcard_vcont
7773 (bool *may_global_wildcard)
7774 {
7775 const notif_client *notif = &notif_client_stop;
7776
7777 remote_notif_get_pending_events (notif);
7778 for (auto &event : get_remote_state ()->stop_reply_queue)
7779 {
7780 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7781 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7782 continue;
7783
7784 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7785 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7786 *may_global_wildcard = false;
7787
7788 /* This may be the first time we heard about this process.
7789 Regardless, we must not do a global wildcard resume, otherwise
7790 we'd resume this process too. */
7791 *may_global_wildcard = false;
7792 if (event->ptid != null_ptid)
7793 {
7794 inferior *inf = find_inferior_ptid (this, event->ptid);
7795 if (inf != NULL)
7796 get_remote_inferior (inf)->may_wildcard_vcont = false;
7797 }
7798 }
7799 }
7800
7801 /* Discard all pending stop replies of inferior INF. */
7802
7803 void
7804 remote_target::discard_pending_stop_replies (struct inferior *inf)
7805 {
7806 struct remote_state *rs = get_remote_state ();
7807 struct remote_notif_state *rns = rs->notif_state;
7808
7809 /* This function can be notified when an inferior exists. When the
7810 target is not remote, the notification state is NULL. */
7811 if (rs->remote_desc == NULL)
7812 return;
7813
7814 struct notif_event *notif_event
7815 = rns->pending_event[notif_client_stop.id].get ();
7816 auto *reply = static_cast<stop_reply *> (notif_event);
7817
7818 /* Discard the in-flight notification. */
7819 if (reply != NULL && reply->ptid.pid () == inf->pid)
7820 {
7821 /* Leave the notification pending, since the server expects that
7822 we acknowledge it with vStopped. But clear its contents, so
7823 that later on when we acknowledge it, we also discard it. */
7824 remote_debug_printf
7825 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7826 reply->ptid.to_string().c_str(),
7827 reply->ws.to_string ().c_str ());
7828 reply->ws.set_ignore ();
7829 }
7830
7831 /* Discard the stop replies we have already pulled with
7832 vStopped. */
7833 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7834 rs->stop_reply_queue.end (),
7835 [=] (const stop_reply_up &event)
7836 {
7837 return event->ptid.pid () == inf->pid;
7838 });
7839 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7840 remote_debug_printf
7841 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7842 (*it)->ptid.to_string().c_str(),
7843 (*it)->ws.to_string ().c_str ());
7844 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7845 }
7846
7847 /* Discard the stop replies for RS in stop_reply_queue. */
7848
7849 void
7850 remote_target::discard_pending_stop_replies_in_queue ()
7851 {
7852 remote_state *rs = get_remote_state ();
7853
7854 /* Discard the stop replies we have already pulled with
7855 vStopped. */
7856 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7857 rs->stop_reply_queue.end (),
7858 [=] (const stop_reply_up &event)
7859 {
7860 return event->rs == rs;
7861 });
7862 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7863 }
7864
7865 /* Remove the first reply in 'stop_reply_queue' which matches
7866 PTID. */
7867
7868 stop_reply_up
7869 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7870 {
7871 remote_state *rs = get_remote_state ();
7872
7873 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7874 rs->stop_reply_queue.end (),
7875 [=] (const stop_reply_up &event)
7876 {
7877 return event->ptid.matches (ptid);
7878 });
7879 stop_reply_up result;
7880 if (iter != rs->stop_reply_queue.end ())
7881 {
7882 result = std::move (*iter);
7883 rs->stop_reply_queue.erase (iter);
7884 }
7885
7886 if (notif_debug)
7887 gdb_printf (gdb_stdlog,
7888 "notif: discard queued event: 'Stop' in %s\n",
7889 ptid.to_string ().c_str ());
7890
7891 return result;
7892 }
7893
7894 /* Look for a queued stop reply belonging to PTID. If one is found,
7895 remove it from the queue, and return it. Returns NULL if none is
7896 found. If there are still queued events left to process, tell the
7897 event loop to get back to target_wait soon. */
7898
7899 stop_reply_up
7900 remote_target::queued_stop_reply (ptid_t ptid)
7901 {
7902 remote_state *rs = get_remote_state ();
7903 stop_reply_up r = remote_notif_remove_queued_reply (ptid);
7904
7905 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7906 {
7907 /* There's still at least an event left. */
7908 rs->mark_async_event_handler ();
7909 }
7910
7911 return r;
7912 }
7913
7914 /* Push a fully parsed stop reply in the stop reply queue. Since we
7915 know that we now have at least one queued event left to pass to the
7916 core side, tell the event loop to get back to target_wait soon. */
7917
7918 void
7919 remote_target::push_stop_reply (stop_reply_up new_event)
7920 {
7921 remote_state *rs = get_remote_state ();
7922 rs->stop_reply_queue.push_back (std::move (new_event));
7923
7924 if (notif_debug)
7925 gdb_printf (gdb_stdlog,
7926 "notif: push 'Stop' %s to queue %d\n",
7927 new_event->ptid.to_string ().c_str (),
7928 int (rs->stop_reply_queue.size ()));
7929
7930 /* Mark the pending event queue only if async mode is currently enabled.
7931 If async mode is not currently enabled, then, if it later becomes
7932 enabled, and there are events in this queue, we will mark the event
7933 token at that point, see remote_target::async. */
7934 if (target_is_async_p ())
7935 rs->mark_async_event_handler ();
7936 }
7937
7938 /* Returns true if we have a stop reply for PTID. */
7939
7940 int
7941 remote_target::peek_stop_reply (ptid_t ptid)
7942 {
7943 remote_state *rs = get_remote_state ();
7944 for (auto &event : rs->stop_reply_queue)
7945 if (ptid == event->ptid
7946 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7947 return 1;
7948 return 0;
7949 }
7950
7951 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7952 starting with P and ending with PEND matches PREFIX. */
7953
7954 static int
7955 strprefix (const char *p, const char *pend, const char *prefix)
7956 {
7957 for ( ; p < pend; p++, prefix++)
7958 if (*p != *prefix)
7959 return 0;
7960 return *prefix == '\0';
7961 }
7962
7963 /* Parse the stop reply in BUF. Either the function succeeds, and the
7964 result is stored in EVENT, or throws an error. */
7965
7966 void
7967 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7968 {
7969 remote_arch_state *rsa = NULL;
7970 ULONGEST addr;
7971 const char *p;
7972 int skipregs = 0;
7973
7974 event->ptid = null_ptid;
7975 event->rs = get_remote_state ();
7976 event->ws.set_ignore ();
7977 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7978 event->regcache.clear ();
7979 event->core = -1;
7980
7981 switch (buf[0])
7982 {
7983 case 'T': /* Status with PC, SP, FP, ... */
7984 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7985 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7986 ss = signal number
7987 n... = register number
7988 r... = register contents
7989 */
7990
7991 p = &buf[3]; /* after Txx */
7992 while (*p)
7993 {
7994 const char *p1;
7995 int fieldsize;
7996
7997 p1 = strchr (p, ':');
7998 if (p1 == NULL)
7999 error (_("Malformed packet(a) (missing colon): %s\n\
8000 Packet: '%s'\n"),
8001 p, buf);
8002 if (p == p1)
8003 error (_("Malformed packet(a) (missing register number): %s\n\
8004 Packet: '%s'\n"),
8005 p, buf);
8006
8007 /* Some "registers" are actually extended stop information.
8008 Note if you're adding a new entry here: GDB 7.9 and
8009 earlier assume that all register "numbers" that start
8010 with an hex digit are real register numbers. Make sure
8011 the server only sends such a packet if it knows the
8012 client understands it. */
8013
8014 if (strprefix (p, p1, "thread"))
8015 event->ptid = read_ptid (++p1, &p);
8016 else if (strprefix (p, p1, "syscall_entry"))
8017 {
8018 ULONGEST sysno;
8019
8020 p = unpack_varlen_hex (++p1, &sysno);
8021 event->ws.set_syscall_entry ((int) sysno);
8022 }
8023 else if (strprefix (p, p1, "syscall_return"))
8024 {
8025 ULONGEST sysno;
8026
8027 p = unpack_varlen_hex (++p1, &sysno);
8028 event->ws.set_syscall_return ((int) sysno);
8029 }
8030 else if (strprefix (p, p1, "watch")
8031 || strprefix (p, p1, "rwatch")
8032 || strprefix (p, p1, "awatch"))
8033 {
8034 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
8035 p = unpack_varlen_hex (++p1, &addr);
8036 event->watch_data_address = (CORE_ADDR) addr;
8037 }
8038 else if (strprefix (p, p1, "swbreak"))
8039 {
8040 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
8041
8042 /* Make sure the stub doesn't forget to indicate support
8043 with qSupported. */
8044 if (m_features.packet_support (PACKET_swbreak_feature)
8045 != PACKET_ENABLE)
8046 error (_("Unexpected swbreak stop reason"));
8047
8048 /* The value part is documented as "must be empty",
8049 though we ignore it, in case we ever decide to make
8050 use of it in a backward compatible way. */
8051 p = strchrnul (p1 + 1, ';');
8052 }
8053 else if (strprefix (p, p1, "hwbreak"))
8054 {
8055 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
8056
8057 /* Make sure the stub doesn't forget to indicate support
8058 with qSupported. */
8059 if (m_features.packet_support (PACKET_hwbreak_feature)
8060 != PACKET_ENABLE)
8061 error (_("Unexpected hwbreak stop reason"));
8062
8063 /* See above. */
8064 p = strchrnul (p1 + 1, ';');
8065 }
8066 else if (strprefix (p, p1, "library"))
8067 {
8068 event->ws.set_loaded ();
8069 p = strchrnul (p1 + 1, ';');
8070 }
8071 else if (strprefix (p, p1, "replaylog"))
8072 {
8073 event->ws.set_no_history ();
8074 /* p1 will indicate "begin" or "end", but it makes
8075 no difference for now, so ignore it. */
8076 p = strchrnul (p1 + 1, ';');
8077 }
8078 else if (strprefix (p, p1, "core"))
8079 {
8080 ULONGEST c;
8081
8082 p = unpack_varlen_hex (++p1, &c);
8083 event->core = c;
8084 }
8085 else if (strprefix (p, p1, "fork"))
8086 event->ws.set_forked (read_ptid (++p1, &p));
8087 else if (strprefix (p, p1, "vfork"))
8088 event->ws.set_vforked (read_ptid (++p1, &p));
8089 else if (strprefix (p, p1, "clone"))
8090 event->ws.set_thread_cloned (read_ptid (++p1, &p));
8091 else if (strprefix (p, p1, "vforkdone"))
8092 {
8093 event->ws.set_vfork_done ();
8094 p = strchrnul (p1 + 1, ';');
8095 }
8096 else if (strprefix (p, p1, "exec"))
8097 {
8098 ULONGEST ignored;
8099 int pathlen;
8100
8101 /* Determine the length of the execd pathname. */
8102 p = unpack_varlen_hex (++p1, &ignored);
8103 pathlen = (p - p1) / 2;
8104
8105 /* Save the pathname for event reporting and for
8106 the next run command. */
8107 gdb::unique_xmalloc_ptr<char> pathname
8108 ((char *) xmalloc (pathlen + 1));
8109 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8110 pathname.get ()[pathlen] = '\0';
8111
8112 /* This is freed during event handling. */
8113 event->ws.set_execd (std::move (pathname));
8114
8115 /* Skip the registers included in this packet, since
8116 they may be for an architecture different from the
8117 one used by the original program. */
8118 skipregs = 1;
8119 }
8120 else if (strprefix (p, p1, "create"))
8121 {
8122 event->ws.set_thread_created ();
8123 p = strchrnul (p1 + 1, ';');
8124 }
8125 else
8126 {
8127 ULONGEST pnum;
8128 const char *p_temp;
8129
8130 if (skipregs)
8131 {
8132 p = strchrnul (p1 + 1, ';');
8133 p++;
8134 continue;
8135 }
8136
8137 /* Maybe a real ``P'' register number. */
8138 p_temp = unpack_varlen_hex (p, &pnum);
8139 /* If the first invalid character is the colon, we got a
8140 register number. Otherwise, it's an unknown stop
8141 reason. */
8142 if (p_temp == p1)
8143 {
8144 /* If we haven't parsed the event's thread yet, find
8145 it now, in order to find the architecture of the
8146 reported expedited registers. */
8147 if (event->ptid == null_ptid)
8148 {
8149 /* If there is no thread-id information then leave
8150 the event->ptid as null_ptid. Later in
8151 process_stop_reply we will pick a suitable
8152 thread. */
8153 const char *thr = strstr (p1 + 1, ";thread:");
8154 if (thr != NULL)
8155 event->ptid = read_ptid (thr + strlen (";thread:"),
8156 NULL);
8157 }
8158
8159 if (rsa == NULL)
8160 {
8161 inferior *inf
8162 = (event->ptid == null_ptid
8163 ? NULL
8164 : find_inferior_ptid (this, event->ptid));
8165 /* If this is the first time we learn anything
8166 about this process, skip the registers
8167 included in this packet, since we don't yet
8168 know which architecture to use to parse them.
8169 We'll determine the architecture later when
8170 we process the stop reply and retrieve the
8171 target description, via
8172 remote_notice_new_inferior ->
8173 post_create_inferior. */
8174 if (inf == NULL)
8175 {
8176 p = strchrnul (p1 + 1, ';');
8177 p++;
8178 continue;
8179 }
8180
8181 event->arch = inf->arch ();
8182 rsa = event->rs->get_remote_arch_state (event->arch);
8183 }
8184
8185 packet_reg *reg
8186 = packet_reg_from_pnum (event->arch, rsa, pnum);
8187 cached_reg_t cached_reg;
8188
8189 if (reg == NULL)
8190 error (_("Remote sent bad register number %s: %s\n\
8191 Packet: '%s'\n"),
8192 hex_string (pnum), p, buf);
8193
8194 cached_reg.num = reg->regnum;
8195 cached_reg.data.reset ((gdb_byte *)
8196 xmalloc (register_size (event->arch,
8197 reg->regnum)));
8198
8199 p = p1 + 1;
8200 fieldsize = hex2bin (p, cached_reg.data.get (),
8201 register_size (event->arch, reg->regnum));
8202 p += 2 * fieldsize;
8203 if (fieldsize < register_size (event->arch, reg->regnum))
8204 warning (_("Remote reply is too short: %s"), buf);
8205
8206 event->regcache.push_back (std::move (cached_reg));
8207 }
8208 else
8209 {
8210 /* Not a number. Silently skip unknown optional
8211 info. */
8212 p = strchrnul (p1 + 1, ';');
8213 }
8214 }
8215
8216 if (*p != ';')
8217 error (_("Remote register badly formatted: %s\nhere: %s"),
8218 buf, p);
8219 ++p;
8220 }
8221
8222 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8223 break;
8224
8225 [[fallthrough]];
8226 case 'S': /* Old style status, just signal only. */
8227 {
8228 int sig;
8229
8230 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8231 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8232 event->ws.set_stopped ((enum gdb_signal) sig);
8233 else
8234 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8235 }
8236 break;
8237 case 'w': /* Thread exited. */
8238 {
8239 ULONGEST value;
8240
8241 p = unpack_varlen_hex (&buf[1], &value);
8242 event->ws.set_thread_exited (value);
8243 if (*p != ';')
8244 error (_("stop reply packet badly formatted: %s"), buf);
8245 event->ptid = read_ptid (++p, NULL);
8246 break;
8247 }
8248 case 'W': /* Target exited. */
8249 case 'X':
8250 {
8251 ULONGEST value;
8252
8253 /* GDB used to accept only 2 hex chars here. Stubs should
8254 only send more if they detect GDB supports multi-process
8255 support. */
8256 p = unpack_varlen_hex (&buf[1], &value);
8257
8258 if (buf[0] == 'W')
8259 {
8260 /* The remote process exited. */
8261 event->ws.set_exited (value);
8262 }
8263 else
8264 {
8265 /* The remote process exited with a signal. */
8266 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8267 event->ws.set_signalled ((enum gdb_signal) value);
8268 else
8269 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8270 }
8271
8272 /* If no process is specified, return null_ptid, and let the
8273 caller figure out the right process to use. */
8274 int pid = 0;
8275 if (*p == '\0')
8276 ;
8277 else if (*p == ';')
8278 {
8279 p++;
8280
8281 if (*p == '\0')
8282 ;
8283 else if (startswith (p, "process:"))
8284 {
8285 ULONGEST upid;
8286
8287 p += sizeof ("process:") - 1;
8288 unpack_varlen_hex (p, &upid);
8289 pid = upid;
8290 }
8291 else
8292 error (_("unknown stop reply packet: %s"), buf);
8293 }
8294 else
8295 error (_("unknown stop reply packet: %s"), buf);
8296 event->ptid = ptid_t (pid);
8297 }
8298 break;
8299 case 'N':
8300 event->ws.set_no_resumed ();
8301 event->ptid = minus_one_ptid;
8302 break;
8303 }
8304 }
8305
8306 /* When the stub wants to tell GDB about a new notification reply, it
8307 sends a notification (%Stop, for example). Those can come it at
8308 any time, hence, we have to make sure that any pending
8309 putpkt/getpkt sequence we're making is finished, before querying
8310 the stub for more events with the corresponding ack command
8311 (vStopped, for example). E.g., if we started a vStopped sequence
8312 immediately upon receiving the notification, something like this
8313 could happen:
8314
8315 1.1) --> Hg 1
8316 1.2) <-- OK
8317 1.3) --> g
8318 1.4) <-- %Stop
8319 1.5) --> vStopped
8320 1.6) <-- (registers reply to step #1.3)
8321
8322 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8323 query.
8324
8325 To solve this, whenever we parse a %Stop notification successfully,
8326 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8327 doing whatever we were doing:
8328
8329 2.1) --> Hg 1
8330 2.2) <-- OK
8331 2.3) --> g
8332 2.4) <-- %Stop
8333 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8334 2.5) <-- (registers reply to step #2.3)
8335
8336 Eventually after step #2.5, we return to the event loop, which
8337 notices there's an event on the
8338 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8339 associated callback --- the function below. At this point, we're
8340 always safe to start a vStopped sequence. :
8341
8342 2.6) --> vStopped
8343 2.7) <-- T05 thread:2
8344 2.8) --> vStopped
8345 2.9) --> OK
8346 */
8347
8348 void
8349 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8350 {
8351 struct remote_state *rs = get_remote_state ();
8352
8353 if (rs->notif_state->pending_event[nc->id] != NULL)
8354 {
8355 if (notif_debug)
8356 gdb_printf (gdb_stdlog,
8357 "notif: process: '%s' ack pending event\n",
8358 nc->name);
8359
8360 /* acknowledge */
8361 nc->ack (this, nc, rs->buf.data (),
8362 std::move (rs->notif_state->pending_event[nc->id]));
8363
8364 while (1)
8365 {
8366 getpkt (&rs->buf);
8367 if (strcmp (rs->buf.data (), "OK") == 0)
8368 break;
8369 else
8370 remote_notif_ack (this, nc, rs->buf.data ());
8371 }
8372 }
8373 else
8374 {
8375 if (notif_debug)
8376 gdb_printf (gdb_stdlog,
8377 "notif: process: '%s' no pending reply\n",
8378 nc->name);
8379 }
8380 }
8381
8382 /* Wrapper around remote_target::remote_notif_get_pending_events to
8383 avoid having to export the whole remote_target class. */
8384
8385 void
8386 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8387 {
8388 remote->remote_notif_get_pending_events (nc);
8389 }
8390
8391 /* Called from process_stop_reply when the stop packet we are responding
8392 to didn't include a process-id or thread-id. STATUS is the stop event
8393 we are responding to.
8394
8395 It is the task of this function to select a suitable thread (or process)
8396 and return its ptid, this is the thread (or process) we will assume the
8397 stop event came from.
8398
8399 In some cases there isn't really any choice about which thread (or
8400 process) is selected, a basic remote with a single process containing a
8401 single thread might choose not to send any process-id or thread-id in
8402 its stop packets, this function will select and return the one and only
8403 thread.
8404
8405 However, if a target supports multiple threads (or processes) and still
8406 doesn't include a thread-id (or process-id) in its stop packet then
8407 first, this is a badly behaving target, and second, we're going to have
8408 to select a thread (or process) at random and use that. This function
8409 will print a warning to the user if it detects that there is the
8410 possibility that GDB is guessing which thread (or process) to
8411 report.
8412
8413 Note that this is called before GDB fetches the updated thread list from the
8414 target. So it's possible for the stop reply to be ambiguous and for GDB to
8415 not realize it. For example, if there's initially one thread, the target
8416 spawns a second thread, and then sends a stop reply without an id that
8417 concerns the first thread. GDB will assume the stop reply is about the
8418 first thread - the only thread it knows about - without printing a warning.
8419 Anyway, if the remote meant for the stop reply to be about the second thread,
8420 then it would be really broken, because GDB doesn't know about that thread
8421 yet. */
8422
8423 ptid_t
8424 remote_target::select_thread_for_ambiguous_stop_reply
8425 (const target_waitstatus &status)
8426 {
8427 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8428
8429 /* Some stop events apply to all threads in an inferior, while others
8430 only apply to a single thread. */
8431 bool process_wide_stop
8432 = (status.kind () == TARGET_WAITKIND_EXITED
8433 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8434
8435 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8436
8437 thread_info *first_resumed_thread = nullptr;
8438 bool ambiguous = false;
8439
8440 /* Consider all non-exited threads of the target, find the first resumed
8441 one. */
8442 for (thread_info *thr : all_non_exited_threads (this))
8443 {
8444 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8445
8446 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8447 continue;
8448
8449 if (first_resumed_thread == nullptr)
8450 first_resumed_thread = thr;
8451 else if (!process_wide_stop
8452 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8453 ambiguous = true;
8454 }
8455
8456 gdb_assert (first_resumed_thread != nullptr);
8457
8458 remote_debug_printf ("first resumed thread is %s",
8459 pid_to_str (first_resumed_thread->ptid).c_str ());
8460 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8461
8462 /* Warn if the remote target is sending ambiguous stop replies. */
8463 if (ambiguous)
8464 {
8465 static bool warned = false;
8466
8467 if (!warned)
8468 {
8469 /* If you are seeing this warning then the remote target has
8470 stopped without specifying a thread-id, but the target
8471 does have multiple threads (or inferiors), and so GDB is
8472 having to guess which thread stopped.
8473
8474 Examples of what might cause this are the target sending
8475 and 'S' stop packet, or a 'T' stop packet and not
8476 including a thread-id.
8477
8478 Additionally, the target might send a 'W' or 'X packet
8479 without including a process-id, when the target has
8480 multiple running inferiors. */
8481 if (process_wide_stop)
8482 warning (_("multi-inferior target stopped without "
8483 "sending a process-id, using first "
8484 "non-exited inferior"));
8485 else
8486 warning (_("multi-threaded target stopped without "
8487 "sending a thread-id, using first "
8488 "non-exited thread"));
8489 warned = true;
8490 }
8491 }
8492
8493 /* If this is a stop for all threads then don't use a particular threads
8494 ptid, instead create a new ptid where only the pid field is set. */
8495 if (process_wide_stop)
8496 return ptid_t (first_resumed_thread->ptid.pid ());
8497 else
8498 return first_resumed_thread->ptid;
8499 }
8500
8501 /* Called when it is decided that STOP_REPLY holds the info of the
8502 event that is to be returned to the core. This function always
8503 destroys STOP_REPLY. */
8504
8505 ptid_t
8506 remote_target::process_stop_reply (stop_reply_up stop_reply,
8507 struct target_waitstatus *status)
8508 {
8509 *status = stop_reply->ws;
8510 ptid_t ptid = stop_reply->ptid;
8511
8512 /* If no thread/process was reported by the stub then select a suitable
8513 thread/process. */
8514 if (ptid == null_ptid)
8515 ptid = select_thread_for_ambiguous_stop_reply (*status);
8516 gdb_assert (ptid != null_ptid);
8517
8518 if (status->kind () != TARGET_WAITKIND_EXITED
8519 && status->kind () != TARGET_WAITKIND_SIGNALLED
8520 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8521 {
8522 remote_notice_new_inferior (ptid, false);
8523
8524 /* Expedited registers. */
8525 if (!stop_reply->regcache.empty ())
8526 {
8527 /* 'w' stop replies don't cary expedited registers (which
8528 wouldn't make any sense for a thread that is gone
8529 already). */
8530 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8531
8532 regcache *regcache
8533 = get_thread_arch_regcache (find_inferior_ptid (this, ptid), ptid,
8534 stop_reply->arch);
8535
8536 for (cached_reg_t &reg : stop_reply->regcache)
8537 regcache->raw_supply (reg.num, reg.data.get ());
8538 }
8539
8540 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8541 remote_thr->core = stop_reply->core;
8542 remote_thr->stop_reason = stop_reply->stop_reason;
8543 remote_thr->watch_data_address = stop_reply->watch_data_address;
8544
8545 if (target_is_non_stop_p ())
8546 {
8547 /* If the target works in non-stop mode, a stop-reply indicates that
8548 only this thread stopped. */
8549 remote_thr->set_not_resumed ();
8550 }
8551 else
8552 {
8553 /* If the target works in all-stop mode, a stop-reply indicates that
8554 all the target's threads stopped. */
8555 for (thread_info *tp : all_non_exited_threads (this))
8556 get_remote_thread_info (tp)->set_not_resumed ();
8557 }
8558 }
8559
8560 return ptid;
8561 }
8562
8563 /* The non-stop mode version of target_wait. */
8564
8565 ptid_t
8566 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8567 target_wait_flags options)
8568 {
8569 struct remote_state *rs = get_remote_state ();
8570 int ret;
8571 bool is_notif = false;
8572
8573 /* If in non-stop mode, get out of getpkt even if a
8574 notification is received. */
8575
8576 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8577 while (1)
8578 {
8579 if (ret != -1 && !is_notif)
8580 switch (rs->buf[0])
8581 {
8582 case 'E': /* Error of some sort. */
8583 /* We're out of sync with the target now. Did it continue
8584 or not? We can't tell which thread it was in non-stop,
8585 so just ignore this. */
8586 warning (_("Remote failure reply: %s"), rs->buf.data ());
8587 break;
8588 case 'O': /* Console output. */
8589 remote_console_output (&rs->buf[1], gdb_stdtarg);
8590 break;
8591 default:
8592 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8593 break;
8594 }
8595
8596 /* Acknowledge a pending stop reply that may have arrived in the
8597 mean time. */
8598 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8599 remote_notif_get_pending_events (&notif_client_stop);
8600
8601 /* If indeed we noticed a stop reply, we're done. */
8602 stop_reply_up stop_reply = queued_stop_reply (ptid);
8603 if (stop_reply != NULL)
8604 return process_stop_reply (std::move (stop_reply), status);
8605
8606 /* Still no event. If we're just polling for an event, then
8607 return to the event loop. */
8608 if (options & TARGET_WNOHANG)
8609 {
8610 status->set_ignore ();
8611 return minus_one_ptid;
8612 }
8613
8614 /* Otherwise do a blocking wait. */
8615 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8616 }
8617 }
8618
8619 /* Return the first resumed thread. */
8620
8621 static ptid_t
8622 first_remote_resumed_thread (remote_target *target)
8623 {
8624 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8625 if (tp->resumed ())
8626 return tp->ptid;
8627 return null_ptid;
8628 }
8629
8630 /* Wait until the remote machine stops, then return, storing status in
8631 STATUS just as `wait' would. */
8632
8633 ptid_t
8634 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8635 target_wait_flags options)
8636 {
8637 struct remote_state *rs = get_remote_state ();
8638 ptid_t event_ptid = null_ptid;
8639 char *buf;
8640 stop_reply_up stop_reply;
8641
8642 again:
8643
8644 status->set_ignore ();
8645
8646 stop_reply = queued_stop_reply (ptid);
8647 if (stop_reply != NULL)
8648 {
8649 /* None of the paths that push a stop reply onto the queue should
8650 have set the waiting_for_stop_reply flag. */
8651 gdb_assert (!rs->waiting_for_stop_reply);
8652 event_ptid = process_stop_reply (std::move (stop_reply), status);
8653 }
8654 else
8655 {
8656 bool forever = ((options & TARGET_WNOHANG) == 0
8657 && rs->wait_forever_enabled_p);
8658
8659 if (!rs->waiting_for_stop_reply)
8660 {
8661 status->set_no_resumed ();
8662 return minus_one_ptid;
8663 }
8664
8665 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8666 _never_ wait for ever -> test on target_is_async_p().
8667 However, before we do that we need to ensure that the caller
8668 knows how to take the target into/out of async mode. */
8669 bool is_notif;
8670 int ret = getpkt (&rs->buf, forever, &is_notif);
8671
8672 /* GDB gets a notification. Return to core as this event is
8673 not interesting. */
8674 if (ret != -1 && is_notif)
8675 return minus_one_ptid;
8676
8677 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8678 return minus_one_ptid;
8679
8680 buf = rs->buf.data ();
8681
8682 /* Assume that the target has acknowledged Ctrl-C unless we receive
8683 an 'F' or 'O' packet. */
8684 if (buf[0] != 'F' && buf[0] != 'O')
8685 rs->ctrlc_pending_p = 0;
8686
8687 switch (buf[0])
8688 {
8689 case 'E': /* Error of some sort. */
8690 /* We're out of sync with the target now. Did it continue or
8691 not? Not is more likely, so report a stop. */
8692 rs->waiting_for_stop_reply = 0;
8693
8694 warning (_("Remote failure reply: %s"), buf);
8695 status->set_stopped (GDB_SIGNAL_0);
8696 break;
8697 case 'F': /* File-I/O request. */
8698 /* GDB may access the inferior memory while handling the File-I/O
8699 request, but we don't want GDB accessing memory while waiting
8700 for a stop reply. See the comments in putpkt_binary. Set
8701 waiting_for_stop_reply to 0 temporarily. */
8702 rs->waiting_for_stop_reply = 0;
8703 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8704 rs->ctrlc_pending_p = 0;
8705 /* GDB handled the File-I/O request, and the target is running
8706 again. Keep waiting for events. */
8707 rs->waiting_for_stop_reply = 1;
8708 break;
8709 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8710 {
8711 /* There is a stop reply to handle. */
8712 rs->waiting_for_stop_reply = 0;
8713
8714 stop_reply
8715 = as_stop_reply_up (remote_notif_parse (this,
8716 &notif_client_stop,
8717 rs->buf.data ()));
8718
8719 event_ptid = process_stop_reply (std::move (stop_reply), status);
8720 break;
8721 }
8722 case 'O': /* Console output. */
8723 remote_console_output (buf + 1, gdb_stdtarg);
8724 break;
8725 case '\0':
8726 if (rs->last_sent_signal != GDB_SIGNAL_0)
8727 {
8728 /* Zero length reply means that we tried 'S' or 'C' and the
8729 remote system doesn't support it. */
8730 target_terminal::ours_for_output ();
8731 gdb_printf
8732 ("Can't send signals to this remote system. %s not sent.\n",
8733 gdb_signal_to_name (rs->last_sent_signal));
8734 rs->last_sent_signal = GDB_SIGNAL_0;
8735 target_terminal::inferior ();
8736
8737 strcpy (buf, rs->last_sent_step ? "s" : "c");
8738 putpkt (buf);
8739 break;
8740 }
8741 [[fallthrough]];
8742 default:
8743 warning (_("Invalid remote reply: %s"), buf);
8744 break;
8745 }
8746 }
8747
8748 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8749 return minus_one_ptid;
8750 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8751 {
8752 /* Nothing interesting happened. If we're doing a non-blocking
8753 poll, we're done. Otherwise, go back to waiting. */
8754 if (options & TARGET_WNOHANG)
8755 return minus_one_ptid;
8756 else
8757 goto again;
8758 }
8759 else if (status->kind () != TARGET_WAITKIND_EXITED
8760 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8761 {
8762 if (event_ptid != null_ptid)
8763 record_currthread (rs, event_ptid);
8764 else
8765 event_ptid = first_remote_resumed_thread (this);
8766 }
8767 else
8768 {
8769 /* A process exit. Invalidate our notion of current thread. */
8770 record_currthread (rs, minus_one_ptid);
8771 /* It's possible that the packet did not include a pid. */
8772 if (event_ptid == null_ptid)
8773 event_ptid = first_remote_resumed_thread (this);
8774 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8775 if (event_ptid == null_ptid)
8776 event_ptid = magic_null_ptid;
8777 }
8778
8779 return event_ptid;
8780 }
8781
8782 /* Wait until the remote machine stops, then return, storing status in
8783 STATUS just as `wait' would. */
8784
8785 ptid_t
8786 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8787 target_wait_flags options)
8788 {
8789 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8790
8791 remote_state *rs = get_remote_state ();
8792
8793 /* Start by clearing the flag that asks for our wait method to be called,
8794 we'll mark it again at the end if needed. If the target is not in
8795 async mode then the async token should not be marked. */
8796 if (target_is_async_p ())
8797 rs->clear_async_event_handler ();
8798 else
8799 gdb_assert (!rs->async_event_handler_marked ());
8800
8801 ptid_t event_ptid;
8802
8803 if (target_is_non_stop_p ())
8804 event_ptid = wait_ns (ptid, status, options);
8805 else
8806 event_ptid = wait_as (ptid, status, options);
8807
8808 if (target_is_async_p ())
8809 {
8810 /* If there are events left in the queue, or unacknowledged
8811 notifications, then tell the event loop to call us again. */
8812 if (!rs->stop_reply_queue.empty ()
8813 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8814 rs->mark_async_event_handler ();
8815 }
8816
8817 return event_ptid;
8818 }
8819
8820 /* Fetch a single register using a 'p' packet. */
8821
8822 int
8823 remote_target::fetch_register_using_p (struct regcache *regcache,
8824 packet_reg *reg)
8825 {
8826 struct gdbarch *gdbarch = regcache->arch ();
8827 struct remote_state *rs = get_remote_state ();
8828 char *buf, *p;
8829 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8830 int i;
8831
8832 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8833 return 0;
8834
8835 if (reg->pnum == -1)
8836 return 0;
8837
8838 p = rs->buf.data ();
8839 *p++ = 'p';
8840 p += hexnumstr (p, reg->pnum);
8841 *p++ = '\0';
8842 putpkt (rs->buf);
8843 getpkt (&rs->buf);
8844
8845 buf = rs->buf.data ();
8846
8847 packet_result result = m_features.packet_ok (rs->buf, PACKET_p);
8848 switch (result.status ())
8849 {
8850 case PACKET_OK:
8851 break;
8852 case PACKET_UNKNOWN:
8853 return 0;
8854 case PACKET_ERROR:
8855 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8856 gdbarch_register_name (regcache->arch (), reg->regnum),
8857 result.err_msg ());
8858 }
8859
8860 /* If this register is unfetchable, tell the regcache. */
8861 if (buf[0] == 'x')
8862 {
8863 regcache->raw_supply (reg->regnum, NULL);
8864 return 1;
8865 }
8866
8867 /* Otherwise, parse and supply the value. */
8868 p = buf;
8869 i = 0;
8870 while (p[0] != 0)
8871 {
8872 if (p[1] == 0)
8873 error (_("fetch_register_using_p: early buf termination"));
8874
8875 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8876 p += 2;
8877 }
8878 regcache->raw_supply (reg->regnum, regp);
8879 return 1;
8880 }
8881
8882 /* Fetch the registers included in the target's 'g' packet. */
8883
8884 int
8885 remote_target::send_g_packet ()
8886 {
8887 struct remote_state *rs = get_remote_state ();
8888 int buf_len;
8889
8890 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8891 putpkt (rs->buf);
8892 getpkt (&rs->buf);
8893 packet_result result = packet_check_result (rs->buf, true);
8894 if (result.status () == PACKET_ERROR)
8895 error (_("Could not read registers; remote failure reply '%s'"),
8896 result.err_msg ());
8897
8898 /* We can get out of synch in various cases. If the first character
8899 in the buffer is not a hex character, assume that has happened
8900 and try to fetch another packet to read. */
8901 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8902 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8903 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8904 && rs->buf[0] != 'x') /* New: unavailable register value. */
8905 {
8906 remote_debug_printf ("Bad register packet; fetching a new packet");
8907 getpkt (&rs->buf);
8908 }
8909
8910 buf_len = strlen (rs->buf.data ());
8911
8912 /* Sanity check the received packet. */
8913 if (buf_len % 2 != 0)
8914 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8915
8916 return buf_len / 2;
8917 }
8918
8919 void
8920 remote_target::process_g_packet (struct regcache *regcache)
8921 {
8922 struct gdbarch *gdbarch = regcache->arch ();
8923 struct remote_state *rs = get_remote_state ();
8924 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8925 int i, buf_len;
8926 char *p;
8927 char *regs;
8928
8929 buf_len = strlen (rs->buf.data ());
8930
8931 /* Further sanity checks, with knowledge of the architecture. */
8932 if (buf_len > 2 * rsa->sizeof_g_packet)
8933 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8934 "bytes): %s"),
8935 rsa->sizeof_g_packet, buf_len / 2,
8936 rs->buf.data ());
8937
8938 /* Save the size of the packet sent to us by the target. It is used
8939 as a heuristic when determining the max size of packets that the
8940 target can safely receive. */
8941 if (rsa->actual_register_packet_size == 0)
8942 rsa->actual_register_packet_size = buf_len;
8943
8944 /* If this is smaller than we guessed the 'g' packet would be,
8945 update our records. A 'g' reply that doesn't include a register's
8946 value implies either that the register is not available, or that
8947 the 'p' packet must be used. */
8948 if (buf_len < 2 * rsa->sizeof_g_packet)
8949 {
8950 long sizeof_g_packet = buf_len / 2;
8951
8952 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8953 {
8954 long offset = rsa->regs[i].offset;
8955 long reg_size = register_size (gdbarch, i);
8956
8957 if (rsa->regs[i].pnum == -1)
8958 continue;
8959
8960 if (offset >= sizeof_g_packet)
8961 rsa->regs[i].in_g_packet = 0;
8962 else if (offset + reg_size > sizeof_g_packet)
8963 error (_("Truncated register %d in remote 'g' packet"), i);
8964 else
8965 rsa->regs[i].in_g_packet = 1;
8966 }
8967
8968 /* Looks valid enough, we can assume this is the correct length
8969 for a 'g' packet. It's important not to adjust
8970 rsa->sizeof_g_packet if we have truncated registers otherwise
8971 this "if" won't be run the next time the method is called
8972 with a packet of the same size and one of the internal errors
8973 below will trigger instead. */
8974 rsa->sizeof_g_packet = sizeof_g_packet;
8975 }
8976
8977 regs = (char *) alloca (rsa->sizeof_g_packet);
8978
8979 /* Unimplemented registers read as all bits zero. */
8980 memset (regs, 0, rsa->sizeof_g_packet);
8981
8982 /* Reply describes registers byte by byte, each byte encoded as two
8983 hex characters. Suck them all up, then supply them to the
8984 register cacheing/storage mechanism. */
8985
8986 p = rs->buf.data ();
8987 for (i = 0; i < rsa->sizeof_g_packet; i++)
8988 {
8989 if (p[0] == 0 || p[1] == 0)
8990 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8991 internal_error (_("unexpected end of 'g' packet reply"));
8992
8993 if (p[0] == 'x' && p[1] == 'x')
8994 regs[i] = 0; /* 'x' */
8995 else
8996 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8997 p += 2;
8998 }
8999
9000 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9001 {
9002 struct packet_reg *r = &rsa->regs[i];
9003 long reg_size = register_size (gdbarch, i);
9004
9005 if (r->in_g_packet)
9006 {
9007 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
9008 /* This shouldn't happen - we adjusted in_g_packet above. */
9009 internal_error (_("unexpected end of 'g' packet reply"));
9010 else if (rs->buf[r->offset * 2] == 'x')
9011 {
9012 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
9013 /* The register isn't available, mark it as such (at
9014 the same time setting the value to zero). */
9015 regcache->raw_supply (r->regnum, NULL);
9016 }
9017 else
9018 regcache->raw_supply (r->regnum, regs + r->offset);
9019 }
9020 }
9021 }
9022
9023 void
9024 remote_target::fetch_registers_using_g (struct regcache *regcache)
9025 {
9026 send_g_packet ();
9027 process_g_packet (regcache);
9028 }
9029
9030 /* Make the remote selected traceframe match GDB's selected
9031 traceframe. */
9032
9033 void
9034 remote_target::set_remote_traceframe ()
9035 {
9036 int newnum;
9037 struct remote_state *rs = get_remote_state ();
9038
9039 if (rs->remote_traceframe_number == get_traceframe_number ())
9040 return;
9041
9042 /* Avoid recursion, remote_trace_find calls us again. */
9043 rs->remote_traceframe_number = get_traceframe_number ();
9044
9045 newnum = target_trace_find (tfind_number,
9046 get_traceframe_number (), 0, 0, NULL);
9047
9048 /* Should not happen. If it does, all bets are off. */
9049 if (newnum != get_traceframe_number ())
9050 warning (_("could not set remote traceframe"));
9051 }
9052
9053 void
9054 remote_target::fetch_registers (struct regcache *regcache, int regnum)
9055 {
9056 struct gdbarch *gdbarch = regcache->arch ();
9057 struct remote_state *rs = get_remote_state ();
9058 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9059 int i;
9060
9061 set_remote_traceframe ();
9062 set_general_thread (regcache->ptid ());
9063
9064 if (regnum >= 0)
9065 {
9066 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9067
9068 gdb_assert (reg != NULL);
9069
9070 /* If this register might be in the 'g' packet, try that first -
9071 we are likely to read more than one register. If this is the
9072 first 'g' packet, we might be overly optimistic about its
9073 contents, so fall back to 'p'. */
9074 if (reg->in_g_packet)
9075 {
9076 fetch_registers_using_g (regcache);
9077 if (reg->in_g_packet)
9078 return;
9079 }
9080
9081 if (fetch_register_using_p (regcache, reg))
9082 return;
9083
9084 /* This register is not available. */
9085 regcache->raw_supply (reg->regnum, NULL);
9086
9087 return;
9088 }
9089
9090 fetch_registers_using_g (regcache);
9091
9092 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9093 if (!rsa->regs[i].in_g_packet)
9094 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
9095 {
9096 /* This register is not available. */
9097 regcache->raw_supply (i, NULL);
9098 }
9099 }
9100
9101 /* Prepare to store registers. Since we may send them all (using a
9102 'G' request), we have to read out the ones we don't want to change
9103 first. */
9104
9105 void
9106 remote_target::prepare_to_store (struct regcache *regcache)
9107 {
9108 struct remote_state *rs = get_remote_state ();
9109 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9110 int i;
9111
9112 /* Make sure the entire registers array is valid. */
9113 switch (m_features.packet_support (PACKET_P))
9114 {
9115 case PACKET_DISABLE:
9116 case PACKET_SUPPORT_UNKNOWN:
9117 /* Make sure all the necessary registers are cached. */
9118 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9119 if (rsa->regs[i].in_g_packet)
9120 regcache->raw_update (rsa->regs[i].regnum);
9121 break;
9122 case PACKET_ENABLE:
9123 break;
9124 }
9125 }
9126
9127 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9128 packet was not recognized. */
9129
9130 int
9131 remote_target::store_register_using_P (const struct regcache *regcache,
9132 packet_reg *reg)
9133 {
9134 struct gdbarch *gdbarch = regcache->arch ();
9135 struct remote_state *rs = get_remote_state ();
9136 /* Try storing a single register. */
9137 char *buf = rs->buf.data ();
9138 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9139 char *p;
9140
9141 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9142 return 0;
9143
9144 if (reg->pnum == -1)
9145 return 0;
9146
9147 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9148 p = buf + strlen (buf);
9149 regcache->raw_collect (reg->regnum, regp);
9150 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9151 putpkt (rs->buf);
9152 getpkt (&rs->buf);
9153
9154 packet_result result = m_features.packet_ok (rs->buf, PACKET_P);
9155 switch (result.status ())
9156 {
9157 case PACKET_OK:
9158 return 1;
9159 case PACKET_ERROR:
9160 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9161 gdbarch_register_name (gdbarch, reg->regnum), result.err_msg ());
9162 case PACKET_UNKNOWN:
9163 return 0;
9164 default:
9165 internal_error (_("Bad result from packet_ok"));
9166 }
9167 }
9168
9169 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9170 contents of the register cache buffer. FIXME: ignores errors. */
9171
9172 void
9173 remote_target::store_registers_using_G (const struct regcache *regcache)
9174 {
9175 struct remote_state *rs = get_remote_state ();
9176 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9177 gdb_byte *regs;
9178 char *p;
9179
9180 /* Extract all the registers in the regcache copying them into a
9181 local buffer. */
9182 {
9183 int i;
9184
9185 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9186 memset (regs, 0, rsa->sizeof_g_packet);
9187 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9188 {
9189 struct packet_reg *r = &rsa->regs[i];
9190
9191 if (r->in_g_packet)
9192 regcache->raw_collect (r->regnum, regs + r->offset);
9193 }
9194 }
9195
9196 /* Command describes registers byte by byte,
9197 each byte encoded as two hex characters. */
9198 p = rs->buf.data ();
9199 *p++ = 'G';
9200 bin2hex (regs, p, rsa->sizeof_g_packet);
9201 putpkt (rs->buf);
9202 getpkt (&rs->buf);
9203 packet_result pkt_status = packet_check_result (rs->buf, true);
9204 if (pkt_status.status () == PACKET_ERROR)
9205 error (_("Could not write registers; remote failure reply '%s'"),
9206 pkt_status.err_msg ());
9207 }
9208
9209 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9210 of the register cache buffer. FIXME: ignores errors. */
9211
9212 void
9213 remote_target::store_registers (struct regcache *regcache, int regnum)
9214 {
9215 struct gdbarch *gdbarch = regcache->arch ();
9216 struct remote_state *rs = get_remote_state ();
9217 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9218 int i;
9219
9220 set_remote_traceframe ();
9221 set_general_thread (regcache->ptid ());
9222
9223 if (regnum >= 0)
9224 {
9225 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9226
9227 gdb_assert (reg != NULL);
9228
9229 /* Always prefer to store registers using the 'P' packet if
9230 possible; we often change only a small number of registers.
9231 Sometimes we change a larger number; we'd need help from a
9232 higher layer to know to use 'G'. */
9233 if (store_register_using_P (regcache, reg))
9234 return;
9235
9236 /* For now, don't complain if we have no way to write the
9237 register. GDB loses track of unavailable registers too
9238 easily. Some day, this may be an error. We don't have
9239 any way to read the register, either... */
9240 if (!reg->in_g_packet)
9241 return;
9242
9243 store_registers_using_G (regcache);
9244 return;
9245 }
9246
9247 store_registers_using_G (regcache);
9248
9249 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9250 if (!rsa->regs[i].in_g_packet)
9251 if (!store_register_using_P (regcache, &rsa->regs[i]))
9252 /* See above for why we do not issue an error here. */
9253 continue;
9254 }
9255 \f
9256
9257 /* Return the number of hex digits in num. */
9258
9259 static int
9260 hexnumlen (ULONGEST num)
9261 {
9262 int i;
9263
9264 for (i = 0; num != 0; i++)
9265 num >>= 4;
9266
9267 return std::max (i, 1);
9268 }
9269
9270 /* Set BUF to the minimum number of hex digits representing NUM. */
9271
9272 static int
9273 hexnumstr (char *buf, ULONGEST num)
9274 {
9275 int len = hexnumlen (num);
9276
9277 return hexnumnstr (buf, num, len);
9278 }
9279
9280
9281 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9282
9283 static int
9284 hexnumnstr (char *buf, ULONGEST num, int width)
9285 {
9286 int i;
9287
9288 buf[width] = '\0';
9289
9290 for (i = width - 1; i >= 0; i--)
9291 {
9292 buf[i] = "0123456789abcdef"[(num & 0xf)];
9293 num >>= 4;
9294 }
9295
9296 return width;
9297 }
9298
9299 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9300
9301 static CORE_ADDR
9302 remote_address_masked (CORE_ADDR addr)
9303 {
9304 unsigned int address_size = remote_address_size;
9305
9306 /* If "remoteaddresssize" was not set, default to target address size. */
9307 if (!address_size)
9308 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9309
9310 if (address_size > 0
9311 && address_size < (sizeof (ULONGEST) * 8))
9312 {
9313 /* Only create a mask when that mask can safely be constructed
9314 in a ULONGEST variable. */
9315 ULONGEST mask = 1;
9316
9317 mask = (mask << address_size) - 1;
9318 addr &= mask;
9319 }
9320 return addr;
9321 }
9322
9323 /* Determine whether the remote target supports binary downloading.
9324 This is accomplished by sending a no-op memory write of zero length
9325 to the target at the specified address. It does not suffice to send
9326 the whole packet, since many stubs strip the eighth bit and
9327 subsequently compute a wrong checksum, which causes real havoc with
9328 remote_write_bytes.
9329
9330 NOTE: This can still lose if the serial line is not eight-bit
9331 clean. In cases like this, the user should clear "remote
9332 X-packet". */
9333
9334 void
9335 remote_target::check_binary_download (CORE_ADDR addr)
9336 {
9337 struct remote_state *rs = get_remote_state ();
9338
9339 switch (m_features.packet_support (PACKET_X))
9340 {
9341 case PACKET_DISABLE:
9342 break;
9343 case PACKET_ENABLE:
9344 break;
9345 case PACKET_SUPPORT_UNKNOWN:
9346 {
9347 char *p;
9348
9349 p = rs->buf.data ();
9350 *p++ = 'X';
9351 p += hexnumstr (p, (ULONGEST) addr);
9352 *p++ = ',';
9353 p += hexnumstr (p, (ULONGEST) 0);
9354 *p++ = ':';
9355 *p = '\0';
9356
9357 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9358 getpkt (&rs->buf);
9359
9360 if (rs->buf[0] == '\0')
9361 {
9362 remote_debug_printf ("binary downloading NOT supported by target");
9363 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9364 }
9365 else
9366 {
9367 remote_debug_printf ("binary downloading supported by target");
9368 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9369 }
9370 break;
9371 }
9372 }
9373 }
9374
9375 /* Helper function to resize the payload in order to try to get a good
9376 alignment. We try to write an amount of data such that the next write will
9377 start on an address aligned on REMOTE_ALIGN_WRITES. */
9378
9379 static int
9380 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9381 {
9382 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9383 }
9384
9385 /* Write memory data directly to the remote machine.
9386 This does not inform the data cache; the data cache uses this.
9387 HEADER is the starting part of the packet.
9388 MEMADDR is the address in the remote memory space.
9389 MYADDR is the address of the buffer in our space.
9390 LEN_UNITS is the number of addressable units to write.
9391 UNIT_SIZE is the length in bytes of an addressable unit.
9392 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9393 should send data as binary ('X'), or hex-encoded ('M').
9394
9395 The function creates packet of the form
9396 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9397
9398 where encoding of <DATA> is terminated by PACKET_FORMAT.
9399
9400 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9401 are omitted.
9402
9403 Return the transferred status, error or OK (an
9404 'enum target_xfer_status' value). Save the number of addressable units
9405 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9406
9407 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9408 exchange between gdb and the stub could look like (?? in place of the
9409 checksum):
9410
9411 -> $m1000,4#??
9412 <- aaaabbbbccccdddd
9413
9414 -> $M1000,3:eeeeffffeeee#??
9415 <- OK
9416
9417 -> $m1000,4#??
9418 <- eeeeffffeeeedddd */
9419
9420 target_xfer_status
9421 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9422 const gdb_byte *myaddr,
9423 ULONGEST len_units,
9424 int unit_size,
9425 ULONGEST *xfered_len_units,
9426 char packet_format, int use_length)
9427 {
9428 struct remote_state *rs = get_remote_state ();
9429 char *p;
9430 char *plen = NULL;
9431 int plenlen = 0;
9432 int todo_units;
9433 int units_written;
9434 int payload_capacity_bytes;
9435 int payload_length_bytes;
9436
9437 if (packet_format != 'X' && packet_format != 'M')
9438 internal_error (_("remote_write_bytes_aux: bad packet format"));
9439
9440 if (len_units == 0)
9441 return TARGET_XFER_EOF;
9442
9443 payload_capacity_bytes = get_memory_write_packet_size ();
9444
9445 /* The packet buffer will be large enough for the payload;
9446 get_memory_packet_size ensures this. */
9447 rs->buf[0] = '\0';
9448
9449 /* Compute the size of the actual payload by subtracting out the
9450 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9451
9452 payload_capacity_bytes -= strlen ("$,:#NN");
9453 if (!use_length)
9454 /* The comma won't be used. */
9455 payload_capacity_bytes += 1;
9456 payload_capacity_bytes -= strlen (header);
9457 payload_capacity_bytes -= hexnumlen (memaddr);
9458
9459 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9460
9461 strcat (rs->buf.data (), header);
9462 p = rs->buf.data () + strlen (header);
9463
9464 /* Compute a best guess of the number of bytes actually transfered. */
9465 if (packet_format == 'X')
9466 {
9467 /* Best guess at number of bytes that will fit. */
9468 todo_units = std::min (len_units,
9469 (ULONGEST) payload_capacity_bytes / unit_size);
9470 if (use_length)
9471 payload_capacity_bytes -= hexnumlen (todo_units);
9472 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9473 }
9474 else
9475 {
9476 /* Number of bytes that will fit. */
9477 todo_units
9478 = std::min (len_units,
9479 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9480 if (use_length)
9481 payload_capacity_bytes -= hexnumlen (todo_units);
9482 todo_units = std::min (todo_units,
9483 (payload_capacity_bytes / unit_size) / 2);
9484 }
9485
9486 if (todo_units <= 0)
9487 internal_error (_("minimum packet size too small to write data"));
9488
9489 /* If we already need another packet, then try to align the end
9490 of this packet to a useful boundary. */
9491 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9492 todo_units = align_for_efficient_write (todo_units, memaddr);
9493
9494 /* Append "<memaddr>". */
9495 memaddr = remote_address_masked (memaddr);
9496 p += hexnumstr (p, (ULONGEST) memaddr);
9497
9498 if (use_length)
9499 {
9500 /* Append ",". */
9501 *p++ = ',';
9502
9503 /* Append the length and retain its location and size. It may need to be
9504 adjusted once the packet body has been created. */
9505 plen = p;
9506 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9507 p += plenlen;
9508 }
9509
9510 /* Append ":". */
9511 *p++ = ':';
9512 *p = '\0';
9513
9514 /* Append the packet body. */
9515 if (packet_format == 'X')
9516 {
9517 /* Binary mode. Send target system values byte by byte, in
9518 increasing byte addresses. Only escape certain critical
9519 characters. */
9520 payload_length_bytes =
9521 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9522 &units_written, payload_capacity_bytes);
9523
9524 /* If not all TODO units fit, then we'll need another packet. Make
9525 a second try to keep the end of the packet aligned. Don't do
9526 this if the packet is tiny. */
9527 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9528 {
9529 int new_todo_units;
9530
9531 new_todo_units = align_for_efficient_write (units_written, memaddr);
9532
9533 if (new_todo_units != units_written)
9534 payload_length_bytes =
9535 remote_escape_output (myaddr, new_todo_units, unit_size,
9536 (gdb_byte *) p, &units_written,
9537 payload_capacity_bytes);
9538 }
9539
9540 p += payload_length_bytes;
9541 if (use_length && units_written < todo_units)
9542 {
9543 /* Escape chars have filled up the buffer prematurely,
9544 and we have actually sent fewer units than planned.
9545 Fix-up the length field of the packet. Use the same
9546 number of characters as before. */
9547 plen += hexnumnstr (plen, (ULONGEST) units_written,
9548 plenlen);
9549 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9550 }
9551 }
9552 else
9553 {
9554 /* Normal mode: Send target system values byte by byte, in
9555 increasing byte addresses. Each byte is encoded as a two hex
9556 value. */
9557 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9558 units_written = todo_units;
9559 }
9560
9561 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9562 getpkt (&rs->buf);
9563
9564 if (rs->buf[0] == 'E')
9565 return TARGET_XFER_E_IO;
9566
9567 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9568 send fewer units than we'd planned. */
9569 *xfered_len_units = (ULONGEST) units_written;
9570 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9571 }
9572
9573 /* Write memory data directly to the remote machine.
9574 This does not inform the data cache; the data cache uses this.
9575 MEMADDR is the address in the remote memory space.
9576 MYADDR is the address of the buffer in our space.
9577 LEN is the number of bytes.
9578
9579 Return the transferred status, error or OK (an
9580 'enum target_xfer_status' value). Save the number of bytes
9581 transferred in *XFERED_LEN. Only transfer a single packet. */
9582
9583 target_xfer_status
9584 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9585 ULONGEST len, int unit_size,
9586 ULONGEST *xfered_len)
9587 {
9588 const char *packet_format = NULL;
9589
9590 /* Check whether the target supports binary download. */
9591 check_binary_download (memaddr);
9592
9593 switch (m_features.packet_support (PACKET_X))
9594 {
9595 case PACKET_ENABLE:
9596 packet_format = "X";
9597 break;
9598 case PACKET_DISABLE:
9599 packet_format = "M";
9600 break;
9601 case PACKET_SUPPORT_UNKNOWN:
9602 internal_error (_("remote_write_bytes: bad internal state"));
9603 default:
9604 internal_error (_("bad switch"));
9605 }
9606
9607 return remote_write_bytes_aux (packet_format,
9608 memaddr, myaddr, len, unit_size, xfered_len,
9609 packet_format[0], 1);
9610 }
9611
9612 /* Read memory data directly from the remote machine.
9613 This does not use the data cache; the data cache uses this.
9614 MEMADDR is the address in the remote memory space.
9615 MYADDR is the address of the buffer in our space.
9616 LEN_UNITS is the number of addressable memory units to read..
9617 UNIT_SIZE is the length in bytes of an addressable unit.
9618
9619 Return the transferred status, error or OK (an
9620 'enum target_xfer_status' value). Save the number of bytes
9621 transferred in *XFERED_LEN_UNITS.
9622
9623 See the comment of remote_write_bytes_aux for an example of
9624 memory read/write exchange between gdb and the stub. */
9625
9626 target_xfer_status
9627 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9628 ULONGEST len_units,
9629 int unit_size, ULONGEST *xfered_len_units)
9630 {
9631 struct remote_state *rs = get_remote_state ();
9632 int buf_size_bytes; /* Max size of packet output buffer. */
9633 char *p;
9634 int todo_units;
9635 int decoded_bytes;
9636
9637 buf_size_bytes = get_memory_read_packet_size ();
9638 /* The packet buffer will be large enough for the payload;
9639 get_memory_packet_size ensures this. */
9640
9641 /* Number of units that will fit. */
9642 todo_units = std::min (len_units,
9643 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9644
9645 /* Construct "m"<memaddr>","<len>". */
9646 memaddr = remote_address_masked (memaddr);
9647 p = rs->buf.data ();
9648 *p++ = 'm';
9649 p += hexnumstr (p, (ULONGEST) memaddr);
9650 *p++ = ',';
9651 p += hexnumstr (p, (ULONGEST) todo_units);
9652 *p = '\0';
9653 putpkt (rs->buf);
9654 getpkt (&rs->buf);
9655 packet_result result = packet_check_result (rs->buf, false);
9656 if (result.status () == PACKET_ERROR)
9657 return TARGET_XFER_E_IO;
9658 /* Reply describes memory byte by byte, each byte encoded as two hex
9659 characters. */
9660 p = rs->buf.data ();
9661 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9662 /* Return what we have. Let higher layers handle partial reads. */
9663 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9664 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9665 }
9666
9667 /* Using the set of read-only target sections of remote, read live
9668 read-only memory.
9669
9670 For interface/parameters/return description see target.h,
9671 to_xfer_partial. */
9672
9673 target_xfer_status
9674 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9675 ULONGEST memaddr,
9676 ULONGEST len,
9677 int unit_size,
9678 ULONGEST *xfered_len)
9679 {
9680 const struct target_section *secp;
9681
9682 secp = target_section_by_addr (this, memaddr);
9683 if (secp != NULL
9684 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9685 {
9686 ULONGEST memend = memaddr + len;
9687
9688 const std::vector<target_section> *table
9689 = target_get_section_table (this);
9690 for (const target_section &p : *table)
9691 {
9692 if (memaddr >= p.addr)
9693 {
9694 if (memend <= p.endaddr)
9695 {
9696 /* Entire transfer is within this section. */
9697 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9698 xfered_len);
9699 }
9700 else if (memaddr >= p.endaddr)
9701 {
9702 /* This section ends before the transfer starts. */
9703 continue;
9704 }
9705 else
9706 {
9707 /* This section overlaps the transfer. Just do half. */
9708 len = p.endaddr - memaddr;
9709 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9710 xfered_len);
9711 }
9712 }
9713 }
9714 }
9715
9716 return TARGET_XFER_EOF;
9717 }
9718
9719 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9720 first if the requested memory is unavailable in traceframe.
9721 Otherwise, fall back to remote_read_bytes_1. */
9722
9723 target_xfer_status
9724 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9725 gdb_byte *myaddr, ULONGEST len, int unit_size,
9726 ULONGEST *xfered_len)
9727 {
9728 if (len == 0)
9729 return TARGET_XFER_EOF;
9730
9731 if (get_traceframe_number () != -1)
9732 {
9733 std::vector<mem_range> available;
9734
9735 /* If we fail to get the set of available memory, then the
9736 target does not support querying traceframe info, and so we
9737 attempt reading from the traceframe anyway (assuming the
9738 target implements the old QTro packet then). */
9739 if (traceframe_available_memory (&available, memaddr, len))
9740 {
9741 if (available.empty () || available[0].start != memaddr)
9742 {
9743 enum target_xfer_status res;
9744
9745 /* Don't read into the traceframe's available
9746 memory. */
9747 if (!available.empty ())
9748 {
9749 LONGEST oldlen = len;
9750
9751 len = available[0].start - memaddr;
9752 gdb_assert (len <= oldlen);
9753 }
9754
9755 /* This goes through the topmost target again. */
9756 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9757 len, unit_size, xfered_len);
9758 if (res == TARGET_XFER_OK)
9759 return TARGET_XFER_OK;
9760 else
9761 {
9762 /* No use trying further, we know some memory starting
9763 at MEMADDR isn't available. */
9764 *xfered_len = len;
9765 return (*xfered_len != 0) ?
9766 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9767 }
9768 }
9769
9770 /* Don't try to read more than how much is available, in
9771 case the target implements the deprecated QTro packet to
9772 cater for older GDBs (the target's knowledge of read-only
9773 sections may be outdated by now). */
9774 len = available[0].length;
9775 }
9776 }
9777
9778 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9779 }
9780
9781 \f
9782
9783 /* Sends a packet with content determined by the printf format string
9784 FORMAT and the remaining arguments, then gets the reply. Returns
9785 whether the packet was a success, a failure, or unknown. */
9786
9787 packet_status
9788 remote_target::remote_send_printf (const char *format, ...)
9789 {
9790 struct remote_state *rs = get_remote_state ();
9791 int max_size = get_remote_packet_size ();
9792 va_list ap;
9793
9794 va_start (ap, format);
9795
9796 rs->buf[0] = '\0';
9797 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9798
9799 va_end (ap);
9800
9801 if (size >= max_size)
9802 internal_error (_("Too long remote packet."));
9803
9804 if (putpkt (rs->buf) < 0)
9805 error (_("Communication problem with target."));
9806
9807 rs->buf[0] = '\0';
9808 getpkt (&rs->buf);
9809
9810 return packet_check_result (rs->buf, true).status ();
9811 }
9812
9813 /* Flash writing can take quite some time. We'll set
9814 effectively infinite timeout for flash operations.
9815 In future, we'll need to decide on a better approach. */
9816 static const int remote_flash_timeout = 1000;
9817
9818 void
9819 remote_target::flash_erase (ULONGEST address, LONGEST length)
9820 {
9821 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9822 enum packet_status ret;
9823 scoped_restore restore_timeout
9824 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9825
9826 ret = remote_send_printf ("vFlashErase:%s,%s",
9827 phex (address, addr_size),
9828 phex (length, 4));
9829 switch (ret)
9830 {
9831 case PACKET_UNKNOWN:
9832 error (_("Remote target does not support flash erase"));
9833 case PACKET_ERROR:
9834 error (_("Error erasing flash with vFlashErase packet"));
9835 default:
9836 break;
9837 }
9838 }
9839
9840 target_xfer_status
9841 remote_target::remote_flash_write (ULONGEST address,
9842 ULONGEST length, ULONGEST *xfered_len,
9843 const gdb_byte *data)
9844 {
9845 scoped_restore restore_timeout
9846 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9847 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9848 xfered_len,'X', 0);
9849 }
9850
9851 void
9852 remote_target::flash_done ()
9853 {
9854 int ret;
9855
9856 scoped_restore restore_timeout
9857 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9858
9859 ret = remote_send_printf ("vFlashDone");
9860
9861 switch (ret)
9862 {
9863 case PACKET_UNKNOWN:
9864 error (_("Remote target does not support vFlashDone"));
9865 case PACKET_ERROR:
9866 error (_("Error finishing flash operation"));
9867 default:
9868 break;
9869 }
9870 }
9871
9872 \f
9873 /* Stuff for dealing with the packets which are part of this protocol.
9874 See comment at top of file for details. */
9875
9876 /* Read a single character from the remote end. The current quit
9877 handler is overridden to avoid quitting in the middle of packet
9878 sequence, as that would break communication with the remote server.
9879 See remote_serial_quit_handler for more detail. */
9880
9881 int
9882 remote_target::readchar (int timeout)
9883 {
9884 int ch;
9885 struct remote_state *rs = get_remote_state ();
9886
9887 try
9888 {
9889 scoped_restore restore_quit_target
9890 = make_scoped_restore (&curr_quit_handler_target, this);
9891 scoped_restore restore_quit
9892 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9893
9894 rs->got_ctrlc_during_io = 0;
9895
9896 ch = serial_readchar (rs->remote_desc, timeout);
9897
9898 if (rs->got_ctrlc_during_io)
9899 set_quit_flag ();
9900 }
9901 catch (const gdb_exception_error &ex)
9902 {
9903 remote_unpush_target (this);
9904 throw_error (TARGET_CLOSE_ERROR,
9905 _("Remote communication error. "
9906 "Target disconnected: %s"),
9907 ex.what ());
9908 }
9909
9910 if (ch >= 0)
9911 return ch;
9912
9913 if (ch == SERIAL_EOF)
9914 {
9915 remote_unpush_target (this);
9916 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9917 }
9918
9919 return ch;
9920 }
9921
9922 /* Wrapper for serial_write that closes the target and throws if
9923 writing fails. The current quit handler is overridden to avoid
9924 quitting in the middle of packet sequence, as that would break
9925 communication with the remote server. See
9926 remote_serial_quit_handler for more detail. */
9927
9928 void
9929 remote_target::remote_serial_write (const char *str, int len)
9930 {
9931 struct remote_state *rs = get_remote_state ();
9932
9933 scoped_restore restore_quit_target
9934 = make_scoped_restore (&curr_quit_handler_target, this);
9935 scoped_restore restore_quit
9936 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9937
9938 rs->got_ctrlc_during_io = 0;
9939
9940 try
9941 {
9942 serial_write (rs->remote_desc, str, len);
9943 }
9944 catch (const gdb_exception_error &ex)
9945 {
9946 remote_unpush_target (this);
9947 throw_error (TARGET_CLOSE_ERROR,
9948 _("Remote communication error. "
9949 "Target disconnected: %s"),
9950 ex.what ());
9951 }
9952
9953 if (rs->got_ctrlc_during_io)
9954 set_quit_flag ();
9955 }
9956
9957 void
9958 remote_target::remote_serial_send_break ()
9959 {
9960 struct remote_state *rs = get_remote_state ();
9961
9962 try
9963 {
9964 serial_send_break (rs->remote_desc);
9965 }
9966 catch (const gdb_exception_error &ex)
9967 {
9968 remote_unpush_target (this);
9969 throw_error (TARGET_CLOSE_ERROR,
9970 _("Remote communication error. "
9971 "Target disconnected: %s"),
9972 ex.what ());
9973 }
9974 }
9975
9976 /* Return a string representing an escaped version of BUF, of len N.
9977 E.g. \n is converted to \\n, \t to \\t, etc. */
9978
9979 static std::string
9980 escape_buffer (const char *buf, int n)
9981 {
9982 string_file stb;
9983
9984 stb.putstrn (buf, n, '\\');
9985 return stb.release ();
9986 }
9987
9988 int
9989 remote_target::putpkt (const char *buf)
9990 {
9991 return putpkt_binary (buf, strlen (buf));
9992 }
9993
9994 /* Wrapper around remote_target::putpkt to avoid exporting
9995 remote_target. */
9996
9997 int
9998 putpkt (remote_target *remote, const char *buf)
9999 {
10000 return remote->putpkt (buf);
10001 }
10002
10003 /* Send a packet to the remote machine, with error checking. The data
10004 of the packet is in BUF. The string in BUF can be at most
10005 get_remote_packet_size () - 5 to account for the $, # and checksum,
10006 and for a possible /0 if we are debugging (remote_debug) and want
10007 to print the sent packet as a string. */
10008
10009 int
10010 remote_target::putpkt_binary (const char *buf, int cnt)
10011 {
10012 struct remote_state *rs = get_remote_state ();
10013 int i;
10014 unsigned char csum = 0;
10015 gdb::def_vector<char> data (cnt + 6);
10016 char *buf2 = data.data ();
10017
10018 int ch;
10019 int tcount = 0;
10020 char *p;
10021
10022 /* Catch cases like trying to read memory or listing threads while
10023 we're waiting for a stop reply. The remote server wouldn't be
10024 ready to handle this request, so we'd hang and timeout. We don't
10025 have to worry about this in synchronous mode, because in that
10026 case it's not possible to issue a command while the target is
10027 running. This is not a problem in non-stop mode, because in that
10028 case, the stub is always ready to process serial input. */
10029 if (!target_is_non_stop_p ()
10030 && target_is_async_p ()
10031 && rs->waiting_for_stop_reply)
10032 {
10033 error (_("Cannot execute this command while the target is running.\n"
10034 "Use the \"interrupt\" command to stop the target\n"
10035 "and then try again."));
10036 }
10037
10038 /* Copy the packet into buffer BUF2, encapsulating it
10039 and giving it a checksum. */
10040
10041 p = buf2;
10042 *p++ = '$';
10043
10044 for (i = 0; i < cnt; i++)
10045 {
10046 csum += buf[i];
10047 *p++ = buf[i];
10048 }
10049 *p++ = '#';
10050 *p++ = tohex ((csum >> 4) & 0xf);
10051 *p++ = tohex (csum & 0xf);
10052
10053 /* Send it over and over until we get a positive ack. */
10054
10055 while (1)
10056 {
10057 if (remote_debug)
10058 {
10059 *p = '\0';
10060
10061 int len = (int) (p - buf2);
10062 int max_chars;
10063
10064 if (remote_packet_max_chars < 0)
10065 max_chars = len;
10066 else
10067 max_chars = remote_packet_max_chars;
10068
10069 std::string str
10070 = escape_buffer (buf2, std::min (len, max_chars));
10071
10072 if (len > max_chars)
10073 remote_debug_printf_nofunc
10074 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
10075 len - max_chars);
10076 else
10077 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
10078 }
10079 remote_serial_write (buf2, p - buf2);
10080
10081 /* If this is a no acks version of the remote protocol, send the
10082 packet and move on. */
10083 if (rs->noack_mode)
10084 break;
10085
10086 /* Read until either a timeout occurs (-2) or '+' is read.
10087 Handle any notification that arrives in the mean time. */
10088 while (1)
10089 {
10090 ch = readchar (remote_timeout);
10091
10092 switch (ch)
10093 {
10094 case '+':
10095 remote_debug_printf_nofunc ("Received Ack");
10096 return 1;
10097 case '-':
10098 remote_debug_printf_nofunc ("Received Nak");
10099 [[fallthrough]];
10100 case SERIAL_TIMEOUT:
10101 tcount++;
10102 if (tcount > 3)
10103 return 0;
10104 break; /* Retransmit buffer. */
10105 case '$':
10106 {
10107 remote_debug_printf ("Packet instead of Ack, ignoring it");
10108 /* It's probably an old response sent because an ACK
10109 was lost. Gobble up the packet and ack it so it
10110 doesn't get retransmitted when we resend this
10111 packet. */
10112 skip_frame ();
10113 remote_serial_write ("+", 1);
10114 continue; /* Now, go look for +. */
10115 }
10116
10117 case '%':
10118 {
10119 int val;
10120
10121 /* If we got a notification, handle it, and go back to looking
10122 for an ack. */
10123 /* We've found the start of a notification. Now
10124 collect the data. */
10125 val = read_frame (&rs->buf);
10126 if (val >= 0)
10127 {
10128 remote_debug_printf_nofunc
10129 (" Notification received: %s",
10130 escape_buffer (rs->buf.data (), val).c_str ());
10131
10132 handle_notification (rs->notif_state, rs->buf.data ());
10133 /* We're in sync now, rewait for the ack. */
10134 tcount = 0;
10135 }
10136 else
10137 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10138 rs->buf.data ());
10139 continue;
10140 }
10141 default:
10142 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10143 rs->buf.data ());
10144 continue;
10145 }
10146 break; /* Here to retransmit. */
10147 }
10148
10149 #if 0
10150 /* This is wrong. If doing a long backtrace, the user should be
10151 able to get out next time we call QUIT, without anything as
10152 violent as interrupt_query. If we want to provide a way out of
10153 here without getting to the next QUIT, it should be based on
10154 hitting ^C twice as in remote_wait. */
10155 if (quit_flag)
10156 {
10157 quit_flag = 0;
10158 interrupt_query ();
10159 }
10160 #endif
10161 }
10162
10163 return 0;
10164 }
10165
10166 /* Come here after finding the start of a frame when we expected an
10167 ack. Do our best to discard the rest of this packet. */
10168
10169 void
10170 remote_target::skip_frame ()
10171 {
10172 int c;
10173
10174 while (1)
10175 {
10176 c = readchar (remote_timeout);
10177 switch (c)
10178 {
10179 case SERIAL_TIMEOUT:
10180 /* Nothing we can do. */
10181 return;
10182 case '#':
10183 /* Discard the two bytes of checksum and stop. */
10184 c = readchar (remote_timeout);
10185 if (c >= 0)
10186 c = readchar (remote_timeout);
10187
10188 return;
10189 case '*': /* Run length encoding. */
10190 /* Discard the repeat count. */
10191 c = readchar (remote_timeout);
10192 if (c < 0)
10193 return;
10194 break;
10195 default:
10196 /* A regular character. */
10197 break;
10198 }
10199 }
10200 }
10201
10202 /* Come here after finding the start of the frame. Collect the rest
10203 into *BUF, verifying the checksum, length, and handling run-length
10204 compression. NUL terminate the buffer. If there is not enough room,
10205 expand *BUF.
10206
10207 Returns -1 on error, number of characters in buffer (ignoring the
10208 trailing NULL) on success. (could be extended to return one of the
10209 SERIAL status indications). */
10210
10211 long
10212 remote_target::read_frame (gdb::char_vector *buf_p)
10213 {
10214 unsigned char csum;
10215 long bc;
10216 int c;
10217 char *buf = buf_p->data ();
10218 struct remote_state *rs = get_remote_state ();
10219
10220 csum = 0;
10221 bc = 0;
10222
10223 while (1)
10224 {
10225 c = readchar (remote_timeout);
10226 switch (c)
10227 {
10228 case SERIAL_TIMEOUT:
10229 remote_debug_printf ("Timeout in mid-packet, retrying");
10230 return -1;
10231
10232 case '$':
10233 remote_debug_printf ("Saw new packet start in middle of old one");
10234 return -1; /* Start a new packet, count retries. */
10235
10236 case '#':
10237 {
10238 unsigned char pktcsum;
10239 int check_0 = 0;
10240 int check_1 = 0;
10241
10242 buf[bc] = '\0';
10243
10244 check_0 = readchar (remote_timeout);
10245 if (check_0 >= 0)
10246 check_1 = readchar (remote_timeout);
10247
10248 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10249 {
10250 remote_debug_printf ("Timeout in checksum, retrying");
10251 return -1;
10252 }
10253 else if (check_0 < 0 || check_1 < 0)
10254 {
10255 remote_debug_printf ("Communication error in checksum");
10256 return -1;
10257 }
10258
10259 /* Don't recompute the checksum; with no ack packets we
10260 don't have any way to indicate a packet retransmission
10261 is necessary. */
10262 if (rs->noack_mode)
10263 return bc;
10264
10265 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10266 if (csum == pktcsum)
10267 return bc;
10268
10269 remote_debug_printf
10270 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10271 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10272
10273 /* Number of characters in buffer ignoring trailing
10274 NULL. */
10275 return -1;
10276 }
10277 case '*': /* Run length encoding. */
10278 {
10279 int repeat;
10280
10281 csum += c;
10282 c = readchar (remote_timeout);
10283 csum += c;
10284 repeat = c - ' ' + 3; /* Compute repeat count. */
10285
10286 /* The character before ``*'' is repeated. */
10287
10288 if (repeat > 0 && repeat <= 255 && bc > 0)
10289 {
10290 if (bc + repeat - 1 >= buf_p->size () - 1)
10291 {
10292 /* Make some more room in the buffer. */
10293 buf_p->resize (buf_p->size () + repeat);
10294 buf = buf_p->data ();
10295 }
10296
10297 memset (&buf[bc], buf[bc - 1], repeat);
10298 bc += repeat;
10299 continue;
10300 }
10301
10302 buf[bc] = '\0';
10303 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10304 return -1;
10305 }
10306 default:
10307 if (bc >= buf_p->size () - 1)
10308 {
10309 /* Make some more room in the buffer. */
10310 buf_p->resize (buf_p->size () * 2);
10311 buf = buf_p->data ();
10312 }
10313
10314 buf[bc++] = c;
10315 csum += c;
10316 continue;
10317 }
10318 }
10319 }
10320
10321 /* Set this to the maximum number of seconds to wait instead of waiting forever
10322 in target_wait(). If this timer times out, then it generates an error and
10323 the command is aborted. This replaces most of the need for timeouts in the
10324 GDB test suite, and makes it possible to distinguish between a hung target
10325 and one with slow communications. */
10326
10327 static int watchdog = 0;
10328 static void
10329 show_watchdog (struct ui_file *file, int from_tty,
10330 struct cmd_list_element *c, const char *value)
10331 {
10332 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10333 }
10334
10335 /* Read a packet from the remote machine, with error checking, and
10336 store it in *BUF. Resize *BUF if necessary to hold the result. If
10337 FOREVER, wait forever rather than timing out; this is used (in
10338 synchronous mode) to wait for a target that is is executing user
10339 code to stop. If FOREVER == false, this function is allowed to time
10340 out gracefully and return an indication of this to the caller.
10341 Otherwise return the number of bytes read. If IS_NOTIF is not
10342 NULL, then consider receiving a notification enough reason to
10343 return to the caller. In this case, *IS_NOTIF is an output boolean
10344 that indicates whether *BUF holds a notification or not (a regular
10345 packet). */
10346
10347 int
10348 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10349 {
10350 struct remote_state *rs = get_remote_state ();
10351 int c;
10352 int tries;
10353 int timeout;
10354 int val = -1;
10355
10356 strcpy (buf->data (), "timeout");
10357
10358 if (forever)
10359 timeout = watchdog > 0 ? watchdog : -1;
10360 else if (is_notif != nullptr)
10361 timeout = 0; /* There should already be a char in the buffer. If
10362 not, bail out. */
10363 else
10364 timeout = remote_timeout;
10365
10366 #define MAX_TRIES 3
10367
10368 /* Process any number of notifications, and then return when
10369 we get a packet. */
10370 for (;;)
10371 {
10372 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10373 times. */
10374 for (tries = 1; tries <= MAX_TRIES; tries++)
10375 {
10376 /* This can loop forever if the remote side sends us
10377 characters continuously, but if it pauses, we'll get
10378 SERIAL_TIMEOUT from readchar because of timeout. Then
10379 we'll count that as a retry.
10380
10381 Note that even when forever is set, we will only wait
10382 forever prior to the start of a packet. After that, we
10383 expect characters to arrive at a brisk pace. They should
10384 show up within remote_timeout intervals. */
10385 do
10386 c = readchar (timeout);
10387 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10388
10389 if (c == SERIAL_TIMEOUT)
10390 {
10391 if (is_notif != nullptr)
10392 return -1; /* Don't complain, it's normal to not get
10393 anything in this case. */
10394
10395 if (forever) /* Watchdog went off? Kill the target. */
10396 {
10397 remote_unpush_target (this);
10398 throw_error (TARGET_CLOSE_ERROR,
10399 _("Watchdog timeout has expired. "
10400 "Target detached."));
10401 }
10402
10403 remote_debug_printf ("Timed out.");
10404 }
10405 else
10406 {
10407 /* We've found the start of a packet or notification.
10408 Now collect the data. */
10409 val = read_frame (buf);
10410 if (val >= 0)
10411 break;
10412 }
10413
10414 remote_serial_write ("-", 1);
10415 }
10416
10417 if (tries > MAX_TRIES)
10418 {
10419 /* We have tried hard enough, and just can't receive the
10420 packet/notification. Give up. */
10421 gdb_printf (_("Ignoring packet error, continuing...\n"));
10422
10423 /* Skip the ack char if we're in no-ack mode. */
10424 if (!rs->noack_mode)
10425 remote_serial_write ("+", 1);
10426 return -1;
10427 }
10428
10429 /* If we got an ordinary packet, return that to our caller. */
10430 if (c == '$')
10431 {
10432 if (remote_debug)
10433 {
10434 int max_chars;
10435
10436 if (remote_packet_max_chars < 0)
10437 max_chars = val;
10438 else
10439 max_chars = remote_packet_max_chars;
10440
10441 std::string str
10442 = escape_buffer (buf->data (),
10443 std::min (val, max_chars));
10444
10445 if (val > max_chars)
10446 remote_debug_printf_nofunc
10447 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10448 val - max_chars);
10449 else
10450 remote_debug_printf_nofunc ("Packet received: %s",
10451 str.c_str ());
10452 }
10453
10454 /* Skip the ack char if we're in no-ack mode. */
10455 if (!rs->noack_mode)
10456 remote_serial_write ("+", 1);
10457 if (is_notif != NULL)
10458 *is_notif = false;
10459 return val;
10460 }
10461
10462 /* If we got a notification, handle it, and go back to looking
10463 for a packet. */
10464 else
10465 {
10466 gdb_assert (c == '%');
10467
10468 remote_debug_printf_nofunc
10469 (" Notification received: %s",
10470 escape_buffer (buf->data (), val).c_str ());
10471
10472 if (is_notif != NULL)
10473 *is_notif = true;
10474
10475 handle_notification (rs->notif_state, buf->data ());
10476
10477 /* Notifications require no acknowledgement. */
10478
10479 if (is_notif != nullptr)
10480 return val;
10481 }
10482 }
10483 }
10484
10485 /* Kill any new fork children of inferior INF that haven't been
10486 processed by follow_fork. */
10487
10488 void
10489 remote_target::kill_new_fork_children (inferior *inf)
10490 {
10491 remote_state *rs = get_remote_state ();
10492 const notif_client *notif = &notif_client_stop;
10493
10494 /* Kill the fork child threads of any threads in inferior INF that are stopped
10495 at a fork event. */
10496 for (thread_info *thread : inf->non_exited_threads ())
10497 {
10498 const target_waitstatus *ws = thread_pending_fork_status (thread);
10499
10500 if (ws == nullptr)
10501 continue;
10502
10503 int child_pid = ws->child_ptid ().pid ();
10504 int res = remote_vkill (child_pid);
10505
10506 if (res != 0)
10507 error (_("Can't kill fork child process %d"), child_pid);
10508 }
10509
10510 /* Check for any pending fork events (not reported or processed yet)
10511 in inferior INF and kill those fork child threads as well. */
10512 remote_notif_get_pending_events (notif);
10513 for (auto &event : rs->stop_reply_queue)
10514 {
10515 if (event->ptid.pid () != inf->pid)
10516 continue;
10517
10518 if (!is_fork_status (event->ws.kind ()))
10519 continue;
10520
10521 int child_pid = event->ws.child_ptid ().pid ();
10522 int res = remote_vkill (child_pid);
10523
10524 if (res != 0)
10525 error (_("Can't kill fork child process %d"), child_pid);
10526 }
10527 }
10528
10529 \f
10530 /* Target hook to kill the current inferior. */
10531
10532 void
10533 remote_target::kill ()
10534 {
10535 int res = -1;
10536 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10537
10538 gdb_assert (inf != nullptr);
10539
10540 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10541 {
10542 /* If we're stopped while forking and we haven't followed yet,
10543 kill the child task. We need to do this before killing the
10544 parent task because if this is a vfork then the parent will
10545 be sleeping. */
10546 kill_new_fork_children (inf);
10547
10548 res = remote_vkill (inf->pid);
10549 if (res == 0)
10550 {
10551 target_mourn_inferior (inferior_ptid);
10552 return;
10553 }
10554 }
10555
10556 /* If we are in 'target remote' mode and we are killing the only
10557 inferior, then we will tell gdbserver to exit and unpush the
10558 target. */
10559 if (res == -1 && !m_features.remote_multi_process_p ()
10560 && number_of_live_inferiors (this) == 1)
10561 {
10562 remote_kill_k ();
10563
10564 /* We've killed the remote end, we get to mourn it. If we are
10565 not in extended mode, mourning the inferior also unpushes
10566 remote_ops from the target stack, which closes the remote
10567 connection. */
10568 target_mourn_inferior (inferior_ptid);
10569
10570 return;
10571 }
10572
10573 error (_("Can't kill process"));
10574 }
10575
10576 /* Send a kill request to the target using the 'vKill' packet. */
10577
10578 int
10579 remote_target::remote_vkill (int pid)
10580 {
10581 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10582 return -1;
10583
10584 remote_state *rs = get_remote_state ();
10585
10586 /* Tell the remote target to detach. */
10587 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10588 putpkt (rs->buf);
10589 getpkt (&rs->buf);
10590
10591 switch ((m_features.packet_ok (rs->buf, PACKET_vKill)).status ())
10592 {
10593 case PACKET_OK:
10594 return 0;
10595 case PACKET_ERROR:
10596 return 1;
10597 case PACKET_UNKNOWN:
10598 return -1;
10599 default:
10600 internal_error (_("Bad result from packet_ok"));
10601 }
10602 }
10603
10604 /* Send a kill request to the target using the 'k' packet. */
10605
10606 void
10607 remote_target::remote_kill_k ()
10608 {
10609 /* Catch errors so the user can quit from gdb even when we
10610 aren't on speaking terms with the remote system. */
10611 try
10612 {
10613 putpkt ("k");
10614 }
10615 catch (const gdb_exception_error &ex)
10616 {
10617 if (ex.error == TARGET_CLOSE_ERROR)
10618 {
10619 /* If we got an (EOF) error that caused the target
10620 to go away, then we're done, that's what we wanted.
10621 "k" is susceptible to cause a premature EOF, given
10622 that the remote server isn't actually required to
10623 reply to "k", and it can happen that it doesn't
10624 even get to reply ACK to the "k". */
10625 return;
10626 }
10627
10628 /* Otherwise, something went wrong. We didn't actually kill
10629 the target. Just propagate the exception, and let the
10630 user or higher layers decide what to do. */
10631 throw;
10632 }
10633 }
10634
10635 void
10636 remote_target::mourn_inferior ()
10637 {
10638 struct remote_state *rs = get_remote_state ();
10639
10640 /* We're no longer interested in notification events of an inferior
10641 that exited or was killed/detached. */
10642 discard_pending_stop_replies (current_inferior ());
10643
10644 /* In 'target remote' mode with one inferior, we close the connection. */
10645 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10646 {
10647 remote_unpush_target (this);
10648 return;
10649 }
10650
10651 /* In case we got here due to an error, but we're going to stay
10652 connected. */
10653 rs->waiting_for_stop_reply = 0;
10654
10655 /* If the current general thread belonged to the process we just
10656 detached from or has exited, the remote side current general
10657 thread becomes undefined. Considering a case like this:
10658
10659 - We just got here due to a detach.
10660 - The process that we're detaching from happens to immediately
10661 report a global breakpoint being hit in non-stop mode, in the
10662 same thread we had selected before.
10663 - GDB attaches to this process again.
10664 - This event happens to be the next event we handle.
10665
10666 GDB would consider that the current general thread didn't need to
10667 be set on the stub side (with Hg), since for all it knew,
10668 GENERAL_THREAD hadn't changed.
10669
10670 Notice that although in all-stop mode, the remote server always
10671 sets the current thread to the thread reporting the stop event,
10672 that doesn't happen in non-stop mode; in non-stop, the stub *must
10673 not* change the current thread when reporting a breakpoint hit,
10674 due to the decoupling of event reporting and event handling.
10675
10676 To keep things simple, we always invalidate our notion of the
10677 current thread. */
10678 record_currthread (rs, minus_one_ptid);
10679
10680 /* Call common code to mark the inferior as not running. */
10681 generic_mourn_inferior ();
10682 }
10683
10684 bool
10685 extended_remote_target::supports_disable_randomization ()
10686 {
10687 return (m_features.packet_support (PACKET_QDisableRandomization)
10688 == PACKET_ENABLE);
10689 }
10690
10691 void
10692 remote_target::extended_remote_disable_randomization (int val)
10693 {
10694 struct remote_state *rs = get_remote_state ();
10695 char *reply;
10696
10697 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10698 "QDisableRandomization:%x", val);
10699 putpkt (rs->buf);
10700 reply = remote_get_noisy_reply ();
10701 if (*reply == '\0')
10702 error (_("Target does not support QDisableRandomization."));
10703 if (strcmp (reply, "OK") != 0)
10704 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10705 }
10706
10707 int
10708 remote_target::extended_remote_run (const std::string &args)
10709 {
10710 struct remote_state *rs = get_remote_state ();
10711 int len;
10712 const char *remote_exec_file = get_remote_exec_file ();
10713
10714 /* If the user has disabled vRun support, or we have detected that
10715 support is not available, do not try it. */
10716 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10717 return -1;
10718
10719 strcpy (rs->buf.data (), "vRun;");
10720 len = strlen (rs->buf.data ());
10721
10722 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10723 error (_("Remote file name too long for run packet"));
10724 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10725 strlen (remote_exec_file));
10726
10727 if (!args.empty ())
10728 {
10729 int i;
10730
10731 gdb_argv argv (args.c_str ());
10732 for (i = 0; argv[i] != NULL; i++)
10733 {
10734 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10735 error (_("Argument list too long for run packet"));
10736 rs->buf[len++] = ';';
10737 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10738 strlen (argv[i]));
10739 }
10740 }
10741
10742 rs->buf[len++] = '\0';
10743
10744 putpkt (rs->buf);
10745 getpkt (&rs->buf);
10746
10747 packet_result result = m_features.packet_ok (rs->buf, PACKET_vRun);
10748 switch (result.status ())
10749 {
10750 case PACKET_OK:
10751 /* We have a wait response. All is well. */
10752 return 0;
10753 case PACKET_UNKNOWN:
10754 return -1;
10755 case PACKET_ERROR:
10756 /* If we have a textual error message, print just that. This
10757 makes remote debugging output the same as native output, when
10758 possible. */
10759 if (result.textual_err_msg ())
10760 error (("%s"), result.err_msg ());
10761 if (remote_exec_file[0] == '\0')
10762 error (_("Running the default executable on the remote target failed; "
10763 "try \"set remote exec-file\"?"));
10764 else
10765 error (_("Running \"%s\" on the remote target failed"),
10766 remote_exec_file);
10767 default:
10768 gdb_assert_not_reached ("bad switch");
10769 }
10770 }
10771
10772 /* Helper function to send set/unset environment packets. ACTION is
10773 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10774 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10775 sent. */
10776
10777 void
10778 remote_target::send_environment_packet (const char *action,
10779 const char *packet,
10780 const char *value)
10781 {
10782 remote_state *rs = get_remote_state ();
10783
10784 /* Convert the environment variable to an hex string, which
10785 is the best format to be transmitted over the wire. */
10786 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10787 strlen (value));
10788
10789 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10790 "%s:%s", packet, encoded_value.c_str ());
10791
10792 putpkt (rs->buf);
10793 getpkt (&rs->buf);
10794 if (strcmp (rs->buf.data (), "OK") != 0)
10795 warning (_("Unable to %s environment variable '%s' on remote."),
10796 action, value);
10797 }
10798
10799 /* Helper function to handle the QEnvironment* packets. */
10800
10801 void
10802 remote_target::extended_remote_environment_support ()
10803 {
10804 remote_state *rs = get_remote_state ();
10805
10806 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10807 {
10808 putpkt ("QEnvironmentReset");
10809 getpkt (&rs->buf);
10810 if (strcmp (rs->buf.data (), "OK") != 0)
10811 warning (_("Unable to reset environment on remote."));
10812 }
10813
10814 gdb_environ *e = &current_inferior ()->environment;
10815
10816 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10817 != PACKET_DISABLE)
10818 {
10819 for (const std::string &el : e->user_set_env ())
10820 send_environment_packet ("set", "QEnvironmentHexEncoded",
10821 el.c_str ());
10822 }
10823
10824
10825 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10826 for (const std::string &el : e->user_unset_env ())
10827 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10828 }
10829
10830 /* Helper function to set the current working directory for the
10831 inferior in the remote target. */
10832
10833 void
10834 remote_target::extended_remote_set_inferior_cwd ()
10835 {
10836 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10837 {
10838 const std::string &inferior_cwd = current_inferior ()->cwd ();
10839 remote_state *rs = get_remote_state ();
10840
10841 if (!inferior_cwd.empty ())
10842 {
10843 std::string hexpath
10844 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10845 inferior_cwd.size ());
10846
10847 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10848 "QSetWorkingDir:%s", hexpath.c_str ());
10849 }
10850 else
10851 {
10852 /* An empty inferior_cwd means that the user wants us to
10853 reset the remote server's inferior's cwd. */
10854 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10855 "QSetWorkingDir:");
10856 }
10857
10858 putpkt (rs->buf);
10859 getpkt (&rs->buf);
10860 packet_result result = m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir);
10861 if (result.status () == PACKET_ERROR)
10862 error (_("\
10863 Remote replied unexpectedly while setting the inferior's working\n\
10864 directory: %s"),
10865 result.err_msg ());
10866 if (result.status () == PACKET_UNKNOWN)
10867 error (_("Remote target failed to process setting the inferior's working directory"));
10868
10869 }
10870 }
10871
10872 /* In the extended protocol we want to be able to do things like
10873 "run" and have them basically work as expected. So we need
10874 a special create_inferior function. We support changing the
10875 executable file and the command line arguments, but not the
10876 environment. */
10877
10878 void
10879 extended_remote_target::create_inferior (const char *exec_file,
10880 const std::string &args,
10881 char **env, int from_tty)
10882 {
10883 int run_worked;
10884 char *stop_reply;
10885 struct remote_state *rs = get_remote_state ();
10886 const char *remote_exec_file = get_remote_exec_file ();
10887
10888 /* If running asynchronously, register the target file descriptor
10889 with the event loop. */
10890 if (target_can_async_p ())
10891 target_async (true);
10892
10893 /* Disable address space randomization if requested (and supported). */
10894 if (supports_disable_randomization ())
10895 extended_remote_disable_randomization (disable_randomization);
10896
10897 /* If startup-with-shell is on, we inform gdbserver to start the
10898 remote inferior using a shell. */
10899 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10900 {
10901 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10902 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10903 putpkt (rs->buf);
10904 getpkt (&rs->buf);
10905 if (strcmp (rs->buf.data (), "OK") != 0)
10906 error (_("\
10907 Remote replied unexpectedly while setting startup-with-shell: %s"),
10908 rs->buf.data ());
10909 }
10910
10911 extended_remote_environment_support ();
10912
10913 extended_remote_set_inferior_cwd ();
10914
10915 /* Now restart the remote server. */
10916 run_worked = extended_remote_run (args) != -1;
10917 if (!run_worked)
10918 {
10919 /* vRun was not supported. Fail if we need it to do what the
10920 user requested. */
10921 if (remote_exec_file[0])
10922 error (_("Remote target does not support \"set remote exec-file\""));
10923 if (!args.empty ())
10924 error (_("Remote target does not support \"set args\" or run ARGS"));
10925
10926 /* Fall back to "R". */
10927 extended_remote_restart ();
10928 }
10929
10930 /* vRun's success return is a stop reply. */
10931 stop_reply = run_worked ? rs->buf.data () : NULL;
10932 add_current_inferior_and_thread (stop_reply);
10933
10934 /* Get updated offsets, if the stub uses qOffsets. */
10935 get_offsets ();
10936 }
10937 \f
10938
10939 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10940 the list of conditions (in agent expression bytecode format), if any, the
10941 target needs to evaluate. The output is placed into the packet buffer
10942 started from BUF and ended at BUF_END. */
10943
10944 static int
10945 remote_add_target_side_condition (struct gdbarch *gdbarch,
10946 struct bp_target_info *bp_tgt, char *buf,
10947 char *buf_end)
10948 {
10949 if (bp_tgt->conditions.empty ())
10950 return 0;
10951
10952 buf += strlen (buf);
10953 xsnprintf (buf, buf_end - buf, "%s", ";");
10954 buf++;
10955
10956 /* Send conditions to the target. */
10957 for (agent_expr *aexpr : bp_tgt->conditions)
10958 {
10959 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10960 buf += strlen (buf);
10961 for (int i = 0; i < aexpr->buf.size (); ++i)
10962 buf = pack_hex_byte (buf, aexpr->buf[i]);
10963 *buf = '\0';
10964 }
10965 return 0;
10966 }
10967
10968 static void
10969 remote_add_target_side_commands (struct gdbarch *gdbarch,
10970 struct bp_target_info *bp_tgt, char *buf)
10971 {
10972 if (bp_tgt->tcommands.empty ())
10973 return;
10974
10975 buf += strlen (buf);
10976
10977 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10978 buf += strlen (buf);
10979
10980 /* Concatenate all the agent expressions that are commands into the
10981 cmds parameter. */
10982 for (agent_expr *aexpr : bp_tgt->tcommands)
10983 {
10984 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10985 buf += strlen (buf);
10986 for (int i = 0; i < aexpr->buf.size (); ++i)
10987 buf = pack_hex_byte (buf, aexpr->buf[i]);
10988 *buf = '\0';
10989 }
10990 }
10991
10992 /* Insert a breakpoint. On targets that have software breakpoint
10993 support, we ask the remote target to do the work; on targets
10994 which don't, we insert a traditional memory breakpoint. */
10995
10996 int
10997 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10998 struct bp_target_info *bp_tgt)
10999 {
11000 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
11001 If it succeeds, then set the support to PACKET_ENABLE. If it
11002 fails, and the user has explicitly requested the Z support then
11003 report an error, otherwise, mark it disabled and go on. */
11004
11005 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11006 {
11007 CORE_ADDR addr = bp_tgt->reqstd_address;
11008 struct remote_state *rs;
11009 char *p, *endbuf;
11010
11011 /* Make sure the remote is pointing at the right process, if
11012 necessary. */
11013 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11014 set_general_process ();
11015
11016 rs = get_remote_state ();
11017 p = rs->buf.data ();
11018 endbuf = p + get_remote_packet_size ();
11019
11020 *(p++) = 'Z';
11021 *(p++) = '0';
11022 *(p++) = ',';
11023 addr = (ULONGEST) remote_address_masked (addr);
11024 p += hexnumstr (p, addr);
11025 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11026
11027 if (supports_evaluation_of_breakpoint_conditions ())
11028 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11029
11030 if (can_run_breakpoint_commands ())
11031 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11032
11033 putpkt (rs->buf);
11034 getpkt (&rs->buf);
11035
11036 switch ((m_features.packet_ok (rs->buf, PACKET_Z0)).status ())
11037 {
11038 case PACKET_ERROR:
11039 return -1;
11040 case PACKET_OK:
11041 return 0;
11042 case PACKET_UNKNOWN:
11043 break;
11044 }
11045 }
11046
11047 /* If this breakpoint has target-side commands but this stub doesn't
11048 support Z0 packets, throw error. */
11049 if (!bp_tgt->tcommands.empty ())
11050 throw_error (NOT_SUPPORTED_ERROR, _("\
11051 Target doesn't support breakpoints that have target side commands."));
11052
11053 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
11054 }
11055
11056 int
11057 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
11058 struct bp_target_info *bp_tgt,
11059 enum remove_bp_reason reason)
11060 {
11061 CORE_ADDR addr = bp_tgt->placed_address;
11062 struct remote_state *rs = get_remote_state ();
11063
11064 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
11065 {
11066 char *p = rs->buf.data ();
11067 char *endbuf = p + get_remote_packet_size ();
11068
11069 /* Make sure the remote is pointing at the right process, if
11070 necessary. */
11071 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11072 set_general_process ();
11073
11074 *(p++) = 'z';
11075 *(p++) = '0';
11076 *(p++) = ',';
11077
11078 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
11079 p += hexnumstr (p, addr);
11080 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
11081
11082 putpkt (rs->buf);
11083 getpkt (&rs->buf);
11084
11085 return (rs->buf[0] == 'E');
11086 }
11087
11088 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
11089 }
11090
11091 static enum Z_packet_type
11092 watchpoint_to_Z_packet (int type)
11093 {
11094 switch (type)
11095 {
11096 case hw_write:
11097 return Z_PACKET_WRITE_WP;
11098 break;
11099 case hw_read:
11100 return Z_PACKET_READ_WP;
11101 break;
11102 case hw_access:
11103 return Z_PACKET_ACCESS_WP;
11104 break;
11105 default:
11106 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
11107 }
11108 }
11109
11110 int
11111 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
11112 enum target_hw_bp_type type, struct expression *cond)
11113 {
11114 struct remote_state *rs = get_remote_state ();
11115 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11116 char *p;
11117 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11118
11119 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11120 + to_underlying (packet))) == PACKET_DISABLE)
11121 return 1;
11122
11123 /* Make sure the remote is pointing at the right process, if
11124 necessary. */
11125 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11126 set_general_process ();
11127
11128 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11129 p = strchr (rs->buf.data (), '\0');
11130 addr = remote_address_masked (addr);
11131 p += hexnumstr (p, (ULONGEST) addr);
11132 xsnprintf (p, endbuf - p, ",%x", len);
11133
11134 putpkt (rs->buf);
11135 getpkt (&rs->buf);
11136
11137 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11138 + to_underlying (packet)))).status ())
11139 {
11140 case PACKET_ERROR:
11141 return -1;
11142 case PACKET_UNKNOWN:
11143 return 1;
11144 case PACKET_OK:
11145 return 0;
11146 }
11147 internal_error (_("remote_insert_watchpoint: reached end of function"));
11148 }
11149
11150 bool
11151 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11152 CORE_ADDR start, int length)
11153 {
11154 CORE_ADDR diff = remote_address_masked (addr - start);
11155
11156 return diff < length;
11157 }
11158
11159
11160 int
11161 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11162 enum target_hw_bp_type type, struct expression *cond)
11163 {
11164 struct remote_state *rs = get_remote_state ();
11165 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11166 char *p;
11167 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11168
11169 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11170 + to_underlying (packet))) == PACKET_DISABLE)
11171 return -1;
11172
11173 /* Make sure the remote is pointing at the right process, if
11174 necessary. */
11175 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11176 set_general_process ();
11177
11178 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11179 p = strchr (rs->buf.data (), '\0');
11180 addr = remote_address_masked (addr);
11181 p += hexnumstr (p, (ULONGEST) addr);
11182 xsnprintf (p, endbuf - p, ",%x", len);
11183 putpkt (rs->buf);
11184 getpkt (&rs->buf);
11185
11186 switch ((m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11187 + to_underlying (packet)))).status ())
11188 {
11189 case PACKET_ERROR:
11190 case PACKET_UNKNOWN:
11191 return -1;
11192 case PACKET_OK:
11193 return 0;
11194 }
11195 internal_error (_("remote_remove_watchpoint: reached end of function"));
11196 }
11197
11198
11199 static int remote_hw_watchpoint_limit = -1;
11200 static int remote_hw_watchpoint_length_limit = -1;
11201 static int remote_hw_breakpoint_limit = -1;
11202
11203 int
11204 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11205 {
11206 if (remote_hw_watchpoint_length_limit == 0)
11207 return 0;
11208 else if (remote_hw_watchpoint_length_limit < 0)
11209 return 1;
11210 else if (len <= remote_hw_watchpoint_length_limit)
11211 return 1;
11212 else
11213 return 0;
11214 }
11215
11216 int
11217 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11218 {
11219 if (type == bp_hardware_breakpoint)
11220 {
11221 if (remote_hw_breakpoint_limit == 0)
11222 return 0;
11223 else if (remote_hw_breakpoint_limit < 0)
11224 return 1;
11225 else if (cnt <= remote_hw_breakpoint_limit)
11226 return 1;
11227 }
11228 else
11229 {
11230 if (remote_hw_watchpoint_limit == 0)
11231 return 0;
11232 else if (remote_hw_watchpoint_limit < 0)
11233 return 1;
11234 else if (ot)
11235 return -1;
11236 else if (cnt <= remote_hw_watchpoint_limit)
11237 return 1;
11238 }
11239 return -1;
11240 }
11241
11242 /* The to_stopped_by_sw_breakpoint method of target remote. */
11243
11244 bool
11245 remote_target::stopped_by_sw_breakpoint ()
11246 {
11247 struct thread_info *thread = inferior_thread ();
11248
11249 return (thread->priv != NULL
11250 && (get_remote_thread_info (thread)->stop_reason
11251 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11252 }
11253
11254 /* The to_supports_stopped_by_sw_breakpoint method of target
11255 remote. */
11256
11257 bool
11258 remote_target::supports_stopped_by_sw_breakpoint ()
11259 {
11260 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11261 }
11262
11263 /* The to_stopped_by_hw_breakpoint method of target remote. */
11264
11265 bool
11266 remote_target::stopped_by_hw_breakpoint ()
11267 {
11268 struct thread_info *thread = inferior_thread ();
11269
11270 return (thread->priv != NULL
11271 && (get_remote_thread_info (thread)->stop_reason
11272 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11273 }
11274
11275 /* The to_supports_stopped_by_hw_breakpoint method of target
11276 remote. */
11277
11278 bool
11279 remote_target::supports_stopped_by_hw_breakpoint ()
11280 {
11281 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11282 }
11283
11284 bool
11285 remote_target::stopped_by_watchpoint ()
11286 {
11287 struct thread_info *thread = inferior_thread ();
11288
11289 return (thread->priv != NULL
11290 && (get_remote_thread_info (thread)->stop_reason
11291 == TARGET_STOPPED_BY_WATCHPOINT));
11292 }
11293
11294 bool
11295 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11296 {
11297 struct thread_info *thread = inferior_thread ();
11298
11299 if (thread->priv != NULL
11300 && (get_remote_thread_info (thread)->stop_reason
11301 == TARGET_STOPPED_BY_WATCHPOINT))
11302 {
11303 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11304 return true;
11305 }
11306
11307 return false;
11308 }
11309
11310
11311 int
11312 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11313 struct bp_target_info *bp_tgt)
11314 {
11315 CORE_ADDR addr = bp_tgt->reqstd_address;
11316 struct remote_state *rs;
11317 char *p, *endbuf;
11318
11319 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11320 return -1;
11321
11322 /* Make sure the remote is pointing at the right process, if
11323 necessary. */
11324 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11325 set_general_process ();
11326
11327 rs = get_remote_state ();
11328 p = rs->buf.data ();
11329 endbuf = p + get_remote_packet_size ();
11330
11331 *(p++) = 'Z';
11332 *(p++) = '1';
11333 *(p++) = ',';
11334
11335 addr = remote_address_masked (addr);
11336 p += hexnumstr (p, (ULONGEST) addr);
11337 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11338
11339 if (supports_evaluation_of_breakpoint_conditions ())
11340 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11341
11342 if (can_run_breakpoint_commands ())
11343 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11344
11345 putpkt (rs->buf);
11346 getpkt (&rs->buf);
11347
11348 packet_result result = m_features.packet_ok (rs->buf, PACKET_Z1);
11349 switch (result.status ())
11350 {
11351 case PACKET_ERROR:
11352 error (_("Remote failure reply: %s"), result.err_msg ());
11353 case PACKET_UNKNOWN:
11354 return -1;
11355 case PACKET_OK:
11356 return 0;
11357 }
11358 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11359 }
11360
11361
11362 int
11363 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11364 struct bp_target_info *bp_tgt)
11365 {
11366 CORE_ADDR addr;
11367 struct remote_state *rs = get_remote_state ();
11368 char *p = rs->buf.data ();
11369 char *endbuf = p + get_remote_packet_size ();
11370
11371 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11372 return -1;
11373
11374 /* Make sure the remote is pointing at the right process, if
11375 necessary. */
11376 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11377 set_general_process ();
11378
11379 *(p++) = 'z';
11380 *(p++) = '1';
11381 *(p++) = ',';
11382
11383 addr = remote_address_masked (bp_tgt->placed_address);
11384 p += hexnumstr (p, (ULONGEST) addr);
11385 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11386
11387 putpkt (rs->buf);
11388 getpkt (&rs->buf);
11389
11390 switch ((m_features.packet_ok (rs->buf, PACKET_Z1)).status ())
11391 {
11392 case PACKET_ERROR:
11393 case PACKET_UNKNOWN:
11394 return -1;
11395 case PACKET_OK:
11396 return 0;
11397 }
11398 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11399 }
11400
11401 /* Verify memory using the "qCRC:" request. */
11402
11403 int
11404 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11405 {
11406 struct remote_state *rs = get_remote_state ();
11407 unsigned long host_crc, target_crc;
11408 char *tmp;
11409
11410 /* It doesn't make sense to use qCRC if the remote target is
11411 connected but not running. */
11412 if (target_has_execution ()
11413 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11414 {
11415 enum packet_status status;
11416
11417 /* Make sure the remote is pointing at the right process. */
11418 set_general_process ();
11419
11420 /* FIXME: assumes lma can fit into long. */
11421 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11422 (long) lma, (long) size);
11423 putpkt (rs->buf);
11424
11425 /* Be clever; compute the host_crc before waiting for target
11426 reply. */
11427 host_crc = xcrc32 (data, size, 0xffffffff);
11428
11429 getpkt (&rs->buf);
11430
11431 status = (m_features.packet_ok (rs->buf, PACKET_qCRC)).status ();
11432 if (status == PACKET_ERROR)
11433 return -1;
11434 else if (status == PACKET_OK)
11435 {
11436 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11437 target_crc = target_crc * 16 + fromhex (*tmp);
11438
11439 return (host_crc == target_crc);
11440 }
11441 }
11442
11443 return simple_verify_memory (this, data, lma, size);
11444 }
11445
11446 /* compare-sections command
11447
11448 With no arguments, compares each loadable section in the exec bfd
11449 with the same memory range on the target, and reports mismatches.
11450 Useful for verifying the image on the target against the exec file. */
11451
11452 static void
11453 compare_sections_command (const char *args, int from_tty)
11454 {
11455 asection *s;
11456 const char *sectname;
11457 bfd_size_type size;
11458 bfd_vma lma;
11459 int matched = 0;
11460 int mismatched = 0;
11461 int res;
11462 int read_only = 0;
11463
11464 if (!current_program_space->exec_bfd ())
11465 error (_("command cannot be used without an exec file"));
11466
11467 if (args != NULL && strcmp (args, "-r") == 0)
11468 {
11469 read_only = 1;
11470 args = NULL;
11471 }
11472
11473 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11474 {
11475 if (!(s->flags & SEC_LOAD))
11476 continue; /* Skip non-loadable section. */
11477
11478 if (read_only && (s->flags & SEC_READONLY) == 0)
11479 continue; /* Skip writeable sections */
11480
11481 size = bfd_section_size (s);
11482 if (size == 0)
11483 continue; /* Skip zero-length section. */
11484
11485 sectname = bfd_section_name (s);
11486 if (args && strcmp (args, sectname) != 0)
11487 continue; /* Not the section selected by user. */
11488
11489 matched = 1; /* Do this section. */
11490 lma = s->lma;
11491
11492 gdb::byte_vector sectdata (size);
11493 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11494 sectdata.data (), 0, size);
11495
11496 res = target_verify_memory (sectdata.data (), lma, size);
11497
11498 if (res == -1)
11499 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11500 paddress (current_inferior ()->arch (), lma),
11501 paddress (current_inferior ()->arch (), lma + size));
11502
11503 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11504 paddress (current_inferior ()->arch (), lma),
11505 paddress (current_inferior ()->arch (), lma + size));
11506 if (res)
11507 gdb_printf ("matched.\n");
11508 else
11509 {
11510 gdb_printf ("MIS-MATCHED!\n");
11511 mismatched++;
11512 }
11513 }
11514 if (mismatched > 0)
11515 warning (_("One or more sections of the target image does "
11516 "not match the loaded file"));
11517 if (args && !matched)
11518 gdb_printf (_("No loaded section named '%s'.\n"), args);
11519 }
11520
11521 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11522 into remote target. The number of bytes written to the remote
11523 target is returned, or -1 for error. */
11524
11525 target_xfer_status
11526 remote_target::remote_write_qxfer (const char *object_name,
11527 const char *annex, const gdb_byte *writebuf,
11528 ULONGEST offset, LONGEST len,
11529 ULONGEST *xfered_len,
11530 const unsigned int which_packet)
11531 {
11532 int i, buf_len;
11533 ULONGEST n;
11534 struct remote_state *rs = get_remote_state ();
11535 int max_size = get_memory_write_packet_size ();
11536
11537 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11538 return TARGET_XFER_E_IO;
11539
11540 /* Insert header. */
11541 i = snprintf (rs->buf.data (), max_size,
11542 "qXfer:%s:write:%s:%s:",
11543 object_name, annex ? annex : "",
11544 phex_nz (offset, sizeof offset));
11545 max_size -= (i + 1);
11546
11547 /* Escape as much data as fits into rs->buf. */
11548 buf_len = remote_escape_output
11549 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11550
11551 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11552 || getpkt (&rs->buf) < 0
11553 || (m_features.packet_ok (rs->buf, which_packet)).status () != PACKET_OK)
11554 return TARGET_XFER_E_IO;
11555
11556 unpack_varlen_hex (rs->buf.data (), &n);
11557
11558 *xfered_len = n;
11559 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11560 }
11561
11562 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11563 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11564 number of bytes read is returned, or 0 for EOF, or -1 for error.
11565 The number of bytes read may be less than LEN without indicating an
11566 EOF. PACKET is checked and updated to indicate whether the remote
11567 target supports this object. */
11568
11569 target_xfer_status
11570 remote_target::remote_read_qxfer (const char *object_name,
11571 const char *annex,
11572 gdb_byte *readbuf, ULONGEST offset,
11573 LONGEST len,
11574 ULONGEST *xfered_len,
11575 const unsigned int which_packet)
11576 {
11577 struct remote_state *rs = get_remote_state ();
11578 LONGEST i, n, packet_len;
11579
11580 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11581 return TARGET_XFER_E_IO;
11582
11583 /* Check whether we've cached an end-of-object packet that matches
11584 this request. */
11585 if (rs->finished_object)
11586 {
11587 if (strcmp (object_name, rs->finished_object) == 0
11588 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11589 && offset == rs->finished_offset)
11590 return TARGET_XFER_EOF;
11591
11592
11593 /* Otherwise, we're now reading something different. Discard
11594 the cache. */
11595 xfree (rs->finished_object);
11596 xfree (rs->finished_annex);
11597 rs->finished_object = NULL;
11598 rs->finished_annex = NULL;
11599 }
11600
11601 /* Request only enough to fit in a single packet. The actual data
11602 may not, since we don't know how much of it will need to be escaped;
11603 the target is free to respond with slightly less data. We subtract
11604 five to account for the response type and the protocol frame. */
11605 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11606 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11607 "qXfer:%s:read:%s:%s,%s",
11608 object_name, annex ? annex : "",
11609 phex_nz (offset, sizeof offset),
11610 phex_nz (n, sizeof n));
11611 i = putpkt (rs->buf);
11612 if (i < 0)
11613 return TARGET_XFER_E_IO;
11614
11615 rs->buf[0] = '\0';
11616 packet_len = getpkt (&rs->buf);
11617 if (packet_len < 0
11618 || m_features.packet_ok (rs->buf, which_packet).status () != PACKET_OK)
11619 return TARGET_XFER_E_IO;
11620
11621 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11622 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11623
11624 /* 'm' means there is (or at least might be) more data after this
11625 batch. That does not make sense unless there's at least one byte
11626 of data in this reply. */
11627 if (rs->buf[0] == 'm' && packet_len == 1)
11628 error (_("Remote qXfer reply contained no data."));
11629
11630 /* Got some data. */
11631 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11632 packet_len - 1, readbuf, n);
11633
11634 /* 'l' is an EOF marker, possibly including a final block of data,
11635 or possibly empty. If we have the final block of a non-empty
11636 object, record this fact to bypass a subsequent partial read. */
11637 if (rs->buf[0] == 'l' && offset + i > 0)
11638 {
11639 rs->finished_object = xstrdup (object_name);
11640 rs->finished_annex = xstrdup (annex ? annex : "");
11641 rs->finished_offset = offset + i;
11642 }
11643
11644 if (i == 0)
11645 return TARGET_XFER_EOF;
11646 else
11647 {
11648 *xfered_len = i;
11649 return TARGET_XFER_OK;
11650 }
11651 }
11652
11653 enum target_xfer_status
11654 remote_target::xfer_partial (enum target_object object,
11655 const char *annex, gdb_byte *readbuf,
11656 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11657 ULONGEST *xfered_len)
11658 {
11659 struct remote_state *rs;
11660 int i;
11661 char *p2;
11662 char query_type;
11663 int unit_size
11664 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11665
11666 set_remote_traceframe ();
11667 set_general_thread (inferior_ptid);
11668
11669 rs = get_remote_state ();
11670
11671 /* Handle memory using the standard memory routines. */
11672 if (object == TARGET_OBJECT_MEMORY)
11673 {
11674 /* If the remote target is connected but not running, we should
11675 pass this request down to a lower stratum (e.g. the executable
11676 file). */
11677 if (!target_has_execution ())
11678 return TARGET_XFER_EOF;
11679
11680 if (writebuf != NULL)
11681 return remote_write_bytes (offset, writebuf, len, unit_size,
11682 xfered_len);
11683 else
11684 return remote_read_bytes (offset, readbuf, len, unit_size,
11685 xfered_len);
11686 }
11687
11688 /* Handle extra signal info using qxfer packets. */
11689 if (object == TARGET_OBJECT_SIGNAL_INFO)
11690 {
11691 if (readbuf)
11692 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11693 xfered_len, PACKET_qXfer_siginfo_read);
11694 else
11695 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11696 xfered_len, PACKET_qXfer_siginfo_write);
11697 }
11698
11699 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11700 {
11701 if (readbuf)
11702 return remote_read_qxfer ("statictrace", annex,
11703 readbuf, offset, len, xfered_len,
11704 PACKET_qXfer_statictrace_read);
11705 else
11706 return TARGET_XFER_E_IO;
11707 }
11708
11709 /* Only handle flash writes. */
11710 if (writebuf != NULL)
11711 {
11712 switch (object)
11713 {
11714 case TARGET_OBJECT_FLASH:
11715 return remote_flash_write (offset, len, xfered_len,
11716 writebuf);
11717
11718 default:
11719 return TARGET_XFER_E_IO;
11720 }
11721 }
11722
11723 /* Map pre-existing objects onto letters. DO NOT do this for new
11724 objects!!! Instead specify new query packets. */
11725 switch (object)
11726 {
11727 case TARGET_OBJECT_AVR:
11728 query_type = 'R';
11729 break;
11730
11731 case TARGET_OBJECT_AUXV:
11732 gdb_assert (annex == NULL);
11733 return remote_read_qxfer
11734 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11735
11736 case TARGET_OBJECT_AVAILABLE_FEATURES:
11737 return remote_read_qxfer
11738 ("features", annex, readbuf, offset, len, xfered_len,
11739 PACKET_qXfer_features);
11740
11741 case TARGET_OBJECT_LIBRARIES:
11742 return remote_read_qxfer
11743 ("libraries", annex, readbuf, offset, len, xfered_len,
11744 PACKET_qXfer_libraries);
11745
11746 case TARGET_OBJECT_LIBRARIES_SVR4:
11747 return remote_read_qxfer
11748 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11749 PACKET_qXfer_libraries_svr4);
11750
11751 case TARGET_OBJECT_MEMORY_MAP:
11752 gdb_assert (annex == NULL);
11753 return remote_read_qxfer
11754 ("memory-map", annex, readbuf, offset, len, xfered_len,
11755 PACKET_qXfer_memory_map);
11756
11757 case TARGET_OBJECT_OSDATA:
11758 /* Should only get here if we're connected. */
11759 gdb_assert (rs->remote_desc);
11760 return remote_read_qxfer
11761 ("osdata", annex, readbuf, offset, len, xfered_len,
11762 PACKET_qXfer_osdata);
11763
11764 case TARGET_OBJECT_THREADS:
11765 gdb_assert (annex == NULL);
11766 return remote_read_qxfer
11767 ("threads", annex, readbuf, offset, len, xfered_len,
11768 PACKET_qXfer_threads);
11769
11770 case TARGET_OBJECT_TRACEFRAME_INFO:
11771 gdb_assert (annex == NULL);
11772 return remote_read_qxfer
11773 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11774 PACKET_qXfer_traceframe_info);
11775
11776 case TARGET_OBJECT_FDPIC:
11777 return remote_read_qxfer
11778 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11779
11780 case TARGET_OBJECT_OPENVMS_UIB:
11781 return remote_read_qxfer
11782 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11783
11784 case TARGET_OBJECT_BTRACE:
11785 return remote_read_qxfer
11786 ("btrace", annex, readbuf, offset, len, xfered_len,
11787 PACKET_qXfer_btrace);
11788
11789 case TARGET_OBJECT_BTRACE_CONF:
11790 return remote_read_qxfer
11791 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11792 PACKET_qXfer_btrace_conf);
11793
11794 case TARGET_OBJECT_EXEC_FILE:
11795 return remote_read_qxfer
11796 ("exec-file", annex, readbuf, offset, len, xfered_len,
11797 PACKET_qXfer_exec_file);
11798
11799 default:
11800 return TARGET_XFER_E_IO;
11801 }
11802
11803 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11804 large enough let the caller deal with it. */
11805 if (len < get_remote_packet_size ())
11806 return TARGET_XFER_E_IO;
11807 len = get_remote_packet_size ();
11808
11809 /* Except for querying the minimum buffer size, target must be open. */
11810 if (!rs->remote_desc)
11811 error (_("remote query is only available after target open"));
11812
11813 gdb_assert (annex != NULL);
11814 gdb_assert (readbuf != NULL);
11815
11816 p2 = rs->buf.data ();
11817 *p2++ = 'q';
11818 *p2++ = query_type;
11819
11820 /* We used one buffer char for the remote protocol q command and
11821 another for the query type. As the remote protocol encapsulation
11822 uses 4 chars plus one extra in case we are debugging
11823 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11824 string. */
11825 i = 0;
11826 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11827 {
11828 /* Bad caller may have sent forbidden characters. */
11829 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11830 *p2++ = annex[i];
11831 i++;
11832 }
11833 *p2 = '\0';
11834 gdb_assert (annex[i] == '\0');
11835
11836 i = putpkt (rs->buf);
11837 if (i < 0)
11838 return TARGET_XFER_E_IO;
11839
11840 getpkt (&rs->buf);
11841 strcpy ((char *) readbuf, rs->buf.data ());
11842
11843 *xfered_len = strlen ((char *) readbuf);
11844 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11845 }
11846
11847 /* Implementation of to_get_memory_xfer_limit. */
11848
11849 ULONGEST
11850 remote_target::get_memory_xfer_limit ()
11851 {
11852 return get_memory_write_packet_size ();
11853 }
11854
11855 int
11856 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11857 const gdb_byte *pattern, ULONGEST pattern_len,
11858 CORE_ADDR *found_addrp)
11859 {
11860 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11861 struct remote_state *rs = get_remote_state ();
11862 int max_size = get_memory_write_packet_size ();
11863
11864 /* Number of packet bytes used to encode the pattern;
11865 this could be more than PATTERN_LEN due to escape characters. */
11866 int escaped_pattern_len;
11867 /* Amount of pattern that was encodable in the packet. */
11868 int used_pattern_len;
11869 int i;
11870 int found;
11871 ULONGEST found_addr;
11872
11873 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11874 {
11875 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11876 == len);
11877 };
11878
11879 /* Don't go to the target if we don't have to. This is done before
11880 checking packet_support to avoid the possibility that a success for this
11881 edge case means the facility works in general. */
11882 if (pattern_len > search_space_len)
11883 return 0;
11884 if (pattern_len == 0)
11885 {
11886 *found_addrp = start_addr;
11887 return 1;
11888 }
11889
11890 /* If we already know the packet isn't supported, fall back to the simple
11891 way of searching memory. */
11892
11893 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11894 {
11895 /* Target doesn't provided special support, fall back and use the
11896 standard support (copy memory and do the search here). */
11897 return simple_search_memory (read_memory, start_addr, search_space_len,
11898 pattern, pattern_len, found_addrp);
11899 }
11900
11901 /* Make sure the remote is pointing at the right process. */
11902 set_general_process ();
11903
11904 /* Insert header. */
11905 i = snprintf (rs->buf.data (), max_size,
11906 "qSearch:memory:%s;%s;",
11907 phex_nz (start_addr, addr_size),
11908 phex_nz (search_space_len, sizeof (search_space_len)));
11909 max_size -= (i + 1);
11910
11911 /* Escape as much data as fits into rs->buf. */
11912 escaped_pattern_len =
11913 remote_escape_output (pattern, pattern_len, 1,
11914 (gdb_byte *) rs->buf.data () + i,
11915 &used_pattern_len, max_size);
11916
11917 /* Bail if the pattern is too large. */
11918 if (used_pattern_len != pattern_len)
11919 error (_("Pattern is too large to transmit to remote target."));
11920
11921 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11922 || getpkt (&rs->buf) < 0
11923 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory).status ()
11924 != PACKET_OK)
11925 {
11926 /* The request may not have worked because the command is not
11927 supported. If so, fall back to the simple way. */
11928 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11929 {
11930 return simple_search_memory (read_memory, start_addr, search_space_len,
11931 pattern, pattern_len, found_addrp);
11932 }
11933 return -1;
11934 }
11935
11936 if (rs->buf[0] == '0')
11937 found = 0;
11938 else if (rs->buf[0] == '1')
11939 {
11940 found = 1;
11941 if (rs->buf[1] != ',')
11942 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11943 unpack_varlen_hex (&rs->buf[2], &found_addr);
11944 *found_addrp = found_addr;
11945 }
11946 else
11947 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11948
11949 return found;
11950 }
11951
11952 void
11953 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11954 {
11955 struct remote_state *rs = get_remote_state ();
11956 char *p = rs->buf.data ();
11957
11958 if (!rs->remote_desc)
11959 error (_("remote rcmd is only available after target open"));
11960
11961 /* Send a NULL command across as an empty command. */
11962 if (command == NULL)
11963 command = "";
11964
11965 /* The query prefix. */
11966 strcpy (rs->buf.data (), "qRcmd,");
11967 p = strchr (rs->buf.data (), '\0');
11968
11969 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11970 > get_remote_packet_size ())
11971 error (_("\"monitor\" command ``%s'' is too long."), command);
11972
11973 /* Encode the actual command. */
11974 bin2hex ((const gdb_byte *) command, p, strlen (command));
11975
11976 if (putpkt (rs->buf) < 0)
11977 error (_("Communication problem with target."));
11978
11979 /* get/display the response */
11980 while (1)
11981 {
11982 char *buf;
11983
11984 /* XXX - see also remote_get_noisy_reply(). */
11985 QUIT; /* Allow user to bail out with ^C. */
11986 rs->buf[0] = '\0';
11987 if (getpkt (&rs->buf) == -1)
11988 {
11989 /* Timeout. Continue to (try to) read responses.
11990 This is better than stopping with an error, assuming the stub
11991 is still executing the (long) monitor command.
11992 If needed, the user can interrupt gdb using C-c, obtaining
11993 an effect similar to stop on timeout. */
11994 continue;
11995 }
11996 buf = rs->buf.data ();
11997 if (buf[0] == 'O' && buf[1] != 'K')
11998 {
11999 /* 'O' message from stub. */
12000 remote_console_output (buf + 1, outbuf);
12001 continue;
12002 }
12003 packet_result result = packet_check_result (buf, false);
12004 switch (result.status ())
12005 {
12006 case PACKET_UNKNOWN:
12007 error (_("Target does not support this command."));
12008 case PACKET_ERROR:
12009 error (_("Protocol error with Rcmd: %s."), result.err_msg ());
12010 case PACKET_OK:
12011 break;
12012 }
12013
12014 if (strcmp (buf, "OK") != 0)
12015 {
12016 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
12017 {
12018 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
12019 gdb_putc (c, outbuf);
12020 }
12021 }
12022 break;
12023 }
12024 }
12025
12026 std::vector<mem_region>
12027 remote_target::memory_map ()
12028 {
12029 std::vector<mem_region> result;
12030 std::optional<gdb::char_vector> text
12031 = target_read_stralloc (current_inferior ()->top_target (),
12032 TARGET_OBJECT_MEMORY_MAP, NULL);
12033
12034 if (text)
12035 result = parse_memory_map (text->data ());
12036
12037 return result;
12038 }
12039
12040 /* Set of callbacks used to implement the 'maint packet' command. */
12041
12042 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
12043 {
12044 /* Called before the packet is sent. BUF is the packet content before
12045 the protocol specific prefix, suffix, and escaping is added. */
12046
12047 void sending (gdb::array_view<const char> &buf) override
12048 {
12049 gdb_puts ("sending: ");
12050 print_packet (buf);
12051 gdb_puts ("\n");
12052 }
12053
12054 /* Called with BUF, the reply from the remote target. */
12055
12056 void received (gdb::array_view<const char> &buf) override
12057 {
12058 gdb_puts ("received: \"");
12059 print_packet (buf);
12060 gdb_puts ("\"\n");
12061 }
12062
12063 private:
12064
12065 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
12066 '\x??' with '??' replaced by the hexadecimal value of the byte. */
12067
12068 static void
12069 print_packet (gdb::array_view<const char> &buf)
12070 {
12071 string_file stb;
12072
12073 for (int i = 0; i < buf.size (); ++i)
12074 {
12075 gdb_byte c = buf[i];
12076 if (isprint (c))
12077 gdb_putc (c, &stb);
12078 else
12079 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
12080 }
12081
12082 gdb_puts (stb.string ().c_str ());
12083 }
12084 };
12085
12086 /* See remote.h. */
12087
12088 void
12089 send_remote_packet (gdb::array_view<const char> &buf,
12090 send_remote_packet_callbacks *callbacks)
12091 {
12092 if (buf.size () == 0 || buf.data ()[0] == '\0')
12093 error (_("a remote packet must not be empty"));
12094
12095 remote_target *remote = get_current_remote_target ();
12096 if (remote == nullptr)
12097 error (_("packets can only be sent to a remote target"));
12098
12099 callbacks->sending (buf);
12100
12101 remote->putpkt_binary (buf.data (), buf.size ());
12102 remote_state *rs = remote->get_remote_state ();
12103 int bytes = remote->getpkt (&rs->buf);
12104
12105 if (bytes < 0)
12106 error (_("error while fetching packet from remote target"));
12107
12108 gdb::array_view<const char> view (&rs->buf[0], bytes);
12109 callbacks->received (view);
12110 }
12111
12112 /* Entry point for the 'maint packet' command. */
12113
12114 static void
12115 cli_packet_command (const char *args, int from_tty)
12116 {
12117 cli_packet_command_callbacks cb;
12118 gdb::array_view<const char> view
12119 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
12120 send_remote_packet (view, &cb);
12121 }
12122
12123 #if 0
12124 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12125
12126 static void display_thread_info (struct gdb_ext_thread_info *info);
12127
12128 static void threadset_test_cmd (char *cmd, int tty);
12129
12130 static void threadalive_test (char *cmd, int tty);
12131
12132 static void threadlist_test_cmd (char *cmd, int tty);
12133
12134 int get_and_display_threadinfo (threadref *ref);
12135
12136 static void threadinfo_test_cmd (char *cmd, int tty);
12137
12138 static int thread_display_step (threadref *ref, void *context);
12139
12140 static void threadlist_update_test_cmd (char *cmd, int tty);
12141
12142 static void init_remote_threadtests (void);
12143
12144 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12145
12146 static void
12147 threadset_test_cmd (const char *cmd, int tty)
12148 {
12149 int sample_thread = SAMPLE_THREAD;
12150
12151 gdb_printf (_("Remote threadset test\n"));
12152 set_general_thread (sample_thread);
12153 }
12154
12155
12156 static void
12157 threadalive_test (const char *cmd, int tty)
12158 {
12159 int sample_thread = SAMPLE_THREAD;
12160 int pid = inferior_ptid.pid ();
12161 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12162
12163 if (remote_thread_alive (ptid))
12164 gdb_printf ("PASS: Thread alive test\n");
12165 else
12166 gdb_printf ("FAIL: Thread alive test\n");
12167 }
12168
12169 void output_threadid (char *title, threadref *ref);
12170
12171 void
12172 output_threadid (char *title, threadref *ref)
12173 {
12174 char hexid[20];
12175
12176 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12177 hexid[16] = 0;
12178 gdb_printf ("%s %s\n", title, (&hexid[0]));
12179 }
12180
12181 static void
12182 threadlist_test_cmd (const char *cmd, int tty)
12183 {
12184 int startflag = 1;
12185 threadref nextthread;
12186 int done, result_count;
12187 threadref threadlist[3];
12188
12189 gdb_printf ("Remote Threadlist test\n");
12190 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12191 &result_count, &threadlist[0]))
12192 gdb_printf ("FAIL: threadlist test\n");
12193 else
12194 {
12195 threadref *scan = threadlist;
12196 threadref *limit = scan + result_count;
12197
12198 while (scan < limit)
12199 output_threadid (" thread ", scan++);
12200 }
12201 }
12202
12203 void
12204 display_thread_info (struct gdb_ext_thread_info *info)
12205 {
12206 output_threadid ("Threadid: ", &info->threadid);
12207 gdb_printf ("Name: %s\n ", info->shortname);
12208 gdb_printf ("State: %s\n", info->display);
12209 gdb_printf ("other: %s\n\n", info->more_display);
12210 }
12211
12212 int
12213 get_and_display_threadinfo (threadref *ref)
12214 {
12215 int result;
12216 int set;
12217 struct gdb_ext_thread_info threadinfo;
12218
12219 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12220 | TAG_MOREDISPLAY | TAG_DISPLAY;
12221 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12222 display_thread_info (&threadinfo);
12223 return result;
12224 }
12225
12226 static void
12227 threadinfo_test_cmd (const char *cmd, int tty)
12228 {
12229 int athread = SAMPLE_THREAD;
12230 threadref thread;
12231 int set;
12232
12233 int_to_threadref (&thread, athread);
12234 gdb_printf ("Remote Threadinfo test\n");
12235 if (!get_and_display_threadinfo (&thread))
12236 gdb_printf ("FAIL cannot get thread info\n");
12237 }
12238
12239 static int
12240 thread_display_step (threadref *ref, void *context)
12241 {
12242 /* output_threadid(" threadstep ",ref); *//* simple test */
12243 return get_and_display_threadinfo (ref);
12244 }
12245
12246 static void
12247 threadlist_update_test_cmd (const char *cmd, int tty)
12248 {
12249 gdb_printf ("Remote Threadlist update test\n");
12250 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12251 }
12252
12253 static void
12254 init_remote_threadtests (void)
12255 {
12256 add_com ("tlist", class_obscure, threadlist_test_cmd,
12257 _("Fetch and print the remote list of "
12258 "thread identifiers, one pkt only."));
12259 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12260 _("Fetch and display info about one thread."));
12261 add_com ("tset", class_obscure, threadset_test_cmd,
12262 _("Test setting to a different thread."));
12263 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12264 _("Iterate through updating all remote thread info."));
12265 add_com ("talive", class_obscure, threadalive_test,
12266 _("Remote thread alive test."));
12267 }
12268
12269 #endif /* 0 */
12270
12271 /* Convert a thread ID to a string. */
12272
12273 std::string
12274 remote_target::pid_to_str (ptid_t ptid)
12275 {
12276 if (ptid == null_ptid)
12277 return normal_pid_to_str (ptid);
12278 else if (ptid.is_pid ())
12279 {
12280 /* Printing an inferior target id. */
12281
12282 /* When multi-process extensions are off, there's no way in the
12283 remote protocol to know the remote process id, if there's any
12284 at all. There's one exception --- when we're connected with
12285 target extended-remote, and we manually attached to a process
12286 with "attach PID". We don't record anywhere a flag that
12287 allows us to distinguish that case from the case of
12288 connecting with extended-remote and the stub already being
12289 attached to a process, and reporting yes to qAttached, hence
12290 no smart special casing here. */
12291 if (!m_features.remote_multi_process_p ())
12292 return "Remote target";
12293
12294 return normal_pid_to_str (ptid);
12295 }
12296 else
12297 {
12298 if (magic_null_ptid == ptid)
12299 return "Thread <main>";
12300 else if (m_features.remote_multi_process_p ())
12301 if (ptid.lwp () == 0)
12302 return normal_pid_to_str (ptid);
12303 else
12304 return string_printf ("Thread %d.%ld",
12305 ptid.pid (), ptid.lwp ());
12306 else
12307 return string_printf ("Thread %ld", ptid.lwp ());
12308 }
12309 }
12310
12311 /* Get the address of the thread local variable in OBJFILE which is
12312 stored at OFFSET within the thread local storage for thread PTID. */
12313
12314 CORE_ADDR
12315 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12316 CORE_ADDR offset)
12317 {
12318 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12319 {
12320 struct remote_state *rs = get_remote_state ();
12321 char *p = rs->buf.data ();
12322 char *endp = p + get_remote_packet_size ();
12323
12324 strcpy (p, "qGetTLSAddr:");
12325 p += strlen (p);
12326 p = write_ptid (p, endp, ptid);
12327 *p++ = ',';
12328 p += hexnumstr (p, offset);
12329 *p++ = ',';
12330 p += hexnumstr (p, lm);
12331 *p++ = '\0';
12332
12333 putpkt (rs->buf);
12334 getpkt (&rs->buf);
12335 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12336 if (result.status () == PACKET_OK)
12337 {
12338 ULONGEST addr;
12339
12340 unpack_varlen_hex (rs->buf.data (), &addr);
12341 return addr;
12342 }
12343 else if (result.status () == PACKET_UNKNOWN)
12344 throw_error (TLS_GENERIC_ERROR,
12345 _("Remote target doesn't support qGetTLSAddr packet"));
12346 else
12347 throw_error (TLS_GENERIC_ERROR,
12348 _("Remote target failed to process qGetTLSAddr request"));
12349 }
12350 else
12351 throw_error (TLS_GENERIC_ERROR,
12352 _("TLS not supported or disabled on this target"));
12353 /* Not reached. */
12354 return 0;
12355 }
12356
12357 /* Provide thread local base, i.e. Thread Information Block address.
12358 Returns 1 if ptid is found and thread_local_base is non zero. */
12359
12360 bool
12361 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12362 {
12363 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12364 {
12365 struct remote_state *rs = get_remote_state ();
12366 char *p = rs->buf.data ();
12367 char *endp = p + get_remote_packet_size ();
12368
12369 strcpy (p, "qGetTIBAddr:");
12370 p += strlen (p);
12371 p = write_ptid (p, endp, ptid);
12372 *p++ = '\0';
12373
12374 putpkt (rs->buf);
12375 getpkt (&rs->buf);
12376 packet_result result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12377 if (result.status () == PACKET_OK)
12378 {
12379 ULONGEST val;
12380 unpack_varlen_hex (rs->buf.data (), &val);
12381 if (addr)
12382 *addr = (CORE_ADDR) val;
12383 return true;
12384 }
12385 else if (result.status () == PACKET_UNKNOWN)
12386 error (_("Remote target doesn't support qGetTIBAddr packet"));
12387 else
12388 error (_("Remote target failed to process qGetTIBAddr request, %s"),
12389 result.err_msg ());
12390 }
12391 else
12392 error (_("qGetTIBAddr not supported or disabled on this target"));
12393 /* Not reached. */
12394 return false;
12395 }
12396
12397 /* Support for inferring a target description based on the current
12398 architecture and the size of a 'g' packet. While the 'g' packet
12399 can have any size (since optional registers can be left off the
12400 end), some sizes are easily recognizable given knowledge of the
12401 approximate architecture. */
12402
12403 struct remote_g_packet_guess
12404 {
12405 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12406 : bytes (bytes_),
12407 tdesc (tdesc_)
12408 {
12409 }
12410
12411 int bytes;
12412 const struct target_desc *tdesc;
12413 };
12414
12415 struct remote_g_packet_data
12416 {
12417 std::vector<remote_g_packet_guess> guesses;
12418 };
12419
12420 static const registry<gdbarch>::key<struct remote_g_packet_data>
12421 remote_g_packet_data_handle;
12422
12423 static struct remote_g_packet_data *
12424 get_g_packet_data (struct gdbarch *gdbarch)
12425 {
12426 struct remote_g_packet_data *data
12427 = remote_g_packet_data_handle.get (gdbarch);
12428 if (data == nullptr)
12429 data = remote_g_packet_data_handle.emplace (gdbarch);
12430 return data;
12431 }
12432
12433 void
12434 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12435 const struct target_desc *tdesc)
12436 {
12437 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12438
12439 gdb_assert (tdesc != NULL);
12440
12441 for (const remote_g_packet_guess &guess : data->guesses)
12442 if (guess.bytes == bytes)
12443 internal_error (_("Duplicate g packet description added for size %d"),
12444 bytes);
12445
12446 data->guesses.emplace_back (bytes, tdesc);
12447 }
12448
12449 /* Return true if remote_read_description would do anything on this target
12450 and architecture, false otherwise. */
12451
12452 static bool
12453 remote_read_description_p (struct target_ops *target)
12454 {
12455 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12456
12457 return !data->guesses.empty ();
12458 }
12459
12460 const struct target_desc *
12461 remote_target::read_description ()
12462 {
12463 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12464
12465 /* Do not try this during initial connection, when we do not know
12466 whether there is a running but stopped thread. */
12467 if (!target_has_execution () || inferior_ptid == null_ptid)
12468 return beneath ()->read_description ();
12469
12470 if (!data->guesses.empty ())
12471 {
12472 int bytes = send_g_packet ();
12473
12474 for (const remote_g_packet_guess &guess : data->guesses)
12475 if (guess.bytes == bytes)
12476 return guess.tdesc;
12477
12478 /* We discard the g packet. A minor optimization would be to
12479 hold on to it, and fill the register cache once we have selected
12480 an architecture, but it's too tricky to do safely. */
12481 }
12482
12483 return beneath ()->read_description ();
12484 }
12485
12486 /* Remote file transfer support. This is host-initiated I/O, not
12487 target-initiated; for target-initiated, see remote-fileio.c. */
12488
12489 /* If *LEFT is at least the length of STRING, copy STRING to
12490 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12491 decrease *LEFT. Otherwise raise an error. */
12492
12493 static void
12494 remote_buffer_add_string (char **buffer, int *left, const char *string)
12495 {
12496 int len = strlen (string);
12497
12498 if (len > *left)
12499 error (_("Packet too long for target."));
12500
12501 memcpy (*buffer, string, len);
12502 *buffer += len;
12503 *left -= len;
12504
12505 /* NUL-terminate the buffer as a convenience, if there is
12506 room. */
12507 if (*left)
12508 **buffer = '\0';
12509 }
12510
12511 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12512 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12513 decrease *LEFT. Otherwise raise an error. */
12514
12515 static void
12516 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12517 int len)
12518 {
12519 if (2 * len > *left)
12520 error (_("Packet too long for target."));
12521
12522 bin2hex (bytes, *buffer, len);
12523 *buffer += 2 * len;
12524 *left -= 2 * len;
12525
12526 /* NUL-terminate the buffer as a convenience, if there is
12527 room. */
12528 if (*left)
12529 **buffer = '\0';
12530 }
12531
12532 /* If *LEFT is large enough, convert VALUE to hex and add it to
12533 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12534 decrease *LEFT. Otherwise raise an error. */
12535
12536 static void
12537 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12538 {
12539 int len = hexnumlen (value);
12540
12541 if (len > *left)
12542 error (_("Packet too long for target."));
12543
12544 hexnumstr (*buffer, value);
12545 *buffer += len;
12546 *left -= len;
12547
12548 /* NUL-terminate the buffer as a convenience, if there is
12549 room. */
12550 if (*left)
12551 **buffer = '\0';
12552 }
12553
12554 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12555 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12556 was included, and *ATTACHMENT to point to the start of the annex
12557 if any. The length of the packet isn't needed here; there may
12558 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12559
12560 Return 0 if the packet could be parsed, -1 if it could not. If
12561 -1 is returned, the other variables may not be initialized. */
12562
12563 static int
12564 remote_hostio_parse_result (const char *buffer, int *retcode,
12565 fileio_error *remote_errno, const char **attachment)
12566 {
12567 char *p, *p2;
12568
12569 *remote_errno = FILEIO_SUCCESS;
12570 *attachment = NULL;
12571
12572 if (buffer[0] != 'F')
12573 return -1;
12574
12575 errno = 0;
12576 *retcode = strtol (&buffer[1], &p, 16);
12577 if (errno != 0 || p == &buffer[1])
12578 return -1;
12579
12580 /* Check for ",errno". */
12581 if (*p == ',')
12582 {
12583 errno = 0;
12584 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12585 if (errno != 0 || p + 1 == p2)
12586 return -1;
12587 p = p2;
12588 }
12589
12590 /* Check for ";attachment". If there is no attachment, the
12591 packet should end here. */
12592 if (*p == ';')
12593 {
12594 *attachment = p + 1;
12595 return 0;
12596 }
12597 else if (*p == '\0')
12598 return 0;
12599 else
12600 return -1;
12601 }
12602
12603 /* Send a prepared I/O packet to the target and read its response.
12604 The prepared packet is in the global RS->BUF before this function
12605 is called, and the answer is there when we return.
12606
12607 COMMAND_BYTES is the length of the request to send, which may include
12608 binary data. WHICH_PACKET is the packet configuration to check
12609 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12610 is set to the error number and -1 is returned. Otherwise the value
12611 returned by the function is returned.
12612
12613 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12614 attachment is expected; an error will be reported if there's a
12615 mismatch. If one is found, *ATTACHMENT will be set to point into
12616 the packet buffer and *ATTACHMENT_LEN will be set to the
12617 attachment's length. */
12618
12619 int
12620 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12621 fileio_error *remote_errno, const char **attachment,
12622 int *attachment_len)
12623 {
12624 struct remote_state *rs = get_remote_state ();
12625 int ret, bytes_read;
12626 const char *attachment_tmp;
12627
12628 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12629 {
12630 *remote_errno = FILEIO_ENOSYS;
12631 return -1;
12632 }
12633
12634 putpkt_binary (rs->buf.data (), command_bytes);
12635 bytes_read = getpkt (&rs->buf);
12636
12637 /* If it timed out, something is wrong. Don't try to parse the
12638 buffer. */
12639 if (bytes_read < 0)
12640 {
12641 *remote_errno = FILEIO_EINVAL;
12642 return -1;
12643 }
12644
12645 switch (m_features.packet_ok (rs->buf, which_packet).status ())
12646 {
12647 case PACKET_ERROR:
12648 *remote_errno = FILEIO_EINVAL;
12649 return -1;
12650 case PACKET_UNKNOWN:
12651 *remote_errno = FILEIO_ENOSYS;
12652 return -1;
12653 case PACKET_OK:
12654 break;
12655 }
12656
12657 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12658 &attachment_tmp))
12659 {
12660 *remote_errno = FILEIO_EINVAL;
12661 return -1;
12662 }
12663
12664 /* Make sure we saw an attachment if and only if we expected one. */
12665 if ((attachment_tmp == NULL && attachment != NULL)
12666 || (attachment_tmp != NULL && attachment == NULL))
12667 {
12668 *remote_errno = FILEIO_EINVAL;
12669 return -1;
12670 }
12671
12672 /* If an attachment was found, it must point into the packet buffer;
12673 work out how many bytes there were. */
12674 if (attachment_tmp != NULL)
12675 {
12676 *attachment = attachment_tmp;
12677 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12678 }
12679
12680 return ret;
12681 }
12682
12683 /* See declaration.h. */
12684
12685 void
12686 readahead_cache::invalidate ()
12687 {
12688 this->fd = -1;
12689 }
12690
12691 /* See declaration.h. */
12692
12693 void
12694 readahead_cache::invalidate_fd (int fd)
12695 {
12696 if (this->fd == fd)
12697 this->fd = -1;
12698 }
12699
12700 /* Set the filesystem remote_hostio functions that take FILENAME
12701 arguments will use. Return 0 on success, or -1 if an error
12702 occurs (and set *REMOTE_ERRNO). */
12703
12704 int
12705 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12706 fileio_error *remote_errno)
12707 {
12708 struct remote_state *rs = get_remote_state ();
12709 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12710 char *p = rs->buf.data ();
12711 int left = get_remote_packet_size () - 1;
12712 char arg[9];
12713 int ret;
12714
12715 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12716 return 0;
12717
12718 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12719 return 0;
12720
12721 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12722
12723 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12724 remote_buffer_add_string (&p, &left, arg);
12725
12726 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12727 remote_errno, NULL, NULL);
12728
12729 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12730 return 0;
12731
12732 if (ret == 0)
12733 rs->fs_pid = required_pid;
12734
12735 return ret;
12736 }
12737
12738 /* Implementation of to_fileio_open. */
12739
12740 int
12741 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12742 int flags, int mode, int warn_if_slow,
12743 fileio_error *remote_errno)
12744 {
12745 struct remote_state *rs = get_remote_state ();
12746 char *p = rs->buf.data ();
12747 int left = get_remote_packet_size () - 1;
12748
12749 if (warn_if_slow)
12750 {
12751 static int warning_issued = 0;
12752
12753 gdb_printf (_("Reading %s from remote target...\n"),
12754 filename);
12755
12756 if (!warning_issued)
12757 {
12758 warning (_("File transfers from remote targets can be slow."
12759 " Use \"set sysroot\" to access files locally"
12760 " instead."));
12761 warning_issued = 1;
12762 }
12763 }
12764
12765 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12766 return -1;
12767
12768 remote_buffer_add_string (&p, &left, "vFile:open:");
12769
12770 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12771 strlen (filename));
12772 remote_buffer_add_string (&p, &left, ",");
12773
12774 remote_buffer_add_int (&p, &left, flags);
12775 remote_buffer_add_string (&p, &left, ",");
12776
12777 remote_buffer_add_int (&p, &left, mode);
12778
12779 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12780 remote_errno, NULL, NULL);
12781 }
12782
12783 int
12784 remote_target::fileio_open (struct inferior *inf, const char *filename,
12785 int flags, int mode, int warn_if_slow,
12786 fileio_error *remote_errno)
12787 {
12788 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12789 remote_errno);
12790 }
12791
12792 /* Implementation of to_fileio_pwrite. */
12793
12794 int
12795 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12796 ULONGEST offset, fileio_error *remote_errno)
12797 {
12798 struct remote_state *rs = get_remote_state ();
12799 char *p = rs->buf.data ();
12800 int left = get_remote_packet_size ();
12801 int out_len;
12802
12803 rs->readahead_cache.invalidate_fd (fd);
12804
12805 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12806
12807 remote_buffer_add_int (&p, &left, fd);
12808 remote_buffer_add_string (&p, &left, ",");
12809
12810 remote_buffer_add_int (&p, &left, offset);
12811 remote_buffer_add_string (&p, &left, ",");
12812
12813 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12814 (get_remote_packet_size ()
12815 - (p - rs->buf.data ())));
12816
12817 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12818 remote_errno, NULL, NULL);
12819 }
12820
12821 int
12822 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12823 ULONGEST offset, fileio_error *remote_errno)
12824 {
12825 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12826 }
12827
12828 /* Helper for the implementation of to_fileio_pread. Read the file
12829 from the remote side with vFile:pread. */
12830
12831 int
12832 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12833 ULONGEST offset, fileio_error *remote_errno)
12834 {
12835 struct remote_state *rs = get_remote_state ();
12836 char *p = rs->buf.data ();
12837 const char *attachment;
12838 int left = get_remote_packet_size ();
12839 int ret, attachment_len;
12840 int read_len;
12841
12842 remote_buffer_add_string (&p, &left, "vFile:pread:");
12843
12844 remote_buffer_add_int (&p, &left, fd);
12845 remote_buffer_add_string (&p, &left, ",");
12846
12847 remote_buffer_add_int (&p, &left, len);
12848 remote_buffer_add_string (&p, &left, ",");
12849
12850 remote_buffer_add_int (&p, &left, offset);
12851
12852 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12853 remote_errno, &attachment,
12854 &attachment_len);
12855
12856 if (ret < 0)
12857 return ret;
12858
12859 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12860 read_buf, len);
12861 if (read_len != ret)
12862 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12863
12864 return ret;
12865 }
12866
12867 /* See declaration.h. */
12868
12869 int
12870 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12871 ULONGEST offset)
12872 {
12873 if (this->fd == fd
12874 && this->offset <= offset
12875 && offset < this->offset + this->buf.size ())
12876 {
12877 ULONGEST max = this->offset + this->buf.size ();
12878
12879 if (offset + len > max)
12880 len = max - offset;
12881
12882 memcpy (read_buf, &this->buf[offset - this->offset], len);
12883 return len;
12884 }
12885
12886 return 0;
12887 }
12888
12889 /* Implementation of to_fileio_pread. */
12890
12891 int
12892 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12893 ULONGEST offset, fileio_error *remote_errno)
12894 {
12895 int ret;
12896 struct remote_state *rs = get_remote_state ();
12897 readahead_cache *cache = &rs->readahead_cache;
12898
12899 ret = cache->pread (fd, read_buf, len, offset);
12900 if (ret > 0)
12901 {
12902 cache->hit_count++;
12903
12904 remote_debug_printf ("readahead cache hit %s",
12905 pulongest (cache->hit_count));
12906 return ret;
12907 }
12908
12909 cache->miss_count++;
12910
12911 remote_debug_printf ("readahead cache miss %s",
12912 pulongest (cache->miss_count));
12913
12914 cache->fd = fd;
12915 cache->offset = offset;
12916 cache->buf.resize (get_remote_packet_size ());
12917
12918 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12919 cache->buf.size (),
12920 cache->offset, remote_errno);
12921 if (ret <= 0)
12922 {
12923 cache->invalidate_fd (fd);
12924 return ret;
12925 }
12926
12927 cache->buf.resize (ret);
12928 return cache->pread (fd, read_buf, len, offset);
12929 }
12930
12931 int
12932 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12933 ULONGEST offset, fileio_error *remote_errno)
12934 {
12935 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12936 }
12937
12938 /* Implementation of to_fileio_close. */
12939
12940 int
12941 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12942 {
12943 struct remote_state *rs = get_remote_state ();
12944 char *p = rs->buf.data ();
12945 int left = get_remote_packet_size () - 1;
12946
12947 rs->readahead_cache.invalidate_fd (fd);
12948
12949 remote_buffer_add_string (&p, &left, "vFile:close:");
12950
12951 remote_buffer_add_int (&p, &left, fd);
12952
12953 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12954 remote_errno, NULL, NULL);
12955 }
12956
12957 int
12958 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12959 {
12960 return remote_hostio_close (fd, remote_errno);
12961 }
12962
12963 /* Implementation of to_fileio_unlink. */
12964
12965 int
12966 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12967 fileio_error *remote_errno)
12968 {
12969 struct remote_state *rs = get_remote_state ();
12970 char *p = rs->buf.data ();
12971 int left = get_remote_packet_size () - 1;
12972
12973 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12974 return -1;
12975
12976 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12977
12978 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12979 strlen (filename));
12980
12981 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12982 remote_errno, NULL, NULL);
12983 }
12984
12985 int
12986 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12987 fileio_error *remote_errno)
12988 {
12989 return remote_hostio_unlink (inf, filename, remote_errno);
12990 }
12991
12992 /* Implementation of to_fileio_readlink. */
12993
12994 std::optional<std::string>
12995 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12996 fileio_error *remote_errno)
12997 {
12998 struct remote_state *rs = get_remote_state ();
12999 char *p = rs->buf.data ();
13000 const char *attachment;
13001 int left = get_remote_packet_size ();
13002 int len, attachment_len;
13003 int read_len;
13004
13005 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
13006 return {};
13007
13008 remote_buffer_add_string (&p, &left, "vFile:readlink:");
13009
13010 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
13011 strlen (filename));
13012
13013 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
13014 remote_errno, &attachment,
13015 &attachment_len);
13016
13017 if (len < 0)
13018 return {};
13019
13020 std::string ret (len, '\0');
13021
13022 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13023 (gdb_byte *) &ret[0], len);
13024 if (read_len != len)
13025 error (_("Readlink returned %d, but %d bytes."), len, read_len);
13026
13027 return ret;
13028 }
13029
13030 /* Implementation of to_fileio_fstat. */
13031
13032 int
13033 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
13034 {
13035 struct remote_state *rs = get_remote_state ();
13036 char *p = rs->buf.data ();
13037 int left = get_remote_packet_size ();
13038 int attachment_len, ret;
13039 const char *attachment;
13040 struct fio_stat fst;
13041 int read_len;
13042
13043 remote_buffer_add_string (&p, &left, "vFile:fstat:");
13044
13045 remote_buffer_add_int (&p, &left, fd);
13046
13047 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
13048 remote_errno, &attachment,
13049 &attachment_len);
13050 if (ret < 0)
13051 {
13052 if (*remote_errno != FILEIO_ENOSYS)
13053 return ret;
13054
13055 /* Strictly we should return -1, ENOSYS here, but when
13056 "set sysroot remote:" was implemented in August 2008
13057 BFD's need for a stat function was sidestepped with
13058 this hack. This was not remedied until March 2015
13059 so we retain the previous behavior to avoid breaking
13060 compatibility.
13061
13062 Note that the memset is a March 2015 addition; older
13063 GDBs set st_size *and nothing else* so the structure
13064 would have garbage in all other fields. This might
13065 break something but retaining the previous behavior
13066 here would be just too wrong. */
13067
13068 memset (st, 0, sizeof (struct stat));
13069 st->st_size = INT_MAX;
13070 return 0;
13071 }
13072
13073 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
13074 (gdb_byte *) &fst, sizeof (fst));
13075
13076 if (read_len != ret)
13077 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
13078
13079 if (read_len != sizeof (fst))
13080 error (_("vFile:fstat returned %d bytes, but expecting %d."),
13081 read_len, (int) sizeof (fst));
13082
13083 remote_fileio_to_host_stat (&fst, st);
13084
13085 return 0;
13086 }
13087
13088 /* Implementation of to_filesystem_is_local. */
13089
13090 bool
13091 remote_target::filesystem_is_local ()
13092 {
13093 /* Valgrind GDB presents itself as a remote target but works
13094 on the local filesystem: it does not implement remote get
13095 and users are not expected to set a sysroot. To handle
13096 this case we treat the remote filesystem as local if the
13097 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
13098 does not support vFile:open. */
13099 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
13100 {
13101 packet_support ps = m_features.packet_support (PACKET_vFile_open);
13102
13103 if (ps == PACKET_SUPPORT_UNKNOWN)
13104 {
13105 int fd;
13106 fileio_error remote_errno;
13107
13108 /* Try opening a file to probe support. The supplied
13109 filename is irrelevant, we only care about whether
13110 the stub recognizes the packet or not. */
13111 fd = remote_hostio_open (NULL, "just probing",
13112 FILEIO_O_RDONLY, 0700, 0,
13113 &remote_errno);
13114
13115 if (fd >= 0)
13116 remote_hostio_close (fd, &remote_errno);
13117
13118 ps = m_features.packet_support (PACKET_vFile_open);
13119 }
13120
13121 if (ps == PACKET_DISABLE)
13122 {
13123 static int warning_issued = 0;
13124
13125 if (!warning_issued)
13126 {
13127 warning (_("remote target does not support file"
13128 " transfer, attempting to access files"
13129 " from local filesystem."));
13130 warning_issued = 1;
13131 }
13132
13133 return true;
13134 }
13135 }
13136
13137 return false;
13138 }
13139
13140 static char *
13141 remote_hostio_error (fileio_error errnum)
13142 {
13143 int host_error = fileio_error_to_host (errnum);
13144
13145 if (host_error == -1)
13146 error (_("Unknown remote I/O error %d"), errnum);
13147 else
13148 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13149 }
13150
13151 /* A RAII wrapper around a remote file descriptor. */
13152
13153 class scoped_remote_fd
13154 {
13155 public:
13156 scoped_remote_fd (remote_target *remote, int fd)
13157 : m_remote (remote), m_fd (fd)
13158 {
13159 }
13160
13161 ~scoped_remote_fd ()
13162 {
13163 if (m_fd != -1)
13164 {
13165 try
13166 {
13167 fileio_error remote_errno;
13168 m_remote->remote_hostio_close (m_fd, &remote_errno);
13169 }
13170 catch (...)
13171 {
13172 /* Swallow exception before it escapes the dtor. If
13173 something goes wrong, likely the connection is gone,
13174 and there's nothing else that can be done. */
13175 }
13176 }
13177 }
13178
13179 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13180
13181 /* Release ownership of the file descriptor, and return it. */
13182 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13183 {
13184 int fd = m_fd;
13185 m_fd = -1;
13186 return fd;
13187 }
13188
13189 /* Return the owned file descriptor. */
13190 int get () const noexcept
13191 {
13192 return m_fd;
13193 }
13194
13195 private:
13196 /* The remote target. */
13197 remote_target *m_remote;
13198
13199 /* The owned remote I/O file descriptor. */
13200 int m_fd;
13201 };
13202
13203 void
13204 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13205 {
13206 remote_target *remote = get_current_remote_target ();
13207
13208 if (remote == nullptr)
13209 error (_("command can only be used with remote target"));
13210
13211 remote->remote_file_put (local_file, remote_file, from_tty);
13212 }
13213
13214 void
13215 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13216 int from_tty)
13217 {
13218 int retcode, bytes, io_size;
13219 fileio_error remote_errno;
13220 int bytes_in_buffer;
13221 int saw_eof;
13222 ULONGEST offset;
13223
13224 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13225 if (file == NULL)
13226 perror_with_name (local_file);
13227
13228 scoped_remote_fd fd
13229 (this, remote_hostio_open (NULL,
13230 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13231 | FILEIO_O_TRUNC),
13232 0700, 0, &remote_errno));
13233 if (fd.get () == -1)
13234 remote_hostio_error (remote_errno);
13235
13236 /* Send up to this many bytes at once. They won't all fit in the
13237 remote packet limit, so we'll transfer slightly fewer. */
13238 io_size = get_remote_packet_size ();
13239 gdb::byte_vector buffer (io_size);
13240
13241 bytes_in_buffer = 0;
13242 saw_eof = 0;
13243 offset = 0;
13244 while (bytes_in_buffer || !saw_eof)
13245 {
13246 if (!saw_eof)
13247 {
13248 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13249 io_size - bytes_in_buffer,
13250 file.get ());
13251 if (bytes == 0)
13252 {
13253 if (ferror (file.get ()))
13254 error (_("Error reading %s."), local_file);
13255 else
13256 {
13257 /* EOF. Unless there is something still in the
13258 buffer from the last iteration, we are done. */
13259 saw_eof = 1;
13260 if (bytes_in_buffer == 0)
13261 break;
13262 }
13263 }
13264 }
13265 else
13266 bytes = 0;
13267
13268 bytes += bytes_in_buffer;
13269 bytes_in_buffer = 0;
13270
13271 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13272 offset, &remote_errno);
13273
13274 if (retcode < 0)
13275 remote_hostio_error (remote_errno);
13276 else if (retcode == 0)
13277 error (_("Remote write of %d bytes returned 0!"), bytes);
13278 else if (retcode < bytes)
13279 {
13280 /* Short write. Save the rest of the read data for the next
13281 write. */
13282 bytes_in_buffer = bytes - retcode;
13283 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13284 }
13285
13286 offset += retcode;
13287 }
13288
13289 if (remote_hostio_close (fd.release (), &remote_errno))
13290 remote_hostio_error (remote_errno);
13291
13292 if (from_tty)
13293 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13294 }
13295
13296 void
13297 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13298 {
13299 remote_target *remote = get_current_remote_target ();
13300
13301 if (remote == nullptr)
13302 error (_("command can only be used with remote target"));
13303
13304 remote->remote_file_get (remote_file, local_file, from_tty);
13305 }
13306
13307 void
13308 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13309 int from_tty)
13310 {
13311 fileio_error remote_errno;
13312 int bytes, io_size;
13313 ULONGEST offset;
13314
13315 scoped_remote_fd fd
13316 (this, remote_hostio_open (NULL,
13317 remote_file, FILEIO_O_RDONLY, 0, 0,
13318 &remote_errno));
13319 if (fd.get () == -1)
13320 remote_hostio_error (remote_errno);
13321
13322 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13323 if (file == NULL)
13324 perror_with_name (local_file);
13325
13326 /* Send up to this many bytes at once. They won't all fit in the
13327 remote packet limit, so we'll transfer slightly fewer. */
13328 io_size = get_remote_packet_size ();
13329 gdb::byte_vector buffer (io_size);
13330
13331 offset = 0;
13332 while (1)
13333 {
13334 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13335 &remote_errno);
13336 if (bytes == 0)
13337 /* Success, but no bytes, means end-of-file. */
13338 break;
13339 if (bytes == -1)
13340 remote_hostio_error (remote_errno);
13341
13342 offset += bytes;
13343
13344 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13345 if (bytes == 0)
13346 perror_with_name (local_file);
13347 }
13348
13349 if (remote_hostio_close (fd.release (), &remote_errno))
13350 remote_hostio_error (remote_errno);
13351
13352 if (from_tty)
13353 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13354 }
13355
13356 void
13357 remote_file_delete (const char *remote_file, int from_tty)
13358 {
13359 remote_target *remote = get_current_remote_target ();
13360
13361 if (remote == nullptr)
13362 error (_("command can only be used with remote target"));
13363
13364 remote->remote_file_delete (remote_file, from_tty);
13365 }
13366
13367 void
13368 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13369 {
13370 int retcode;
13371 fileio_error remote_errno;
13372
13373 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13374 if (retcode == -1)
13375 remote_hostio_error (remote_errno);
13376
13377 if (from_tty)
13378 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13379 }
13380
13381 static void
13382 remote_put_command (const char *args, int from_tty)
13383 {
13384 if (args == NULL)
13385 error_no_arg (_("file to put"));
13386
13387 gdb_argv argv (args);
13388 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13389 error (_("Invalid parameters to remote put"));
13390
13391 remote_file_put (argv[0], argv[1], from_tty);
13392 }
13393
13394 static void
13395 remote_get_command (const char *args, int from_tty)
13396 {
13397 if (args == NULL)
13398 error_no_arg (_("file to get"));
13399
13400 gdb_argv argv (args);
13401 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13402 error (_("Invalid parameters to remote get"));
13403
13404 remote_file_get (argv[0], argv[1], from_tty);
13405 }
13406
13407 static void
13408 remote_delete_command (const char *args, int from_tty)
13409 {
13410 if (args == NULL)
13411 error_no_arg (_("file to delete"));
13412
13413 gdb_argv argv (args);
13414 if (argv[0] == NULL || argv[1] != NULL)
13415 error (_("Invalid parameters to remote delete"));
13416
13417 remote_file_delete (argv[0], from_tty);
13418 }
13419
13420 bool
13421 remote_target::can_execute_reverse ()
13422 {
13423 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13424 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13425 return true;
13426 else
13427 return false;
13428 }
13429
13430 bool
13431 remote_target::supports_non_stop ()
13432 {
13433 return true;
13434 }
13435
13436 bool
13437 remote_target::supports_disable_randomization ()
13438 {
13439 /* Only supported in extended mode. */
13440 return false;
13441 }
13442
13443 bool
13444 remote_target::supports_multi_process ()
13445 {
13446 return m_features.remote_multi_process_p ();
13447 }
13448
13449 int
13450 remote_target::remote_supports_cond_tracepoints ()
13451 {
13452 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13453 == PACKET_ENABLE);
13454 }
13455
13456 bool
13457 remote_target::supports_evaluation_of_breakpoint_conditions ()
13458 {
13459 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13460 == PACKET_ENABLE);
13461 }
13462
13463 int
13464 remote_target::remote_supports_fast_tracepoints ()
13465 {
13466 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13467 }
13468
13469 int
13470 remote_target::remote_supports_static_tracepoints ()
13471 {
13472 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13473 }
13474
13475 int
13476 remote_target::remote_supports_install_in_trace ()
13477 {
13478 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13479 }
13480
13481 bool
13482 remote_target::supports_enable_disable_tracepoint ()
13483 {
13484 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13485 == PACKET_ENABLE);
13486 }
13487
13488 bool
13489 remote_target::supports_string_tracing ()
13490 {
13491 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13492 }
13493
13494 bool
13495 remote_target::can_run_breakpoint_commands ()
13496 {
13497 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13498 }
13499
13500 void
13501 remote_target::trace_init ()
13502 {
13503 struct remote_state *rs = get_remote_state ();
13504
13505 putpkt ("QTinit");
13506 remote_get_noisy_reply ();
13507 if (strcmp (rs->buf.data (), "OK") != 0)
13508 error (_("Target does not support this command."));
13509 }
13510
13511 /* Recursive routine to walk through command list including loops, and
13512 download packets for each command. */
13513
13514 void
13515 remote_target::remote_download_command_source (int num, ULONGEST addr,
13516 struct command_line *cmds)
13517 {
13518 struct remote_state *rs = get_remote_state ();
13519 struct command_line *cmd;
13520
13521 for (cmd = cmds; cmd; cmd = cmd->next)
13522 {
13523 QUIT; /* Allow user to bail out with ^C. */
13524 strcpy (rs->buf.data (), "QTDPsrc:");
13525 encode_source_string (num, addr, "cmd", cmd->line,
13526 rs->buf.data () + strlen (rs->buf.data ()),
13527 rs->buf.size () - strlen (rs->buf.data ()));
13528 putpkt (rs->buf);
13529 remote_get_noisy_reply ();
13530 if (strcmp (rs->buf.data (), "OK"))
13531 warning (_("Target does not support source download."));
13532
13533 if (cmd->control_type == while_control
13534 || cmd->control_type == while_stepping_control)
13535 {
13536 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13537
13538 QUIT; /* Allow user to bail out with ^C. */
13539 strcpy (rs->buf.data (), "QTDPsrc:");
13540 encode_source_string (num, addr, "cmd", "end",
13541 rs->buf.data () + strlen (rs->buf.data ()),
13542 rs->buf.size () - strlen (rs->buf.data ()));
13543 putpkt (rs->buf);
13544 remote_get_noisy_reply ();
13545 if (strcmp (rs->buf.data (), "OK"))
13546 warning (_("Target does not support source download."));
13547 }
13548 }
13549 }
13550
13551 void
13552 remote_target::download_tracepoint (struct bp_location *loc)
13553 {
13554 CORE_ADDR tpaddr;
13555 char addrbuf[40];
13556 std::vector<std::string> tdp_actions;
13557 std::vector<std::string> stepping_actions;
13558 char *pkt;
13559 struct breakpoint *b = loc->owner;
13560 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13561 struct remote_state *rs = get_remote_state ();
13562 int ret;
13563 const char *err_msg = _("Tracepoint packet too large for target.");
13564 size_t size_left;
13565
13566 /* We use a buffer other than rs->buf because we'll build strings
13567 across multiple statements, and other statements in between could
13568 modify rs->buf. */
13569 gdb::char_vector buf (get_remote_packet_size ());
13570
13571 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13572
13573 tpaddr = loc->address;
13574 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13575 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13576 b->number, addrbuf, /* address */
13577 (b->enable_state == bp_enabled ? 'E' : 'D'),
13578 t->step_count, t->pass_count);
13579
13580 if (ret < 0 || ret >= buf.size ())
13581 error ("%s", err_msg);
13582
13583 /* Fast tracepoints are mostly handled by the target, but we can
13584 tell the target how big of an instruction block should be moved
13585 around. */
13586 if (b->type == bp_fast_tracepoint)
13587 {
13588 /* Only test for support at download time; we may not know
13589 target capabilities at definition time. */
13590 if (remote_supports_fast_tracepoints ())
13591 {
13592 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13593 NULL))
13594 {
13595 size_left = buf.size () - strlen (buf.data ());
13596 ret = snprintf (buf.data () + strlen (buf.data ()),
13597 size_left, ":F%x",
13598 gdb_insn_length (loc->gdbarch, tpaddr));
13599
13600 if (ret < 0 || ret >= size_left)
13601 error ("%s", err_msg);
13602 }
13603 else
13604 /* If it passed validation at definition but fails now,
13605 something is very wrong. */
13606 internal_error (_("Fast tracepoint not valid during download"));
13607 }
13608 else
13609 /* Fast tracepoints are functionally identical to regular
13610 tracepoints, so don't take lack of support as a reason to
13611 give up on the trace run. */
13612 warning (_("Target does not support fast tracepoints, "
13613 "downloading %d as regular tracepoint"), b->number);
13614 }
13615 else if (b->type == bp_static_tracepoint
13616 || b->type == bp_static_marker_tracepoint)
13617 {
13618 /* Only test for support at download time; we may not know
13619 target capabilities at definition time. */
13620 if (remote_supports_static_tracepoints ())
13621 {
13622 struct static_tracepoint_marker marker;
13623
13624 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13625 {
13626 size_left = buf.size () - strlen (buf.data ());
13627 ret = snprintf (buf.data () + strlen (buf.data ()),
13628 size_left, ":S");
13629
13630 if (ret < 0 || ret >= size_left)
13631 error ("%s", err_msg);
13632 }
13633 else
13634 error (_("Static tracepoint not valid during download"));
13635 }
13636 else
13637 /* Fast tracepoints are functionally identical to regular
13638 tracepoints, so don't take lack of support as a reason
13639 to give up on the trace run. */
13640 error (_("Target does not support static tracepoints"));
13641 }
13642 /* If the tracepoint has a conditional, make it into an agent
13643 expression and append to the definition. */
13644 if (loc->cond)
13645 {
13646 /* Only test support at download time, we may not know target
13647 capabilities at definition time. */
13648 if (remote_supports_cond_tracepoints ())
13649 {
13650 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13651 loc->cond.get ());
13652
13653 size_left = buf.size () - strlen (buf.data ());
13654
13655 ret = snprintf (buf.data () + strlen (buf.data ()),
13656 size_left, ":X%x,", (int) aexpr->buf.size ());
13657
13658 if (ret < 0 || ret >= size_left)
13659 error ("%s", err_msg);
13660
13661 size_left = buf.size () - strlen (buf.data ());
13662
13663 /* Two bytes to encode each aexpr byte, plus the terminating
13664 null byte. */
13665 if (aexpr->buf.size () * 2 + 1 > size_left)
13666 error ("%s", err_msg);
13667
13668 pkt = buf.data () + strlen (buf.data ());
13669
13670 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13671 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13672 *pkt = '\0';
13673 }
13674 else
13675 warning (_("Target does not support conditional tracepoints, "
13676 "ignoring tp %d cond"), b->number);
13677 }
13678
13679 if (b->commands || !default_collect.empty ())
13680 {
13681 size_left = buf.size () - strlen (buf.data ());
13682
13683 ret = snprintf (buf.data () + strlen (buf.data ()),
13684 size_left, "-");
13685
13686 if (ret < 0 || ret >= size_left)
13687 error ("%s", err_msg);
13688 }
13689
13690 putpkt (buf.data ());
13691 remote_get_noisy_reply ();
13692 if (strcmp (rs->buf.data (), "OK"))
13693 error (_("Target does not support tracepoints."));
13694
13695 /* do_single_steps (t); */
13696 for (auto action_it = tdp_actions.begin ();
13697 action_it != tdp_actions.end (); action_it++)
13698 {
13699 QUIT; /* Allow user to bail out with ^C. */
13700
13701 bool has_more = ((action_it + 1) != tdp_actions.end ()
13702 || !stepping_actions.empty ());
13703
13704 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13705 b->number, addrbuf, /* address */
13706 action_it->c_str (),
13707 has_more ? '-' : 0);
13708
13709 if (ret < 0 || ret >= buf.size ())
13710 error ("%s", err_msg);
13711
13712 putpkt (buf.data ());
13713 remote_get_noisy_reply ();
13714 if (strcmp (rs->buf.data (), "OK"))
13715 error (_("Error on target while setting tracepoints."));
13716 }
13717
13718 for (auto action_it = stepping_actions.begin ();
13719 action_it != stepping_actions.end (); action_it++)
13720 {
13721 QUIT; /* Allow user to bail out with ^C. */
13722
13723 bool is_first = action_it == stepping_actions.begin ();
13724 bool has_more = (action_it + 1) != stepping_actions.end ();
13725
13726 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13727 b->number, addrbuf, /* address */
13728 is_first ? "S" : "",
13729 action_it->c_str (),
13730 has_more ? "-" : "");
13731
13732 if (ret < 0 || ret >= buf.size ())
13733 error ("%s", err_msg);
13734
13735 putpkt (buf.data ());
13736 remote_get_noisy_reply ();
13737 if (strcmp (rs->buf.data (), "OK"))
13738 error (_("Error on target while setting tracepoints."));
13739 }
13740
13741 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13742 {
13743 if (b->locspec != nullptr)
13744 {
13745 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13746
13747 if (ret < 0 || ret >= buf.size ())
13748 error ("%s", err_msg);
13749
13750 const char *str = b->locspec->to_string ();
13751 encode_source_string (b->number, loc->address, "at", str,
13752 buf.data () + strlen (buf.data ()),
13753 buf.size () - strlen (buf.data ()));
13754 putpkt (buf.data ());
13755 remote_get_noisy_reply ();
13756 if (strcmp (rs->buf.data (), "OK"))
13757 warning (_("Target does not support source download."));
13758 }
13759 if (b->cond_string)
13760 {
13761 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13762
13763 if (ret < 0 || ret >= buf.size ())
13764 error ("%s", err_msg);
13765
13766 encode_source_string (b->number, loc->address,
13767 "cond", b->cond_string.get (),
13768 buf.data () + strlen (buf.data ()),
13769 buf.size () - strlen (buf.data ()));
13770 putpkt (buf.data ());
13771 remote_get_noisy_reply ();
13772 if (strcmp (rs->buf.data (), "OK"))
13773 warning (_("Target does not support source download."));
13774 }
13775 remote_download_command_source (b->number, loc->address,
13776 breakpoint_commands (b));
13777 }
13778 }
13779
13780 bool
13781 remote_target::can_download_tracepoint ()
13782 {
13783 struct remote_state *rs = get_remote_state ();
13784 struct trace_status *ts;
13785 int status;
13786
13787 /* Don't try to install tracepoints until we've relocated our
13788 symbols, and fetched and merged the target's tracepoint list with
13789 ours. */
13790 if (rs->starting_up)
13791 return false;
13792
13793 ts = current_trace_status ();
13794 status = get_trace_status (ts);
13795
13796 if (status == -1 || !ts->running_known || !ts->running)
13797 return false;
13798
13799 /* If we are in a tracing experiment, but remote stub doesn't support
13800 installing tracepoint in trace, we have to return. */
13801 if (!remote_supports_install_in_trace ())
13802 return false;
13803
13804 return true;
13805 }
13806
13807
13808 void
13809 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13810 {
13811 struct remote_state *rs = get_remote_state ();
13812 char *p;
13813
13814 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13815 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13816 tsv.builtin);
13817 p = rs->buf.data () + strlen (rs->buf.data ());
13818 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13819 >= get_remote_packet_size ())
13820 error (_("Trace state variable name too long for tsv definition packet"));
13821 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13822 *p++ = '\0';
13823 putpkt (rs->buf);
13824 remote_get_noisy_reply ();
13825 if (rs->buf[0] == '\0')
13826 error (_("Target does not support this command."));
13827 if (strcmp (rs->buf.data (), "OK") != 0)
13828 error (_("Error on target while downloading trace state variable."));
13829 }
13830
13831 void
13832 remote_target::enable_tracepoint (struct bp_location *location)
13833 {
13834 struct remote_state *rs = get_remote_state ();
13835
13836 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13837 location->owner->number,
13838 phex (location->address, sizeof (CORE_ADDR)));
13839 putpkt (rs->buf);
13840 remote_get_noisy_reply ();
13841 if (rs->buf[0] == '\0')
13842 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13843 if (strcmp (rs->buf.data (), "OK") != 0)
13844 error (_("Error on target while enabling tracepoint."));
13845 }
13846
13847 void
13848 remote_target::disable_tracepoint (struct bp_location *location)
13849 {
13850 struct remote_state *rs = get_remote_state ();
13851
13852 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13853 location->owner->number,
13854 phex (location->address, sizeof (CORE_ADDR)));
13855 putpkt (rs->buf);
13856 remote_get_noisy_reply ();
13857 if (rs->buf[0] == '\0')
13858 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13859 if (strcmp (rs->buf.data (), "OK") != 0)
13860 error (_("Error on target while disabling tracepoint."));
13861 }
13862
13863 void
13864 remote_target::trace_set_readonly_regions ()
13865 {
13866 asection *s;
13867 bfd_size_type size;
13868 bfd_vma vma;
13869 int anysecs = 0;
13870 int offset = 0;
13871 bfd *abfd = current_program_space->exec_bfd ();
13872
13873 if (!abfd)
13874 return; /* No information to give. */
13875
13876 struct remote_state *rs = get_remote_state ();
13877
13878 strcpy (rs->buf.data (), "QTro");
13879 offset = strlen (rs->buf.data ());
13880 for (s = abfd->sections; s; s = s->next)
13881 {
13882 char tmp1[40], tmp2[40];
13883 int sec_length;
13884
13885 if ((s->flags & SEC_LOAD) == 0
13886 /* || (s->flags & SEC_CODE) == 0 */
13887 || (s->flags & SEC_READONLY) == 0)
13888 continue;
13889
13890 anysecs = 1;
13891 vma = bfd_section_vma (s);
13892 size = bfd_section_size (s);
13893 bfd_sprintf_vma (abfd, tmp1, vma);
13894 bfd_sprintf_vma (abfd, tmp2, vma + size);
13895 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13896 if (offset + sec_length + 1 > rs->buf.size ())
13897 {
13898 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13899 != PACKET_ENABLE)
13900 warning (_("\
13901 Too many sections for read-only sections definition packet."));
13902 break;
13903 }
13904 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13905 tmp1, tmp2);
13906 offset += sec_length;
13907 }
13908 if (anysecs)
13909 {
13910 putpkt (rs->buf);
13911 getpkt (&rs->buf);
13912 }
13913 }
13914
13915 void
13916 remote_target::trace_start ()
13917 {
13918 struct remote_state *rs = get_remote_state ();
13919
13920 putpkt ("QTStart");
13921 remote_get_noisy_reply ();
13922 if (rs->buf[0] == '\0')
13923 error (_("Target does not support this command."));
13924 if (strcmp (rs->buf.data (), "OK") != 0)
13925 error (_("Bogus reply from target: %s"), rs->buf.data ());
13926 }
13927
13928 int
13929 remote_target::get_trace_status (struct trace_status *ts)
13930 {
13931 /* Initialize it just to avoid a GCC false warning. */
13932 char *p = NULL;
13933 struct remote_state *rs = get_remote_state ();
13934
13935 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13936 return -1;
13937
13938 /* FIXME we need to get register block size some other way. */
13939 trace_regblock_size
13940 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13941
13942 putpkt ("qTStatus");
13943
13944 try
13945 {
13946 p = remote_get_noisy_reply ();
13947 }
13948 catch (const gdb_exception_error &ex)
13949 {
13950 if (ex.error != TARGET_CLOSE_ERROR)
13951 {
13952 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13953 return -1;
13954 }
13955 throw;
13956 }
13957
13958 packet_result result = m_features.packet_ok (p, PACKET_qTStatus);
13959
13960 switch (result.status ())
13961 {
13962 case PACKET_ERROR:
13963 error (_("Remote failure reply: %s"), result.err_msg ());
13964 /* If the remote target doesn't do tracing, flag it. */
13965 case PACKET_UNKNOWN:
13966 return -1;
13967 }
13968
13969 /* We're working with a live target. */
13970 ts->filename = NULL;
13971
13972 if (*p++ != 'T')
13973 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13974
13975 /* Function 'parse_trace_status' sets default value of each field of
13976 'ts' at first, so we don't have to do it here. */
13977 parse_trace_status (p, ts);
13978
13979 return ts->running;
13980 }
13981
13982 void
13983 remote_target::get_tracepoint_status (tracepoint *tp,
13984 struct uploaded_tp *utp)
13985 {
13986 struct remote_state *rs = get_remote_state ();
13987 char *reply;
13988 size_t size = get_remote_packet_size ();
13989
13990 if (tp)
13991 {
13992 tp->hit_count = 0;
13993 tp->traceframe_usage = 0;
13994 for (bp_location &loc : tp->locations ())
13995 {
13996 /* If the tracepoint was never downloaded, don't go asking for
13997 any status. */
13998 if (tp->number_on_target == 0)
13999 continue;
14000 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
14001 phex_nz (loc.address, 0));
14002 putpkt (rs->buf);
14003 reply = remote_get_noisy_reply ();
14004 if (reply && *reply)
14005 {
14006 if (*reply == 'V')
14007 parse_tracepoint_status (reply + 1, tp, utp);
14008 }
14009 }
14010 }
14011 else if (utp)
14012 {
14013 utp->hit_count = 0;
14014 utp->traceframe_usage = 0;
14015 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
14016 phex_nz (utp->addr, 0));
14017 putpkt (rs->buf);
14018 reply = remote_get_noisy_reply ();
14019 if (reply && *reply)
14020 {
14021 if (*reply == 'V')
14022 parse_tracepoint_status (reply + 1, tp, utp);
14023 }
14024 }
14025 }
14026
14027 void
14028 remote_target::trace_stop ()
14029 {
14030 struct remote_state *rs = get_remote_state ();
14031
14032 putpkt ("QTStop");
14033 remote_get_noisy_reply ();
14034 if (rs->buf[0] == '\0')
14035 error (_("Target does not support this command."));
14036 if (strcmp (rs->buf.data (), "OK") != 0)
14037 error (_("Bogus reply from target: %s"), rs->buf.data ());
14038 }
14039
14040 int
14041 remote_target::trace_find (enum trace_find_type type, int num,
14042 CORE_ADDR addr1, CORE_ADDR addr2,
14043 int *tpp)
14044 {
14045 struct remote_state *rs = get_remote_state ();
14046 char *endbuf = rs->buf.data () + get_remote_packet_size ();
14047 char *p, *reply;
14048 int target_frameno = -1, target_tracept = -1;
14049
14050 /* Lookups other than by absolute frame number depend on the current
14051 trace selected, so make sure it is correct on the remote end
14052 first. */
14053 if (type != tfind_number)
14054 set_remote_traceframe ();
14055
14056 p = rs->buf.data ();
14057 strcpy (p, "QTFrame:");
14058 p = strchr (p, '\0');
14059 switch (type)
14060 {
14061 case tfind_number:
14062 xsnprintf (p, endbuf - p, "%x", num);
14063 break;
14064 case tfind_pc:
14065 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
14066 break;
14067 case tfind_tp:
14068 xsnprintf (p, endbuf - p, "tdp:%x", num);
14069 break;
14070 case tfind_range:
14071 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
14072 phex_nz (addr2, 0));
14073 break;
14074 case tfind_outside:
14075 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
14076 phex_nz (addr2, 0));
14077 break;
14078 default:
14079 error (_("Unknown trace find type %d"), type);
14080 }
14081
14082 putpkt (rs->buf);
14083 reply = remote_get_noisy_reply ();
14084 if (*reply == '\0')
14085 error (_("Target does not support this command."));
14086
14087 while (reply && *reply)
14088 switch (*reply)
14089 {
14090 case 'F':
14091 p = ++reply;
14092 target_frameno = (int) strtol (p, &reply, 16);
14093 if (reply == p)
14094 error (_("Unable to parse trace frame number"));
14095 /* Don't update our remote traceframe number cache on failure
14096 to select a remote traceframe. */
14097 if (target_frameno == -1)
14098 return -1;
14099 break;
14100 case 'T':
14101 p = ++reply;
14102 target_tracept = (int) strtol (p, &reply, 16);
14103 if (reply == p)
14104 error (_("Unable to parse tracepoint number"));
14105 break;
14106 case 'O': /* "OK"? */
14107 if (reply[1] == 'K' && reply[2] == '\0')
14108 reply += 2;
14109 else
14110 error (_("Bogus reply from target: %s"), reply);
14111 break;
14112 default:
14113 error (_("Bogus reply from target: %s"), reply);
14114 }
14115 if (tpp)
14116 *tpp = target_tracept;
14117
14118 rs->remote_traceframe_number = target_frameno;
14119 return target_frameno;
14120 }
14121
14122 bool
14123 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
14124 {
14125 struct remote_state *rs = get_remote_state ();
14126 char *reply;
14127 ULONGEST uval;
14128
14129 set_remote_traceframe ();
14130
14131 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
14132 putpkt (rs->buf);
14133 reply = remote_get_noisy_reply ();
14134 if (reply && *reply)
14135 {
14136 if (*reply == 'V')
14137 {
14138 unpack_varlen_hex (reply + 1, &uval);
14139 *val = (LONGEST) uval;
14140 return true;
14141 }
14142 }
14143 return false;
14144 }
14145
14146 int
14147 remote_target::save_trace_data (const char *filename)
14148 {
14149 struct remote_state *rs = get_remote_state ();
14150 char *p, *reply;
14151
14152 p = rs->buf.data ();
14153 strcpy (p, "QTSave:");
14154 p += strlen (p);
14155 if ((p - rs->buf.data ()) + strlen (filename) * 2
14156 >= get_remote_packet_size ())
14157 error (_("Remote file name too long for trace save packet"));
14158 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14159 *p++ = '\0';
14160 putpkt (rs->buf);
14161 reply = remote_get_noisy_reply ();
14162 if (*reply == '\0')
14163 error (_("Target does not support this command."));
14164 if (strcmp (reply, "OK") != 0)
14165 error (_("Bogus reply from target: %s"), reply);
14166 return 0;
14167 }
14168
14169 /* This is basically a memory transfer, but needs to be its own packet
14170 because we don't know how the target actually organizes its trace
14171 memory, plus we want to be able to ask for as much as possible, but
14172 not be unhappy if we don't get as much as we ask for. */
14173
14174 LONGEST
14175 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14176 {
14177 struct remote_state *rs = get_remote_state ();
14178 char *reply;
14179 char *p;
14180 int rslt;
14181
14182 p = rs->buf.data ();
14183 strcpy (p, "qTBuffer:");
14184 p += strlen (p);
14185 p += hexnumstr (p, offset);
14186 *p++ = ',';
14187 p += hexnumstr (p, len);
14188 *p++ = '\0';
14189
14190 putpkt (rs->buf);
14191 reply = remote_get_noisy_reply ();
14192 if (reply && *reply)
14193 {
14194 /* 'l' by itself means we're at the end of the buffer and
14195 there is nothing more to get. */
14196 if (*reply == 'l')
14197 return 0;
14198
14199 /* Convert the reply into binary. Limit the number of bytes to
14200 convert according to our passed-in buffer size, rather than
14201 what was returned in the packet; if the target is
14202 unexpectedly generous and gives us a bigger reply than we
14203 asked for, we don't want to crash. */
14204 rslt = hex2bin (reply, buf, len);
14205 return rslt;
14206 }
14207
14208 /* Something went wrong, flag as an error. */
14209 return -1;
14210 }
14211
14212 void
14213 remote_target::set_disconnected_tracing (int val)
14214 {
14215 struct remote_state *rs = get_remote_state ();
14216
14217 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14218 == PACKET_ENABLE)
14219 {
14220 char *reply;
14221
14222 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14223 "QTDisconnected:%x", val);
14224 putpkt (rs->buf);
14225 reply = remote_get_noisy_reply ();
14226 if (*reply == '\0')
14227 error (_("Target does not support this command."));
14228 if (strcmp (reply, "OK") != 0)
14229 error (_("Bogus reply from target: %s"), reply);
14230 }
14231 else if (val)
14232 warning (_("Target does not support disconnected tracing."));
14233 }
14234
14235 int
14236 remote_target::core_of_thread (ptid_t ptid)
14237 {
14238 thread_info *info = this->find_thread (ptid);
14239
14240 if (info != NULL && info->priv != NULL)
14241 return get_remote_thread_info (info)->core;
14242
14243 return -1;
14244 }
14245
14246 void
14247 remote_target::set_circular_trace_buffer (int val)
14248 {
14249 struct remote_state *rs = get_remote_state ();
14250 char *reply;
14251
14252 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14253 "QTBuffer:circular:%x", val);
14254 putpkt (rs->buf);
14255 reply = remote_get_noisy_reply ();
14256 if (*reply == '\0')
14257 error (_("Target does not support this command."));
14258 if (strcmp (reply, "OK") != 0)
14259 error (_("Bogus reply from target: %s"), reply);
14260 }
14261
14262 traceframe_info_up
14263 remote_target::traceframe_info ()
14264 {
14265 std::optional<gdb::char_vector> text
14266 = target_read_stralloc (current_inferior ()->top_target (),
14267 TARGET_OBJECT_TRACEFRAME_INFO,
14268 NULL);
14269 if (text)
14270 return parse_traceframe_info (text->data ());
14271
14272 return NULL;
14273 }
14274
14275 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14276 instruction on which a fast tracepoint may be placed. Returns -1
14277 if the packet is not supported, and 0 if the minimum instruction
14278 length is unknown. */
14279
14280 int
14281 remote_target::get_min_fast_tracepoint_insn_len ()
14282 {
14283 struct remote_state *rs = get_remote_state ();
14284 char *reply;
14285
14286 /* If we're not debugging a process yet, the IPA can't be
14287 loaded. */
14288 if (!target_has_execution ())
14289 return 0;
14290
14291 /* Make sure the remote is pointing at the right process. */
14292 set_general_process ();
14293
14294 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14295 putpkt (rs->buf);
14296 reply = remote_get_noisy_reply ();
14297 if (*reply == '\0')
14298 return -1;
14299 else
14300 {
14301 ULONGEST min_insn_len;
14302
14303 unpack_varlen_hex (reply, &min_insn_len);
14304
14305 return (int) min_insn_len;
14306 }
14307 }
14308
14309 void
14310 remote_target::set_trace_buffer_size (LONGEST val)
14311 {
14312 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14313 {
14314 struct remote_state *rs = get_remote_state ();
14315 char *buf = rs->buf.data ();
14316 char *endbuf = buf + get_remote_packet_size ();
14317
14318 gdb_assert (val >= 0 || val == -1);
14319 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14320 /* Send -1 as literal "-1" to avoid host size dependency. */
14321 if (val < 0)
14322 {
14323 *buf++ = '-';
14324 buf += hexnumstr (buf, (ULONGEST) -val);
14325 }
14326 else
14327 buf += hexnumstr (buf, (ULONGEST) val);
14328
14329 putpkt (rs->buf);
14330 remote_get_noisy_reply ();
14331 packet_result result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14332 switch (result.status ())
14333 {
14334 case PACKET_ERROR:
14335 warning (_("Error reply from target: %s"), result.err_msg ());
14336 break;
14337 case PACKET_UNKNOWN:
14338 warning (_("Remote target failed to process the request "));
14339 }
14340 }
14341 }
14342
14343 bool
14344 remote_target::set_trace_notes (const char *user, const char *notes,
14345 const char *stop_notes)
14346 {
14347 struct remote_state *rs = get_remote_state ();
14348 char *reply;
14349 char *buf = rs->buf.data ();
14350 char *endbuf = buf + get_remote_packet_size ();
14351 int nbytes;
14352
14353 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14354 if (user)
14355 {
14356 buf += xsnprintf (buf, endbuf - buf, "user:");
14357 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14358 buf += 2 * nbytes;
14359 *buf++ = ';';
14360 }
14361 if (notes)
14362 {
14363 buf += xsnprintf (buf, endbuf - buf, "notes:");
14364 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14365 buf += 2 * nbytes;
14366 *buf++ = ';';
14367 }
14368 if (stop_notes)
14369 {
14370 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14371 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14372 buf += 2 * nbytes;
14373 *buf++ = ';';
14374 }
14375 /* Ensure the buffer is terminated. */
14376 *buf = '\0';
14377
14378 putpkt (rs->buf);
14379 reply = remote_get_noisy_reply ();
14380 if (*reply == '\0')
14381 return false;
14382
14383 if (strcmp (reply, "OK") != 0)
14384 error (_("Bogus reply from target: %s"), reply);
14385
14386 return true;
14387 }
14388
14389 bool
14390 remote_target::use_agent (bool use)
14391 {
14392 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14393 {
14394 struct remote_state *rs = get_remote_state ();
14395
14396 /* If the stub supports QAgent. */
14397 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14398 putpkt (rs->buf);
14399 getpkt (&rs->buf);
14400
14401 if (strcmp (rs->buf.data (), "OK") == 0)
14402 {
14403 ::use_agent = use;
14404 return true;
14405 }
14406 }
14407
14408 return false;
14409 }
14410
14411 bool
14412 remote_target::can_use_agent ()
14413 {
14414 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14415 }
14416
14417 #if defined (HAVE_LIBEXPAT)
14418
14419 /* Check the btrace document version. */
14420
14421 static void
14422 check_xml_btrace_version (struct gdb_xml_parser *parser,
14423 const struct gdb_xml_element *element,
14424 void *user_data,
14425 std::vector<gdb_xml_value> &attributes)
14426 {
14427 const char *version
14428 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14429
14430 if (strcmp (version, "1.0") != 0)
14431 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14432 }
14433
14434 /* Parse a btrace "block" xml record. */
14435
14436 static void
14437 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14438 const struct gdb_xml_element *element,
14439 void *user_data,
14440 std::vector<gdb_xml_value> &attributes)
14441 {
14442 struct btrace_data *btrace;
14443 ULONGEST *begin, *end;
14444
14445 btrace = (struct btrace_data *) user_data;
14446
14447 switch (btrace->format)
14448 {
14449 case BTRACE_FORMAT_BTS:
14450 break;
14451
14452 case BTRACE_FORMAT_NONE:
14453 btrace->format = BTRACE_FORMAT_BTS;
14454 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14455 break;
14456
14457 default:
14458 gdb_xml_error (parser, _("Btrace format error."));
14459 }
14460
14461 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14462 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14463 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14464 }
14465
14466 /* Parse a "raw" xml record. */
14467
14468 static void
14469 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14470 gdb_byte **pdata, size_t *psize)
14471 {
14472 gdb_byte *bin;
14473 size_t len, size;
14474
14475 len = strlen (body_text);
14476 if (len % 2 != 0)
14477 gdb_xml_error (parser, _("Bad raw data size."));
14478
14479 size = len / 2;
14480
14481 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14482 bin = data.get ();
14483
14484 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14485 while (len > 0)
14486 {
14487 char hi, lo;
14488
14489 hi = *body_text++;
14490 lo = *body_text++;
14491
14492 if (hi == 0 || lo == 0)
14493 gdb_xml_error (parser, _("Bad hex encoding."));
14494
14495 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14496 len -= 2;
14497 }
14498
14499 *pdata = data.release ();
14500 *psize = size;
14501 }
14502
14503 /* Parse a btrace pt-config "cpu" xml record. */
14504
14505 static void
14506 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14507 const struct gdb_xml_element *element,
14508 void *user_data,
14509 std::vector<gdb_xml_value> &attributes)
14510 {
14511 struct btrace_data *btrace;
14512 const char *vendor;
14513 ULONGEST *family, *model, *stepping;
14514
14515 vendor
14516 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14517 family
14518 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14519 model
14520 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14521 stepping
14522 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14523
14524 btrace = (struct btrace_data *) user_data;
14525
14526 if (strcmp (vendor, "GenuineIntel") == 0)
14527 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14528
14529 btrace->variant.pt.config.cpu.family = *family;
14530 btrace->variant.pt.config.cpu.model = *model;
14531 btrace->variant.pt.config.cpu.stepping = *stepping;
14532 }
14533
14534 /* Parse a btrace pt "raw" xml record. */
14535
14536 static void
14537 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14538 const struct gdb_xml_element *element,
14539 void *user_data, const char *body_text)
14540 {
14541 struct btrace_data *btrace;
14542
14543 btrace = (struct btrace_data *) user_data;
14544 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14545 &btrace->variant.pt.size);
14546 }
14547
14548 /* Parse a btrace "pt" xml record. */
14549
14550 static void
14551 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14552 const struct gdb_xml_element *element,
14553 void *user_data,
14554 std::vector<gdb_xml_value> &attributes)
14555 {
14556 struct btrace_data *btrace;
14557
14558 btrace = (struct btrace_data *) user_data;
14559 btrace->format = BTRACE_FORMAT_PT;
14560 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14561 btrace->variant.pt.data = NULL;
14562 btrace->variant.pt.size = 0;
14563 }
14564
14565 static const struct gdb_xml_attribute block_attributes[] = {
14566 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14567 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14568 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14569 };
14570
14571 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14572 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14573 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14574 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14575 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14576 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14577 };
14578
14579 static const struct gdb_xml_element btrace_pt_config_children[] = {
14580 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14581 parse_xml_btrace_pt_config_cpu, NULL },
14582 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14583 };
14584
14585 static const struct gdb_xml_element btrace_pt_children[] = {
14586 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14587 NULL },
14588 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14589 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14590 };
14591
14592 static const struct gdb_xml_attribute btrace_attributes[] = {
14593 { "version", GDB_XML_AF_NONE, NULL, NULL },
14594 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14595 };
14596
14597 static const struct gdb_xml_element btrace_children[] = {
14598 { "block", block_attributes, NULL,
14599 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14600 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14601 NULL },
14602 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14603 };
14604
14605 static const struct gdb_xml_element btrace_elements[] = {
14606 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14607 check_xml_btrace_version, NULL },
14608 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14609 };
14610
14611 #endif /* defined (HAVE_LIBEXPAT) */
14612
14613 /* Parse a branch trace xml document XML into DATA. */
14614
14615 static void
14616 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14617 {
14618 #if defined (HAVE_LIBEXPAT)
14619
14620 int errcode;
14621 btrace_data result;
14622 result.format = BTRACE_FORMAT_NONE;
14623
14624 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14625 buffer, &result);
14626 if (errcode != 0)
14627 error (_("Error parsing branch trace."));
14628
14629 /* Keep parse results. */
14630 *btrace = std::move (result);
14631
14632 #else /* !defined (HAVE_LIBEXPAT) */
14633
14634 error (_("Cannot process branch trace. XML support was disabled at "
14635 "compile time."));
14636
14637 #endif /* !defined (HAVE_LIBEXPAT) */
14638 }
14639
14640 #if defined (HAVE_LIBEXPAT)
14641
14642 /* Parse a btrace-conf "bts" xml record. */
14643
14644 static void
14645 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14646 const struct gdb_xml_element *element,
14647 void *user_data,
14648 std::vector<gdb_xml_value> &attributes)
14649 {
14650 struct btrace_config *conf;
14651 struct gdb_xml_value *size;
14652
14653 conf = (struct btrace_config *) user_data;
14654 conf->format = BTRACE_FORMAT_BTS;
14655 conf->bts.size = 0;
14656
14657 size = xml_find_attribute (attributes, "size");
14658 if (size != NULL)
14659 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14660 }
14661
14662 /* Parse a btrace-conf "pt" xml record. */
14663
14664 static void
14665 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14666 const struct gdb_xml_element *element,
14667 void *user_data,
14668 std::vector<gdb_xml_value> &attributes)
14669 {
14670 struct btrace_config *conf;
14671 struct gdb_xml_value *size;
14672
14673 conf = (struct btrace_config *) user_data;
14674 conf->format = BTRACE_FORMAT_PT;
14675 conf->pt.size = 0;
14676
14677 size = xml_find_attribute (attributes, "size");
14678 if (size != NULL)
14679 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14680 }
14681
14682 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14683 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14684 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14685 };
14686
14687 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14688 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14689 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14690 };
14691
14692 static const struct gdb_xml_element btrace_conf_children[] = {
14693 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14694 parse_xml_btrace_conf_bts, NULL },
14695 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14696 parse_xml_btrace_conf_pt, NULL },
14697 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14698 };
14699
14700 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14701 { "version", GDB_XML_AF_NONE, NULL, NULL },
14702 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14703 };
14704
14705 static const struct gdb_xml_element btrace_conf_elements[] = {
14706 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14707 GDB_XML_EF_NONE, NULL, NULL },
14708 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14709 };
14710
14711 #endif /* defined (HAVE_LIBEXPAT) */
14712
14713 /* Parse a branch trace configuration xml document XML into CONF. */
14714
14715 static void
14716 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14717 {
14718 #if defined (HAVE_LIBEXPAT)
14719
14720 int errcode;
14721 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14722 btrace_conf_elements, xml, conf);
14723 if (errcode != 0)
14724 error (_("Error parsing branch trace configuration."));
14725
14726 #else /* !defined (HAVE_LIBEXPAT) */
14727
14728 error (_("Cannot process the branch trace configuration. XML support "
14729 "was disabled at compile time."));
14730
14731 #endif /* !defined (HAVE_LIBEXPAT) */
14732 }
14733
14734 /* Reset our idea of our target's btrace configuration. */
14735
14736 static void
14737 remote_btrace_reset (remote_state *rs)
14738 {
14739 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14740 }
14741
14742 /* Synchronize the configuration with the target. */
14743
14744 void
14745 remote_target::btrace_sync_conf (const btrace_config *conf)
14746 {
14747 struct remote_state *rs;
14748 char *buf, *pos, *endbuf;
14749
14750 rs = get_remote_state ();
14751 buf = rs->buf.data ();
14752 endbuf = buf + get_remote_packet_size ();
14753
14754 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14755 && conf->bts.size != rs->btrace_config.bts.size)
14756 {
14757 pos = buf;
14758 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14759 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14760 conf->bts.size);
14761
14762 putpkt (buf);
14763 getpkt (&rs->buf);
14764
14765 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size);
14766 if (result.status () == PACKET_ERROR)
14767 error (_("Failed to configure the BTS buffer size: %s"), result.err_msg ());
14768
14769 rs->btrace_config.bts.size = conf->bts.size;
14770 }
14771
14772 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14773 && conf->pt.size != rs->btrace_config.pt.size)
14774 {
14775 pos = buf;
14776 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14777 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14778 conf->pt.size);
14779
14780 putpkt (buf);
14781 getpkt (&rs->buf);
14782
14783 packet_result result = m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size);
14784 if (result.status () == PACKET_ERROR)
14785 error (_("Failed to configure the trace buffer size: %s"), result.err_msg ());
14786
14787 rs->btrace_config.pt.size = conf->pt.size;
14788 }
14789 }
14790
14791 /* Read TP's btrace configuration from the target and store it into CONF. */
14792
14793 static void
14794 btrace_read_config (thread_info *tp, btrace_config *conf)
14795 {
14796 /* target_read_stralloc relies on INFERIOR_PTID. */
14797 scoped_restore_current_thread restore_thread;
14798 switch_to_thread (tp);
14799
14800 std::optional<gdb::char_vector> xml
14801 = target_read_stralloc (current_inferior ()->top_target (),
14802 TARGET_OBJECT_BTRACE_CONF, "");
14803 if (xml)
14804 parse_xml_btrace_conf (conf, xml->data ());
14805 }
14806
14807 /* Maybe reopen target btrace. */
14808
14809 void
14810 remote_target::remote_btrace_maybe_reopen ()
14811 {
14812 struct remote_state *rs = get_remote_state ();
14813 int btrace_target_pushed = 0;
14814 #if !defined (HAVE_LIBIPT)
14815 int warned = 0;
14816 #endif
14817
14818 /* Don't bother walking the entirety of the remote thread list when
14819 we know the feature isn't supported by the remote. */
14820 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14821 return;
14822
14823 for (thread_info *tp : all_non_exited_threads (this))
14824 {
14825 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14826 btrace_read_config (tp, &rs->btrace_config);
14827
14828 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14829 continue;
14830
14831 #if !defined (HAVE_LIBIPT)
14832 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14833 {
14834 if (!warned)
14835 {
14836 warned = 1;
14837 warning (_("Target is recording using Intel Processor Trace "
14838 "but support was disabled at compile time."));
14839 }
14840
14841 continue;
14842 }
14843 #endif /* !defined (HAVE_LIBIPT) */
14844
14845 /* Push target, once, but before anything else happens. This way our
14846 changes to the threads will be cleaned up by unpushing the target
14847 in case btrace_read_config () throws. */
14848 if (!btrace_target_pushed)
14849 {
14850 btrace_target_pushed = 1;
14851 record_btrace_push_target ();
14852 gdb_printf (_("Target is recording using %s.\n"),
14853 btrace_format_string (rs->btrace_config.format));
14854 }
14855
14856 tp->btrace.target
14857 = new btrace_target_info { tp->ptid, rs->btrace_config };
14858 }
14859 }
14860
14861 /* Enable branch tracing. */
14862
14863 struct btrace_target_info *
14864 remote_target::enable_btrace (thread_info *tp,
14865 const struct btrace_config *conf)
14866 {
14867 struct packet_config *packet = NULL;
14868 struct remote_state *rs = get_remote_state ();
14869 char *buf = rs->buf.data ();
14870 char *endbuf = buf + get_remote_packet_size ();
14871
14872 unsigned int which_packet;
14873 switch (conf->format)
14874 {
14875 case BTRACE_FORMAT_BTS:
14876 which_packet = PACKET_Qbtrace_bts;
14877 break;
14878 case BTRACE_FORMAT_PT:
14879 which_packet = PACKET_Qbtrace_pt;
14880 break;
14881 default:
14882 internal_error (_("Bad branch btrace format: %u."),
14883 (unsigned int) conf->format);
14884 }
14885
14886 packet = &m_features.m_protocol_packets[which_packet];
14887 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14888 error (_("Target does not support branch tracing."));
14889
14890 btrace_sync_conf (conf);
14891
14892 ptid_t ptid = tp->ptid;
14893 set_general_thread (ptid);
14894
14895 buf += xsnprintf (buf, endbuf - buf, "%s",
14896 packets_descriptions[which_packet].name);
14897 putpkt (rs->buf);
14898 getpkt (&rs->buf);
14899
14900 packet_result result = m_features.packet_ok (rs->buf, which_packet);
14901 if (result.status () == PACKET_ERROR)
14902 error (_("Could not enable branch tracing for %s: %s"),
14903 target_pid_to_str (ptid).c_str (), result.err_msg ());
14904
14905 btrace_target_info *tinfo = new btrace_target_info { ptid };
14906
14907 /* If we fail to read the configuration, we lose some information, but the
14908 tracing itself is not impacted. */
14909 try
14910 {
14911 btrace_read_config (tp, &tinfo->conf);
14912 }
14913 catch (const gdb_exception_error &err)
14914 {
14915 if (err.message != NULL)
14916 warning ("%s", err.what ());
14917 }
14918
14919 return tinfo;
14920 }
14921
14922 /* Disable branch tracing. */
14923
14924 void
14925 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14926 {
14927 struct remote_state *rs = get_remote_state ();
14928 char *buf = rs->buf.data ();
14929 char *endbuf = buf + get_remote_packet_size ();
14930
14931 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14932 error (_("Target does not support branch tracing."));
14933
14934 set_general_thread (tinfo->ptid);
14935
14936 buf += xsnprintf (buf, endbuf - buf, "%s",
14937 packets_descriptions[PACKET_Qbtrace_off].name);
14938 putpkt (rs->buf);
14939 getpkt (&rs->buf);
14940
14941 packet_result result = m_features.packet_ok (rs->buf, PACKET_Qbtrace_off);
14942 if (result.status () == PACKET_ERROR)
14943 error (_("Could not disable branch tracing for %s: %s"),
14944 target_pid_to_str (tinfo->ptid).c_str (), result.err_msg ());
14945
14946 delete tinfo;
14947 }
14948
14949 /* Teardown branch tracing. */
14950
14951 void
14952 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14953 {
14954 /* We must not talk to the target during teardown. */
14955 delete tinfo;
14956 }
14957
14958 /* Read the branch trace. */
14959
14960 enum btrace_error
14961 remote_target::read_btrace (struct btrace_data *btrace,
14962 struct btrace_target_info *tinfo,
14963 enum btrace_read_type type)
14964 {
14965 const char *annex;
14966
14967 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14968 error (_("Target does not support branch tracing."));
14969
14970 #if !defined(HAVE_LIBEXPAT)
14971 error (_("Cannot process branch tracing result. XML parsing not supported."));
14972 #endif
14973
14974 switch (type)
14975 {
14976 case BTRACE_READ_ALL:
14977 annex = "all";
14978 break;
14979 case BTRACE_READ_NEW:
14980 annex = "new";
14981 break;
14982 case BTRACE_READ_DELTA:
14983 annex = "delta";
14984 break;
14985 default:
14986 internal_error (_("Bad branch tracing read type: %u."),
14987 (unsigned int) type);
14988 }
14989
14990 std::optional<gdb::char_vector> xml
14991 = target_read_stralloc (current_inferior ()->top_target (),
14992 TARGET_OBJECT_BTRACE, annex);
14993 if (!xml)
14994 return BTRACE_ERR_UNKNOWN;
14995
14996 parse_xml_btrace (btrace, xml->data ());
14997
14998 return BTRACE_ERR_NONE;
14999 }
15000
15001 const struct btrace_config *
15002 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
15003 {
15004 return &tinfo->conf;
15005 }
15006
15007 bool
15008 remote_target::augmented_libraries_svr4_read ()
15009 {
15010 return
15011 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
15012 == PACKET_ENABLE);
15013 }
15014
15015 /* Implementation of to_load. */
15016
15017 void
15018 remote_target::load (const char *name, int from_tty)
15019 {
15020 generic_load (name, from_tty);
15021 }
15022
15023 /* Accepts an integer PID; returns a string representing a file that
15024 can be opened on the remote side to get the symbols for the child
15025 process. Returns NULL if the operation is not supported. */
15026
15027 const char *
15028 remote_target::pid_to_exec_file (int pid)
15029 {
15030 static std::optional<gdb::char_vector> filename;
15031 char *annex = NULL;
15032
15033 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
15034 return NULL;
15035
15036 inferior *inf = find_inferior_pid (this, pid);
15037 if (inf == NULL)
15038 internal_error (_("not currently attached to process %d"), pid);
15039
15040 if (!inf->fake_pid_p)
15041 {
15042 const int annex_size = 9;
15043
15044 annex = (char *) alloca (annex_size);
15045 xsnprintf (annex, annex_size, "%x", pid);
15046 }
15047
15048 filename = target_read_stralloc (current_inferior ()->top_target (),
15049 TARGET_OBJECT_EXEC_FILE, annex);
15050
15051 return filename ? filename->data () : nullptr;
15052 }
15053
15054 /* Implement the to_can_do_single_step target_ops method. */
15055
15056 int
15057 remote_target::can_do_single_step ()
15058 {
15059 /* We can only tell whether target supports single step or not by
15060 supported s and S vCont actions if the stub supports vContSupported
15061 feature. If the stub doesn't support vContSupported feature,
15062 we have conservatively to think target doesn't supports single
15063 step. */
15064 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
15065 {
15066 struct remote_state *rs = get_remote_state ();
15067
15068 return rs->supports_vCont.s && rs->supports_vCont.S;
15069 }
15070 else
15071 return 0;
15072 }
15073
15074 /* Implementation of the to_execution_direction method for the remote
15075 target. */
15076
15077 enum exec_direction_kind
15078 remote_target::execution_direction ()
15079 {
15080 struct remote_state *rs = get_remote_state ();
15081
15082 return rs->last_resume_exec_dir;
15083 }
15084
15085 /* Return pointer to the thread_info struct which corresponds to
15086 THREAD_HANDLE (having length HANDLE_LEN). */
15087
15088 thread_info *
15089 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
15090 int handle_len,
15091 inferior *inf)
15092 {
15093 for (thread_info *tp : all_non_exited_threads (this))
15094 {
15095 remote_thread_info *priv = get_remote_thread_info (tp);
15096
15097 if (tp->inf == inf && priv != NULL)
15098 {
15099 if (handle_len != priv->thread_handle.size ())
15100 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
15101 handle_len, priv->thread_handle.size ());
15102 if (memcmp (thread_handle, priv->thread_handle.data (),
15103 handle_len) == 0)
15104 return tp;
15105 }
15106 }
15107
15108 return NULL;
15109 }
15110
15111 gdb::array_view<const gdb_byte>
15112 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15113 {
15114 remote_thread_info *priv = get_remote_thread_info (tp);
15115 return priv->thread_handle;
15116 }
15117
15118 bool
15119 remote_target::can_async_p ()
15120 {
15121 /* This flag should be checked in the common target.c code. */
15122 gdb_assert (target_async_permitted);
15123
15124 /* We're async whenever the serial device can. */
15125 return get_remote_state ()->can_async_p ();
15126 }
15127
15128 bool
15129 remote_target::is_async_p ()
15130 {
15131 /* We're async whenever the serial device is. */
15132 return get_remote_state ()->is_async_p ();
15133 }
15134
15135 /* Pass the SERIAL event on and up to the client. One day this code
15136 will be able to delay notifying the client of an event until the
15137 point where an entire packet has been received. */
15138
15139 static serial_event_ftype remote_async_serial_handler;
15140
15141 static void
15142 remote_async_serial_handler (struct serial *scb, void *context)
15143 {
15144 /* Don't propogate error information up to the client. Instead let
15145 the client find out about the error by querying the target. */
15146 inferior_event_handler (INF_REG_EVENT);
15147 }
15148
15149 int
15150 remote_target::async_wait_fd ()
15151 {
15152 struct remote_state *rs = get_remote_state ();
15153 return rs->remote_desc->fd;
15154 }
15155
15156 void
15157 remote_target::async (bool enable)
15158 {
15159 struct remote_state *rs = get_remote_state ();
15160
15161 if (enable)
15162 {
15163 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15164
15165 /* If there are pending events in the stop reply queue tell the
15166 event loop to process them. */
15167 if (!rs->stop_reply_queue.empty ())
15168 rs->mark_async_event_handler ();
15169
15170 /* For simplicity, below we clear the pending events token
15171 without remembering whether it is marked, so here we always
15172 mark it. If there's actually no pending notification to
15173 process, this ends up being a no-op (other than a spurious
15174 event-loop wakeup). */
15175 if (target_is_non_stop_p ())
15176 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15177 }
15178 else
15179 {
15180 serial_async (rs->remote_desc, NULL, NULL);
15181 /* If the core is disabling async, it doesn't want to be
15182 disturbed with target events. Clear all async event sources
15183 too. */
15184 rs->clear_async_event_handler ();
15185
15186 if (target_is_non_stop_p ())
15187 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15188 }
15189 }
15190
15191 /* Implementation of the to_thread_events method. */
15192
15193 void
15194 remote_target::thread_events (int enable)
15195 {
15196 struct remote_state *rs = get_remote_state ();
15197 size_t size = get_remote_packet_size ();
15198
15199 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15200 return;
15201
15202 if (rs->last_thread_events == enable)
15203 return;
15204
15205 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15206 putpkt (rs->buf);
15207 getpkt (&rs->buf);
15208
15209 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadEvents);
15210 switch (result.status ())
15211 {
15212 case PACKET_OK:
15213 if (strcmp (rs->buf.data (), "OK") != 0)
15214 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15215 rs->last_thread_events = enable;
15216 break;
15217 case PACKET_ERROR:
15218 warning (_("Remote failure reply: %s"), result.err_msg ());
15219 break;
15220 case PACKET_UNKNOWN:
15221 break;
15222 }
15223 }
15224
15225 /* Implementation of the supports_set_thread_options target
15226 method. */
15227
15228 bool
15229 remote_target::supports_set_thread_options (gdb_thread_options options)
15230 {
15231 remote_state *rs = get_remote_state ();
15232 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15233 && (rs->supported_thread_options & options) == options);
15234 }
15235
15236 /* For coalescing reasons, actually sending the options to the target
15237 happens at resume time, via this function. See target_resume for
15238 all-stop, and target_commit_resumed for non-stop. */
15239
15240 void
15241 remote_target::commit_requested_thread_options ()
15242 {
15243 struct remote_state *rs = get_remote_state ();
15244
15245 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15246 return;
15247
15248 char *p = rs->buf.data ();
15249 char *endp = p + get_remote_packet_size ();
15250
15251 /* Clear options for all threads by default. Note that unlike
15252 vCont, the rightmost options that match a thread apply, so we
15253 don't have to worry about whether we can use wildcard ptids. */
15254 strcpy (p, "QThreadOptions;0");
15255 p += strlen (p);
15256
15257 /* Send the QThreadOptions packet stored in P. */
15258 auto flush = [&] ()
15259 {
15260 *p++ = '\0';
15261
15262 putpkt (rs->buf);
15263 getpkt (&rs->buf, 0);
15264
15265 packet_result result = m_features.packet_ok (rs->buf, PACKET_QThreadOptions);
15266 switch (result.status ())
15267 {
15268 case PACKET_OK:
15269 if (strcmp (rs->buf.data (), "OK") != 0)
15270 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15271 break;
15272 case PACKET_ERROR:
15273 error (_("Remote failure reply: %s"), result.err_msg ());
15274 case PACKET_UNKNOWN:
15275 gdb_assert_not_reached ("PACKET_UNKNOWN");
15276 break;
15277 }
15278 };
15279
15280 /* Prepare P for another QThreadOptions packet. */
15281 auto restart = [&] ()
15282 {
15283 p = rs->buf.data ();
15284 strcpy (p, "QThreadOptions");
15285 p += strlen (p);
15286 };
15287
15288 /* Now set non-zero options for threads that need them. We don't
15289 bother with the case of all threads of a process wanting the same
15290 non-zero options as that's not an expected scenario. */
15291 for (thread_info *tp : all_non_exited_threads (this))
15292 {
15293 gdb_thread_options options = tp->thread_options ();
15294
15295 if (options == 0)
15296 continue;
15297
15298 /* It might be possible to we have more threads with options
15299 than can fit a single QThreadOptions packet. So build each
15300 options/thread pair in this separate buffer to make sure it
15301 fits. */
15302 constexpr size_t max_options_size = 100;
15303 char obuf[max_options_size];
15304 char *obuf_p = obuf;
15305 char *obuf_endp = obuf + max_options_size;
15306
15307 *obuf_p++ = ';';
15308 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15309 phex_nz (options, sizeof (options)));
15310 if (tp->ptid != magic_null_ptid)
15311 {
15312 *obuf_p++ = ':';
15313 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15314 }
15315
15316 size_t osize = obuf_p - obuf;
15317 if (osize > endp - p)
15318 {
15319 /* This new options/thread pair doesn't fit the packet
15320 buffer. Send what we have already. */
15321 flush ();
15322 restart ();
15323
15324 /* Should now fit. */
15325 gdb_assert (osize <= endp - p);
15326 }
15327
15328 memcpy (p, obuf, osize);
15329 p += osize;
15330 }
15331
15332 flush ();
15333 }
15334
15335 static void
15336 show_remote_cmd (const char *args, int from_tty)
15337 {
15338 /* We can't just use cmd_show_list here, because we want to skip
15339 the redundant "show remote Z-packet" and the legacy aliases. */
15340 struct cmd_list_element *list = remote_show_cmdlist;
15341 struct ui_out *uiout = current_uiout;
15342
15343 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15344 for (; list != NULL; list = list->next)
15345 if (strcmp (list->name, "Z-packet") == 0)
15346 continue;
15347 else if (list->type == not_set_cmd)
15348 /* Alias commands are exactly like the original, except they
15349 don't have the normal type. */
15350 continue;
15351 else
15352 {
15353 ui_out_emit_tuple option_emitter (uiout, "option");
15354
15355 uiout->field_string ("name", list->name);
15356 uiout->text (": ");
15357 if (list->type == show_cmd)
15358 do_show_command (NULL, from_tty, list);
15359 else
15360 cmd_func (list, NULL, from_tty);
15361 }
15362 }
15363
15364 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15365 offer all inferiors using that program space a change to look up symbols. */
15366
15367 static void
15368 remote_objfile_changed_check_symbols (program_space *pspace)
15369 {
15370 /* The affected program space is possibly shared by multiple inferiors.
15371 Consider sending a qSymbol packet for each of the inferiors using that
15372 program space. */
15373 for (inferior *inf : all_inferiors ())
15374 {
15375 if (inf->pspace != pspace)
15376 continue;
15377
15378 /* Check whether the inferior's process target is a remote target. */
15379 remote_target *remote = as_remote_target (inf->process_target ());
15380 if (remote == nullptr)
15381 continue;
15382
15383 /* When we are attaching or handling a fork child and the shared library
15384 subsystem reads the list of loaded libraries, we receive new objfile
15385 events in between each found library. The libraries are read in an
15386 undefined order, so if we gave the remote side a chance to look up
15387 symbols between each objfile, we might give it an inconsistent picture
15388 of the inferior. It could appear that a library A appears loaded but
15389 a library B does not, even though library A requires library B. That
15390 would present a state that couldn't normally exist in the inferior.
15391
15392 So, skip these events, we'll give the remote a chance to look up
15393 symbols once all the loaded libraries and their symbols are known to
15394 GDB. */
15395 if (inf->in_initial_library_scan)
15396 continue;
15397
15398 if (!remote->has_execution (inf))
15399 continue;
15400
15401 /* Need to switch to a specific thread, because remote_check_symbols will
15402 set the general thread using INFERIOR_PTID.
15403
15404 It's possible to have inferiors with no thread here, because we are
15405 called very early in the connection process, while the inferior is
15406 being set up, before threads are added. Just skip it, start_remote_1
15407 also calls remote_check_symbols when it's done setting things up. */
15408 thread_info *thread = any_thread_of_inferior (inf);
15409 if (thread != nullptr)
15410 {
15411 scoped_restore_current_thread restore_thread;
15412 switch_to_thread (thread);
15413 remote->remote_check_symbols ();
15414 }
15415 }
15416 }
15417
15418 /* Function to be called whenever a new objfile (shlib) is detected. */
15419
15420 static void
15421 remote_new_objfile (struct objfile *objfile)
15422 {
15423 remote_objfile_changed_check_symbols (objfile->pspace);
15424 }
15425
15426 /* Pull all the tracepoints defined on the target and create local
15427 data structures representing them. We don't want to create real
15428 tracepoints yet, we don't want to mess up the user's existing
15429 collection. */
15430
15431 int
15432 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15433 {
15434 struct remote_state *rs = get_remote_state ();
15435 char *p;
15436
15437 /* Ask for a first packet of tracepoint definition. */
15438 putpkt ("qTfP");
15439 getpkt (&rs->buf);
15440 p = rs->buf.data ();
15441 while (*p && *p != 'l')
15442 {
15443 parse_tracepoint_definition (p, utpp);
15444 /* Ask for another packet of tracepoint definition. */
15445 putpkt ("qTsP");
15446 getpkt (&rs->buf);
15447 p = rs->buf.data ();
15448 }
15449 return 0;
15450 }
15451
15452 int
15453 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15454 {
15455 struct remote_state *rs = get_remote_state ();
15456 char *p;
15457
15458 /* Ask for a first packet of variable definition. */
15459 putpkt ("qTfV");
15460 getpkt (&rs->buf);
15461 p = rs->buf.data ();
15462 while (*p && *p != 'l')
15463 {
15464 parse_tsv_definition (p, utsvp);
15465 /* Ask for another packet of variable definition. */
15466 putpkt ("qTsV");
15467 getpkt (&rs->buf);
15468 p = rs->buf.data ();
15469 }
15470 return 0;
15471 }
15472
15473 /* The "set/show range-stepping" show hook. */
15474
15475 static void
15476 show_range_stepping (struct ui_file *file, int from_tty,
15477 struct cmd_list_element *c,
15478 const char *value)
15479 {
15480 gdb_printf (file,
15481 _("Debugger's willingness to use range stepping "
15482 "is %s.\n"), value);
15483 }
15484
15485 /* Return true if the vCont;r action is supported by the remote
15486 stub. */
15487
15488 bool
15489 remote_target::vcont_r_supported ()
15490 {
15491 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15492 && get_remote_state ()->supports_vCont.r);
15493 }
15494
15495 /* The "set/show range-stepping" set hook. */
15496
15497 static void
15498 set_range_stepping (const char *ignore_args, int from_tty,
15499 struct cmd_list_element *c)
15500 {
15501 /* When enabling, check whether range stepping is actually supported
15502 by the target, and warn if not. */
15503 if (use_range_stepping)
15504 {
15505 remote_target *remote = get_current_remote_target ();
15506 if (remote == NULL
15507 || !remote->vcont_r_supported ())
15508 warning (_("Range stepping is not supported by the current target"));
15509 }
15510 }
15511
15512 static void
15513 show_remote_debug (struct ui_file *file, int from_tty,
15514 struct cmd_list_element *c, const char *value)
15515 {
15516 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15517 value);
15518 }
15519
15520 static void
15521 show_remote_timeout (struct ui_file *file, int from_tty,
15522 struct cmd_list_element *c, const char *value)
15523 {
15524 gdb_printf (file,
15525 _("Timeout limit to wait for target to respond is %s.\n"),
15526 value);
15527 }
15528
15529 /* Implement the "supports_memory_tagging" target_ops method. */
15530
15531 bool
15532 remote_target::supports_memory_tagging ()
15533 {
15534 return m_features.remote_memory_tagging_p ();
15535 }
15536
15537 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15538
15539 static void
15540 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15541 size_t len, int type)
15542 {
15543 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15544
15545 std::string request = string_printf ("qMemTags:%s,%s:%s",
15546 phex_nz (address, addr_size),
15547 phex_nz (len, sizeof (len)),
15548 phex_nz (type, sizeof (type)));
15549
15550 strcpy (packet.data (), request.c_str ());
15551 }
15552
15553 /* Parse the qMemTags packet reply into TAGS.
15554
15555 Return true if successful, false otherwise. */
15556
15557 static bool
15558 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15559 gdb::byte_vector &tags)
15560 {
15561 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15562 return false;
15563
15564 /* Copy the tag data. */
15565 tags = hex2bin (reply.data () + 1);
15566
15567 return true;
15568 }
15569
15570 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15571
15572 static void
15573 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15574 size_t len, int type,
15575 const gdb::byte_vector &tags)
15576 {
15577 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15578
15579 /* Put together the main packet, address and length. */
15580 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15581 phex_nz (address, addr_size),
15582 phex_nz (len, sizeof (len)),
15583 phex_nz (type, sizeof (type)));
15584 request += bin2hex (tags.data (), tags.size ());
15585
15586 /* Check if we have exceeded the maximum packet size. */
15587 if (packet.size () < request.length ())
15588 error (_("Contents too big for packet QMemTags."));
15589
15590 strcpy (packet.data (), request.c_str ());
15591 }
15592
15593 static void
15594 create_is_address_tagged_request (gdbarch *gdbarch, gdb::char_vector &packet,
15595 CORE_ADDR address)
15596 {
15597 int addr_size;
15598 std::string request;
15599
15600 addr_size = gdbarch_addr_bit (gdbarch) / 8;
15601 request = string_printf ("qIsAddressTagged:%s", phex_nz (address, addr_size));
15602
15603 if (packet.size () < request.length () + 1)
15604 error (_("Contents too big for packet qIsAddressTagged."));
15605
15606 strcpy (packet.data (), request.c_str ());
15607 }
15608
15609 static bool
15610 check_is_address_tagged_reply (remote_target *remote, gdb::char_vector &packet,
15611 bool &tagged)
15612 {
15613 gdb_assert (remote != nullptr);
15614 /* Check reply and disable qIsAddressTagged usage if it's not supported. */
15615 packet_result result = remote->m_features.packet_ok (packet,
15616 PACKET_qIsAddressTagged);
15617
15618 /* Return false on error (Exx), empty reply (packet not supported), or reply
15619 size doesn't match 2 hex digits. */
15620 if ((result.status () != PACKET_OK) || (strlen (packet.data ()) != 2))
15621 return false;
15622
15623 gdb_byte reply;
15624 /* Convert only 2 hex digits, i.e. 1 byte in hex format. */
15625 hex2bin (packet.data (), &reply, 1);
15626
15627 if (reply == 0x00 || reply == 0x01)
15628 {
15629 tagged = !!reply;
15630 return true;
15631 }
15632
15633 /* Invalid reply. */
15634 return false;
15635 }
15636
15637 /* Implement the "fetch_memtags" target_ops method. */
15638
15639 bool
15640 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15641 gdb::byte_vector &tags, int type)
15642 {
15643 /* Make sure the qMemTags packet is supported. */
15644 if (!m_features.remote_memory_tagging_p ())
15645 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15646
15647 struct remote_state *rs = get_remote_state ();
15648
15649 create_fetch_memtags_request (rs->buf, address, len, type);
15650
15651 putpkt (rs->buf);
15652 getpkt (&rs->buf);
15653
15654 return parse_fetch_memtags_reply (rs->buf, tags);
15655 }
15656
15657 /* Implement the "store_memtags" target_ops method. */
15658
15659 bool
15660 remote_target::store_memtags (CORE_ADDR address, size_t len,
15661 const gdb::byte_vector &tags, int type)
15662 {
15663 /* Make sure the QMemTags packet is supported. */
15664 if (!m_features.remote_memory_tagging_p ())
15665 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15666
15667 struct remote_state *rs = get_remote_state ();
15668
15669 create_store_memtags_request (rs->buf, address, len, type, tags);
15670
15671 putpkt (rs->buf);
15672 getpkt (&rs->buf);
15673
15674 /* Verify if the request was successful. */
15675 return packet_check_result (rs->buf, true).status () == PACKET_OK;
15676 }
15677
15678 /* Implement the "is_address_tagged" target_ops method. */
15679
15680 bool
15681 remote_target::is_address_tagged (gdbarch *gdbarch, CORE_ADDR address)
15682 {
15683 /* Firstly, attempt to check the address using the qIsAddressTagged
15684 packet. */
15685 if (m_features.packet_support (PACKET_qIsAddressTagged) != PACKET_DISABLE)
15686 {
15687 remote_target *remote = get_current_remote_target ();
15688 struct remote_state *rs = get_remote_state ();
15689 bool is_addr_tagged;
15690
15691 create_is_address_tagged_request (gdbarch, rs->buf, address);
15692
15693 putpkt (rs->buf);
15694 getpkt (&rs->buf);
15695
15696 /* If qIsAddressTagged is not supported PACKET_qIsAddressTagged will be
15697 set to PACKET_DISABLE so no further attempt is made to check addresses
15698 using this packet and the fallback mechanism below will be used
15699 instead. Also, if the check fails due to an error (Exx reply) the
15700 fallback is used too. Otherwise, the qIsAddressTagged query succeeded
15701 and is_addr_tagged is valid. */
15702 if (check_is_address_tagged_reply (remote, rs->buf, is_addr_tagged))
15703 return is_addr_tagged;
15704 }
15705
15706 /* Fallback to arch-specific method of checking whether an address is tagged
15707 in case check via qIsAddressTagged fails. */
15708 return gdbarch_tagged_address_p (gdbarch, address);
15709 }
15710
15711 /* Return true if remote target T is non-stop. */
15712
15713 bool
15714 remote_target_is_non_stop_p (remote_target *t)
15715 {
15716 scoped_restore_current_thread restore_thread;
15717 switch_to_target_no_thread (t);
15718
15719 return target_is_non_stop_p ();
15720 }
15721
15722 #if GDB_SELF_TEST
15723
15724 namespace selftests {
15725
15726 static void
15727 test_memory_tagging_functions ()
15728 {
15729 remote_target remote;
15730
15731 struct packet_config *config
15732 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15733
15734 scoped_restore restore_memtag_support_
15735 = make_scoped_restore (&config->support);
15736
15737 struct gdbarch *gdbarch = current_inferior ()->arch ();
15738
15739 /* Test memory tagging packet support. */
15740 config->support = PACKET_SUPPORT_UNKNOWN;
15741 SELF_CHECK (remote.supports_memory_tagging () == false);
15742 config->support = PACKET_DISABLE;
15743 SELF_CHECK (remote.supports_memory_tagging () == false);
15744 config->support = PACKET_ENABLE;
15745 SELF_CHECK (remote.supports_memory_tagging () == true);
15746
15747 /* Setup testing. */
15748 gdb::char_vector packet;
15749 gdb::byte_vector tags, bv;
15750 std::string expected, reply;
15751 packet.resize (32000);
15752
15753 /* Test creating a qMemTags request. */
15754
15755 expected = "qMemTags:0,0:0";
15756 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15757 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15758
15759 expected = "qMemTags:deadbeef,10:1";
15760 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15761 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15762
15763 /* Test parsing a qMemTags reply. */
15764
15765 /* Error reply, tags vector unmodified. */
15766 reply = "E00";
15767 strcpy (packet.data (), reply.c_str ());
15768 tags.resize (0);
15769 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15770 SELF_CHECK (tags.size () == 0);
15771
15772 /* Valid reply, tags vector updated. */
15773 tags.resize (0);
15774 bv.resize (0);
15775
15776 for (int i = 0; i < 5; i++)
15777 bv.push_back (i);
15778
15779 reply = "m" + bin2hex (bv.data (), bv.size ());
15780 strcpy (packet.data (), reply.c_str ());
15781
15782 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15783 SELF_CHECK (tags.size () == 5);
15784
15785 for (int i = 0; i < 5; i++)
15786 SELF_CHECK (tags[i] == i);
15787
15788 /* Test creating a QMemTags request. */
15789
15790 /* Empty tag data. */
15791 tags.resize (0);
15792 expected = "QMemTags:0,0:0:";
15793 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15794 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15795 expected.length ()) == 0);
15796
15797 /* Non-empty tag data. */
15798 tags.resize (0);
15799 for (int i = 0; i < 5; i++)
15800 tags.push_back (i);
15801 expected = "QMemTags:deadbeef,ff:1:0001020304";
15802 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15803 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15804 expected.length ()) == 0);
15805
15806 /* Test creating a qIsAddressTagged request. */
15807 expected = "qIsAddressTagged:deadbeef";
15808 create_is_address_tagged_request (gdbarch, packet, 0xdeadbeef);
15809 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15810
15811 /* Test error reply on qIsAddressTagged request. */
15812 reply = "E00";
15813 strcpy (packet.data (), reply.c_str ());
15814 /* is_tagged must not change, hence it's tested too. */
15815 bool is_tagged = false;
15816 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15817 false);
15818 SELF_CHECK (is_tagged == false);
15819
15820 /* Test 'tagged' as reply. */
15821 reply = "01";
15822 strcpy (packet.data (), reply.c_str ());
15823 /* Because the byte is 01, is_tagged should be set to true. */
15824 is_tagged = false;
15825 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15826 true);
15827 SELF_CHECK (is_tagged == true);
15828
15829 /* Test 'not tagged' as reply. */
15830 reply = "00";
15831 strcpy (packet.data (), reply.c_str ());
15832 /* Because the byte is 00, is_tagged should be set to false. */
15833 is_tagged = true;
15834 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15835 true);
15836 SELF_CHECK (is_tagged == false);
15837
15838 /* Test an invalid reply (neither 00 nor 01). */
15839 reply = "04";
15840 strcpy (packet.data (), reply.c_str ());
15841 /* Because the byte is invalid is_tagged must not change. */
15842 is_tagged = false;
15843 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15844 false);
15845 SELF_CHECK (is_tagged == false);
15846
15847 /* Test malformed reply of incorrect length. */
15848 reply = "0104A590001234006";
15849 strcpy (packet.data (), reply.c_str ());
15850 /* Because this is a malformed reply is_tagged must not change. */
15851 is_tagged = false;
15852 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15853 false);
15854 SELF_CHECK (is_tagged == false);
15855
15856 /* Test empty reply. */
15857 reply = "";
15858 strcpy (packet.data (), reply.c_str ());
15859 /* is_tagged must not change, hence it's tested too. */
15860 is_tagged = true;
15861 /* On the previous tests, qIsAddressTagged packet was auto detected and set
15862 as supported. But an empty reply means the packet is unsupported, so for
15863 testing the empty reply the support is reset to unknown state, otherwise
15864 packet_ok will complain. */
15865 remote.m_features.m_protocol_packets[PACKET_qIsAddressTagged].support =
15866 PACKET_SUPPORT_UNKNOWN;
15867 SELF_CHECK (check_is_address_tagged_reply (&remote, packet, is_tagged) ==
15868 false);
15869 SELF_CHECK (is_tagged == true);
15870 }
15871
15872 static void
15873 test_packet_check_result ()
15874 {
15875 std::string buf = "E.msg";
15876 packet_result result = packet_check_result (buf.data (), true);
15877
15878 SELF_CHECK (result.status () == PACKET_ERROR);
15879 SELF_CHECK (strcmp(result.err_msg (), "msg") == 0);
15880
15881 result = packet_check_result ("E01", true);
15882 SELF_CHECK (result.status () == PACKET_ERROR);
15883 SELF_CHECK (strcmp(result.err_msg (), "01") == 0);
15884
15885 SELF_CHECK (packet_check_result ("E1", true).status () == PACKET_OK);
15886
15887 SELF_CHECK (packet_check_result ("E000", true).status () == PACKET_OK);
15888
15889 result = packet_check_result ("E.", true);
15890 SELF_CHECK (result.status () == PACKET_ERROR);
15891 SELF_CHECK (strcmp(result.err_msg (), "no error provided") == 0);
15892
15893 SELF_CHECK (packet_check_result ("some response", true).status () == PACKET_OK);
15894
15895 SELF_CHECK (packet_check_result ("", true).status () == PACKET_UNKNOWN);
15896
15897 result = packet_check_result ("E.msg", false);
15898 SELF_CHECK (result.status () == PACKET_OK);
15899 }
15900 } // namespace selftests
15901 #endif /* GDB_SELF_TEST */
15902
15903 void _initialize_remote ();
15904 void
15905 _initialize_remote ()
15906 {
15907 add_target (remote_target_info, remote_target::open);
15908 add_target (extended_remote_target_info, extended_remote_target::open);
15909
15910 /* Hook into new objfile notification. */
15911 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15912 gdb::observers::all_objfiles_removed.attach
15913 (remote_objfile_changed_check_symbols, "remote");
15914
15915 #if 0
15916 init_remote_threadtests ();
15917 #endif
15918
15919 /* set/show remote ... */
15920
15921 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15922 Remote protocol specific variables.\n\
15923 Configure various remote-protocol specific variables such as\n\
15924 the packets being used."),
15925 &remote_set_cmdlist,
15926 0 /* allow-unknown */, &setlist);
15927 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15928 Remote protocol specific variables.\n\
15929 Configure various remote-protocol specific variables such as\n\
15930 the packets being used."),
15931 &remote_show_cmdlist,
15932 0 /* allow-unknown */, &showlist);
15933
15934 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15935 Compare section data on target to the exec file.\n\
15936 Argument is a single section name (default: all loaded sections).\n\
15937 To compare only read-only loaded sections, specify the -r option."),
15938 &cmdlist);
15939
15940 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15941 Send an arbitrary packet to a remote target.\n\
15942 maintenance packet TEXT\n\
15943 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15944 this command sends the string TEXT to the inferior, and displays the\n\
15945 response packet. GDB supplies the initial `$' character, and the\n\
15946 terminating `#' character and checksum."),
15947 &maintenancelist);
15948
15949 set_show_commands remotebreak_cmds
15950 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15951 Set whether to send break if interrupted."), _("\
15952 Show whether to send break if interrupted."), _("\
15953 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15954 set_remotebreak, show_remotebreak,
15955 &setlist, &showlist);
15956 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15957 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15958
15959 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15960 interrupt_sequence_modes, &interrupt_sequence_mode,
15961 _("\
15962 Set interrupt sequence to remote target."), _("\
15963 Show interrupt sequence to remote target."), _("\
15964 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15965 NULL, show_interrupt_sequence,
15966 &remote_set_cmdlist,
15967 &remote_show_cmdlist);
15968
15969 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15970 &interrupt_on_connect, _("\
15971 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15972 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15973 If set, interrupt sequence is sent to remote target."),
15974 NULL, NULL,
15975 &remote_set_cmdlist, &remote_show_cmdlist);
15976
15977 /* Install commands for configuring memory read/write packets. */
15978
15979 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15980 Set the maximum number of bytes per memory write packet (deprecated)."),
15981 &setlist);
15982 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15983 Show the maximum number of bytes per memory write packet (deprecated)."),
15984 &showlist);
15985 add_cmd ("memory-write-packet-size", no_class,
15986 set_memory_write_packet_size, _("\
15987 Set the maximum number of bytes per memory-write packet.\n\
15988 Specify the number of bytes in a packet or 0 (zero) for the\n\
15989 default packet size. The actual limit is further reduced\n\
15990 dependent on the target. Specify \"fixed\" to disable the\n\
15991 further restriction and \"limit\" to enable that restriction."),
15992 &remote_set_cmdlist);
15993 add_cmd ("memory-read-packet-size", no_class,
15994 set_memory_read_packet_size, _("\
15995 Set the maximum number of bytes per memory-read packet.\n\
15996 Specify the number of bytes in a packet or 0 (zero) for the\n\
15997 default packet size. The actual limit is further reduced\n\
15998 dependent on the target. Specify \"fixed\" to disable the\n\
15999 further restriction and \"limit\" to enable that restriction."),
16000 &remote_set_cmdlist);
16001 add_cmd ("memory-write-packet-size", no_class,
16002 show_memory_write_packet_size,
16003 _("Show the maximum number of bytes per memory-write packet."),
16004 &remote_show_cmdlist);
16005 add_cmd ("memory-read-packet-size", no_class,
16006 show_memory_read_packet_size,
16007 _("Show the maximum number of bytes per memory-read packet."),
16008 &remote_show_cmdlist);
16009
16010 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
16011 &remote_hw_watchpoint_limit, _("\
16012 Set the maximum number of target hardware watchpoints."), _("\
16013 Show the maximum number of target hardware watchpoints."), _("\
16014 Specify \"unlimited\" for unlimited hardware watchpoints."),
16015 NULL, show_hardware_watchpoint_limit,
16016 &remote_set_cmdlist,
16017 &remote_show_cmdlist);
16018 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
16019 no_class,
16020 &remote_hw_watchpoint_length_limit, _("\
16021 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
16022 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
16023 Specify \"unlimited\" to allow watchpoints of unlimited size."),
16024 NULL, show_hardware_watchpoint_length_limit,
16025 &remote_set_cmdlist, &remote_show_cmdlist);
16026 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
16027 &remote_hw_breakpoint_limit, _("\
16028 Set the maximum number of target hardware breakpoints."), _("\
16029 Show the maximum number of target hardware breakpoints."), _("\
16030 Specify \"unlimited\" for unlimited hardware breakpoints."),
16031 NULL, show_hardware_breakpoint_limit,
16032 &remote_set_cmdlist, &remote_show_cmdlist);
16033
16034 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
16035 &remote_address_size, _("\
16036 Set the maximum size of the address (in bits) in a memory packet."), _("\
16037 Show the maximum size of the address (in bits) in a memory packet."), NULL,
16038 NULL,
16039 NULL, /* FIXME: i18n: */
16040 &setlist, &showlist);
16041
16042 init_all_packet_configs ();
16043
16044 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
16045
16046 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
16047
16048 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
16049 0);
16050
16051 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
16052 "catch-syscalls", 0);
16053
16054 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
16055 "program-signals", 0);
16056
16057 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
16058 "set-working-dir", 0);
16059
16060 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
16061 "startup-with-shell", 0);
16062
16063 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
16064 "environment-hex-encoded", 0);
16065
16066 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
16067 "environment-reset", 0);
16068
16069 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
16070 "environment-unset", 0);
16071
16072 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
16073
16074 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
16075
16076 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
16077
16078 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
16079
16080 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
16081
16082 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
16083
16084 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
16085
16086 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
16087
16088 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
16089 "read-aux-vector", 0);
16090
16091 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
16092 "pid-to-exec-file", 0);
16093
16094 add_packet_config_cmd (PACKET_qXfer_features,
16095 "qXfer:features:read", "target-features", 0);
16096
16097 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
16098 "library-info", 0);
16099
16100 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
16101 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
16102
16103 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
16104 "memory-map", 0);
16105
16106 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
16107
16108 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
16109 0);
16110
16111 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
16112 "read-siginfo-object", 0);
16113
16114 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
16115 "write-siginfo-object", 0);
16116
16117 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
16118 "qXfer:traceframe-info:read", "traceframe-info", 0);
16119
16120 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
16121 "unwind-info-block", 0);
16122
16123 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
16124 "get-thread-local-storage-address", 0);
16125
16126 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
16127 "get-thread-information-block-address", 0);
16128
16129 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
16130
16131 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
16132
16133 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
16134 0);
16135
16136 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
16137 "search-memory", 0);
16138
16139 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
16140
16141 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
16142
16143 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
16144
16145 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
16146
16147 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
16148 0);
16149
16150 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
16151
16152 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
16153 0);
16154
16155 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
16156 "hostio-readlink", 0);
16157
16158 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
16159
16160 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
16161
16162 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
16163
16164 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
16165
16166 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
16167
16168 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
16169
16170 add_packet_config_cmd (PACKET_ConditionalTracepoints,
16171 "ConditionalTracepoints", "conditional-tracepoints",
16172 0);
16173
16174 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
16175 "ConditionalBreakpoints", "conditional-breakpoints",
16176 0);
16177
16178 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
16179 "breakpoint-commands", 0);
16180
16181 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
16182 "fast-tracepoints", 0);
16183
16184 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
16185 "TracepointSource", 0);
16186
16187 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
16188
16189 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
16190 "static-tracepoints", 0);
16191
16192 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
16193 "install-in-trace", 0);
16194
16195 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
16196 "qXfer:statictrace:read", "read-sdata-object", 0);
16197
16198 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
16199 "read-fdpic-loadmap", 0);
16200
16201 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
16202 "disable-randomization", 0);
16203
16204 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
16205
16206 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
16207 "trace-buffer-size", 0);
16208
16209 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
16210 0);
16211
16212 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
16213 0);
16214
16215 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
16216 0);
16217
16218 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
16219
16220 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
16221 "read-btrace-conf", 0);
16222
16223 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
16224 "btrace-conf-bts-size", 0);
16225
16226 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
16227 "multiprocess-feature", 0);
16228
16229 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
16230 "swbreak-feature", 0);
16231
16232 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
16233 "hwbreak-feature", 0);
16234
16235 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
16236 "fork-event-feature", 0);
16237
16238 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
16239 "vfork-event-feature", 0);
16240
16241 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
16242 "btrace-conf-pt-size", 0);
16243
16244 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
16245 "verbose-resume-supported", 0);
16246
16247 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
16248 "exec-event-feature", 0);
16249
16250 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
16251
16252 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
16253 0);
16254
16255 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
16256 "thread-options", 0);
16257
16258 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
16259 "no-resumed-stop-reply", 0);
16260
16261 add_packet_config_cmd (PACKET_memory_tagging_feature,
16262 "memory-tagging-feature", "memory-tagging-feature", 0);
16263
16264 add_packet_config_cmd (PACKET_qIsAddressTagged,
16265 "qIsAddressTagged", "memory-tagging-address-check", 0);
16266
16267 /* Assert that we've registered "set remote foo-packet" commands
16268 for all packet configs. */
16269 {
16270 int i;
16271
16272 for (i = 0; i < PACKET_MAX; i++)
16273 {
16274 /* Ideally all configs would have a command associated. Some
16275 still don't though. */
16276 int excepted;
16277
16278 switch (i)
16279 {
16280 case PACKET_QNonStop:
16281 case PACKET_EnableDisableTracepoints_feature:
16282 case PACKET_tracenz_feature:
16283 case PACKET_DisconnectedTracing_feature:
16284 case PACKET_augmented_libraries_svr4_read_feature:
16285 case PACKET_qCRC:
16286 /* Additions to this list need to be well justified:
16287 pre-existing packets are OK; new packets are not. */
16288 excepted = 1;
16289 break;
16290 default:
16291 excepted = 0;
16292 break;
16293 }
16294
16295 /* This catches both forgetting to add a config command, and
16296 forgetting to remove a packet from the exception list. */
16297 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16298 }
16299 }
16300
16301 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16302 Z sub-packet has its own set and show commands, but users may
16303 have sets to this variable in their .gdbinit files (or in their
16304 documentation). */
16305 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16306 &remote_Z_packet_detect, _("\
16307 Set use of remote protocol `Z' packets."), _("\
16308 Show use of remote protocol `Z' packets."), _("\
16309 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16310 packets."),
16311 set_remote_protocol_Z_packet_cmd,
16312 show_remote_protocol_Z_packet_cmd,
16313 /* FIXME: i18n: Use of remote protocol
16314 `Z' packets is %s. */
16315 &remote_set_cmdlist, &remote_show_cmdlist);
16316
16317 add_basic_prefix_cmd ("remote", class_files, _("\
16318 Manipulate files on the remote system.\n\
16319 Transfer files to and from the remote target system."),
16320 &remote_cmdlist,
16321 0 /* allow-unknown */, &cmdlist);
16322
16323 add_cmd ("put", class_files, remote_put_command,
16324 _("Copy a local file to the remote system."),
16325 &remote_cmdlist);
16326
16327 add_cmd ("get", class_files, remote_get_command,
16328 _("Copy a remote file to the local system."),
16329 &remote_cmdlist);
16330
16331 add_cmd ("delete", class_files, remote_delete_command,
16332 _("Delete a remote file."),
16333 &remote_cmdlist);
16334
16335 add_setshow_string_noescape_cmd ("exec-file", class_files,
16336 &remote_exec_file_var, _("\
16337 Set the remote pathname for \"run\"."), _("\
16338 Show the remote pathname for \"run\"."), NULL,
16339 set_remote_exec_file,
16340 show_remote_exec_file,
16341 &remote_set_cmdlist,
16342 &remote_show_cmdlist);
16343
16344 add_setshow_boolean_cmd ("range-stepping", class_run,
16345 &use_range_stepping, _("\
16346 Enable or disable range stepping."), _("\
16347 Show whether target-assisted range stepping is enabled."), _("\
16348 If on, and the target supports it, when stepping a source line, GDB\n\
16349 tells the target to step the corresponding range of addresses itself instead\n\
16350 of issuing multiple single-steps. This speeds up source level\n\
16351 stepping. If off, GDB always issues single-steps, even if range\n\
16352 stepping is supported by the target. The default is on."),
16353 set_range_stepping,
16354 show_range_stepping,
16355 &setlist,
16356 &showlist);
16357
16358 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16359 Set watchdog timer."), _("\
16360 Show watchdog timer."), _("\
16361 When non-zero, this timeout is used instead of waiting forever for a target\n\
16362 to finish a low-level step or continue operation. If the specified amount\n\
16363 of time passes without a response from the target, an error occurs."),
16364 NULL,
16365 show_watchdog,
16366 &setlist, &showlist);
16367
16368 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16369 &remote_packet_max_chars, _("\
16370 Set the maximum number of characters to display for each remote packet."), _("\
16371 Show the maximum number of characters to display for each remote packet."), _("\
16372 Specify \"unlimited\" to display all the characters."),
16373 NULL, show_remote_packet_max_chars,
16374 &setdebuglist, &showdebuglist);
16375
16376 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16377 _("Set debugging of remote protocol."),
16378 _("Show debugging of remote protocol."),
16379 _("\
16380 When enabled, each packet sent or received with the remote target\n\
16381 is displayed."),
16382 NULL,
16383 show_remote_debug,
16384 &setdebuglist, &showdebuglist);
16385
16386 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16387 &remote_timeout, _("\
16388 Set timeout limit to wait for target to respond."), _("\
16389 Show timeout limit to wait for target to respond."), _("\
16390 This value is used to set the time limit for gdb to wait for a response\n\
16391 from the target."),
16392 NULL,
16393 show_remote_timeout,
16394 &setlist, &showlist);
16395
16396 /* Eventually initialize fileio. See fileio.c */
16397 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16398
16399 #if GDB_SELF_TEST
16400 selftests::register_test ("remote_memory_tagging",
16401 selftests::test_memory_tagging_functions);
16402 selftests::register_test ("packet_check_result",
16403 selftests::test_packet_check_result);
16404 #endif
16405 }