Thread options & clone events (core + remote)
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2023 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 "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdbthread.h"
34 #include "remote.h"
35 #include "remote-notif.h"
36 #include "regcache.h"
37 #include "value.h"
38 #include "observable.h"
39 #include "solib.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "target-descriptions.h"
43 #include "gdb_bfd.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
46 #include "disasm.h"
47 #include "location.h"
48
49 #include "gdbsupport/gdb_sys_time.h"
50
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
54
55 #include <signal.h>
56 #include "serial.h"
57
58 #include "gdbcore.h"
59
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
62 #include <sys/stat.h>
63 #include "xml-support.h"
64
65 #include "memory-map.h"
66
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70 #include "gdbsupport/agent.h"
71 #include "btrace.h"
72 #include "record-btrace.h"
73 #include "gdbsupport/scoped_restore.h"
74 #include "gdbsupport/environ.h"
75 #include "gdbsupport/byte-vector.h"
76 #include "gdbsupport/search.h"
77 #include <algorithm>
78 #include <iterator>
79 #include <unordered_map>
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
82
83 /* The remote target. */
84
85 static const char remote_doc[] = N_("\
86 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87 Specify the serial device it is connected to\n\
88 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
90 /* See remote.h */
91
92 bool remote_debug = false;
93
94 #define OPAQUETHREADBYTES 8
95
96 /* a 64 bit opaque identifier */
97 typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99 struct gdb_ext_thread_info;
100 struct threads_listing_context;
101 typedef int (*rmt_thread_action) (threadref *ref, void *context);
102 struct protocol_feature;
103 struct packet_reg;
104
105 struct stop_reply;
106 typedef std::unique_ptr<stop_reply> stop_reply_up;
107
108 /* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
111
112 enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121 static const char *
122 get_packet_support_name (auto_boolean support)
123 {
124 switch (support)
125 {
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
134 }
135 }
136
137 /* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
139
140 static const char *
141 get_target_type_name (bool target_connected)
142 {
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
147 }
148
149 /* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152 enum packet_result
153 {
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157 };
158
159 /* Enumeration of packets for a remote target. */
160
161 enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
212
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints,
215
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints,
218
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands,
221
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints,
224
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints,
227
228 /* Support for installing tracepoints while a trace experiment is
229 running. */
230 PACKET_InstallInTrace,
231
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
244
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
247
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents,
250
251 /* Support for the QThreadOptions packet. */
252 PACKET_QThreadOptions,
253
254 /* Support for multi-process extensions. */
255 PACKET_multiprocess_feature,
256
257 /* Support for enabling and disabling tracepoints while a trace
258 experiment is running. */
259 PACKET_EnableDisableTracepoints_feature,
260
261 /* Support for collecting strings using the tracenz bytecode. */
262 PACKET_tracenz_feature,
263
264 /* Support for continuing to run a trace experiment while GDB is
265 disconnected. */
266 PACKET_DisconnectedTracing_feature,
267
268 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
269 PACKET_augmented_libraries_svr4_read_feature,
270
271 /* Support for the qXfer:btrace-conf:read packet. */
272 PACKET_qXfer_btrace_conf,
273
274 /* Support for the Qbtrace-conf:bts:size packet. */
275 PACKET_Qbtrace_conf_bts_size,
276
277 /* Support for swbreak+ feature. */
278 PACKET_swbreak_feature,
279
280 /* Support for hwbreak+ feature. */
281 PACKET_hwbreak_feature,
282
283 /* Support for fork events. */
284 PACKET_fork_event_feature,
285
286 /* Support for vfork events. */
287 PACKET_vfork_event_feature,
288
289 /* Support for the Qbtrace-conf:pt:size packet. */
290 PACKET_Qbtrace_conf_pt_size,
291
292 /* Support for exec events. */
293 PACKET_exec_event_feature,
294
295 /* Support for query supported vCont actions. */
296 PACKET_vContSupported,
297
298 /* Support remote CTRL-C. */
299 PACKET_vCtrlC,
300
301 /* Support TARGET_WAITKIND_NO_RESUMED. */
302 PACKET_no_resumed,
303
304 /* Support for memory tagging, allocation tag fetch/store
305 packets and the tag violation stop replies. */
306 PACKET_memory_tagging_feature,
307
308 PACKET_MAX
309 };
310
311 struct threads_listing_context;
312
313 /* Stub vCont actions support.
314
315 Each field is a boolean flag indicating whether the stub reports
316 support for the corresponding action. */
317
318 struct vCont_action_support
319 {
320 /* vCont;t */
321 bool t = false;
322
323 /* vCont;r */
324 bool r = false;
325
326 /* vCont;s */
327 bool s = false;
328
329 /* vCont;S */
330 bool S = false;
331 };
332
333 /* About this many threadids fit in a packet. */
334
335 #define MAXTHREADLISTRESULTS 32
336
337 /* Data for the vFile:pread readahead cache. */
338
339 struct readahead_cache
340 {
341 /* Invalidate the readahead cache. */
342 void invalidate ();
343
344 /* Invalidate the readahead cache if it is holding data for FD. */
345 void invalidate_fd (int fd);
346
347 /* Serve pread from the readahead cache. Returns number of bytes
348 read, or 0 if the request can't be served from the cache. */
349 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
350
351 /* The file descriptor for the file that is being cached. -1 if the
352 cache is invalid. */
353 int fd = -1;
354
355 /* The offset into the file that the cache buffer corresponds
356 to. */
357 ULONGEST offset = 0;
358
359 /* The buffer holding the cache contents. */
360 gdb::byte_vector buf;
361
362 /* Cache hit and miss counters. */
363 ULONGEST hit_count = 0;
364 ULONGEST miss_count = 0;
365 };
366
367 /* Description of the remote protocol for a given architecture. */
368
369 struct packet_reg
370 {
371 long offset; /* Offset into G packet. */
372 long regnum; /* GDB's internal register number. */
373 LONGEST pnum; /* Remote protocol register number. */
374 int in_g_packet; /* Always part of G packet. */
375 /* long size in bytes; == register_size (arch, regnum);
376 at present. */
377 /* char *name; == gdbarch_register_name (arch, regnum);
378 at present. */
379 };
380
381 struct remote_arch_state
382 {
383 explicit remote_arch_state (struct gdbarch *gdbarch);
384
385 /* Description of the remote protocol registers. */
386 long sizeof_g_packet;
387
388 /* Description of the remote protocol registers indexed by REGNUM
389 (making an array gdbarch_num_regs in size). */
390 std::unique_ptr<packet_reg[]> regs;
391
392 /* This is the size (in chars) of the first response to the ``g''
393 packet. It is used as a heuristic when determining the maximum
394 size of memory-read and memory-write packets. A target will
395 typically only reserve a buffer large enough to hold the ``g''
396 packet. The size does not include packet overhead (headers and
397 trailers). */
398 long actual_register_packet_size;
399
400 /* This is the maximum size (in chars) of a non read/write packet.
401 It is also used as a cap on the size of read/write packets. */
402 long remote_packet_size;
403 };
404
405 /* Description of the remote protocol state for the currently
406 connected target. This is per-target state, and independent of the
407 selected architecture. */
408
409 class remote_state
410 {
411 public:
412
413 remote_state ();
414 ~remote_state ();
415
416 /* Get the remote arch state for GDBARCH. */
417 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
418
419 void create_async_event_handler ()
420 {
421 gdb_assert (m_async_event_handler_token == nullptr);
422 m_async_event_handler_token
423 = ::create_async_event_handler ([] (gdb_client_data data)
424 {
425 inferior_event_handler (INF_REG_EVENT);
426 },
427 nullptr, "remote");
428 }
429
430 void mark_async_event_handler ()
431 {
432 gdb_assert (this->is_async_p ());
433 ::mark_async_event_handler (m_async_event_handler_token);
434 }
435
436 void clear_async_event_handler ()
437 { ::clear_async_event_handler (m_async_event_handler_token); }
438
439 bool async_event_handler_marked () const
440 { return ::async_event_handler_marked (m_async_event_handler_token); }
441
442 void delete_async_event_handler ()
443 {
444 if (m_async_event_handler_token != nullptr)
445 ::delete_async_event_handler (&m_async_event_handler_token);
446 }
447
448 bool is_async_p () const
449 {
450 /* We're async whenever the serial device is. */
451 gdb_assert (this->remote_desc != nullptr);
452 return serial_is_async_p (this->remote_desc);
453 }
454
455 bool can_async_p () const
456 {
457 /* We can async whenever the serial device can. */
458 gdb_assert (this->remote_desc != nullptr);
459 return serial_can_async_p (this->remote_desc);
460 }
461
462 public: /* data */
463
464 /* A buffer to use for incoming packets, and its current size. The
465 buffer is grown dynamically for larger incoming packets.
466 Outgoing packets may also be constructed in this buffer.
467 The size of the buffer is always at least REMOTE_PACKET_SIZE;
468 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
469 packets. */
470 gdb::char_vector buf;
471
472 /* True if we're going through initial connection setup (finding out
473 about the remote side's threads, relocating symbols, etc.). */
474 bool starting_up = false;
475
476 /* If we negotiated packet size explicitly (and thus can bypass
477 heuristics for the largest packet size that will not overflow
478 a buffer in the stub), this will be set to that packet size.
479 Otherwise zero, meaning to use the guessed size. */
480 long explicit_packet_size = 0;
481
482 /* True, if in no ack mode. That is, neither GDB nor the stub will
483 expect acks from each other. The connection is assumed to be
484 reliable. */
485 bool noack_mode = false;
486
487 /* True if we're connected in extended remote mode. */
488 bool extended = false;
489
490 /* True if we resumed the target and we're waiting for the target to
491 stop. In the mean time, we can't start another command/query.
492 The remote server wouldn't be ready to process it, so we'd
493 timeout waiting for a reply that would never come and eventually
494 we'd close the connection. This can happen in asynchronous mode
495 because we allow GDB commands while the target is running. */
496 bool waiting_for_stop_reply = false;
497
498 /* The status of the stub support for the various vCont actions. */
499 vCont_action_support supports_vCont;
500
501 /* True if the user has pressed Ctrl-C, but the target hasn't
502 responded to that. */
503 bool ctrlc_pending_p = false;
504
505 /* True if we saw a Ctrl-C while reading or writing from/to the
506 remote descriptor. At that point it is not safe to send a remote
507 interrupt packet, so we instead remember we saw the Ctrl-C and
508 process it once we're done with sending/receiving the current
509 packet, which should be shortly. If however that takes too long,
510 and the user presses Ctrl-C again, we offer to disconnect. */
511 bool got_ctrlc_during_io = false;
512
513 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
514 remote_open knows that we don't have a file open when the program
515 starts. */
516 struct serial *remote_desc = nullptr;
517
518 /* These are the threads which we last sent to the remote system. The
519 TID member will be -1 for all or -2 for not sent yet. */
520 ptid_t general_thread = null_ptid;
521 ptid_t continue_thread = null_ptid;
522
523 /* This is the traceframe which we last selected on the remote system.
524 It will be -1 if no traceframe is selected. */
525 int remote_traceframe_number = -1;
526
527 char *last_pass_packet = nullptr;
528
529 /* The last QProgramSignals packet sent to the target. We bypass
530 sending a new program signals list down to the target if the new
531 packet is exactly the same as the last we sent. IOW, we only let
532 the target know about program signals list changes. */
533 char *last_program_signals_packet = nullptr;
534
535 /* Similarly, the last QThreadEvents state we sent to the
536 target. */
537 bool last_thread_events = false;
538
539 gdb_signal last_sent_signal = GDB_SIGNAL_0;
540
541 bool last_sent_step = false;
542
543 /* The execution direction of the last resume we got. */
544 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
545
546 char *finished_object = nullptr;
547 char *finished_annex = nullptr;
548 ULONGEST finished_offset = 0;
549
550 /* Should we try the 'ThreadInfo' query packet?
551
552 This variable (NOT available to the user: auto-detect only!)
553 determines whether GDB will use the new, simpler "ThreadInfo"
554 query or the older, more complex syntax for thread queries.
555 This is an auto-detect variable (set to true at each connect,
556 and set to false when the target fails to recognize it). */
557 bool use_threadinfo_query = false;
558 bool use_threadextra_query = false;
559
560 threadref echo_nextthread {};
561 threadref nextthread {};
562 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
563
564 /* The state of remote notification. */
565 struct remote_notif_state *notif_state = nullptr;
566
567 /* The branch trace configuration. */
568 struct btrace_config btrace_config {};
569
570 /* The argument to the last "vFile:setfs:" packet we sent, used
571 to avoid sending repeated unnecessary "vFile:setfs:" packets.
572 Initialized to -1 to indicate that no "vFile:setfs:" packet
573 has yet been sent. */
574 int fs_pid = -1;
575
576 /* A readahead cache for vFile:pread. Often, reading a binary
577 involves a sequence of small reads. E.g., when parsing an ELF
578 file. A readahead cache helps mostly the case of remote
579 debugging on a connection with higher latency, due to the
580 request/reply nature of the RSP. We only cache data for a single
581 file descriptor at a time. */
582 struct readahead_cache readahead_cache;
583
584 /* The list of already fetched and acknowledged stop events. This
585 queue is used for notification Stop, and other notifications
586 don't need queue for their events, because the notification
587 events of Stop can't be consumed immediately, so that events
588 should be queued first, and be consumed by remote_wait_{ns,as}
589 one per time. Other notifications can consume their events
590 immediately, so queue is not needed for them. */
591 std::vector<stop_reply_up> stop_reply_queue;
592
593 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
594 ``forever'' still use the normal timeout mechanism. This is
595 currently used by the ASYNC code to guarentee that target reads
596 during the initial connect always time-out. Once getpkt has been
597 modified to return a timeout indication and, in turn
598 remote_wait()/wait_for_inferior() have gained a timeout parameter
599 this can go away. */
600 bool wait_forever_enabled_p = true;
601
602 /* The set of thread options the target reported it supports, via
603 qSupported. */
604 gdb_thread_options supported_thread_options = 0;
605
606 private:
607 /* Asynchronous signal handle registered as event loop source for
608 when we have pending events ready to be passed to the core. */
609 async_event_handler *m_async_event_handler_token = nullptr;
610
611 /* Mapping of remote protocol data for each gdbarch. Usually there
612 is only one entry here, though we may see more with stubs that
613 support multi-process. */
614 std::unordered_map<struct gdbarch *, remote_arch_state>
615 m_arch_states;
616 };
617
618 static const target_info remote_target_info = {
619 "remote",
620 N_("Remote target using gdb-specific protocol"),
621 remote_doc
622 };
623
624 /* Description of a remote packet. */
625
626 struct packet_description
627 {
628 /* Name of the packet used for gdb output. */
629 const char *name;
630
631 /* Title of the packet, used by the set/show remote name-packet
632 commands to identify the individual packages and gdb output. */
633 const char *title;
634 };
635
636 /* Configuration of a remote packet. */
637
638 struct packet_config
639 {
640 /* If auto, GDB auto-detects support for this packet or feature,
641 either through qSupported, or by trying the packet and looking
642 at the response. If true, GDB assumes the target supports this
643 packet. If false, the packet is disabled. Configs that don't
644 have an associated command always have this set to auto. */
645 enum auto_boolean detect;
646
647 /* Does the target support this packet? */
648 enum packet_support support;
649 };
650
651 /* User configurable variables for the number of characters in a
652 memory read/write packet. MIN (rsa->remote_packet_size,
653 rsa->sizeof_g_packet) is the default. Some targets need smaller
654 values (fifo overruns, et.al.) and some users need larger values
655 (speed up transfers). The variables ``preferred_*'' (the user
656 request), ``current_*'' (what was actually set) and ``forced_*''
657 (Positive - a soft limit, negative - a hard limit). */
658
659 struct memory_packet_config
660 {
661 const char *name;
662 long size;
663 int fixed_p;
664 };
665
666 /* These global variables contain the default configuration for every new
667 remote_feature object. */
668 static memory_packet_config memory_read_packet_config =
669 {
670 "memory-read-packet-size",
671 };
672 static memory_packet_config memory_write_packet_config =
673 {
674 "memory-write-packet-size",
675 };
676
677 /* This global array contains packet descriptions (name and title). */
678 static packet_description packets_descriptions[PACKET_MAX];
679 /* This global array contains the default configuration for every new
680 per-remote target array. */
681 static packet_config remote_protocol_packets[PACKET_MAX];
682
683 /* Description of a remote target's features. It stores the configuration
684 and provides functions to determine supported features of the target. */
685
686 struct remote_features
687 {
688 remote_features ()
689 {
690 m_memory_read_packet_config = memory_read_packet_config;
691 m_memory_write_packet_config = memory_write_packet_config;
692
693 std::copy (std::begin (remote_protocol_packets),
694 std::end (remote_protocol_packets),
695 std::begin (m_protocol_packets));
696 }
697 ~remote_features () = default;
698
699 DISABLE_COPY_AND_ASSIGN (remote_features);
700
701 /* Returns whether a given packet defined by its enum value is supported. */
702 enum packet_support packet_support (int) const;
703
704 /* Returns the packet's corresponding "set remote foo-packet" command
705 state. See struct packet_config for more details. */
706 enum auto_boolean packet_set_cmd_state (int packet) const
707 { return m_protocol_packets[packet].detect; }
708
709 /* Returns true if the multi-process extensions are in effect. */
710 int remote_multi_process_p () const
711 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
712
713 /* Returns true if fork events are supported. */
714 int remote_fork_event_p () const
715 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
716
717 /* Returns true if vfork events are supported. */
718 int remote_vfork_event_p () const
719 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
720
721 /* Returns true if exec events are supported. */
722 int remote_exec_event_p () const
723 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
724
725 /* Returns true if memory tagging is supported, false otherwise. */
726 bool remote_memory_tagging_p () const
727 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
728
729 /* Reset all packets back to "unknown support". Called when opening a
730 new connection to a remote target. */
731 void reset_all_packet_configs_support ();
732
733 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
734 support configuration accordingly. */
735 packet_result packet_ok (const char *buf, const int which_packet);
736 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
737
738 /* Configuration of a remote target's memory read packet. */
739 memory_packet_config m_memory_read_packet_config;
740 /* Configuration of a remote target's memory write packet. */
741 memory_packet_config m_memory_write_packet_config;
742
743 /* The per-remote target array which stores a remote's packet
744 configurations. */
745 packet_config m_protocol_packets[PACKET_MAX];
746 };
747
748 class remote_target : public process_stratum_target
749 {
750 public:
751 remote_target () = default;
752 ~remote_target () override;
753
754 const target_info &info () const override
755 { return remote_target_info; }
756
757 const char *connection_string () override;
758
759 thread_control_capabilities get_thread_control_capabilities () override
760 { return tc_schedlock; }
761
762 /* Open a remote connection. */
763 static void open (const char *, int);
764
765 void close () override;
766
767 void detach (inferior *, int) override;
768 void disconnect (const char *, int) override;
769
770 void commit_requested_thread_options ();
771
772 void commit_resumed () override;
773 void resume (ptid_t, int, enum gdb_signal) override;
774 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
775 bool has_pending_events () override;
776
777 void fetch_registers (struct regcache *, int) override;
778 void store_registers (struct regcache *, int) override;
779 void prepare_to_store (struct regcache *) override;
780
781 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
782
783 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
784 enum remove_bp_reason) override;
785
786
787 bool stopped_by_sw_breakpoint () override;
788 bool supports_stopped_by_sw_breakpoint () override;
789
790 bool stopped_by_hw_breakpoint () override;
791
792 bool supports_stopped_by_hw_breakpoint () override;
793
794 bool stopped_by_watchpoint () override;
795
796 bool stopped_data_address (CORE_ADDR *) override;
797
798 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
799
800 int can_use_hw_breakpoint (enum bptype, int, int) override;
801
802 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
803
804 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
805
806 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
807
808 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
809 struct expression *) override;
810
811 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
812 struct expression *) override;
813
814 void kill () override;
815
816 void load (const char *, int) override;
817
818 void mourn_inferior () override;
819
820 void pass_signals (gdb::array_view<const unsigned char>) override;
821
822 int set_syscall_catchpoint (int, bool, int,
823 gdb::array_view<const int>) override;
824
825 void program_signals (gdb::array_view<const unsigned char>) override;
826
827 bool thread_alive (ptid_t ptid) override;
828
829 const char *thread_name (struct thread_info *) override;
830
831 void update_thread_list () override;
832
833 std::string pid_to_str (ptid_t) override;
834
835 const char *extra_thread_info (struct thread_info *) override;
836
837 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
838
839 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
840 int handle_len,
841 inferior *inf) override;
842
843 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
844 override;
845
846 void stop (ptid_t) override;
847
848 void interrupt () override;
849
850 void pass_ctrlc () override;
851
852 enum target_xfer_status xfer_partial (enum target_object object,
853 const char *annex,
854 gdb_byte *readbuf,
855 const gdb_byte *writebuf,
856 ULONGEST offset, ULONGEST len,
857 ULONGEST *xfered_len) override;
858
859 ULONGEST get_memory_xfer_limit () override;
860
861 void rcmd (const char *command, struct ui_file *output) override;
862
863 const char *pid_to_exec_file (int pid) override;
864
865 void log_command (const char *cmd) override
866 {
867 serial_log_command (this, cmd);
868 }
869
870 CORE_ADDR get_thread_local_address (ptid_t ptid,
871 CORE_ADDR load_module_addr,
872 CORE_ADDR offset) override;
873
874 bool can_execute_reverse () override;
875
876 std::vector<mem_region> memory_map () override;
877
878 void flash_erase (ULONGEST address, LONGEST length) override;
879
880 void flash_done () override;
881
882 const struct target_desc *read_description () override;
883
884 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
885 const gdb_byte *pattern, ULONGEST pattern_len,
886 CORE_ADDR *found_addrp) override;
887
888 bool can_async_p () override;
889
890 bool is_async_p () override;
891
892 void async (bool) override;
893
894 int async_wait_fd () override;
895
896 void thread_events (int) override;
897
898 bool supports_set_thread_options (gdb_thread_options) override;
899
900 int can_do_single_step () override;
901
902 void terminal_inferior () override;
903
904 void terminal_ours () override;
905
906 bool supports_non_stop () override;
907
908 bool supports_multi_process () override;
909
910 bool supports_disable_randomization () override;
911
912 bool filesystem_is_local () override;
913
914
915 int fileio_open (struct inferior *inf, const char *filename,
916 int flags, int mode, int warn_if_slow,
917 fileio_error *target_errno) override;
918
919 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
920 ULONGEST offset, fileio_error *target_errno) override;
921
922 int fileio_pread (int fd, gdb_byte *read_buf, int len,
923 ULONGEST offset, fileio_error *target_errno) override;
924
925 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
926
927 int fileio_close (int fd, fileio_error *target_errno) override;
928
929 int fileio_unlink (struct inferior *inf,
930 const char *filename,
931 fileio_error *target_errno) override;
932
933 gdb::optional<std::string>
934 fileio_readlink (struct inferior *inf,
935 const char *filename,
936 fileio_error *target_errno) override;
937
938 bool supports_enable_disable_tracepoint () override;
939
940 bool supports_string_tracing () override;
941
942 int remote_supports_cond_tracepoints ();
943
944 bool supports_evaluation_of_breakpoint_conditions () override;
945
946 int remote_supports_fast_tracepoints ();
947
948 int remote_supports_static_tracepoints ();
949
950 int remote_supports_install_in_trace ();
951
952 bool can_run_breakpoint_commands () override;
953
954 void trace_init () override;
955
956 void download_tracepoint (struct bp_location *location) override;
957
958 bool can_download_tracepoint () override;
959
960 void download_trace_state_variable (const trace_state_variable &tsv) override;
961
962 void enable_tracepoint (struct bp_location *location) override;
963
964 void disable_tracepoint (struct bp_location *location) override;
965
966 void trace_set_readonly_regions () override;
967
968 void trace_start () override;
969
970 int get_trace_status (struct trace_status *ts) override;
971
972 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
973 override;
974
975 void trace_stop () override;
976
977 int trace_find (enum trace_find_type type, int num,
978 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
979
980 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
981
982 int save_trace_data (const char *filename) override;
983
984 int upload_tracepoints (struct uploaded_tp **utpp) override;
985
986 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
987
988 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
989
990 int get_min_fast_tracepoint_insn_len () override;
991
992 void set_disconnected_tracing (int val) override;
993
994 void set_circular_trace_buffer (int val) override;
995
996 void set_trace_buffer_size (LONGEST val) override;
997
998 bool set_trace_notes (const char *user, const char *notes,
999 const char *stopnotes) override;
1000
1001 int core_of_thread (ptid_t ptid) override;
1002
1003 int verify_memory (const gdb_byte *data,
1004 CORE_ADDR memaddr, ULONGEST size) override;
1005
1006
1007 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
1008
1009 void set_permissions () override;
1010
1011 bool static_tracepoint_marker_at (CORE_ADDR,
1012 struct static_tracepoint_marker *marker)
1013 override;
1014
1015 std::vector<static_tracepoint_marker>
1016 static_tracepoint_markers_by_strid (const char *id) override;
1017
1018 traceframe_info_up traceframe_info () override;
1019
1020 bool use_agent (bool use) override;
1021 bool can_use_agent () override;
1022
1023 struct btrace_target_info *
1024 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1025
1026 void disable_btrace (struct btrace_target_info *tinfo) override;
1027
1028 void teardown_btrace (struct btrace_target_info *tinfo) override;
1029
1030 enum btrace_error read_btrace (struct btrace_data *data,
1031 struct btrace_target_info *btinfo,
1032 enum btrace_read_type type) override;
1033
1034 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1035 bool augmented_libraries_svr4_read () override;
1036 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1037 void follow_clone (ptid_t child_ptid) override;
1038 void follow_exec (inferior *, ptid_t, const char *) override;
1039 int insert_fork_catchpoint (int) override;
1040 int remove_fork_catchpoint (int) override;
1041 int insert_vfork_catchpoint (int) override;
1042 int remove_vfork_catchpoint (int) override;
1043 int insert_exec_catchpoint (int) override;
1044 int remove_exec_catchpoint (int) override;
1045 enum exec_direction_kind execution_direction () override;
1046
1047 bool supports_memory_tagging () override;
1048
1049 bool fetch_memtags (CORE_ADDR address, size_t len,
1050 gdb::byte_vector &tags, int type) override;
1051
1052 bool store_memtags (CORE_ADDR address, size_t len,
1053 const gdb::byte_vector &tags, int type) override;
1054
1055 public: /* Remote specific methods. */
1056
1057 void remote_download_command_source (int num, ULONGEST addr,
1058 struct command_line *cmds);
1059
1060 void remote_file_put (const char *local_file, const char *remote_file,
1061 int from_tty);
1062 void remote_file_get (const char *remote_file, const char *local_file,
1063 int from_tty);
1064 void remote_file_delete (const char *remote_file, int from_tty);
1065
1066 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1067 ULONGEST offset, fileio_error *remote_errno);
1068 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1069 ULONGEST offset, fileio_error *remote_errno);
1070 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1071 ULONGEST offset, fileio_error *remote_errno);
1072
1073 int remote_hostio_send_command (int command_bytes, int which_packet,
1074 fileio_error *remote_errno, const char **attachment,
1075 int *attachment_len);
1076 int remote_hostio_set_filesystem (struct inferior *inf,
1077 fileio_error *remote_errno);
1078 /* We should get rid of this and use fileio_open directly. */
1079 int remote_hostio_open (struct inferior *inf, const char *filename,
1080 int flags, int mode, int warn_if_slow,
1081 fileio_error *remote_errno);
1082 int remote_hostio_close (int fd, fileio_error *remote_errno);
1083
1084 int remote_hostio_unlink (inferior *inf, const char *filename,
1085 fileio_error *remote_errno);
1086
1087 struct remote_state *get_remote_state ();
1088
1089 long get_remote_packet_size (void);
1090 long get_memory_packet_size (struct memory_packet_config *config);
1091
1092 long get_memory_write_packet_size ();
1093 long get_memory_read_packet_size ();
1094
1095 char *append_pending_thread_resumptions (char *p, char *endp,
1096 ptid_t ptid);
1097 static void open_1 (const char *name, int from_tty, int extended_p);
1098 void start_remote (int from_tty, int extended_p);
1099 void remote_detach_1 (struct inferior *inf, int from_tty);
1100
1101 char *append_resumption (char *p, char *endp,
1102 ptid_t ptid, int step, gdb_signal siggnal);
1103 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1104 gdb_signal siggnal);
1105
1106 thread_info *add_current_inferior_and_thread (const char *wait_status);
1107
1108 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1109 target_wait_flags options);
1110 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1111 target_wait_flags options);
1112
1113 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1114 target_waitstatus *status);
1115
1116 ptid_t select_thread_for_ambiguous_stop_reply
1117 (const struct target_waitstatus &status);
1118
1119 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1120
1121 void print_one_stopped_thread (thread_info *thread);
1122 void process_initial_stop_replies (int from_tty);
1123
1124 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1125 bool silent_p);
1126
1127 void btrace_sync_conf (const btrace_config *conf);
1128
1129 void remote_btrace_maybe_reopen ();
1130
1131 void remove_new_children (threads_listing_context *context);
1132 void kill_new_fork_children (inferior *inf);
1133 void discard_pending_stop_replies (struct inferior *inf);
1134 int stop_reply_queue_length ();
1135
1136 void check_pending_events_prevent_wildcard_vcont
1137 (bool *may_global_wildcard_vcont);
1138
1139 void discard_pending_stop_replies_in_queue ();
1140 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1141 struct stop_reply *queued_stop_reply (ptid_t ptid);
1142 int peek_stop_reply (ptid_t ptid);
1143 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1144
1145 void remote_stop_ns (ptid_t ptid);
1146 void remote_interrupt_as ();
1147 void remote_interrupt_ns ();
1148
1149 char *remote_get_noisy_reply ();
1150 int remote_query_attached (int pid);
1151 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1152 int try_open_exec);
1153
1154 ptid_t remote_current_thread (ptid_t oldpid);
1155 ptid_t get_current_thread (const char *wait_status);
1156
1157 void set_thread (ptid_t ptid, int gen);
1158 void set_general_thread (ptid_t ptid);
1159 void set_continue_thread (ptid_t ptid);
1160 void set_general_process ();
1161
1162 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1163
1164 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1165 gdb_ext_thread_info *info);
1166 int remote_get_threadinfo (threadref *threadid, int fieldset,
1167 gdb_ext_thread_info *info);
1168
1169 int parse_threadlist_response (const char *pkt, int result_limit,
1170 threadref *original_echo,
1171 threadref *resultlist,
1172 int *doneflag);
1173 int remote_get_threadlist (int startflag, threadref *nextthread,
1174 int result_limit, int *done, int *result_count,
1175 threadref *threadlist);
1176
1177 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1178 void *context, int looplimit);
1179
1180 int remote_get_threads_with_ql (threads_listing_context *context);
1181 int remote_get_threads_with_qxfer (threads_listing_context *context);
1182 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1183
1184 void extended_remote_restart ();
1185
1186 void get_offsets ();
1187
1188 void remote_check_symbols ();
1189
1190 void remote_supported_packet (const struct protocol_feature *feature,
1191 enum packet_support support,
1192 const char *argument);
1193
1194 void remote_query_supported ();
1195
1196 void remote_packet_size (const protocol_feature *feature,
1197 packet_support support, const char *value);
1198 void remote_supported_thread_options (const protocol_feature *feature,
1199 enum packet_support support,
1200 const char *value);
1201
1202 void remote_serial_quit_handler ();
1203
1204 void remote_detach_pid (int pid);
1205
1206 void remote_vcont_probe ();
1207
1208 void remote_resume_with_hc (ptid_t ptid, int step,
1209 gdb_signal siggnal);
1210
1211 void send_interrupt_sequence ();
1212 void interrupt_query ();
1213
1214 void remote_notif_get_pending_events (const notif_client *nc);
1215
1216 int fetch_register_using_p (struct regcache *regcache,
1217 packet_reg *reg);
1218 int send_g_packet ();
1219 void process_g_packet (struct regcache *regcache);
1220 void fetch_registers_using_g (struct regcache *regcache);
1221 int store_register_using_P (const struct regcache *regcache,
1222 packet_reg *reg);
1223 void store_registers_using_G (const struct regcache *regcache);
1224
1225 void set_remote_traceframe ();
1226
1227 void check_binary_download (CORE_ADDR addr);
1228
1229 target_xfer_status remote_write_bytes_aux (const char *header,
1230 CORE_ADDR memaddr,
1231 const gdb_byte *myaddr,
1232 ULONGEST len_units,
1233 int unit_size,
1234 ULONGEST *xfered_len_units,
1235 char packet_format,
1236 int use_length);
1237
1238 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1239 const gdb_byte *myaddr, ULONGEST len,
1240 int unit_size, ULONGEST *xfered_len);
1241
1242 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1243 ULONGEST len_units,
1244 int unit_size, ULONGEST *xfered_len_units);
1245
1246 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1247 ULONGEST memaddr,
1248 ULONGEST len,
1249 int unit_size,
1250 ULONGEST *xfered_len);
1251
1252 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1253 gdb_byte *myaddr, ULONGEST len,
1254 int unit_size,
1255 ULONGEST *xfered_len);
1256
1257 packet_result remote_send_printf (const char *format, ...)
1258 ATTRIBUTE_PRINTF (2, 3);
1259
1260 target_xfer_status remote_flash_write (ULONGEST address,
1261 ULONGEST length, ULONGEST *xfered_len,
1262 const gdb_byte *data);
1263
1264 int readchar (int timeout);
1265
1266 void remote_serial_write (const char *str, int len);
1267
1268 int putpkt (const char *buf);
1269 int putpkt_binary (const char *buf, int cnt);
1270
1271 int putpkt (const gdb::char_vector &buf)
1272 {
1273 return putpkt (buf.data ());
1274 }
1275
1276 void skip_frame ();
1277 long read_frame (gdb::char_vector *buf_p);
1278 int getpkt (gdb::char_vector *buf, bool forever = false,
1279 bool *is_notif = nullptr);
1280 int remote_vkill (int pid);
1281 void remote_kill_k ();
1282
1283 void extended_remote_disable_randomization (int val);
1284 int extended_remote_run (const std::string &args);
1285
1286 void send_environment_packet (const char *action,
1287 const char *packet,
1288 const char *value);
1289
1290 void extended_remote_environment_support ();
1291 void extended_remote_set_inferior_cwd ();
1292
1293 target_xfer_status remote_write_qxfer (const char *object_name,
1294 const char *annex,
1295 const gdb_byte *writebuf,
1296 ULONGEST offset, LONGEST len,
1297 ULONGEST *xfered_len,
1298 const unsigned int which_packet);
1299
1300 target_xfer_status remote_read_qxfer (const char *object_name,
1301 const char *annex,
1302 gdb_byte *readbuf, ULONGEST offset,
1303 LONGEST len,
1304 ULONGEST *xfered_len,
1305 const unsigned int which_packet);
1306
1307 void push_stop_reply (struct stop_reply *new_event);
1308
1309 bool vcont_r_supported ();
1310
1311 remote_features m_features;
1312
1313 private:
1314
1315 bool start_remote_1 (int from_tty, int extended_p);
1316
1317 /* The remote state. Don't reference this directly. Use the
1318 get_remote_state method instead. */
1319 remote_state m_remote_state;
1320 };
1321
1322 static const target_info extended_remote_target_info = {
1323 "extended-remote",
1324 N_("Extended remote target using gdb-specific protocol"),
1325 remote_doc
1326 };
1327
1328 /* Set up the extended remote target by extending the standard remote
1329 target and adding to it. */
1330
1331 class extended_remote_target final : public remote_target
1332 {
1333 public:
1334 const target_info &info () const override
1335 { return extended_remote_target_info; }
1336
1337 /* Open an extended-remote connection. */
1338 static void open (const char *, int);
1339
1340 bool can_create_inferior () override { return true; }
1341 void create_inferior (const char *, const std::string &,
1342 char **, int) override;
1343
1344 void detach (inferior *, int) override;
1345
1346 bool can_attach () override { return true; }
1347 void attach (const char *, int) override;
1348
1349 void post_attach (int) override;
1350 bool supports_disable_randomization () override;
1351 };
1352
1353 struct stop_reply : public notif_event
1354 {
1355 ~stop_reply ();
1356
1357 /* The identifier of the thread about this event */
1358 ptid_t ptid;
1359
1360 /* The remote state this event is associated with. When the remote
1361 connection, represented by a remote_state object, is closed,
1362 all the associated stop_reply events should be released. */
1363 struct remote_state *rs;
1364
1365 struct target_waitstatus ws;
1366
1367 /* The architecture associated with the expedited registers. */
1368 gdbarch *arch;
1369
1370 /* Expedited registers. This makes remote debugging a bit more
1371 efficient for those targets that provide critical registers as
1372 part of their normal status mechanism (as another roundtrip to
1373 fetch them is avoided). */
1374 std::vector<cached_reg_t> regcache;
1375
1376 enum target_stop_reason stop_reason;
1377
1378 CORE_ADDR watch_data_address;
1379
1380 int core;
1381 };
1382
1383 /* Return TARGET as a remote_target if it is one, else nullptr. */
1384
1385 static remote_target *
1386 as_remote_target (process_stratum_target *target)
1387 {
1388 return dynamic_cast<remote_target *> (target);
1389 }
1390
1391 /* See remote.h. */
1392
1393 bool
1394 is_remote_target (process_stratum_target *target)
1395 {
1396 return as_remote_target (target) != nullptr;
1397 }
1398
1399 /* Per-program-space data key. */
1400 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1401 remote_pspace_data;
1402
1403 /* The variable registered as the control variable used by the
1404 remote exec-file commands. While the remote exec-file setting is
1405 per-program-space, the set/show machinery uses this as the
1406 location of the remote exec-file value. */
1407 static std::string remote_exec_file_var;
1408
1409 /* The size to align memory write packets, when practical. The protocol
1410 does not guarantee any alignment, and gdb will generate short
1411 writes and unaligned writes, but even as a best-effort attempt this
1412 can improve bulk transfers. For instance, if a write is misaligned
1413 relative to the target's data bus, the stub may need to make an extra
1414 round trip fetching data from the target. This doesn't make a
1415 huge difference, but it's easy to do, so we try to be helpful.
1416
1417 The alignment chosen is arbitrary; usually data bus width is
1418 important here, not the possibly larger cache line size. */
1419 enum { REMOTE_ALIGN_WRITES = 16 };
1420
1421 /* Prototypes for local functions. */
1422
1423 static int hexnumlen (ULONGEST num);
1424
1425 static int stubhex (int ch);
1426
1427 static int hexnumstr (char *, ULONGEST);
1428
1429 static int hexnumnstr (char *, ULONGEST, int);
1430
1431 static CORE_ADDR remote_address_masked (CORE_ADDR);
1432
1433 static int stub_unpack_int (const char *buff, int fieldlength);
1434
1435 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1436 cmd_list_element *c);
1437
1438 static void show_packet_config_cmd (ui_file *file,
1439 const unsigned int which_packet,
1440 remote_target *remote);
1441
1442 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1443 int from_tty,
1444 struct cmd_list_element *c,
1445 const char *value);
1446
1447 static ptid_t read_ptid (const char *buf, const char **obuf);
1448
1449 static bool remote_read_description_p (struct target_ops *target);
1450
1451 static void remote_console_output (const char *msg);
1452
1453 static void remote_btrace_reset (remote_state *rs);
1454
1455 static void remote_unpush_and_throw (remote_target *target);
1456
1457 /* For "remote". */
1458
1459 static struct cmd_list_element *remote_cmdlist;
1460
1461 /* For "set remote" and "show remote". */
1462
1463 static struct cmd_list_element *remote_set_cmdlist;
1464 static struct cmd_list_element *remote_show_cmdlist;
1465
1466 /* Controls whether GDB is willing to use range stepping. */
1467
1468 static bool use_range_stepping = true;
1469
1470 /* From the remote target's point of view, each thread is in one of these three
1471 states. */
1472 enum class resume_state
1473 {
1474 /* Not resumed - we haven't been asked to resume this thread. */
1475 NOT_RESUMED,
1476
1477 /* We have been asked to resume this thread, but haven't sent a vCont action
1478 for it yet. We'll need to consider it next time commit_resume is
1479 called. */
1480 RESUMED_PENDING_VCONT,
1481
1482 /* We have been asked to resume this thread, and we have sent a vCont action
1483 for it. */
1484 RESUMED,
1485 };
1486
1487 /* Information about a thread's pending vCont-resume. Used when a thread is in
1488 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1489 stores this information which is then picked up by
1490 remote_target::commit_resume to know which is the proper action for this
1491 thread to include in the vCont packet. */
1492 struct resumed_pending_vcont_info
1493 {
1494 /* True if the last resume call for this thread was a step request, false
1495 if a continue request. */
1496 bool step;
1497
1498 /* The signal specified in the last resume call for this thread. */
1499 gdb_signal sig;
1500 };
1501
1502 /* Private data that we'll store in (struct thread_info)->priv. */
1503 struct remote_thread_info : public private_thread_info
1504 {
1505 std::string extra;
1506 std::string name;
1507 int core = -1;
1508
1509 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1510 sequence of bytes. */
1511 gdb::byte_vector thread_handle;
1512
1513 /* Whether the target stopped for a breakpoint/watchpoint. */
1514 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1515
1516 /* This is set to the data address of the access causing the target
1517 to stop for a watchpoint. */
1518 CORE_ADDR watch_data_address = 0;
1519
1520 /* Get the thread's resume state. */
1521 enum resume_state get_resume_state () const
1522 {
1523 return m_resume_state;
1524 }
1525
1526 /* Put the thread in the NOT_RESUMED state. */
1527 void set_not_resumed ()
1528 {
1529 m_resume_state = resume_state::NOT_RESUMED;
1530 }
1531
1532 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1533 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1534 {
1535 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1536 m_resumed_pending_vcont_info.step = step;
1537 m_resumed_pending_vcont_info.sig = sig;
1538 }
1539
1540 /* Get the information this thread's pending vCont-resumption.
1541
1542 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1543 state. */
1544 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1545 {
1546 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1547
1548 return m_resumed_pending_vcont_info;
1549 }
1550
1551 /* Put the thread in the VCONT_RESUMED state. */
1552 void set_resumed ()
1553 {
1554 m_resume_state = resume_state::RESUMED;
1555 }
1556
1557 private:
1558 /* Resume state for this thread. This is used to implement vCont action
1559 coalescing (only when the target operates in non-stop mode).
1560
1561 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1562 which notes that this thread must be considered in the next commit_resume
1563 call.
1564
1565 remote_target::commit_resume sends a vCont packet with actions for the
1566 threads in the RESUMED_PENDING_VCONT state and moves them to the
1567 VCONT_RESUMED state.
1568
1569 When reporting a stop to the core for a thread, that thread is moved back
1570 to the NOT_RESUMED state. */
1571 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1572
1573 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1574 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1575 };
1576
1577 remote_state::remote_state ()
1578 : buf (400)
1579 {
1580 }
1581
1582 remote_state::~remote_state ()
1583 {
1584 xfree (this->last_pass_packet);
1585 xfree (this->last_program_signals_packet);
1586 xfree (this->finished_object);
1587 xfree (this->finished_annex);
1588 }
1589
1590 /* Utility: generate error from an incoming stub packet. */
1591 static void
1592 trace_error (char *buf)
1593 {
1594 if (*buf++ != 'E')
1595 return; /* not an error msg */
1596 switch (*buf)
1597 {
1598 case '1': /* malformed packet error */
1599 if (*++buf == '0') /* general case: */
1600 error (_("remote.c: error in outgoing packet."));
1601 else
1602 error (_("remote.c: error in outgoing packet at field #%ld."),
1603 strtol (buf, NULL, 16));
1604 default:
1605 error (_("Target returns error code '%s'."), buf);
1606 }
1607 }
1608
1609 /* Utility: wait for reply from stub, while accepting "O" packets. */
1610
1611 char *
1612 remote_target::remote_get_noisy_reply ()
1613 {
1614 struct remote_state *rs = get_remote_state ();
1615
1616 do /* Loop on reply from remote stub. */
1617 {
1618 char *buf;
1619
1620 QUIT; /* Allow user to bail out with ^C. */
1621 getpkt (&rs->buf);
1622 buf = rs->buf.data ();
1623 if (buf[0] == 'E')
1624 trace_error (buf);
1625 else if (startswith (buf, "qRelocInsn:"))
1626 {
1627 ULONGEST ul;
1628 CORE_ADDR from, to, org_to;
1629 const char *p, *pp;
1630 int adjusted_size = 0;
1631 int relocated = 0;
1632
1633 p = buf + strlen ("qRelocInsn:");
1634 pp = unpack_varlen_hex (p, &ul);
1635 if (*pp != ';')
1636 error (_("invalid qRelocInsn packet: %s"), buf);
1637 from = ul;
1638
1639 p = pp + 1;
1640 unpack_varlen_hex (p, &ul);
1641 to = ul;
1642
1643 org_to = to;
1644
1645 try
1646 {
1647 gdbarch_relocate_instruction (current_inferior ()->arch (),
1648 &to, from);
1649 relocated = 1;
1650 }
1651 catch (const gdb_exception &ex)
1652 {
1653 if (ex.error == MEMORY_ERROR)
1654 {
1655 /* Propagate memory errors silently back to the
1656 target. The stub may have limited the range of
1657 addresses we can write to, for example. */
1658 }
1659 else
1660 {
1661 /* Something unexpectedly bad happened. Be verbose
1662 so we can tell what, and propagate the error back
1663 to the stub, so it doesn't get stuck waiting for
1664 a response. */
1665 exception_fprintf (gdb_stderr, ex,
1666 _("warning: relocating instruction: "));
1667 }
1668 putpkt ("E01");
1669 }
1670
1671 if (relocated)
1672 {
1673 adjusted_size = to - org_to;
1674
1675 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1676 putpkt (buf);
1677 }
1678 }
1679 else if (buf[0] == 'O' && buf[1] != 'K')
1680 remote_console_output (buf + 1); /* 'O' message from stub */
1681 else
1682 return buf; /* Here's the actual reply. */
1683 }
1684 while (1);
1685 }
1686
1687 struct remote_arch_state *
1688 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1689 {
1690 remote_arch_state *rsa;
1691
1692 auto it = this->m_arch_states.find (gdbarch);
1693 if (it == this->m_arch_states.end ())
1694 {
1695 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1696 std::forward_as_tuple (gdbarch),
1697 std::forward_as_tuple (gdbarch));
1698 rsa = &p.first->second;
1699
1700 /* Make sure that the packet buffer is plenty big enough for
1701 this architecture. */
1702 if (this->buf.size () < rsa->remote_packet_size)
1703 this->buf.resize (2 * rsa->remote_packet_size);
1704 }
1705 else
1706 rsa = &it->second;
1707
1708 return rsa;
1709 }
1710
1711 /* Fetch the global remote target state. */
1712
1713 remote_state *
1714 remote_target::get_remote_state ()
1715 {
1716 /* Make sure that the remote architecture state has been
1717 initialized, because doing so might reallocate rs->buf. Any
1718 function which calls getpkt also needs to be mindful of changes
1719 to rs->buf, but this call limits the number of places which run
1720 into trouble. */
1721 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1722
1723 return &m_remote_state;
1724 }
1725
1726 /* Fetch the remote exec-file from the current program space. */
1727
1728 static const char *
1729 get_remote_exec_file (void)
1730 {
1731 char *remote_exec_file;
1732
1733 remote_exec_file = remote_pspace_data.get (current_program_space);
1734 if (remote_exec_file == NULL)
1735 return "";
1736
1737 return remote_exec_file;
1738 }
1739
1740 /* Set the remote exec file for PSPACE. */
1741
1742 static void
1743 set_pspace_remote_exec_file (struct program_space *pspace,
1744 const char *remote_exec_file)
1745 {
1746 char *old_file = remote_pspace_data.get (pspace);
1747
1748 xfree (old_file);
1749 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1750 }
1751
1752 /* The "set/show remote exec-file" set command hook. */
1753
1754 static void
1755 set_remote_exec_file (const char *ignored, int from_tty,
1756 struct cmd_list_element *c)
1757 {
1758 set_pspace_remote_exec_file (current_program_space,
1759 remote_exec_file_var.c_str ());
1760 }
1761
1762 /* The "set/show remote exec-file" show command hook. */
1763
1764 static void
1765 show_remote_exec_file (struct ui_file *file, int from_tty,
1766 struct cmd_list_element *cmd, const char *value)
1767 {
1768 gdb_printf (file, "%s\n", get_remote_exec_file ());
1769 }
1770
1771 static int
1772 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1773 {
1774 int regnum, num_remote_regs, offset;
1775 struct packet_reg **remote_regs;
1776
1777 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1778 {
1779 struct packet_reg *r = &regs[regnum];
1780
1781 if (register_size (gdbarch, regnum) == 0)
1782 /* Do not try to fetch zero-sized (placeholder) registers. */
1783 r->pnum = -1;
1784 else
1785 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1786
1787 r->regnum = regnum;
1788 }
1789
1790 /* Define the g/G packet format as the contents of each register
1791 with a remote protocol number, in order of ascending protocol
1792 number. */
1793
1794 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1795 for (num_remote_regs = 0, regnum = 0;
1796 regnum < gdbarch_num_regs (gdbarch);
1797 regnum++)
1798 if (regs[regnum].pnum != -1)
1799 remote_regs[num_remote_regs++] = &regs[regnum];
1800
1801 std::sort (remote_regs, remote_regs + num_remote_regs,
1802 [] (const packet_reg *a, const packet_reg *b)
1803 { return a->pnum < b->pnum; });
1804
1805 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1806 {
1807 remote_regs[regnum]->in_g_packet = 1;
1808 remote_regs[regnum]->offset = offset;
1809 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1810 }
1811
1812 return offset;
1813 }
1814
1815 /* Given the architecture described by GDBARCH, return the remote
1816 protocol register's number and the register's offset in the g/G
1817 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1818 If the target does not have a mapping for REGNUM, return false,
1819 otherwise, return true. */
1820
1821 int
1822 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1823 int *pnum, int *poffset)
1824 {
1825 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1826
1827 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1828
1829 map_regcache_remote_table (gdbarch, regs.data ());
1830
1831 *pnum = regs[regnum].pnum;
1832 *poffset = regs[regnum].offset;
1833
1834 return *pnum != -1;
1835 }
1836
1837 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1838 {
1839 /* Use the architecture to build a regnum<->pnum table, which will be
1840 1:1 unless a feature set specifies otherwise. */
1841 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1842
1843 /* Record the maximum possible size of the g packet - it may turn out
1844 to be smaller. */
1845 this->sizeof_g_packet
1846 = map_regcache_remote_table (gdbarch, this->regs.get ());
1847
1848 /* Default maximum number of characters in a packet body. Many
1849 remote stubs have a hardwired buffer size of 400 bytes
1850 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1851 as the maximum packet-size to ensure that the packet and an extra
1852 NUL character can always fit in the buffer. This stops GDB
1853 trashing stubs that try to squeeze an extra NUL into what is
1854 already a full buffer (As of 1999-12-04 that was most stubs). */
1855 this->remote_packet_size = 400 - 1;
1856
1857 /* This one is filled in when a ``g'' packet is received. */
1858 this->actual_register_packet_size = 0;
1859
1860 /* Should rsa->sizeof_g_packet needs more space than the
1861 default, adjust the size accordingly. Remember that each byte is
1862 encoded as two characters. 32 is the overhead for the packet
1863 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1864 (``$NN:G...#NN'') is a better guess, the below has been padded a
1865 little. */
1866 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1867 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1868 }
1869
1870 /* Get a pointer to the current remote target. If not connected to a
1871 remote target, return NULL. */
1872
1873 static remote_target *
1874 get_current_remote_target ()
1875 {
1876 target_ops *proc_target = current_inferior ()->process_target ();
1877 return dynamic_cast<remote_target *> (proc_target);
1878 }
1879
1880 /* Return the current allowed size of a remote packet. This is
1881 inferred from the current architecture, and should be used to
1882 limit the length of outgoing packets. */
1883 long
1884 remote_target::get_remote_packet_size ()
1885 {
1886 struct remote_state *rs = get_remote_state ();
1887 remote_arch_state *rsa
1888 = rs->get_remote_arch_state (current_inferior ()->arch ());
1889
1890 if (rs->explicit_packet_size)
1891 return rs->explicit_packet_size;
1892
1893 return rsa->remote_packet_size;
1894 }
1895
1896 static struct packet_reg *
1897 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1898 long regnum)
1899 {
1900 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1901 return NULL;
1902 else
1903 {
1904 struct packet_reg *r = &rsa->regs[regnum];
1905
1906 gdb_assert (r->regnum == regnum);
1907 return r;
1908 }
1909 }
1910
1911 static struct packet_reg *
1912 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1913 LONGEST pnum)
1914 {
1915 int i;
1916
1917 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1918 {
1919 struct packet_reg *r = &rsa->regs[i];
1920
1921 if (r->pnum == pnum)
1922 return r;
1923 }
1924 return NULL;
1925 }
1926
1927 /* Allow the user to specify what sequence to send to the remote
1928 when he requests a program interruption: Although ^C is usually
1929 what remote systems expect (this is the default, here), it is
1930 sometimes preferable to send a break. On other systems such
1931 as the Linux kernel, a break followed by g, which is Magic SysRq g
1932 is required in order to interrupt the execution. */
1933 const char interrupt_sequence_control_c[] = "Ctrl-C";
1934 const char interrupt_sequence_break[] = "BREAK";
1935 const char interrupt_sequence_break_g[] = "BREAK-g";
1936 static const char *const interrupt_sequence_modes[] =
1937 {
1938 interrupt_sequence_control_c,
1939 interrupt_sequence_break,
1940 interrupt_sequence_break_g,
1941 NULL
1942 };
1943 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1944
1945 static void
1946 show_interrupt_sequence (struct ui_file *file, int from_tty,
1947 struct cmd_list_element *c,
1948 const char *value)
1949 {
1950 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1951 gdb_printf (file,
1952 _("Send the ASCII ETX character (Ctrl-c) "
1953 "to the remote target to interrupt the "
1954 "execution of the program.\n"));
1955 else if (interrupt_sequence_mode == interrupt_sequence_break)
1956 gdb_printf (file,
1957 _("send a break signal to the remote target "
1958 "to interrupt the execution of the program.\n"));
1959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1960 gdb_printf (file,
1961 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1962 "the remote target to interrupt the execution "
1963 "of Linux kernel.\n"));
1964 else
1965 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1966 interrupt_sequence_mode);
1967 }
1968
1969 /* This boolean variable specifies whether interrupt_sequence is sent
1970 to the remote target when gdb connects to it.
1971 This is mostly needed when you debug the Linux kernel: The Linux kernel
1972 expects BREAK g which is Magic SysRq g for connecting gdb. */
1973 static bool interrupt_on_connect = false;
1974
1975 /* This variable is used to implement the "set/show remotebreak" commands.
1976 Since these commands are now deprecated in favor of "set/show remote
1977 interrupt-sequence", it no longer has any effect on the code. */
1978 static bool remote_break;
1979
1980 static void
1981 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1982 {
1983 if (remote_break)
1984 interrupt_sequence_mode = interrupt_sequence_break;
1985 else
1986 interrupt_sequence_mode = interrupt_sequence_control_c;
1987 }
1988
1989 static void
1990 show_remotebreak (struct ui_file *file, int from_tty,
1991 struct cmd_list_element *c,
1992 const char *value)
1993 {
1994 }
1995
1996 /* This variable sets the number of bits in an address that are to be
1997 sent in a memory ("M" or "m") packet. Normally, after stripping
1998 leading zeros, the entire address would be sent. This variable
1999 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2000 initial implementation of remote.c restricted the address sent in
2001 memory packets to ``host::sizeof long'' bytes - (typically 32
2002 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2003 address was never sent. Since fixing this bug may cause a break in
2004 some remote targets this variable is principally provided to
2005 facilitate backward compatibility. */
2006
2007 static unsigned int remote_address_size;
2008
2009 \f
2010 /* The default max memory-write-packet-size, when the setting is
2011 "fixed". The 16k is historical. (It came from older GDB's using
2012 alloca for buffers and the knowledge (folklore?) that some hosts
2013 don't cope very well with large alloca calls.) */
2014 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2015
2016 /* The minimum remote packet size for memory transfers. Ensures we
2017 can write at least one byte. */
2018 #define MIN_MEMORY_PACKET_SIZE 20
2019
2020 /* Get the memory packet size, assuming it is fixed. */
2021
2022 static long
2023 get_fixed_memory_packet_size (struct memory_packet_config *config)
2024 {
2025 gdb_assert (config->fixed_p);
2026
2027 if (config->size <= 0)
2028 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2029 else
2030 return config->size;
2031 }
2032
2033 /* Compute the current size of a read/write packet. Since this makes
2034 use of ``actual_register_packet_size'' the computation is dynamic. */
2035
2036 long
2037 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2038 {
2039 struct remote_state *rs = get_remote_state ();
2040 remote_arch_state *rsa
2041 = rs->get_remote_arch_state (current_inferior ()->arch ());
2042
2043 long what_they_get;
2044 if (config->fixed_p)
2045 what_they_get = get_fixed_memory_packet_size (config);
2046 else
2047 {
2048 what_they_get = get_remote_packet_size ();
2049 /* Limit the packet to the size specified by the user. */
2050 if (config->size > 0
2051 && what_they_get > config->size)
2052 what_they_get = config->size;
2053
2054 /* Limit it to the size of the targets ``g'' response unless we have
2055 permission from the stub to use a larger packet size. */
2056 if (rs->explicit_packet_size == 0
2057 && rsa->actual_register_packet_size > 0
2058 && what_they_get > rsa->actual_register_packet_size)
2059 what_they_get = rsa->actual_register_packet_size;
2060 }
2061 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2062 what_they_get = MIN_MEMORY_PACKET_SIZE;
2063
2064 /* Make sure there is room in the global buffer for this packet
2065 (including its trailing NUL byte). */
2066 if (rs->buf.size () < what_they_get + 1)
2067 rs->buf.resize (2 * what_they_get);
2068
2069 return what_they_get;
2070 }
2071
2072 /* Update the size of a read/write packet. If they user wants
2073 something really big then do a sanity check. */
2074
2075 static void
2076 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2077 bool target_connected)
2078 {
2079 int fixed_p = config->fixed_p;
2080 long size = config->size;
2081
2082 if (args == NULL)
2083 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2084 else if (strcmp (args, "hard") == 0
2085 || strcmp (args, "fixed") == 0)
2086 fixed_p = 1;
2087 else if (strcmp (args, "soft") == 0
2088 || strcmp (args, "limit") == 0)
2089 fixed_p = 0;
2090 else
2091 {
2092 char *end;
2093
2094 size = strtoul (args, &end, 0);
2095 if (args == end)
2096 error (_("Invalid %s (bad syntax)."), config->name);
2097
2098 /* Instead of explicitly capping the size of a packet to or
2099 disallowing it, the user is allowed to set the size to
2100 something arbitrarily large. */
2101 }
2102
2103 /* Extra checks? */
2104 if (fixed_p && !config->fixed_p)
2105 {
2106 /* So that the query shows the correct value. */
2107 long query_size = (size <= 0
2108 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2109 : size);
2110
2111 if (target_connected
2112 && !query (_("The target may not be able to correctly handle a %s\n"
2113 "of %ld bytes. Change the packet size? "),
2114 config->name, query_size))
2115 error (_("Packet size not changed."));
2116 else if (!target_connected
2117 && !query (_("Future remote targets may not be able to "
2118 "correctly handle a %s\nof %ld bytes. Change the "
2119 "packet size for future remote targets? "),
2120 config->name, query_size))
2121 error (_("Packet size not changed."));
2122 }
2123 /* Update the config. */
2124 config->fixed_p = fixed_p;
2125 config->size = size;
2126
2127 const char *target_type = get_target_type_name (target_connected);
2128 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2129 args);
2130
2131 }
2132
2133 /* Show the memory-read or write-packet size configuration CONFIG of the
2134 target REMOTE. If REMOTE is nullptr, the default configuration for future
2135 remote targets should be passed in CONFIG. */
2136
2137 static void
2138 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2139 {
2140 const char *target_type = get_target_type_name (remote != nullptr);
2141
2142 if (config->size == 0)
2143 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2144 else
2145 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2146 config->size);
2147
2148 if (config->fixed_p)
2149 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2150 get_fixed_memory_packet_size (config));
2151 else
2152 {
2153 if (remote != nullptr)
2154 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2155 remote->get_memory_packet_size (config));
2156 else
2157 gdb_puts ("The actual limit will be further reduced "
2158 "dependent on the target.\n");
2159 }
2160 }
2161
2162 /* Configure the memory-write-packet size of the currently selected target. If
2163 no target is available, the default configuration for future remote targets
2164 is configured. */
2165
2166 static void
2167 set_memory_write_packet_size (const char *args, int from_tty)
2168 {
2169 remote_target *remote = get_current_remote_target ();
2170 if (remote != nullptr)
2171 {
2172 set_memory_packet_size
2173 (args, &remote->m_features.m_memory_write_packet_config, true);
2174 }
2175 else
2176 {
2177 memory_packet_config* config = &memory_write_packet_config;
2178 set_memory_packet_size (args, config, false);
2179 }
2180 }
2181
2182 /* Display the memory-write-packet size of the currently selected target. If
2183 no target is available, the default configuration for future remote targets
2184 is shown. */
2185
2186 static void
2187 show_memory_write_packet_size (const char *args, int from_tty)
2188 {
2189 remote_target *remote = get_current_remote_target ();
2190 if (remote != nullptr)
2191 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2192 remote);
2193 else
2194 show_memory_packet_size (&memory_write_packet_config, nullptr);
2195 }
2196
2197 /* Show the number of hardware watchpoints that can be used. */
2198
2199 static void
2200 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2201 struct cmd_list_element *c,
2202 const char *value)
2203 {
2204 gdb_printf (file, _("The maximum number of target hardware "
2205 "watchpoints is %s.\n"), value);
2206 }
2207
2208 /* Show the length limit (in bytes) for hardware watchpoints. */
2209
2210 static void
2211 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2212 struct cmd_list_element *c,
2213 const char *value)
2214 {
2215 gdb_printf (file, _("The maximum length (in bytes) of a target "
2216 "hardware watchpoint is %s.\n"), value);
2217 }
2218
2219 /* Show the number of hardware breakpoints that can be used. */
2220
2221 static void
2222 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2223 struct cmd_list_element *c,
2224 const char *value)
2225 {
2226 gdb_printf (file, _("The maximum number of target hardware "
2227 "breakpoints is %s.\n"), value);
2228 }
2229
2230 /* Controls the maximum number of characters to display in the debug output
2231 for each remote packet. The remaining characters are omitted. */
2232
2233 static int remote_packet_max_chars = 512;
2234
2235 /* Show the maximum number of characters to display for each remote packet
2236 when remote debugging is enabled. */
2237
2238 static void
2239 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2240 struct cmd_list_element *c,
2241 const char *value)
2242 {
2243 gdb_printf (file, _("Number of remote packet characters to "
2244 "display is %s.\n"), value);
2245 }
2246
2247 long
2248 remote_target::get_memory_write_packet_size ()
2249 {
2250 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2251 }
2252
2253 /* Configure the memory-read-packet size of the currently selected target. If
2254 no target is available, the default configuration for future remote targets
2255 is adapted. */
2256
2257 static void
2258 set_memory_read_packet_size (const char *args, int from_tty)
2259 {
2260 remote_target *remote = get_current_remote_target ();
2261 if (remote != nullptr)
2262 set_memory_packet_size
2263 (args, &remote->m_features.m_memory_read_packet_config, true);
2264 else
2265 {
2266 memory_packet_config* config = &memory_read_packet_config;
2267 set_memory_packet_size (args, config, false);
2268 }
2269
2270 }
2271
2272 /* Display the memory-read-packet size of the currently selected target. If
2273 no target is available, the default configuration for future remote targets
2274 is shown. */
2275
2276 static void
2277 show_memory_read_packet_size (const char *args, int from_tty)
2278 {
2279 remote_target *remote = get_current_remote_target ();
2280 if (remote != nullptr)
2281 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2282 remote);
2283 else
2284 show_memory_packet_size (&memory_read_packet_config, nullptr);
2285 }
2286
2287 long
2288 remote_target::get_memory_read_packet_size ()
2289 {
2290 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2291
2292 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2293 extra buffer size argument before the memory read size can be
2294 increased beyond this. */
2295 if (size > get_remote_packet_size ())
2296 size = get_remote_packet_size ();
2297 return size;
2298 }
2299
2300 static enum packet_support packet_config_support (const packet_config *config);
2301
2302
2303 static void
2304 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2305 cmd_list_element *c)
2306 {
2307 remote_target *remote = get_current_remote_target ();
2308 gdb_assert (c->var.has_value ());
2309
2310 auto *default_config = static_cast<packet_config *> (c->context ());
2311 const int packet_idx = std::distance (remote_protocol_packets,
2312 default_config);
2313
2314 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2315 {
2316 const char *name = packets_descriptions[packet_idx].name;
2317 const auto_boolean value = c->var->get<auto_boolean> ();
2318 const char *support = get_packet_support_name (value);
2319 const char *target_type = get_target_type_name (remote != nullptr);
2320
2321 if (remote != nullptr)
2322 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2323 else
2324 remote_protocol_packets[packet_idx].detect = value;
2325
2326 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2327 target_type, support);
2328 return;
2329 }
2330
2331 internal_error (_("Could not find config for %s"), c->name);
2332 }
2333
2334 static void
2335 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2336 remote_target *remote)
2337 {
2338 const char *support = "internal-error";
2339 const char *target_type = get_target_type_name (remote != nullptr);
2340
2341 packet_config *config;
2342 if (remote != nullptr)
2343 config = &remote->m_features.m_protocol_packets[which_packet];
2344 else
2345 config = &remote_protocol_packets[which_packet];
2346
2347 switch (packet_config_support (config))
2348 {
2349 case PACKET_ENABLE:
2350 support = "enabled";
2351 break;
2352 case PACKET_DISABLE:
2353 support = "disabled";
2354 break;
2355 case PACKET_SUPPORT_UNKNOWN:
2356 support = "unknown";
2357 break;
2358 }
2359 switch (config->detect)
2360 {
2361 case AUTO_BOOLEAN_AUTO:
2362 gdb_printf (file,
2363 _("Support for the '%s' packet %s is \"auto\", "
2364 "currently %s.\n"),
2365 packets_descriptions[which_packet].name, target_type,
2366 support);
2367 break;
2368 case AUTO_BOOLEAN_TRUE:
2369 case AUTO_BOOLEAN_FALSE:
2370 gdb_printf (file,
2371 _("Support for the '%s' packet %s is \"%s\".\n"),
2372 packets_descriptions[which_packet].name, target_type,
2373 get_packet_support_name (config->detect));
2374 break;
2375 }
2376 }
2377
2378 static void
2379 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2380 const char *title, int legacy)
2381 {
2382 packets_descriptions[which_packet].name = name;
2383 packets_descriptions[which_packet].title = title;
2384
2385 packet_config *config = &remote_protocol_packets[which_packet];
2386
2387 gdb::unique_xmalloc_ptr<char> set_doc
2388 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2389 name, title);
2390 gdb::unique_xmalloc_ptr<char> show_doc
2391 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2392 name, title);
2393 /* set/show TITLE-packet {auto,on,off} */
2394 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2395 set_show_commands cmds
2396 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2397 &config->detect, set_doc.get (),
2398 show_doc.get (), NULL, /* help_doc */
2399 set_remote_protocol_packet_cmd,
2400 show_remote_protocol_packet_cmd,
2401 &remote_set_cmdlist, &remote_show_cmdlist);
2402 cmds.show->set_context (config);
2403 cmds.set->set_context (config);
2404
2405 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2406 if (legacy)
2407 {
2408 /* It's not clear who should take ownership of the LEGACY_NAME string
2409 created below, so, for now, place the string into a static vector
2410 which ensures the strings is released when GDB exits. */
2411 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2412 gdb::unique_xmalloc_ptr<char> legacy_name
2413 = xstrprintf ("%s-packet", name);
2414 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2415 &remote_set_cmdlist);
2416 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2417 &remote_show_cmdlist);
2418 legacy_names.emplace_back (std::move (legacy_name));
2419 }
2420 }
2421
2422 static enum packet_result
2423 packet_check_result (const char *buf)
2424 {
2425 if (buf[0] != '\0')
2426 {
2427 /* The stub recognized the packet request. Check that the
2428 operation succeeded. */
2429 if (buf[0] == 'E'
2430 && isxdigit (buf[1]) && isxdigit (buf[2])
2431 && buf[3] == '\0')
2432 /* "Enn" - definitely an error. */
2433 return PACKET_ERROR;
2434
2435 /* Always treat "E." as an error. This will be used for
2436 more verbose error messages, such as E.memtypes. */
2437 if (buf[0] == 'E' && buf[1] == '.')
2438 return PACKET_ERROR;
2439
2440 /* The packet may or may not be OK. Just assume it is. */
2441 return PACKET_OK;
2442 }
2443 else
2444 /* The stub does not support the packet. */
2445 return PACKET_UNKNOWN;
2446 }
2447
2448 static enum packet_result
2449 packet_check_result (const gdb::char_vector &buf)
2450 {
2451 return packet_check_result (buf.data ());
2452 }
2453
2454 packet_result
2455 remote_features::packet_ok (const char *buf, const int which_packet)
2456 {
2457 packet_config *config = &m_protocol_packets[which_packet];
2458 packet_description *descr = &packets_descriptions[which_packet];
2459
2460 enum packet_result result;
2461
2462 if (config->detect != AUTO_BOOLEAN_TRUE
2463 && config->support == PACKET_DISABLE)
2464 internal_error (_("packet_ok: attempt to use a disabled packet"));
2465
2466 result = packet_check_result (buf);
2467 switch (result)
2468 {
2469 case PACKET_OK:
2470 case PACKET_ERROR:
2471 /* The stub recognized the packet request. */
2472 if (config->support == PACKET_SUPPORT_UNKNOWN)
2473 {
2474 remote_debug_printf ("Packet %s (%s) is supported",
2475 descr->name, descr->title);
2476 config->support = PACKET_ENABLE;
2477 }
2478 break;
2479 case PACKET_UNKNOWN:
2480 /* The stub does not support the packet. */
2481 if (config->detect == AUTO_BOOLEAN_AUTO
2482 && config->support == PACKET_ENABLE)
2483 {
2484 /* If the stub previously indicated that the packet was
2485 supported then there is a protocol error. */
2486 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2487 descr->name, descr->title);
2488 }
2489 else if (config->detect == AUTO_BOOLEAN_TRUE)
2490 {
2491 /* The user set it wrong. */
2492 error (_("Enabled packet %s (%s) not recognized by stub"),
2493 descr->name, descr->title);
2494 }
2495
2496 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2497 descr->title);
2498 config->support = PACKET_DISABLE;
2499 break;
2500 }
2501
2502 return result;
2503 }
2504
2505 packet_result
2506 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2507 {
2508 return packet_ok (buf.data (), which_packet);
2509 }
2510
2511 /* Returns whether a given packet or feature is supported. This takes
2512 into account the state of the corresponding "set remote foo-packet"
2513 command, which may be used to bypass auto-detection. */
2514
2515 static enum packet_support
2516 packet_config_support (const packet_config *config)
2517 {
2518 switch (config->detect)
2519 {
2520 case AUTO_BOOLEAN_TRUE:
2521 return PACKET_ENABLE;
2522 case AUTO_BOOLEAN_FALSE:
2523 return PACKET_DISABLE;
2524 case AUTO_BOOLEAN_AUTO:
2525 return config->support;
2526 default:
2527 gdb_assert_not_reached ("bad switch");
2528 }
2529 }
2530
2531 packet_support
2532 remote_features::packet_support (int packet) const
2533 {
2534 const packet_config *config = &m_protocol_packets[packet];
2535 return packet_config_support (config);
2536 }
2537
2538 static void
2539 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2540 struct cmd_list_element *c,
2541 const char *value)
2542 {
2543 remote_target *remote = get_current_remote_target ();
2544 gdb_assert (c->var.has_value ());
2545
2546 auto *default_config = static_cast<packet_config *> (c->context ());
2547 const int packet_idx = std::distance (remote_protocol_packets,
2548 default_config);
2549
2550 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2551 {
2552 show_packet_config_cmd (file, packet_idx, remote);
2553 return;
2554 }
2555 internal_error (_("Could not find config for %s"), c->name);
2556 }
2557
2558 /* Should we try one of the 'Z' requests? */
2559
2560 enum Z_packet_type
2561 {
2562 Z_PACKET_SOFTWARE_BP,
2563 Z_PACKET_HARDWARE_BP,
2564 Z_PACKET_WRITE_WP,
2565 Z_PACKET_READ_WP,
2566 Z_PACKET_ACCESS_WP,
2567 NR_Z_PACKET_TYPES
2568 };
2569
2570 /* For compatibility with older distributions. Provide a ``set remote
2571 Z-packet ...'' command that updates all the Z packet types. */
2572
2573 static enum auto_boolean remote_Z_packet_detect;
2574
2575 static void
2576 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2577 struct cmd_list_element *c)
2578 {
2579 remote_target *remote = get_current_remote_target ();
2580 int i;
2581
2582 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2583 {
2584 if (remote != nullptr)
2585 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2586 = remote_Z_packet_detect;
2587 else
2588 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2589 }
2590
2591 const char *support = get_packet_support_name (remote_Z_packet_detect);
2592 const char *target_type = get_target_type_name (remote != nullptr);
2593 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2594 support);
2595
2596 }
2597
2598 static void
2599 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2600 struct cmd_list_element *c,
2601 const char *value)
2602 {
2603 remote_target *remote = get_current_remote_target ();
2604 int i;
2605
2606 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2607 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2608 }
2609
2610 /* Insert fork catchpoint target routine. If fork events are enabled
2611 then return success, nothing more to do. */
2612
2613 int
2614 remote_target::insert_fork_catchpoint (int pid)
2615 {
2616 return !m_features.remote_fork_event_p ();
2617 }
2618
2619 /* Remove fork catchpoint target routine. Nothing to do, just
2620 return success. */
2621
2622 int
2623 remote_target::remove_fork_catchpoint (int pid)
2624 {
2625 return 0;
2626 }
2627
2628 /* Insert vfork catchpoint target routine. If vfork events are enabled
2629 then return success, nothing more to do. */
2630
2631 int
2632 remote_target::insert_vfork_catchpoint (int pid)
2633 {
2634 return !m_features.remote_vfork_event_p ();
2635 }
2636
2637 /* Remove vfork catchpoint target routine. Nothing to do, just
2638 return success. */
2639
2640 int
2641 remote_target::remove_vfork_catchpoint (int pid)
2642 {
2643 return 0;
2644 }
2645
2646 /* Insert exec catchpoint target routine. If exec events are
2647 enabled, just return success. */
2648
2649 int
2650 remote_target::insert_exec_catchpoint (int pid)
2651 {
2652 return !m_features.remote_exec_event_p ();
2653 }
2654
2655 /* Remove exec catchpoint target routine. Nothing to do, just
2656 return success. */
2657
2658 int
2659 remote_target::remove_exec_catchpoint (int pid)
2660 {
2661 return 0;
2662 }
2663
2664 \f
2665
2666 /* Take advantage of the fact that the TID field is not used, to tag
2667 special ptids with it set to != 0. */
2668 static const ptid_t magic_null_ptid (42000, -1, 1);
2669 static const ptid_t not_sent_ptid (42000, -2, 1);
2670 static const ptid_t any_thread_ptid (42000, 0, 1);
2671
2672 /* Find out if the stub attached to PID (and hence GDB should offer to
2673 detach instead of killing it when bailing out). */
2674
2675 int
2676 remote_target::remote_query_attached (int pid)
2677 {
2678 struct remote_state *rs = get_remote_state ();
2679 size_t size = get_remote_packet_size ();
2680
2681 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2682 return 0;
2683
2684 if (m_features.remote_multi_process_p ())
2685 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2686 else
2687 xsnprintf (rs->buf.data (), size, "qAttached");
2688
2689 putpkt (rs->buf);
2690 getpkt (&rs->buf);
2691
2692 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2693 {
2694 case PACKET_OK:
2695 if (strcmp (rs->buf.data (), "1") == 0)
2696 return 1;
2697 break;
2698 case PACKET_ERROR:
2699 warning (_("Remote failure reply: %s"), rs->buf.data ());
2700 break;
2701 case PACKET_UNKNOWN:
2702 break;
2703 }
2704
2705 return 0;
2706 }
2707
2708 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2709 has been invented by GDB, instead of reported by the target. Since
2710 we can be connected to a remote system before before knowing about
2711 any inferior, mark the target with execution when we find the first
2712 inferior. If ATTACHED is 1, then we had just attached to this
2713 inferior. If it is 0, then we just created this inferior. If it
2714 is -1, then try querying the remote stub to find out if it had
2715 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2716 attempt to open this inferior's executable as the main executable
2717 if no main executable is open already. */
2718
2719 inferior *
2720 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2721 int try_open_exec)
2722 {
2723 struct inferior *inf;
2724
2725 /* Check whether this process we're learning about is to be
2726 considered attached, or if is to be considered to have been
2727 spawned by the stub. */
2728 if (attached == -1)
2729 attached = remote_query_attached (pid);
2730
2731 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2732 {
2733 /* If the target shares code across all inferiors, then every
2734 attach adds a new inferior. */
2735 inf = add_inferior (pid);
2736
2737 /* ... and every inferior is bound to the same program space.
2738 However, each inferior may still have its own address
2739 space. */
2740 inf->aspace = maybe_new_address_space ();
2741 inf->pspace = current_program_space;
2742 }
2743 else
2744 {
2745 /* In the traditional debugging scenario, there's a 1-1 match
2746 between program/address spaces. We simply bind the inferior
2747 to the program space's address space. */
2748 inf = current_inferior ();
2749
2750 /* However, if the current inferior is already bound to a
2751 process, find some other empty inferior. */
2752 if (inf->pid != 0)
2753 {
2754 inf = nullptr;
2755 for (inferior *it : all_inferiors ())
2756 if (it->pid == 0)
2757 {
2758 inf = it;
2759 break;
2760 }
2761 }
2762 if (inf == nullptr)
2763 {
2764 /* Since all inferiors were already bound to a process, add
2765 a new inferior. */
2766 inf = add_inferior_with_spaces ();
2767 }
2768 switch_to_inferior_no_thread (inf);
2769 inf->push_target (this);
2770 inferior_appeared (inf, pid);
2771 }
2772
2773 inf->attach_flag = attached;
2774 inf->fake_pid_p = fake_pid_p;
2775
2776 /* If no main executable is currently open then attempt to
2777 open the file that was executed to create this inferior. */
2778 if (try_open_exec && get_exec_file (0) == NULL)
2779 exec_file_locate_attach (pid, 0, 1);
2780
2781 /* Check for exec file mismatch, and let the user solve it. */
2782 validate_exec_file (1);
2783
2784 return inf;
2785 }
2786
2787 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2788 static remote_thread_info *get_remote_thread_info (remote_target *target,
2789 ptid_t ptid);
2790
2791 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2792 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2793 remote_state::starting_up flag) is true then the new thread is added
2794 silently, otherwise the new thread will be announced to the user. */
2795
2796 thread_info *
2797 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2798 bool silent_p)
2799 {
2800 struct remote_state *rs = get_remote_state ();
2801 struct thread_info *thread;
2802
2803 /* GDB historically didn't pull threads in the initial connection
2804 setup. If the remote target doesn't even have a concept of
2805 threads (e.g., a bare-metal target), even if internally we
2806 consider that a single-threaded target, mentioning a new thread
2807 might be confusing to the user. Be silent then, preserving the
2808 age old behavior. */
2809 if (rs->starting_up || silent_p)
2810 thread = add_thread_silent (this, ptid);
2811 else
2812 thread = add_thread (this, ptid);
2813
2814 if (executing)
2815 get_remote_thread_info (thread)->set_resumed ();
2816 set_executing (this, ptid, executing);
2817 set_running (this, ptid, running);
2818
2819 return thread;
2820 }
2821
2822 /* Come here when we learn about a thread id from the remote target.
2823 It may be the first time we hear about such thread, so take the
2824 opportunity to add it to GDB's thread list. In case this is the
2825 first time we're noticing its corresponding inferior, add it to
2826 GDB's inferior list as well. EXECUTING indicates whether the
2827 thread is (internally) executing or stopped. */
2828
2829 void
2830 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2831 {
2832 /* In non-stop mode, we assume new found threads are (externally)
2833 running until proven otherwise with a stop reply. In all-stop,
2834 we can only get here if all threads are stopped. */
2835 bool running = target_is_non_stop_p ();
2836
2837 /* If this is a new thread, add it to GDB's thread list.
2838 If we leave it up to WFI to do this, bad things will happen. */
2839
2840 thread_info *tp = this->find_thread (currthread);
2841 if (tp != NULL && tp->state == THREAD_EXITED)
2842 {
2843 /* We're seeing an event on a thread id we knew had exited.
2844 This has to be a new thread reusing the old id. Add it. */
2845 remote_add_thread (currthread, running, executing, false);
2846 return;
2847 }
2848
2849 if (!in_thread_list (this, currthread))
2850 {
2851 struct inferior *inf = NULL;
2852 int pid = currthread.pid ();
2853
2854 if (inferior_ptid.is_pid ()
2855 && pid == inferior_ptid.pid ())
2856 {
2857 /* inferior_ptid has no thread member yet. This can happen
2858 with the vAttach -> remote_wait,"TAAthread:" path if the
2859 stub doesn't support qC. This is the first stop reported
2860 after an attach, so this is the main thread. Update the
2861 ptid in the thread list. */
2862 if (in_thread_list (this, ptid_t (pid)))
2863 thread_change_ptid (this, inferior_ptid, currthread);
2864 else
2865 {
2866 thread_info *thr
2867 = remote_add_thread (currthread, running, executing, false);
2868 switch_to_thread (thr);
2869 }
2870 return;
2871 }
2872
2873 if (magic_null_ptid == inferior_ptid)
2874 {
2875 /* inferior_ptid is not set yet. This can happen with the
2876 vRun -> remote_wait,"TAAthread:" path if the stub
2877 doesn't support qC. This is the first stop reported
2878 after an attach, so this is the main thread. Update the
2879 ptid in the thread list. */
2880 thread_change_ptid (this, inferior_ptid, currthread);
2881 return;
2882 }
2883
2884 /* When connecting to a target remote, or to a target
2885 extended-remote which already was debugging an inferior, we
2886 may not know about it yet. Add it before adding its child
2887 thread, so notifications are emitted in a sensible order. */
2888 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2889 {
2890 bool fake_pid_p = !m_features.remote_multi_process_p ();
2891
2892 inf = remote_add_inferior (fake_pid_p,
2893 currthread.pid (), -1, 1);
2894 }
2895
2896 /* This is really a new thread. Add it. */
2897 thread_info *new_thr
2898 = remote_add_thread (currthread, running, executing, false);
2899
2900 /* If we found a new inferior, let the common code do whatever
2901 it needs to with it (e.g., read shared libraries, insert
2902 breakpoints), unless we're just setting up an all-stop
2903 connection. */
2904 if (inf != NULL)
2905 {
2906 struct remote_state *rs = get_remote_state ();
2907
2908 if (!rs->starting_up)
2909 notice_new_inferior (new_thr, executing, 0);
2910 }
2911 }
2912 }
2913
2914 /* Return THREAD's private thread data, creating it if necessary. */
2915
2916 static remote_thread_info *
2917 get_remote_thread_info (thread_info *thread)
2918 {
2919 gdb_assert (thread != NULL);
2920
2921 if (thread->priv == NULL)
2922 thread->priv.reset (new remote_thread_info);
2923
2924 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2925 }
2926
2927 /* Return PTID's private thread data, creating it if necessary. */
2928
2929 static remote_thread_info *
2930 get_remote_thread_info (remote_target *target, ptid_t ptid)
2931 {
2932 thread_info *thr = target->find_thread (ptid);
2933 return get_remote_thread_info (thr);
2934 }
2935
2936 /* Call this function as a result of
2937 1) A halt indication (T packet) containing a thread id
2938 2) A direct query of currthread
2939 3) Successful execution of set thread */
2940
2941 static void
2942 record_currthread (struct remote_state *rs, ptid_t currthread)
2943 {
2944 rs->general_thread = currthread;
2945 }
2946
2947 /* If 'QPassSignals' is supported, tell the remote stub what signals
2948 it can simply pass through to the inferior without reporting. */
2949
2950 void
2951 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2952 {
2953 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2954 {
2955 char *pass_packet, *p;
2956 int count = 0;
2957 struct remote_state *rs = get_remote_state ();
2958
2959 gdb_assert (pass_signals.size () < 256);
2960 for (size_t i = 0; i < pass_signals.size (); i++)
2961 {
2962 if (pass_signals[i])
2963 count++;
2964 }
2965 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2966 strcpy (pass_packet, "QPassSignals:");
2967 p = pass_packet + strlen (pass_packet);
2968 for (size_t i = 0; i < pass_signals.size (); i++)
2969 {
2970 if (pass_signals[i])
2971 {
2972 if (i >= 16)
2973 *p++ = tohex (i >> 4);
2974 *p++ = tohex (i & 15);
2975 if (count)
2976 *p++ = ';';
2977 else
2978 break;
2979 count--;
2980 }
2981 }
2982 *p = 0;
2983 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2984 {
2985 putpkt (pass_packet);
2986 getpkt (&rs->buf);
2987 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2988 xfree (rs->last_pass_packet);
2989 rs->last_pass_packet = pass_packet;
2990 }
2991 else
2992 xfree (pass_packet);
2993 }
2994 }
2995
2996 /* If 'QCatchSyscalls' is supported, tell the remote stub
2997 to report syscalls to GDB. */
2998
2999 int
3000 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3001 gdb::array_view<const int> syscall_counts)
3002 {
3003 const char *catch_packet;
3004 enum packet_result result;
3005 int n_sysno = 0;
3006
3007 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3008 {
3009 /* Not supported. */
3010 return 1;
3011 }
3012
3013 if (needed && any_count == 0)
3014 {
3015 /* Count how many syscalls are to be caught. */
3016 for (size_t i = 0; i < syscall_counts.size (); i++)
3017 {
3018 if (syscall_counts[i] != 0)
3019 n_sysno++;
3020 }
3021 }
3022
3023 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3024 pid, needed, any_count, n_sysno);
3025
3026 std::string built_packet;
3027 if (needed)
3028 {
3029 /* Prepare a packet with the sysno list, assuming max 8+1
3030 characters for a sysno. If the resulting packet size is too
3031 big, fallback on the non-selective packet. */
3032 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3033 built_packet.reserve (maxpktsz);
3034 built_packet = "QCatchSyscalls:1";
3035 if (any_count == 0)
3036 {
3037 /* Add in each syscall to be caught. */
3038 for (size_t i = 0; i < syscall_counts.size (); i++)
3039 {
3040 if (syscall_counts[i] != 0)
3041 string_appendf (built_packet, ";%zx", i);
3042 }
3043 }
3044 if (built_packet.size () > get_remote_packet_size ())
3045 {
3046 /* catch_packet too big. Fallback to less efficient
3047 non selective mode, with GDB doing the filtering. */
3048 catch_packet = "QCatchSyscalls:1";
3049 }
3050 else
3051 catch_packet = built_packet.c_str ();
3052 }
3053 else
3054 catch_packet = "QCatchSyscalls:0";
3055
3056 struct remote_state *rs = get_remote_state ();
3057
3058 putpkt (catch_packet);
3059 getpkt (&rs->buf);
3060 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3061 if (result == PACKET_OK)
3062 return 0;
3063 else
3064 return -1;
3065 }
3066
3067 /* If 'QProgramSignals' is supported, tell the remote stub what
3068 signals it should pass through to the inferior when detaching. */
3069
3070 void
3071 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3072 {
3073 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3074 {
3075 char *packet, *p;
3076 int count = 0;
3077 struct remote_state *rs = get_remote_state ();
3078
3079 gdb_assert (signals.size () < 256);
3080 for (size_t i = 0; i < signals.size (); i++)
3081 {
3082 if (signals[i])
3083 count++;
3084 }
3085 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3086 strcpy (packet, "QProgramSignals:");
3087 p = packet + strlen (packet);
3088 for (size_t i = 0; i < signals.size (); i++)
3089 {
3090 if (signal_pass_state (i))
3091 {
3092 if (i >= 16)
3093 *p++ = tohex (i >> 4);
3094 *p++ = tohex (i & 15);
3095 if (count)
3096 *p++ = ';';
3097 else
3098 break;
3099 count--;
3100 }
3101 }
3102 *p = 0;
3103 if (!rs->last_program_signals_packet
3104 || strcmp (rs->last_program_signals_packet, packet) != 0)
3105 {
3106 putpkt (packet);
3107 getpkt (&rs->buf);
3108 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3109 xfree (rs->last_program_signals_packet);
3110 rs->last_program_signals_packet = packet;
3111 }
3112 else
3113 xfree (packet);
3114 }
3115 }
3116
3117 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3118 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3119 thread. If GEN is set, set the general thread, if not, then set
3120 the step/continue thread. */
3121 void
3122 remote_target::set_thread (ptid_t ptid, int gen)
3123 {
3124 struct remote_state *rs = get_remote_state ();
3125 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3126 char *buf = rs->buf.data ();
3127 char *endbuf = buf + get_remote_packet_size ();
3128
3129 if (state == ptid)
3130 return;
3131
3132 *buf++ = 'H';
3133 *buf++ = gen ? 'g' : 'c';
3134 if (ptid == magic_null_ptid)
3135 xsnprintf (buf, endbuf - buf, "0");
3136 else if (ptid == any_thread_ptid)
3137 xsnprintf (buf, endbuf - buf, "0");
3138 else if (ptid == minus_one_ptid)
3139 xsnprintf (buf, endbuf - buf, "-1");
3140 else
3141 write_ptid (buf, endbuf, ptid);
3142 putpkt (rs->buf);
3143 getpkt (&rs->buf);
3144 if (gen)
3145 rs->general_thread = ptid;
3146 else
3147 rs->continue_thread = ptid;
3148 }
3149
3150 void
3151 remote_target::set_general_thread (ptid_t ptid)
3152 {
3153 set_thread (ptid, 1);
3154 }
3155
3156 void
3157 remote_target::set_continue_thread (ptid_t ptid)
3158 {
3159 set_thread (ptid, 0);
3160 }
3161
3162 /* Change the remote current process. Which thread within the process
3163 ends up selected isn't important, as long as it is the same process
3164 as what INFERIOR_PTID points to.
3165
3166 This comes from that fact that there is no explicit notion of
3167 "selected process" in the protocol. The selected process for
3168 general operations is the process the selected general thread
3169 belongs to. */
3170
3171 void
3172 remote_target::set_general_process ()
3173 {
3174 /* If the remote can't handle multiple processes, don't bother. */
3175 if (!m_features.remote_multi_process_p ())
3176 return;
3177
3178 remote_state *rs = get_remote_state ();
3179
3180 /* We only need to change the remote current thread if it's pointing
3181 at some other process. */
3182 if (rs->general_thread.pid () != inferior_ptid.pid ())
3183 set_general_thread (inferior_ptid);
3184 }
3185
3186 \f
3187 /* Return nonzero if this is the main thread that we made up ourselves
3188 to model non-threaded targets as single-threaded. */
3189
3190 static int
3191 remote_thread_always_alive (ptid_t ptid)
3192 {
3193 if (ptid == magic_null_ptid)
3194 /* The main thread is always alive. */
3195 return 1;
3196
3197 if (ptid.pid () != 0 && ptid.lwp () == 0)
3198 /* The main thread is always alive. This can happen after a
3199 vAttach, if the remote side doesn't support
3200 multi-threading. */
3201 return 1;
3202
3203 return 0;
3204 }
3205
3206 /* Return nonzero if the thread PTID is still alive on the remote
3207 system. */
3208
3209 bool
3210 remote_target::thread_alive (ptid_t ptid)
3211 {
3212 struct remote_state *rs = get_remote_state ();
3213 char *p, *endp;
3214
3215 /* Check if this is a thread that we made up ourselves to model
3216 non-threaded targets as single-threaded. */
3217 if (remote_thread_always_alive (ptid))
3218 return 1;
3219
3220 p = rs->buf.data ();
3221 endp = p + get_remote_packet_size ();
3222
3223 *p++ = 'T';
3224 write_ptid (p, endp, ptid);
3225
3226 putpkt (rs->buf);
3227 getpkt (&rs->buf);
3228 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3229 }
3230
3231 /* Return a pointer to a thread name if we know it and NULL otherwise.
3232 The thread_info object owns the memory for the name. */
3233
3234 const char *
3235 remote_target::thread_name (struct thread_info *info)
3236 {
3237 if (info->priv != NULL)
3238 {
3239 const std::string &name = get_remote_thread_info (info)->name;
3240 return !name.empty () ? name.c_str () : NULL;
3241 }
3242
3243 return NULL;
3244 }
3245
3246 /* About these extended threadlist and threadinfo packets. They are
3247 variable length packets but, the fields within them are often fixed
3248 length. They are redundant enough to send over UDP as is the
3249 remote protocol in general. There is a matching unit test module
3250 in libstub. */
3251
3252 /* WARNING: This threadref data structure comes from the remote O.S.,
3253 libstub protocol encoding, and remote.c. It is not particularly
3254 changeable. */
3255
3256 /* Right now, the internal structure is int. We want it to be bigger.
3257 Plan to fix this. */
3258
3259 typedef int gdb_threadref; /* Internal GDB thread reference. */
3260
3261 /* gdb_ext_thread_info is an internal GDB data structure which is
3262 equivalent to the reply of the remote threadinfo packet. */
3263
3264 struct gdb_ext_thread_info
3265 {
3266 threadref threadid; /* External form of thread reference. */
3267 int active; /* Has state interesting to GDB?
3268 regs, stack. */
3269 char display[256]; /* Brief state display, name,
3270 blocked/suspended. */
3271 char shortname[32]; /* To be used to name threads. */
3272 char more_display[256]; /* Long info, statistics, queue depth,
3273 whatever. */
3274 };
3275
3276 /* The volume of remote transfers can be limited by submitting
3277 a mask containing bits specifying the desired information.
3278 Use a union of these values as the 'selection' parameter to
3279 get_thread_info. FIXME: Make these TAG names more thread specific. */
3280
3281 #define TAG_THREADID 1
3282 #define TAG_EXISTS 2
3283 #define TAG_DISPLAY 4
3284 #define TAG_THREADNAME 8
3285 #define TAG_MOREDISPLAY 16
3286
3287 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3288
3289 static const char *unpack_nibble (const char *buf, int *val);
3290
3291 static const char *unpack_byte (const char *buf, int *value);
3292
3293 static char *pack_int (char *buf, int value);
3294
3295 static const char *unpack_int (const char *buf, int *value);
3296
3297 static const char *unpack_string (const char *src, char *dest, int length);
3298
3299 static char *pack_threadid (char *pkt, threadref *id);
3300
3301 static const char *unpack_threadid (const char *inbuf, threadref *id);
3302
3303 void int_to_threadref (threadref *id, int value);
3304
3305 static int threadref_to_int (threadref *ref);
3306
3307 static void copy_threadref (threadref *dest, threadref *src);
3308
3309 static int threadmatch (threadref *dest, threadref *src);
3310
3311 static char *pack_threadinfo_request (char *pkt, int mode,
3312 threadref *id);
3313
3314 static char *pack_threadlist_request (char *pkt, int startflag,
3315 int threadcount,
3316 threadref *nextthread);
3317
3318 static int remote_newthread_step (threadref *ref, void *context);
3319
3320
3321 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3322 buffer we're allowed to write to. Returns
3323 BUF+CHARACTERS_WRITTEN. */
3324
3325 char *
3326 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3327 {
3328 int pid, tid;
3329
3330 if (m_features.remote_multi_process_p ())
3331 {
3332 pid = ptid.pid ();
3333 if (pid < 0)
3334 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3335 else
3336 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3337 }
3338 tid = ptid.lwp ();
3339 if (tid < 0)
3340 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3341 else
3342 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3343
3344 return buf;
3345 }
3346
3347 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3348 last parsed char. Returns null_ptid if no thread id is found, and
3349 throws an error if the thread id has an invalid format. */
3350
3351 static ptid_t
3352 read_ptid (const char *buf, const char **obuf)
3353 {
3354 const char *p = buf;
3355 const char *pp;
3356 ULONGEST pid = 0, tid = 0;
3357
3358 if (*p == 'p')
3359 {
3360 /* Multi-process ptid. */
3361 pp = unpack_varlen_hex (p + 1, &pid);
3362 if (*pp != '.')
3363 error (_("invalid remote ptid: %s"), p);
3364
3365 p = pp;
3366 pp = unpack_varlen_hex (p + 1, &tid);
3367 if (obuf)
3368 *obuf = pp;
3369 return ptid_t (pid, tid);
3370 }
3371
3372 /* No multi-process. Just a tid. */
3373 pp = unpack_varlen_hex (p, &tid);
3374
3375 /* Return null_ptid when no thread id is found. */
3376 if (p == pp)
3377 {
3378 if (obuf)
3379 *obuf = pp;
3380 return null_ptid;
3381 }
3382
3383 /* Since the stub is not sending a process id, default to what's
3384 current_inferior, unless it doesn't have a PID yet. If so,
3385 then since there's no way to know the pid of the reported
3386 threads, use the magic number. */
3387 inferior *inf = current_inferior ();
3388 if (inf->pid == 0)
3389 pid = magic_null_ptid.pid ();
3390 else
3391 pid = inf->pid;
3392
3393 if (obuf)
3394 *obuf = pp;
3395 return ptid_t (pid, tid);
3396 }
3397
3398 static int
3399 stubhex (int ch)
3400 {
3401 if (ch >= 'a' && ch <= 'f')
3402 return ch - 'a' + 10;
3403 if (ch >= '0' && ch <= '9')
3404 return ch - '0';
3405 if (ch >= 'A' && ch <= 'F')
3406 return ch - 'A' + 10;
3407 return -1;
3408 }
3409
3410 static int
3411 stub_unpack_int (const char *buff, int fieldlength)
3412 {
3413 int nibble;
3414 int retval = 0;
3415
3416 while (fieldlength)
3417 {
3418 nibble = stubhex (*buff++);
3419 retval |= nibble;
3420 fieldlength--;
3421 if (fieldlength)
3422 retval = retval << 4;
3423 }
3424 return retval;
3425 }
3426
3427 static const char *
3428 unpack_nibble (const char *buf, int *val)
3429 {
3430 *val = fromhex (*buf++);
3431 return buf;
3432 }
3433
3434 static const char *
3435 unpack_byte (const char *buf, int *value)
3436 {
3437 *value = stub_unpack_int (buf, 2);
3438 return buf + 2;
3439 }
3440
3441 static char *
3442 pack_int (char *buf, int value)
3443 {
3444 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3445 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3446 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3447 buf = pack_hex_byte (buf, (value & 0xff));
3448 return buf;
3449 }
3450
3451 static const char *
3452 unpack_int (const char *buf, int *value)
3453 {
3454 *value = stub_unpack_int (buf, 8);
3455 return buf + 8;
3456 }
3457
3458 #if 0 /* Currently unused, uncomment when needed. */
3459 static char *pack_string (char *pkt, char *string);
3460
3461 static char *
3462 pack_string (char *pkt, char *string)
3463 {
3464 char ch;
3465 int len;
3466
3467 len = strlen (string);
3468 if (len > 200)
3469 len = 200; /* Bigger than most GDB packets, junk??? */
3470 pkt = pack_hex_byte (pkt, len);
3471 while (len-- > 0)
3472 {
3473 ch = *string++;
3474 if ((ch == '\0') || (ch == '#'))
3475 ch = '*'; /* Protect encapsulation. */
3476 *pkt++ = ch;
3477 }
3478 return pkt;
3479 }
3480 #endif /* 0 (unused) */
3481
3482 static const char *
3483 unpack_string (const char *src, char *dest, int length)
3484 {
3485 while (length--)
3486 *dest++ = *src++;
3487 *dest = '\0';
3488 return src;
3489 }
3490
3491 static char *
3492 pack_threadid (char *pkt, threadref *id)
3493 {
3494 char *limit;
3495 unsigned char *altid;
3496
3497 altid = (unsigned char *) id;
3498 limit = pkt + BUF_THREAD_ID_SIZE;
3499 while (pkt < limit)
3500 pkt = pack_hex_byte (pkt, *altid++);
3501 return pkt;
3502 }
3503
3504
3505 static const char *
3506 unpack_threadid (const char *inbuf, threadref *id)
3507 {
3508 char *altref;
3509 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3510 int x, y;
3511
3512 altref = (char *) id;
3513
3514 while (inbuf < limit)
3515 {
3516 x = stubhex (*inbuf++);
3517 y = stubhex (*inbuf++);
3518 *altref++ = (x << 4) | y;
3519 }
3520 return inbuf;
3521 }
3522
3523 /* Externally, threadrefs are 64 bits but internally, they are still
3524 ints. This is due to a mismatch of specifications. We would like
3525 to use 64bit thread references internally. This is an adapter
3526 function. */
3527
3528 void
3529 int_to_threadref (threadref *id, int value)
3530 {
3531 unsigned char *scan;
3532
3533 scan = (unsigned char *) id;
3534 {
3535 int i = 4;
3536 while (i--)
3537 *scan++ = 0;
3538 }
3539 *scan++ = (value >> 24) & 0xff;
3540 *scan++ = (value >> 16) & 0xff;
3541 *scan++ = (value >> 8) & 0xff;
3542 *scan++ = (value & 0xff);
3543 }
3544
3545 static int
3546 threadref_to_int (threadref *ref)
3547 {
3548 int i, value = 0;
3549 unsigned char *scan;
3550
3551 scan = *ref;
3552 scan += 4;
3553 i = 4;
3554 while (i-- > 0)
3555 value = (value << 8) | ((*scan++) & 0xff);
3556 return value;
3557 }
3558
3559 static void
3560 copy_threadref (threadref *dest, threadref *src)
3561 {
3562 int i;
3563 unsigned char *csrc, *cdest;
3564
3565 csrc = (unsigned char *) src;
3566 cdest = (unsigned char *) dest;
3567 i = 8;
3568 while (i--)
3569 *cdest++ = *csrc++;
3570 }
3571
3572 static int
3573 threadmatch (threadref *dest, threadref *src)
3574 {
3575 /* Things are broken right now, so just assume we got a match. */
3576 #if 0
3577 unsigned char *srcp, *destp;
3578 int i, result;
3579 srcp = (char *) src;
3580 destp = (char *) dest;
3581
3582 result = 1;
3583 while (i-- > 0)
3584 result &= (*srcp++ == *destp++) ? 1 : 0;
3585 return result;
3586 #endif
3587 return 1;
3588 }
3589
3590 /*
3591 threadid:1, # always request threadid
3592 context_exists:2,
3593 display:4,
3594 unique_name:8,
3595 more_display:16
3596 */
3597
3598 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3599
3600 static char *
3601 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3602 {
3603 *pkt++ = 'q'; /* Info Query */
3604 *pkt++ = 'P'; /* process or thread info */
3605 pkt = pack_int (pkt, mode); /* mode */
3606 pkt = pack_threadid (pkt, id); /* threadid */
3607 *pkt = '\0'; /* terminate */
3608 return pkt;
3609 }
3610
3611 /* These values tag the fields in a thread info response packet. */
3612 /* Tagging the fields allows us to request specific fields and to
3613 add more fields as time goes by. */
3614
3615 #define TAG_THREADID 1 /* Echo the thread identifier. */
3616 #define TAG_EXISTS 2 /* Is this process defined enough to
3617 fetch registers and its stack? */
3618 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3619 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3620 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3621 the process. */
3622
3623 int
3624 remote_target::remote_unpack_thread_info_response (const char *pkt,
3625 threadref *expectedref,
3626 gdb_ext_thread_info *info)
3627 {
3628 struct remote_state *rs = get_remote_state ();
3629 int mask, length;
3630 int tag;
3631 threadref ref;
3632 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3633 int retval = 1;
3634
3635 /* info->threadid = 0; FIXME: implement zero_threadref. */
3636 info->active = 0;
3637 info->display[0] = '\0';
3638 info->shortname[0] = '\0';
3639 info->more_display[0] = '\0';
3640
3641 /* Assume the characters indicating the packet type have been
3642 stripped. */
3643 pkt = unpack_int (pkt, &mask); /* arg mask */
3644 pkt = unpack_threadid (pkt, &ref);
3645
3646 if (mask == 0)
3647 warning (_("Incomplete response to threadinfo request."));
3648 if (!threadmatch (&ref, expectedref))
3649 { /* This is an answer to a different request. */
3650 warning (_("ERROR RMT Thread info mismatch."));
3651 return 0;
3652 }
3653 copy_threadref (&info->threadid, &ref);
3654
3655 /* Loop on tagged fields , try to bail if something goes wrong. */
3656
3657 /* Packets are terminated with nulls. */
3658 while ((pkt < limit) && mask && *pkt)
3659 {
3660 pkt = unpack_int (pkt, &tag); /* tag */
3661 pkt = unpack_byte (pkt, &length); /* length */
3662 if (!(tag & mask)) /* Tags out of synch with mask. */
3663 {
3664 warning (_("ERROR RMT: threadinfo tag mismatch."));
3665 retval = 0;
3666 break;
3667 }
3668 if (tag == TAG_THREADID)
3669 {
3670 if (length != 16)
3671 {
3672 warning (_("ERROR RMT: length of threadid is not 16."));
3673 retval = 0;
3674 break;
3675 }
3676 pkt = unpack_threadid (pkt, &ref);
3677 mask = mask & ~TAG_THREADID;
3678 continue;
3679 }
3680 if (tag == TAG_EXISTS)
3681 {
3682 info->active = stub_unpack_int (pkt, length);
3683 pkt += length;
3684 mask = mask & ~(TAG_EXISTS);
3685 if (length > 8)
3686 {
3687 warning (_("ERROR RMT: 'exists' length too long."));
3688 retval = 0;
3689 break;
3690 }
3691 continue;
3692 }
3693 if (tag == TAG_THREADNAME)
3694 {
3695 pkt = unpack_string (pkt, &info->shortname[0], length);
3696 mask = mask & ~TAG_THREADNAME;
3697 continue;
3698 }
3699 if (tag == TAG_DISPLAY)
3700 {
3701 pkt = unpack_string (pkt, &info->display[0], length);
3702 mask = mask & ~TAG_DISPLAY;
3703 continue;
3704 }
3705 if (tag == TAG_MOREDISPLAY)
3706 {
3707 pkt = unpack_string (pkt, &info->more_display[0], length);
3708 mask = mask & ~TAG_MOREDISPLAY;
3709 continue;
3710 }
3711 warning (_("ERROR RMT: unknown thread info tag."));
3712 break; /* Not a tag we know about. */
3713 }
3714 return retval;
3715 }
3716
3717 int
3718 remote_target::remote_get_threadinfo (threadref *threadid,
3719 int fieldset,
3720 gdb_ext_thread_info *info)
3721 {
3722 struct remote_state *rs = get_remote_state ();
3723 int result;
3724
3725 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3726 putpkt (rs->buf);
3727 getpkt (&rs->buf);
3728
3729 if (rs->buf[0] == '\0')
3730 return 0;
3731
3732 result = remote_unpack_thread_info_response (&rs->buf[2],
3733 threadid, info);
3734 return result;
3735 }
3736
3737 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3738
3739 static char *
3740 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3741 threadref *nextthread)
3742 {
3743 *pkt++ = 'q'; /* info query packet */
3744 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3745 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3746 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3747 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3748 *pkt = '\0';
3749 return pkt;
3750 }
3751
3752 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3753
3754 int
3755 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3756 threadref *original_echo,
3757 threadref *resultlist,
3758 int *doneflag)
3759 {
3760 struct remote_state *rs = get_remote_state ();
3761 int count, resultcount, done;
3762
3763 resultcount = 0;
3764 /* Assume the 'q' and 'M chars have been stripped. */
3765 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3766 /* done parse past here */
3767 pkt = unpack_byte (pkt, &count); /* count field */
3768 pkt = unpack_nibble (pkt, &done);
3769 /* The first threadid is the argument threadid. */
3770 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3771 while ((count-- > 0) && (pkt < limit))
3772 {
3773 pkt = unpack_threadid (pkt, resultlist++);
3774 if (resultcount++ >= result_limit)
3775 break;
3776 }
3777 if (doneflag)
3778 *doneflag = done;
3779 return resultcount;
3780 }
3781
3782 /* Fetch the next batch of threads from the remote. Returns -1 if the
3783 qL packet is not supported, 0 on error and 1 on success. */
3784
3785 int
3786 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3787 int result_limit, int *done, int *result_count,
3788 threadref *threadlist)
3789 {
3790 struct remote_state *rs = get_remote_state ();
3791 int result = 1;
3792
3793 /* Truncate result limit to be smaller than the packet size. */
3794 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3795 >= get_remote_packet_size ())
3796 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3797
3798 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3799 nextthread);
3800 putpkt (rs->buf);
3801 getpkt (&rs->buf);
3802 if (rs->buf[0] == '\0')
3803 {
3804 /* Packet not supported. */
3805 return -1;
3806 }
3807
3808 *result_count =
3809 parse_threadlist_response (&rs->buf[2], result_limit,
3810 &rs->echo_nextthread, threadlist, done);
3811
3812 if (!threadmatch (&rs->echo_nextthread, nextthread))
3813 {
3814 /* FIXME: This is a good reason to drop the packet. */
3815 /* Possibly, there is a duplicate response. */
3816 /* Possibilities :
3817 retransmit immediatly - race conditions
3818 retransmit after timeout - yes
3819 exit
3820 wait for packet, then exit
3821 */
3822 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3823 return 0; /* I choose simply exiting. */
3824 }
3825 if (*result_count <= 0)
3826 {
3827 if (*done != 1)
3828 {
3829 warning (_("RMT ERROR : failed to get remote thread list."));
3830 result = 0;
3831 }
3832 return result; /* break; */
3833 }
3834 if (*result_count > result_limit)
3835 {
3836 *result_count = 0;
3837 warning (_("RMT ERROR: threadlist response longer than requested."));
3838 return 0;
3839 }
3840 return result;
3841 }
3842
3843 /* Fetch the list of remote threads, with the qL packet, and call
3844 STEPFUNCTION for each thread found. Stops iterating and returns 1
3845 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3846 STEPFUNCTION returns false. If the packet is not supported,
3847 returns -1. */
3848
3849 int
3850 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3851 void *context, int looplimit)
3852 {
3853 struct remote_state *rs = get_remote_state ();
3854 int done, i, result_count;
3855 int startflag = 1;
3856 int result = 1;
3857 int loopcount = 0;
3858
3859 done = 0;
3860 while (!done)
3861 {
3862 if (loopcount++ > looplimit)
3863 {
3864 result = 0;
3865 warning (_("Remote fetch threadlist -infinite loop-."));
3866 break;
3867 }
3868 result = remote_get_threadlist (startflag, &rs->nextthread,
3869 MAXTHREADLISTRESULTS,
3870 &done, &result_count,
3871 rs->resultthreadlist);
3872 if (result <= 0)
3873 break;
3874 /* Clear for later iterations. */
3875 startflag = 0;
3876 /* Setup to resume next batch of thread references, set nextthread. */
3877 if (result_count >= 1)
3878 copy_threadref (&rs->nextthread,
3879 &rs->resultthreadlist[result_count - 1]);
3880 i = 0;
3881 while (result_count--)
3882 {
3883 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3884 {
3885 result = 0;
3886 break;
3887 }
3888 }
3889 }
3890 return result;
3891 }
3892
3893 /* A thread found on the remote target. */
3894
3895 struct thread_item
3896 {
3897 explicit thread_item (ptid_t ptid_)
3898 : ptid (ptid_)
3899 {}
3900
3901 thread_item (thread_item &&other) = default;
3902 thread_item &operator= (thread_item &&other) = default;
3903
3904 DISABLE_COPY_AND_ASSIGN (thread_item);
3905
3906 /* The thread's PTID. */
3907 ptid_t ptid;
3908
3909 /* The thread's extra info. */
3910 std::string extra;
3911
3912 /* The thread's name. */
3913 std::string name;
3914
3915 /* The core the thread was running on. -1 if not known. */
3916 int core = -1;
3917
3918 /* The thread handle associated with the thread. */
3919 gdb::byte_vector thread_handle;
3920 };
3921
3922 /* Context passed around to the various methods listing remote
3923 threads. As new threads are found, they're added to the ITEMS
3924 vector. */
3925
3926 struct threads_listing_context
3927 {
3928 /* Return true if this object contains an entry for a thread with ptid
3929 PTID. */
3930
3931 bool contains_thread (ptid_t ptid) const
3932 {
3933 auto match_ptid = [&] (const thread_item &item)
3934 {
3935 return item.ptid == ptid;
3936 };
3937
3938 auto it = std::find_if (this->items.begin (),
3939 this->items.end (),
3940 match_ptid);
3941
3942 return it != this->items.end ();
3943 }
3944
3945 /* Remove the thread with ptid PTID. */
3946
3947 void remove_thread (ptid_t ptid)
3948 {
3949 auto match_ptid = [&] (const thread_item &item)
3950 {
3951 return item.ptid == ptid;
3952 };
3953
3954 auto it = std::remove_if (this->items.begin (),
3955 this->items.end (),
3956 match_ptid);
3957
3958 if (it != this->items.end ())
3959 this->items.erase (it);
3960 }
3961
3962 /* The threads found on the remote target. */
3963 std::vector<thread_item> items;
3964 };
3965
3966 static int
3967 remote_newthread_step (threadref *ref, void *data)
3968 {
3969 struct threads_listing_context *context
3970 = (struct threads_listing_context *) data;
3971 int pid = inferior_ptid.pid ();
3972 int lwp = threadref_to_int (ref);
3973 ptid_t ptid (pid, lwp);
3974
3975 context->items.emplace_back (ptid);
3976
3977 return 1; /* continue iterator */
3978 }
3979
3980 #define CRAZY_MAX_THREADS 1000
3981
3982 ptid_t
3983 remote_target::remote_current_thread (ptid_t oldpid)
3984 {
3985 struct remote_state *rs = get_remote_state ();
3986
3987 putpkt ("qC");
3988 getpkt (&rs->buf);
3989 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3990 {
3991 const char *obuf;
3992 ptid_t result;
3993
3994 result = read_ptid (&rs->buf[2], &obuf);
3995 if (*obuf != '\0')
3996 remote_debug_printf ("warning: garbage in qC reply");
3997
3998 return result;
3999 }
4000 else
4001 return oldpid;
4002 }
4003
4004 /* List remote threads using the deprecated qL packet. */
4005
4006 int
4007 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4008 {
4009 if (remote_threadlist_iterator (remote_newthread_step, context,
4010 CRAZY_MAX_THREADS) >= 0)
4011 return 1;
4012
4013 return 0;
4014 }
4015
4016 #if defined(HAVE_LIBEXPAT)
4017
4018 static void
4019 start_thread (struct gdb_xml_parser *parser,
4020 const struct gdb_xml_element *element,
4021 void *user_data,
4022 std::vector<gdb_xml_value> &attributes)
4023 {
4024 struct threads_listing_context *data
4025 = (struct threads_listing_context *) user_data;
4026 struct gdb_xml_value *attr;
4027
4028 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4029 ptid_t ptid = read_ptid (id, NULL);
4030
4031 data->items.emplace_back (ptid);
4032 thread_item &item = data->items.back ();
4033
4034 attr = xml_find_attribute (attributes, "core");
4035 if (attr != NULL)
4036 item.core = *(ULONGEST *) attr->value.get ();
4037
4038 attr = xml_find_attribute (attributes, "name");
4039 if (attr != NULL)
4040 item.name = (const char *) attr->value.get ();
4041
4042 attr = xml_find_attribute (attributes, "handle");
4043 if (attr != NULL)
4044 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4045 }
4046
4047 static void
4048 end_thread (struct gdb_xml_parser *parser,
4049 const struct gdb_xml_element *element,
4050 void *user_data, const char *body_text)
4051 {
4052 struct threads_listing_context *data
4053 = (struct threads_listing_context *) user_data;
4054
4055 if (body_text != NULL && *body_text != '\0')
4056 data->items.back ().extra = body_text;
4057 }
4058
4059 const struct gdb_xml_attribute thread_attributes[] = {
4060 { "id", GDB_XML_AF_NONE, NULL, NULL },
4061 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4062 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4063 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4064 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4065 };
4066
4067 const struct gdb_xml_element thread_children[] = {
4068 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4069 };
4070
4071 const struct gdb_xml_element threads_children[] = {
4072 { "thread", thread_attributes, thread_children,
4073 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4074 start_thread, end_thread },
4075 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4076 };
4077
4078 const struct gdb_xml_element threads_elements[] = {
4079 { "threads", NULL, threads_children,
4080 GDB_XML_EF_NONE, NULL, NULL },
4081 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4082 };
4083
4084 #endif
4085
4086 /* List remote threads using qXfer:threads:read. */
4087
4088 int
4089 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4090 {
4091 #if defined(HAVE_LIBEXPAT)
4092 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4093 {
4094 gdb::optional<gdb::char_vector> xml
4095 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4096
4097 if (xml && (*xml)[0] != '\0')
4098 {
4099 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4100 threads_elements, xml->data (), context);
4101 }
4102
4103 return 1;
4104 }
4105 #endif
4106
4107 return 0;
4108 }
4109
4110 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4111
4112 int
4113 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4114 {
4115 struct remote_state *rs = get_remote_state ();
4116
4117 if (rs->use_threadinfo_query)
4118 {
4119 const char *bufp;
4120
4121 putpkt ("qfThreadInfo");
4122 getpkt (&rs->buf);
4123 bufp = rs->buf.data ();
4124 if (bufp[0] != '\0') /* q packet recognized */
4125 {
4126 while (*bufp++ == 'm') /* reply contains one or more TID */
4127 {
4128 do
4129 {
4130 ptid_t ptid = read_ptid (bufp, &bufp);
4131 context->items.emplace_back (ptid);
4132 }
4133 while (*bufp++ == ','); /* comma-separated list */
4134 putpkt ("qsThreadInfo");
4135 getpkt (&rs->buf);
4136 bufp = rs->buf.data ();
4137 }
4138 return 1;
4139 }
4140 else
4141 {
4142 /* Packet not recognized. */
4143 rs->use_threadinfo_query = 0;
4144 }
4145 }
4146
4147 return 0;
4148 }
4149
4150 /* Return true if INF only has one non-exited thread. */
4151
4152 static bool
4153 has_single_non_exited_thread (inferior *inf)
4154 {
4155 int count = 0;
4156 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4157 if (++count > 1)
4158 break;
4159 return count == 1;
4160 }
4161
4162 /* Implement the to_update_thread_list function for the remote
4163 targets. */
4164
4165 void
4166 remote_target::update_thread_list ()
4167 {
4168 struct threads_listing_context context;
4169 int got_list = 0;
4170
4171 /* We have a few different mechanisms to fetch the thread list. Try
4172 them all, starting with the most preferred one first, falling
4173 back to older methods. */
4174 if (remote_get_threads_with_qxfer (&context)
4175 || remote_get_threads_with_qthreadinfo (&context)
4176 || remote_get_threads_with_ql (&context))
4177 {
4178 got_list = 1;
4179
4180 if (context.items.empty ()
4181 && remote_thread_always_alive (inferior_ptid))
4182 {
4183 /* Some targets don't really support threads, but still
4184 reply an (empty) thread list in response to the thread
4185 listing packets, instead of replying "packet not
4186 supported". Exit early so we don't delete the main
4187 thread. */
4188 return;
4189 }
4190
4191 /* CONTEXT now holds the current thread list on the remote
4192 target end. Delete GDB-side threads no longer found on the
4193 target. */
4194 for (thread_info *tp : all_threads_safe ())
4195 {
4196 if (tp->inf->process_target () != this)
4197 continue;
4198
4199 if (!context.contains_thread (tp->ptid))
4200 {
4201 /* Do not remove the thread if it is the last thread in
4202 the inferior. This situation happens when we have a
4203 pending exit process status to process. Otherwise we
4204 may end up with a seemingly live inferior (i.e. pid
4205 != 0) that has no threads. */
4206 if (has_single_non_exited_thread (tp->inf))
4207 continue;
4208
4209 /* Not found. */
4210 delete_thread (tp);
4211 }
4212 }
4213
4214 /* Remove any unreported fork/vfork/clone child threads from
4215 CONTEXT so that we don't interfere with follow
4216 fork/vfork/clone, which is where creation of such threads is
4217 handled. */
4218 remove_new_children (&context);
4219
4220 /* And now add threads we don't know about yet to our list. */
4221 for (thread_item &item : context.items)
4222 {
4223 if (item.ptid != null_ptid)
4224 {
4225 /* In non-stop mode, we assume new found threads are
4226 executing until proven otherwise with a stop reply.
4227 In all-stop, we can only get here if all threads are
4228 stopped. */
4229 bool executing = target_is_non_stop_p ();
4230
4231 remote_notice_new_inferior (item.ptid, executing);
4232
4233 thread_info *tp = this->find_thread (item.ptid);
4234 remote_thread_info *info = get_remote_thread_info (tp);
4235 info->core = item.core;
4236 info->extra = std::move (item.extra);
4237 info->name = std::move (item.name);
4238 info->thread_handle = std::move (item.thread_handle);
4239 }
4240 }
4241 }
4242
4243 if (!got_list)
4244 {
4245 /* If no thread listing method is supported, then query whether
4246 each known thread is alive, one by one, with the T packet.
4247 If the target doesn't support threads at all, then this is a
4248 no-op. See remote_thread_alive. */
4249 prune_threads ();
4250 }
4251 }
4252
4253 /*
4254 * Collect a descriptive string about the given thread.
4255 * The target may say anything it wants to about the thread
4256 * (typically info about its blocked / runnable state, name, etc.).
4257 * This string will appear in the info threads display.
4258 *
4259 * Optional: targets are not required to implement this function.
4260 */
4261
4262 const char *
4263 remote_target::extra_thread_info (thread_info *tp)
4264 {
4265 struct remote_state *rs = get_remote_state ();
4266 int set;
4267 threadref id;
4268 struct gdb_ext_thread_info threadinfo;
4269
4270 if (rs->remote_desc == 0) /* paranoia */
4271 internal_error (_("remote_threads_extra_info"));
4272
4273 if (tp->ptid == magic_null_ptid
4274 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4275 /* This is the main thread which was added by GDB. The remote
4276 server doesn't know about it. */
4277 return NULL;
4278
4279 std::string &extra = get_remote_thread_info (tp)->extra;
4280
4281 /* If already have cached info, use it. */
4282 if (!extra.empty ())
4283 return extra.c_str ();
4284
4285 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4286 {
4287 /* If we're using qXfer:threads:read, then the extra info is
4288 included in the XML. So if we didn't have anything cached,
4289 it's because there's really no extra info. */
4290 return NULL;
4291 }
4292
4293 if (rs->use_threadextra_query)
4294 {
4295 char *b = rs->buf.data ();
4296 char *endb = b + get_remote_packet_size ();
4297
4298 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4299 b += strlen (b);
4300 write_ptid (b, endb, tp->ptid);
4301
4302 putpkt (rs->buf);
4303 getpkt (&rs->buf);
4304 if (rs->buf[0] != 0)
4305 {
4306 extra.resize (strlen (rs->buf.data ()) / 2);
4307 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4308 return extra.c_str ();
4309 }
4310 }
4311
4312 /* If the above query fails, fall back to the old method. */
4313 rs->use_threadextra_query = 0;
4314 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4315 | TAG_MOREDISPLAY | TAG_DISPLAY;
4316 int_to_threadref (&id, tp->ptid.lwp ());
4317 if (remote_get_threadinfo (&id, set, &threadinfo))
4318 if (threadinfo.active)
4319 {
4320 if (*threadinfo.shortname)
4321 string_appendf (extra, " Name: %s", threadinfo.shortname);
4322 if (*threadinfo.display)
4323 {
4324 if (!extra.empty ())
4325 extra += ',';
4326 string_appendf (extra, " State: %s", threadinfo.display);
4327 }
4328 if (*threadinfo.more_display)
4329 {
4330 if (!extra.empty ())
4331 extra += ',';
4332 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4333 }
4334 return extra.c_str ();
4335 }
4336 return NULL;
4337 }
4338 \f
4339
4340 bool
4341 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4342 struct static_tracepoint_marker *marker)
4343 {
4344 struct remote_state *rs = get_remote_state ();
4345 char *p = rs->buf.data ();
4346
4347 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4348 p += strlen (p);
4349 p += hexnumstr (p, addr);
4350 putpkt (rs->buf);
4351 getpkt (&rs->buf);
4352 p = rs->buf.data ();
4353
4354 if (*p == 'E')
4355 error (_("Remote failure reply: %s"), p);
4356
4357 if (*p++ == 'm')
4358 {
4359 parse_static_tracepoint_marker_definition (p, NULL, marker);
4360 return true;
4361 }
4362
4363 return false;
4364 }
4365
4366 std::vector<static_tracepoint_marker>
4367 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4368 {
4369 struct remote_state *rs = get_remote_state ();
4370 std::vector<static_tracepoint_marker> markers;
4371 const char *p;
4372 static_tracepoint_marker marker;
4373
4374 /* Ask for a first packet of static tracepoint marker
4375 definition. */
4376 putpkt ("qTfSTM");
4377 getpkt (&rs->buf);
4378 p = rs->buf.data ();
4379 if (*p == 'E')
4380 error (_("Remote failure reply: %s"), p);
4381
4382 while (*p++ == 'm')
4383 {
4384 do
4385 {
4386 parse_static_tracepoint_marker_definition (p, &p, &marker);
4387
4388 if (strid == NULL || marker.str_id == strid)
4389 markers.push_back (std::move (marker));
4390 }
4391 while (*p++ == ','); /* comma-separated list */
4392 /* Ask for another packet of static tracepoint definition. */
4393 putpkt ("qTsSTM");
4394 getpkt (&rs->buf);
4395 p = rs->buf.data ();
4396 }
4397
4398 return markers;
4399 }
4400
4401 \f
4402 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4403
4404 ptid_t
4405 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4406 {
4407 return ptid_t (inferior_ptid.pid (), lwp);
4408 }
4409 \f
4410
4411 /* Restart the remote side; this is an extended protocol operation. */
4412
4413 void
4414 remote_target::extended_remote_restart ()
4415 {
4416 struct remote_state *rs = get_remote_state ();
4417
4418 /* Send the restart command; for reasons I don't understand the
4419 remote side really expects a number after the "R". */
4420 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4421 putpkt (rs->buf);
4422
4423 remote_fileio_reset ();
4424 }
4425 \f
4426 /* Clean up connection to a remote debugger. */
4427
4428 void
4429 remote_target::close ()
4430 {
4431 /* Make sure we leave stdin registered in the event loop. */
4432 terminal_ours ();
4433
4434 trace_reset_local_state ();
4435
4436 delete this;
4437 }
4438
4439 remote_target::~remote_target ()
4440 {
4441 struct remote_state *rs = get_remote_state ();
4442
4443 /* Check for NULL because we may get here with a partially
4444 constructed target/connection. */
4445 if (rs->remote_desc == nullptr)
4446 return;
4447
4448 serial_close (rs->remote_desc);
4449
4450 /* We are destroying the remote target, so we should discard
4451 everything of this target. */
4452 discard_pending_stop_replies_in_queue ();
4453
4454 rs->delete_async_event_handler ();
4455
4456 delete rs->notif_state;
4457 }
4458
4459 /* Query the remote side for the text, data and bss offsets. */
4460
4461 void
4462 remote_target::get_offsets ()
4463 {
4464 struct remote_state *rs = get_remote_state ();
4465 char *buf;
4466 char *ptr;
4467 int lose, num_segments = 0, do_sections, do_segments;
4468 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4469
4470 if (current_program_space->symfile_object_file == NULL)
4471 return;
4472
4473 putpkt ("qOffsets");
4474 getpkt (&rs->buf);
4475 buf = rs->buf.data ();
4476
4477 if (buf[0] == '\000')
4478 return; /* Return silently. Stub doesn't support
4479 this command. */
4480 if (buf[0] == 'E')
4481 {
4482 warning (_("Remote failure reply: %s"), buf);
4483 return;
4484 }
4485
4486 /* Pick up each field in turn. This used to be done with scanf, but
4487 scanf will make trouble if CORE_ADDR size doesn't match
4488 conversion directives correctly. The following code will work
4489 with any size of CORE_ADDR. */
4490 text_addr = data_addr = bss_addr = 0;
4491 ptr = buf;
4492 lose = 0;
4493
4494 if (startswith (ptr, "Text="))
4495 {
4496 ptr += 5;
4497 /* Don't use strtol, could lose on big values. */
4498 while (*ptr && *ptr != ';')
4499 text_addr = (text_addr << 4) + fromhex (*ptr++);
4500
4501 if (startswith (ptr, ";Data="))
4502 {
4503 ptr += 6;
4504 while (*ptr && *ptr != ';')
4505 data_addr = (data_addr << 4) + fromhex (*ptr++);
4506 }
4507 else
4508 lose = 1;
4509
4510 if (!lose && startswith (ptr, ";Bss="))
4511 {
4512 ptr += 5;
4513 while (*ptr && *ptr != ';')
4514 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4515
4516 if (bss_addr != data_addr)
4517 warning (_("Target reported unsupported offsets: %s"), buf);
4518 }
4519 else
4520 lose = 1;
4521 }
4522 else if (startswith (ptr, "TextSeg="))
4523 {
4524 ptr += 8;
4525 /* Don't use strtol, could lose on big values. */
4526 while (*ptr && *ptr != ';')
4527 text_addr = (text_addr << 4) + fromhex (*ptr++);
4528 num_segments = 1;
4529
4530 if (startswith (ptr, ";DataSeg="))
4531 {
4532 ptr += 9;
4533 while (*ptr && *ptr != ';')
4534 data_addr = (data_addr << 4) + fromhex (*ptr++);
4535 num_segments++;
4536 }
4537 }
4538 else
4539 lose = 1;
4540
4541 if (lose)
4542 error (_("Malformed response to offset query, %s"), buf);
4543 else if (*ptr != '\0')
4544 warning (_("Target reported unsupported offsets: %s"), buf);
4545
4546 objfile *objf = current_program_space->symfile_object_file;
4547 section_offsets offs = objf->section_offsets;
4548
4549 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4550 do_segments = (data != NULL);
4551 do_sections = num_segments == 0;
4552
4553 if (num_segments > 0)
4554 {
4555 segments[0] = text_addr;
4556 segments[1] = data_addr;
4557 }
4558 /* If we have two segments, we can still try to relocate everything
4559 by assuming that the .text and .data offsets apply to the whole
4560 text and data segments. Convert the offsets given in the packet
4561 to base addresses for symfile_map_offsets_to_segments. */
4562 else if (data != nullptr && data->segments.size () == 2)
4563 {
4564 segments[0] = data->segments[0].base + text_addr;
4565 segments[1] = data->segments[1].base + data_addr;
4566 num_segments = 2;
4567 }
4568 /* If the object file has only one segment, assume that it is text
4569 rather than data; main programs with no writable data are rare,
4570 but programs with no code are useless. Of course the code might
4571 have ended up in the data segment... to detect that we would need
4572 the permissions here. */
4573 else if (data && data->segments.size () == 1)
4574 {
4575 segments[0] = data->segments[0].base + text_addr;
4576 num_segments = 1;
4577 }
4578 /* There's no way to relocate by segment. */
4579 else
4580 do_segments = 0;
4581
4582 if (do_segments)
4583 {
4584 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4585 data.get (), offs,
4586 num_segments, segments);
4587
4588 if (ret == 0 && !do_sections)
4589 error (_("Can not handle qOffsets TextSeg "
4590 "response with this symbol file"));
4591
4592 if (ret > 0)
4593 do_sections = 0;
4594 }
4595
4596 if (do_sections)
4597 {
4598 offs[SECT_OFF_TEXT (objf)] = text_addr;
4599
4600 /* This is a temporary kludge to force data and bss to use the
4601 same offsets because that's what nlmconv does now. The real
4602 solution requires changes to the stub and remote.c that I
4603 don't have time to do right now. */
4604
4605 offs[SECT_OFF_DATA (objf)] = data_addr;
4606 offs[SECT_OFF_BSS (objf)] = data_addr;
4607 }
4608
4609 objfile_relocate (objf, offs);
4610 }
4611
4612 /* Send interrupt_sequence to remote target. */
4613
4614 void
4615 remote_target::send_interrupt_sequence ()
4616 {
4617 struct remote_state *rs = get_remote_state ();
4618
4619 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4620 remote_serial_write ("\x03", 1);
4621 else if (interrupt_sequence_mode == interrupt_sequence_break)
4622 serial_send_break (rs->remote_desc);
4623 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4624 {
4625 serial_send_break (rs->remote_desc);
4626 remote_serial_write ("g", 1);
4627 }
4628 else
4629 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4630 interrupt_sequence_mode);
4631 }
4632
4633
4634 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4635 and extract the PTID. Returns NULL_PTID if not found. */
4636
4637 static ptid_t
4638 stop_reply_extract_thread (const char *stop_reply)
4639 {
4640 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4641 {
4642 const char *p;
4643
4644 /* Txx r:val ; r:val (...) */
4645 p = &stop_reply[3];
4646
4647 /* Look for "register" named "thread". */
4648 while (*p != '\0')
4649 {
4650 const char *p1;
4651
4652 p1 = strchr (p, ':');
4653 if (p1 == NULL)
4654 return null_ptid;
4655
4656 if (strncmp (p, "thread", p1 - p) == 0)
4657 return read_ptid (++p1, &p);
4658
4659 p1 = strchr (p, ';');
4660 if (p1 == NULL)
4661 return null_ptid;
4662 p1++;
4663
4664 p = p1;
4665 }
4666 }
4667
4668 return null_ptid;
4669 }
4670
4671 /* Determine the remote side's current thread. If we have a stop
4672 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4673 "thread" register we can extract the current thread from. If not,
4674 ask the remote which is the current thread with qC. The former
4675 method avoids a roundtrip. */
4676
4677 ptid_t
4678 remote_target::get_current_thread (const char *wait_status)
4679 {
4680 ptid_t ptid = null_ptid;
4681
4682 /* Note we don't use remote_parse_stop_reply as that makes use of
4683 the target architecture, which we haven't yet fully determined at
4684 this point. */
4685 if (wait_status != NULL)
4686 ptid = stop_reply_extract_thread (wait_status);
4687 if (ptid == null_ptid)
4688 ptid = remote_current_thread (inferior_ptid);
4689
4690 return ptid;
4691 }
4692
4693 /* Query the remote target for which is the current thread/process,
4694 add it to our tables, and update INFERIOR_PTID. The caller is
4695 responsible for setting the state such that the remote end is ready
4696 to return the current thread.
4697
4698 This function is called after handling the '?' or 'vRun' packets,
4699 whose response is a stop reply from which we can also try
4700 extracting the thread. If the target doesn't support the explicit
4701 qC query, we infer the current thread from that stop reply, passed
4702 in in WAIT_STATUS, which may be NULL.
4703
4704 The function returns pointer to the main thread of the inferior. */
4705
4706 thread_info *
4707 remote_target::add_current_inferior_and_thread (const char *wait_status)
4708 {
4709 bool fake_pid_p = false;
4710
4711 switch_to_no_thread ();
4712
4713 /* Now, if we have thread information, update the current thread's
4714 ptid. */
4715 ptid_t curr_ptid = get_current_thread (wait_status);
4716
4717 if (curr_ptid != null_ptid)
4718 {
4719 if (!m_features.remote_multi_process_p ())
4720 fake_pid_p = true;
4721 }
4722 else
4723 {
4724 /* Without this, some commands which require an active target
4725 (such as kill) won't work. This variable serves (at least)
4726 double duty as both the pid of the target process (if it has
4727 such), and as a flag indicating that a target is active. */
4728 curr_ptid = magic_null_ptid;
4729 fake_pid_p = true;
4730 }
4731
4732 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4733
4734 /* Add the main thread and switch to it. Don't try reading
4735 registers yet, since we haven't fetched the target description
4736 yet. */
4737 thread_info *tp = add_thread_silent (this, curr_ptid);
4738 switch_to_thread_no_regs (tp);
4739
4740 return tp;
4741 }
4742
4743 /* Print info about a thread that was found already stopped on
4744 connection. */
4745
4746 void
4747 remote_target::print_one_stopped_thread (thread_info *thread)
4748 {
4749 target_waitstatus ws;
4750
4751 /* If there is a pending waitstatus, use it. If there isn't it's because
4752 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4753 and process_initial_stop_replies decided it wasn't interesting to save
4754 and report to the core. */
4755 if (thread->has_pending_waitstatus ())
4756 {
4757 ws = thread->pending_waitstatus ();
4758 thread->clear_pending_waitstatus ();
4759 }
4760 else
4761 {
4762 ws.set_stopped (GDB_SIGNAL_0);
4763 }
4764
4765 switch_to_thread (thread);
4766 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4767 set_current_sal_from_frame (get_current_frame ());
4768
4769 /* For "info program". */
4770 set_last_target_status (this, thread->ptid, ws);
4771
4772 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4773 {
4774 enum gdb_signal sig = ws.sig ();
4775
4776 if (signal_print_state (sig))
4777 notify_signal_received (sig);
4778 }
4779
4780 notify_normal_stop (nullptr, 1);
4781 }
4782
4783 /* Process all initial stop replies the remote side sent in response
4784 to the ? packet. These indicate threads that were already stopped
4785 on initial connection. We mark these threads as stopped and print
4786 their current frame before giving the user the prompt. */
4787
4788 void
4789 remote_target::process_initial_stop_replies (int from_tty)
4790 {
4791 int pending_stop_replies = stop_reply_queue_length ();
4792 struct thread_info *selected = NULL;
4793 struct thread_info *lowest_stopped = NULL;
4794 struct thread_info *first = NULL;
4795
4796 /* This is only used when the target is non-stop. */
4797 gdb_assert (target_is_non_stop_p ());
4798
4799 /* Consume the initial pending events. */
4800 while (pending_stop_replies-- > 0)
4801 {
4802 ptid_t waiton_ptid = minus_one_ptid;
4803 ptid_t event_ptid;
4804 struct target_waitstatus ws;
4805 int ignore_event = 0;
4806
4807 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4808 if (remote_debug)
4809 print_target_wait_results (waiton_ptid, event_ptid, ws);
4810
4811 switch (ws.kind ())
4812 {
4813 case TARGET_WAITKIND_IGNORE:
4814 case TARGET_WAITKIND_NO_RESUMED:
4815 case TARGET_WAITKIND_SIGNALLED:
4816 case TARGET_WAITKIND_EXITED:
4817 /* We shouldn't see these, but if we do, just ignore. */
4818 remote_debug_printf ("event ignored");
4819 ignore_event = 1;
4820 break;
4821
4822 default:
4823 break;
4824 }
4825
4826 if (ignore_event)
4827 continue;
4828
4829 thread_info *evthread = this->find_thread (event_ptid);
4830
4831 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4832 {
4833 enum gdb_signal sig = ws.sig ();
4834
4835 /* Stubs traditionally report SIGTRAP as initial signal,
4836 instead of signal 0. Suppress it. */
4837 if (sig == GDB_SIGNAL_TRAP)
4838 sig = GDB_SIGNAL_0;
4839 evthread->set_stop_signal (sig);
4840 ws.set_stopped (sig);
4841 }
4842
4843 if (ws.kind () != TARGET_WAITKIND_STOPPED
4844 || ws.sig () != GDB_SIGNAL_0)
4845 evthread->set_pending_waitstatus (ws);
4846
4847 set_executing (this, event_ptid, false);
4848 set_running (this, event_ptid, false);
4849 get_remote_thread_info (evthread)->set_not_resumed ();
4850 }
4851
4852 /* "Notice" the new inferiors before anything related to
4853 registers/memory. */
4854 for (inferior *inf : all_non_exited_inferiors (this))
4855 {
4856 inf->needs_setup = true;
4857
4858 if (non_stop)
4859 {
4860 thread_info *thread = any_live_thread_of_inferior (inf);
4861 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4862 from_tty);
4863 }
4864 }
4865
4866 /* If all-stop on top of non-stop, pause all threads. Note this
4867 records the threads' stop pc, so must be done after "noticing"
4868 the inferiors. */
4869 if (!non_stop)
4870 {
4871 {
4872 /* At this point, the remote target is not async. It needs to be for
4873 the poll in stop_all_threads to consider events from it, so enable
4874 it temporarily. */
4875 gdb_assert (!this->is_async_p ());
4876 SCOPE_EXIT { target_async (false); };
4877 target_async (true);
4878 stop_all_threads ("remote connect in all-stop");
4879 }
4880
4881 /* If all threads of an inferior were already stopped, we
4882 haven't setup the inferior yet. */
4883 for (inferior *inf : all_non_exited_inferiors (this))
4884 {
4885 if (inf->needs_setup)
4886 {
4887 thread_info *thread = any_live_thread_of_inferior (inf);
4888 switch_to_thread_no_regs (thread);
4889 setup_inferior (0);
4890 }
4891 }
4892 }
4893
4894 /* Now go over all threads that are stopped, and print their current
4895 frame. If all-stop, then if there's a signalled thread, pick
4896 that as current. */
4897 for (thread_info *thread : all_non_exited_threads (this))
4898 {
4899 if (first == NULL)
4900 first = thread;
4901
4902 if (!non_stop)
4903 thread->set_running (false);
4904 else if (thread->state != THREAD_STOPPED)
4905 continue;
4906
4907 if (selected == nullptr && thread->has_pending_waitstatus ())
4908 selected = thread;
4909
4910 if (lowest_stopped == NULL
4911 || thread->inf->num < lowest_stopped->inf->num
4912 || thread->per_inf_num < lowest_stopped->per_inf_num)
4913 lowest_stopped = thread;
4914
4915 if (non_stop)
4916 print_one_stopped_thread (thread);
4917 }
4918
4919 /* In all-stop, we only print the status of one thread, and leave
4920 others with their status pending. */
4921 if (!non_stop)
4922 {
4923 thread_info *thread = selected;
4924 if (thread == NULL)
4925 thread = lowest_stopped;
4926 if (thread == NULL)
4927 thread = first;
4928
4929 print_one_stopped_thread (thread);
4930 }
4931 }
4932
4933 /* Mark a remote_target as starting (by setting the starting_up flag within
4934 its remote_state) for the lifetime of this object. The reference count
4935 on the remote target is temporarily incremented, to prevent the target
4936 being deleted under our feet. */
4937
4938 struct scoped_mark_target_starting
4939 {
4940 /* Constructor, TARGET is the target to be marked as starting, its
4941 reference count will be incremented. */
4942 scoped_mark_target_starting (remote_target *target)
4943 : m_remote_target (remote_target_ref::new_reference (target)),
4944 m_restore_starting_up (set_starting_up_flag (target))
4945 { /* Nothing. */ }
4946
4947 private:
4948
4949 /* Helper function, set the starting_up flag on TARGET and return an
4950 object which, when it goes out of scope, will restore the previous
4951 value of the starting_up flag. */
4952 static scoped_restore_tmpl<bool>
4953 set_starting_up_flag (remote_target *target)
4954 {
4955 remote_state *rs = target->get_remote_state ();
4956 gdb_assert (!rs->starting_up);
4957 return make_scoped_restore (&rs->starting_up, true);
4958 }
4959
4960 /* A gdb::ref_ptr pointer to a remote_target. */
4961 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4962
4963 /* A reference to the target on which we are operating. */
4964 remote_target_ref m_remote_target;
4965
4966 /* An object which restores the previous value of the starting_up flag
4967 when it goes out of scope. */
4968 scoped_restore_tmpl<bool> m_restore_starting_up;
4969 };
4970
4971 /* Helper for remote_target::start_remote, start the remote connection and
4972 sync state. Return true if everything goes OK, otherwise, return false.
4973 This function exists so that the scoped_restore created within it will
4974 expire before we return to remote_target::start_remote. */
4975
4976 bool
4977 remote_target::start_remote_1 (int from_tty, int extended_p)
4978 {
4979 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4980
4981 struct remote_state *rs = get_remote_state ();
4982
4983 /* Signal other parts that we're going through the initial setup,
4984 and so things may not be stable yet. E.g., we don't try to
4985 install tracepoints until we've relocated symbols. Also, a
4986 Ctrl-C before we're connected and synced up can't interrupt the
4987 target. Instead, it offers to drop the (potentially wedged)
4988 connection. */
4989 scoped_mark_target_starting target_is_starting (this);
4990
4991 QUIT;
4992
4993 if (interrupt_on_connect)
4994 send_interrupt_sequence ();
4995
4996 /* Ack any packet which the remote side has already sent. */
4997 remote_serial_write ("+", 1);
4998
4999 /* The first packet we send to the target is the optional "supported
5000 packets" request. If the target can answer this, it will tell us
5001 which later probes to skip. */
5002 remote_query_supported ();
5003
5004 /* Check vCont support and set the remote state's vCont_action_support
5005 attribute. */
5006 remote_vcont_probe ();
5007
5008 /* If the stub wants to get a QAllow, compose one and send it. */
5009 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5010 set_permissions ();
5011
5012 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5013 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5014 as a reply to known packet. For packet "vFile:setfs:" it is an
5015 invalid reply and GDB would return error in
5016 remote_hostio_set_filesystem, making remote files access impossible.
5017 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5018 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5019 {
5020 const char v_mustreplyempty[] = "vMustReplyEmpty";
5021
5022 putpkt (v_mustreplyempty);
5023 getpkt (&rs->buf);
5024 if (strcmp (rs->buf.data (), "OK") == 0)
5025 {
5026 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5027 = PACKET_DISABLE;
5028 }
5029 else if (strcmp (rs->buf.data (), "") != 0)
5030 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5031 rs->buf.data ());
5032 }
5033
5034 /* Next, we possibly activate noack mode.
5035
5036 If the QStartNoAckMode packet configuration is set to AUTO,
5037 enable noack mode if the stub reported a wish for it with
5038 qSupported.
5039
5040 If set to TRUE, then enable noack mode even if the stub didn't
5041 report it in qSupported. If the stub doesn't reply OK, the
5042 session ends with an error.
5043
5044 If FALSE, then don't activate noack mode, regardless of what the
5045 stub claimed should be the default with qSupported. */
5046
5047 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5048 {
5049 putpkt ("QStartNoAckMode");
5050 getpkt (&rs->buf);
5051 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5052 rs->noack_mode = 1;
5053 }
5054
5055 if (extended_p)
5056 {
5057 /* Tell the remote that we are using the extended protocol. */
5058 putpkt ("!");
5059 getpkt (&rs->buf);
5060 }
5061
5062 /* Let the target know which signals it is allowed to pass down to
5063 the program. */
5064 update_signals_program_target ();
5065
5066 /* Next, if the target can specify a description, read it. We do
5067 this before anything involving memory or registers. */
5068 target_find_description ();
5069
5070 /* Next, now that we know something about the target, update the
5071 address spaces in the program spaces. */
5072 update_address_spaces ();
5073
5074 /* On OSs where the list of libraries is global to all
5075 processes, we fetch them early. */
5076 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5077 solib_add (NULL, from_tty, auto_solib_add);
5078
5079 if (target_is_non_stop_p ())
5080 {
5081 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5082 error (_("Non-stop mode requested, but remote "
5083 "does not support non-stop"));
5084
5085 putpkt ("QNonStop:1");
5086 getpkt (&rs->buf);
5087
5088 if (strcmp (rs->buf.data (), "OK") != 0)
5089 error (_("Remote refused setting non-stop mode with: %s"),
5090 rs->buf.data ());
5091
5092 /* Find about threads and processes the stub is already
5093 controlling. We default to adding them in the running state.
5094 The '?' query below will then tell us about which threads are
5095 stopped. */
5096 this->update_thread_list ();
5097 }
5098 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5099 {
5100 /* Don't assume that the stub can operate in all-stop mode.
5101 Request it explicitly. */
5102 putpkt ("QNonStop:0");
5103 getpkt (&rs->buf);
5104
5105 if (strcmp (rs->buf.data (), "OK") != 0)
5106 error (_("Remote refused setting all-stop mode with: %s"),
5107 rs->buf.data ());
5108 }
5109
5110 /* Upload TSVs regardless of whether the target is running or not. The
5111 remote stub, such as GDBserver, may have some predefined or builtin
5112 TSVs, even if the target is not running. */
5113 if (get_trace_status (current_trace_status ()) != -1)
5114 {
5115 struct uploaded_tsv *uploaded_tsvs = NULL;
5116
5117 upload_trace_state_variables (&uploaded_tsvs);
5118 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5119 }
5120
5121 /* Check whether the target is running now. */
5122 putpkt ("?");
5123 getpkt (&rs->buf);
5124
5125 if (!target_is_non_stop_p ())
5126 {
5127 char *wait_status = NULL;
5128
5129 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5130 {
5131 if (!extended_p)
5132 error (_("The target is not running (try extended-remote?)"));
5133 return false;
5134 }
5135 else
5136 {
5137 /* Save the reply for later. */
5138 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5139 strcpy (wait_status, rs->buf.data ());
5140 }
5141
5142 /* Fetch thread list. */
5143 target_update_thread_list ();
5144
5145 /* Let the stub know that we want it to return the thread. */
5146 set_continue_thread (minus_one_ptid);
5147
5148 if (thread_count (this) == 0)
5149 {
5150 /* Target has no concept of threads at all. GDB treats
5151 non-threaded target as single-threaded; add a main
5152 thread. */
5153 thread_info *tp = add_current_inferior_and_thread (wait_status);
5154 get_remote_thread_info (tp)->set_resumed ();
5155 }
5156 else
5157 {
5158 /* We have thread information; select the thread the target
5159 says should be current. If we're reconnecting to a
5160 multi-threaded program, this will ideally be the thread
5161 that last reported an event before GDB disconnected. */
5162 ptid_t curr_thread = get_current_thread (wait_status);
5163 if (curr_thread == null_ptid)
5164 {
5165 /* Odd... The target was able to list threads, but not
5166 tell us which thread was current (no "thread"
5167 register in T stop reply?). Just pick the first
5168 thread in the thread list then. */
5169
5170 remote_debug_printf ("warning: couldn't determine remote "
5171 "current thread; picking first in list.");
5172
5173 for (thread_info *tp : all_non_exited_threads (this,
5174 minus_one_ptid))
5175 {
5176 switch_to_thread (tp);
5177 break;
5178 }
5179 }
5180 else
5181 switch_to_thread (this->find_thread (curr_thread));
5182
5183 get_remote_thread_info (inferior_thread ())->set_resumed ();
5184 }
5185
5186 /* init_wait_for_inferior should be called before get_offsets in order
5187 to manage `inserted' flag in bp loc in a correct state.
5188 breakpoint_init_inferior, called from init_wait_for_inferior, set
5189 `inserted' flag to 0, while before breakpoint_re_set, called from
5190 start_remote, set `inserted' flag to 1. In the initialization of
5191 inferior, breakpoint_init_inferior should be called first, and then
5192 breakpoint_re_set can be called. If this order is broken, state of
5193 `inserted' flag is wrong, and cause some problems on breakpoint
5194 manipulation. */
5195 init_wait_for_inferior ();
5196
5197 get_offsets (); /* Get text, data & bss offsets. */
5198
5199 /* If we could not find a description using qXfer, and we know
5200 how to do it some other way, try again. This is not
5201 supported for non-stop; it could be, but it is tricky if
5202 there are no stopped threads when we connect. */
5203 if (remote_read_description_p (this)
5204 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5205 {
5206 target_clear_description ();
5207 target_find_description ();
5208 }
5209
5210 /* Use the previously fetched status. */
5211 gdb_assert (wait_status != NULL);
5212 struct notif_event *reply
5213 = remote_notif_parse (this, &notif_client_stop, wait_status);
5214 push_stop_reply ((struct stop_reply *) reply);
5215
5216 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5217 }
5218 else
5219 {
5220 /* Clear WFI global state. Do this before finding about new
5221 threads and inferiors, and setting the current inferior.
5222 Otherwise we would clear the proceed status of the current
5223 inferior when we want its stop_soon state to be preserved
5224 (see notice_new_inferior). */
5225 init_wait_for_inferior ();
5226
5227 /* In non-stop, we will either get an "OK", meaning that there
5228 are no stopped threads at this time; or, a regular stop
5229 reply. In the latter case, there may be more than one thread
5230 stopped --- we pull them all out using the vStopped
5231 mechanism. */
5232 if (strcmp (rs->buf.data (), "OK") != 0)
5233 {
5234 const notif_client *notif = &notif_client_stop;
5235
5236 /* remote_notif_get_pending_replies acks this one, and gets
5237 the rest out. */
5238 rs->notif_state->pending_event[notif_client_stop.id]
5239 = remote_notif_parse (this, notif, rs->buf.data ());
5240 remote_notif_get_pending_events (notif);
5241 }
5242
5243 if (thread_count (this) == 0)
5244 {
5245 if (!extended_p)
5246 error (_("The target is not running (try extended-remote?)"));
5247 return false;
5248 }
5249
5250 /* Report all signals during attach/startup. */
5251 pass_signals ({});
5252
5253 /* If there are already stopped threads, mark them stopped and
5254 report their stops before giving the prompt to the user. */
5255 process_initial_stop_replies (from_tty);
5256
5257 if (target_can_async_p ())
5258 target_async (true);
5259 }
5260
5261 /* Give the target a chance to look up symbols. */
5262 for (inferior *inf : all_inferiors (this))
5263 {
5264 /* The inferiors that exist at this point were created from what
5265 was found already running on the remote side, so we know they
5266 have execution. */
5267 gdb_assert (this->has_execution (inf));
5268
5269 /* No use without a symbol-file. */
5270 if (inf->pspace->symfile_object_file == nullptr)
5271 continue;
5272
5273 /* Need to switch to a specific thread, because remote_check_symbols
5274 uses INFERIOR_PTID to set the general thread. */
5275 scoped_restore_current_thread restore_thread;
5276 thread_info *thread = any_thread_of_inferior (inf);
5277 switch_to_thread (thread);
5278 this->remote_check_symbols ();
5279 }
5280
5281 /* Possibly the target has been engaged in a trace run started
5282 previously; find out where things are at. */
5283 if (get_trace_status (current_trace_status ()) != -1)
5284 {
5285 struct uploaded_tp *uploaded_tps = NULL;
5286
5287 if (current_trace_status ()->running)
5288 gdb_printf (_("Trace is already running on the target.\n"));
5289
5290 upload_tracepoints (&uploaded_tps);
5291
5292 merge_uploaded_tracepoints (&uploaded_tps);
5293 }
5294
5295 /* Possibly the target has been engaged in a btrace record started
5296 previously; find out where things are at. */
5297 remote_btrace_maybe_reopen ();
5298
5299 return true;
5300 }
5301
5302 /* Start the remote connection and sync state. */
5303
5304 void
5305 remote_target::start_remote (int from_tty, int extended_p)
5306 {
5307 if (start_remote_1 (from_tty, extended_p)
5308 && breakpoints_should_be_inserted_now ())
5309 insert_breakpoints ();
5310 }
5311
5312 const char *
5313 remote_target::connection_string ()
5314 {
5315 remote_state *rs = get_remote_state ();
5316
5317 if (rs->remote_desc->name != NULL)
5318 return rs->remote_desc->name;
5319 else
5320 return NULL;
5321 }
5322
5323 /* Open a connection to a remote debugger.
5324 NAME is the filename used for communication. */
5325
5326 void
5327 remote_target::open (const char *name, int from_tty)
5328 {
5329 open_1 (name, from_tty, 0);
5330 }
5331
5332 /* Open a connection to a remote debugger using the extended
5333 remote gdb protocol. NAME is the filename used for communication. */
5334
5335 void
5336 extended_remote_target::open (const char *name, int from_tty)
5337 {
5338 open_1 (name, from_tty, 1 /*extended_p */);
5339 }
5340
5341 void
5342 remote_features::reset_all_packet_configs_support ()
5343 {
5344 int i;
5345
5346 for (i = 0; i < PACKET_MAX; i++)
5347 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5348 }
5349
5350 /* Initialize all packet configs. */
5351
5352 static void
5353 init_all_packet_configs (void)
5354 {
5355 int i;
5356
5357 for (i = 0; i < PACKET_MAX; i++)
5358 {
5359 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5360 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5361 }
5362 }
5363
5364 /* Symbol look-up. */
5365
5366 void
5367 remote_target::remote_check_symbols ()
5368 {
5369 char *tmp;
5370 int end;
5371
5372 /* It doesn't make sense to send a qSymbol packet for an inferior that
5373 doesn't have execution, because the remote side doesn't know about
5374 inferiors without execution. */
5375 gdb_assert (target_has_execution ());
5376
5377 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5378 return;
5379
5380 /* Make sure the remote is pointing at the right process. Note
5381 there's no way to select "no process". */
5382 set_general_process ();
5383
5384 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5385 because we need both at the same time. */
5386 gdb::char_vector msg (get_remote_packet_size ());
5387 gdb::char_vector reply (get_remote_packet_size ());
5388
5389 /* Invite target to request symbol lookups. */
5390
5391 putpkt ("qSymbol::");
5392 getpkt (&reply);
5393 m_features.packet_ok (reply, PACKET_qSymbol);
5394
5395 while (startswith (reply.data (), "qSymbol:"))
5396 {
5397 struct bound_minimal_symbol sym;
5398
5399 tmp = &reply[8];
5400 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5401 strlen (tmp) / 2);
5402 msg[end] = '\0';
5403 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5404 if (sym.minsym == NULL)
5405 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5406 &reply[8]);
5407 else
5408 {
5409 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5410 CORE_ADDR sym_addr = sym.value_address ();
5411
5412 /* If this is a function address, return the start of code
5413 instead of any data function descriptor. */
5414 sym_addr = gdbarch_convert_from_func_ptr_addr
5415 (current_inferior ()->arch (), sym_addr,
5416 current_inferior ()->top_target ());
5417
5418 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5419 phex_nz (sym_addr, addr_size), &reply[8]);
5420 }
5421
5422 putpkt (msg.data ());
5423 getpkt (&reply);
5424 }
5425 }
5426
5427 static struct serial *
5428 remote_serial_open (const char *name)
5429 {
5430 static int udp_warning = 0;
5431
5432 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5433 of in ser-tcp.c, because it is the remote protocol assuming that the
5434 serial connection is reliable and not the serial connection promising
5435 to be. */
5436 if (!udp_warning && startswith (name, "udp:"))
5437 {
5438 warning (_("The remote protocol may be unreliable over UDP.\n"
5439 "Some events may be lost, rendering further debugging "
5440 "impossible."));
5441 udp_warning = 1;
5442 }
5443
5444 return serial_open (name);
5445 }
5446
5447 /* Inform the target of our permission settings. The permission flags
5448 work without this, but if the target knows the settings, it can do
5449 a couple things. First, it can add its own check, to catch cases
5450 that somehow manage to get by the permissions checks in target
5451 methods. Second, if the target is wired to disallow particular
5452 settings (for instance, a system in the field that is not set up to
5453 be able to stop at a breakpoint), it can object to any unavailable
5454 permissions. */
5455
5456 void
5457 remote_target::set_permissions ()
5458 {
5459 struct remote_state *rs = get_remote_state ();
5460
5461 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5462 "WriteReg:%x;WriteMem:%x;"
5463 "InsertBreak:%x;InsertTrace:%x;"
5464 "InsertFastTrace:%x;Stop:%x",
5465 may_write_registers, may_write_memory,
5466 may_insert_breakpoints, may_insert_tracepoints,
5467 may_insert_fast_tracepoints, may_stop);
5468 putpkt (rs->buf);
5469 getpkt (&rs->buf);
5470
5471 /* If the target didn't like the packet, warn the user. Do not try
5472 to undo the user's settings, that would just be maddening. */
5473 if (strcmp (rs->buf.data (), "OK") != 0)
5474 warning (_("Remote refused setting permissions with: %s"),
5475 rs->buf.data ());
5476 }
5477
5478 /* This type describes each known response to the qSupported
5479 packet. */
5480 struct protocol_feature
5481 {
5482 /* The name of this protocol feature. */
5483 const char *name;
5484
5485 /* The default for this protocol feature. */
5486 enum packet_support default_support;
5487
5488 /* The function to call when this feature is reported, or after
5489 qSupported processing if the feature is not supported.
5490 The first argument points to this structure. The second
5491 argument indicates whether the packet requested support be
5492 enabled, disabled, or probed (or the default, if this function
5493 is being called at the end of processing and this feature was
5494 not reported). The third argument may be NULL; if not NULL, it
5495 is a NUL-terminated string taken from the packet following
5496 this feature's name and an equals sign. */
5497 void (*func) (remote_target *remote, const struct protocol_feature *,
5498 enum packet_support, const char *);
5499
5500 /* The corresponding packet for this feature. Only used if
5501 FUNC is remote_supported_packet. */
5502 int packet;
5503 };
5504
5505 static void
5506 remote_supported_packet (remote_target *remote,
5507 const struct protocol_feature *feature,
5508 enum packet_support support,
5509 const char *argument)
5510 {
5511 if (argument)
5512 {
5513 warning (_("Remote qSupported response supplied an unexpected value for"
5514 " \"%s\"."), feature->name);
5515 return;
5516 }
5517
5518 remote->m_features.m_protocol_packets[feature->packet].support = support;
5519 }
5520
5521 void
5522 remote_target::remote_packet_size (const protocol_feature *feature,
5523 enum packet_support support,
5524 const char *value)
5525 {
5526 struct remote_state *rs = get_remote_state ();
5527
5528 int packet_size;
5529 char *value_end;
5530
5531 if (support != PACKET_ENABLE)
5532 return;
5533
5534 if (value == NULL || *value == '\0')
5535 {
5536 warning (_("Remote target reported \"%s\" without a size."),
5537 feature->name);
5538 return;
5539 }
5540
5541 errno = 0;
5542 packet_size = strtol (value, &value_end, 16);
5543 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5544 {
5545 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5546 feature->name, value);
5547 return;
5548 }
5549
5550 /* Record the new maximum packet size. */
5551 rs->explicit_packet_size = packet_size;
5552 }
5553
5554 static void
5555 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5556 enum packet_support support, const char *value)
5557 {
5558 remote->remote_packet_size (feature, support, value);
5559 }
5560
5561 void
5562 remote_target::remote_supported_thread_options (const protocol_feature *feature,
5563 enum packet_support support,
5564 const char *value)
5565 {
5566 struct remote_state *rs = get_remote_state ();
5567
5568 m_features.m_protocol_packets[feature->packet].support = support;
5569
5570 if (support != PACKET_ENABLE)
5571 return;
5572
5573 if (value == nullptr || *value == '\0')
5574 {
5575 warning (_("Remote target reported \"%s\" without supported options."),
5576 feature->name);
5577 return;
5578 }
5579
5580 ULONGEST options = 0;
5581 const char *p = unpack_varlen_hex (value, &options);
5582
5583 if (*p != '\0')
5584 {
5585 warning (_("Remote target reported \"%s\" with "
5586 "bad thread options: \"%s\"."),
5587 feature->name, value);
5588 return;
5589 }
5590
5591 /* Record the set of supported options. */
5592 rs->supported_thread_options = (gdb_thread_option) options;
5593 }
5594
5595 static void
5596 remote_supported_thread_options (remote_target *remote,
5597 const protocol_feature *feature,
5598 enum packet_support support,
5599 const char *value)
5600 {
5601 remote->remote_supported_thread_options (feature, support, value);
5602 }
5603
5604 static const struct protocol_feature remote_protocol_features[] = {
5605 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5606 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5607 PACKET_qXfer_auxv },
5608 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5609 PACKET_qXfer_exec_file },
5610 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5611 PACKET_qXfer_features },
5612 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5613 PACKET_qXfer_libraries },
5614 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5615 PACKET_qXfer_libraries_svr4 },
5616 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5617 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5618 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5619 PACKET_qXfer_memory_map },
5620 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5621 PACKET_qXfer_osdata },
5622 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5623 PACKET_qXfer_threads },
5624 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5625 PACKET_qXfer_traceframe_info },
5626 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5627 PACKET_QPassSignals },
5628 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5629 PACKET_QCatchSyscalls },
5630 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5631 PACKET_QProgramSignals },
5632 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5633 PACKET_QSetWorkingDir },
5634 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5635 PACKET_QStartupWithShell },
5636 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5637 PACKET_QEnvironmentHexEncoded },
5638 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5639 PACKET_QEnvironmentReset },
5640 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5641 PACKET_QEnvironmentUnset },
5642 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5643 PACKET_QStartNoAckMode },
5644 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5645 PACKET_multiprocess_feature },
5646 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5647 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5648 PACKET_qXfer_siginfo_read },
5649 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5650 PACKET_qXfer_siginfo_write },
5651 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5652 PACKET_ConditionalTracepoints },
5653 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5654 PACKET_ConditionalBreakpoints },
5655 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5656 PACKET_BreakpointCommands },
5657 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5658 PACKET_FastTracepoints },
5659 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5660 PACKET_StaticTracepoints },
5661 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5662 PACKET_InstallInTrace},
5663 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5664 PACKET_DisconnectedTracing_feature },
5665 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5666 PACKET_bc },
5667 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5668 PACKET_bs },
5669 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5670 PACKET_TracepointSource },
5671 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5672 PACKET_QAllow },
5673 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5674 PACKET_EnableDisableTracepoints_feature },
5675 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5676 PACKET_qXfer_fdpic },
5677 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5678 PACKET_qXfer_uib },
5679 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5680 PACKET_QDisableRandomization },
5681 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5682 { "QTBuffer:size", PACKET_DISABLE,
5683 remote_supported_packet, PACKET_QTBuffer_size},
5684 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5685 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5686 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5687 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5688 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5689 PACKET_qXfer_btrace },
5690 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5691 PACKET_qXfer_btrace_conf },
5692 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5693 PACKET_Qbtrace_conf_bts_size },
5694 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5695 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5696 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5697 PACKET_fork_event_feature },
5698 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5699 PACKET_vfork_event_feature },
5700 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5701 PACKET_exec_event_feature },
5702 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5703 PACKET_Qbtrace_conf_pt_size },
5704 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5705 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5706 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5707 PACKET_QThreadOptions },
5708 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5709 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5710 PACKET_memory_tagging_feature },
5711 };
5712
5713 static char *remote_support_xml;
5714
5715 /* Register string appended to "xmlRegisters=" in qSupported query. */
5716
5717 void
5718 register_remote_support_xml (const char *xml)
5719 {
5720 #if defined(HAVE_LIBEXPAT)
5721 if (remote_support_xml == NULL)
5722 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5723 else
5724 {
5725 char *copy = xstrdup (remote_support_xml + 13);
5726 char *saveptr;
5727 char *p = strtok_r (copy, ",", &saveptr);
5728
5729 do
5730 {
5731 if (strcmp (p, xml) == 0)
5732 {
5733 /* already there */
5734 xfree (copy);
5735 return;
5736 }
5737 }
5738 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5739 xfree (copy);
5740
5741 remote_support_xml = reconcat (remote_support_xml,
5742 remote_support_xml, ",", xml,
5743 (char *) NULL);
5744 }
5745 #endif
5746 }
5747
5748 static void
5749 remote_query_supported_append (std::string *msg, const char *append)
5750 {
5751 if (!msg->empty ())
5752 msg->append (";");
5753 msg->append (append);
5754 }
5755
5756 void
5757 remote_target::remote_query_supported ()
5758 {
5759 struct remote_state *rs = get_remote_state ();
5760 char *next;
5761 int i;
5762 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5763
5764 /* The packet support flags are handled differently for this packet
5765 than for most others. We treat an error, a disabled packet, and
5766 an empty response identically: any features which must be reported
5767 to be used will be automatically disabled. An empty buffer
5768 accomplishes this, since that is also the representation for a list
5769 containing no features. */
5770
5771 rs->buf[0] = 0;
5772 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5773 {
5774 std::string q;
5775
5776 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5777 != AUTO_BOOLEAN_FALSE)
5778 remote_query_supported_append (&q, "multiprocess+");
5779
5780 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5781 != AUTO_BOOLEAN_FALSE)
5782 remote_query_supported_append (&q, "swbreak+");
5783
5784 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5785 != AUTO_BOOLEAN_FALSE)
5786 remote_query_supported_append (&q, "hwbreak+");
5787
5788 remote_query_supported_append (&q, "qRelocInsn+");
5789
5790 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5791 != AUTO_BOOLEAN_FALSE)
5792 remote_query_supported_append (&q, "fork-events+");
5793
5794 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5795 != AUTO_BOOLEAN_FALSE)
5796 remote_query_supported_append (&q, "vfork-events+");
5797
5798 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5799 != AUTO_BOOLEAN_FALSE)
5800 remote_query_supported_append (&q, "exec-events+");
5801
5802 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5803 != AUTO_BOOLEAN_FALSE)
5804 remote_query_supported_append (&q, "vContSupported+");
5805
5806 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5807 != AUTO_BOOLEAN_FALSE)
5808 remote_query_supported_append (&q, "QThreadEvents+");
5809
5810 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5811 != AUTO_BOOLEAN_FALSE)
5812 remote_query_supported_append (&q, "QThreadOptions+");
5813
5814 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5815 != AUTO_BOOLEAN_FALSE)
5816 remote_query_supported_append (&q, "no-resumed+");
5817
5818 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5819 != AUTO_BOOLEAN_FALSE)
5820 remote_query_supported_append (&q, "memory-tagging+");
5821
5822 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5823 the qSupported:xmlRegisters=i386 handling. */
5824 if (remote_support_xml != NULL
5825 && (m_features.packet_support (PACKET_qXfer_features)
5826 != PACKET_DISABLE))
5827 remote_query_supported_append (&q, remote_support_xml);
5828
5829 q = "qSupported:" + q;
5830 putpkt (q.c_str ());
5831
5832 getpkt (&rs->buf);
5833
5834 /* If an error occurred, warn, but do not return - just reset the
5835 buffer to empty and go on to disable features. */
5836 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5837 {
5838 warning (_("Remote failure reply: %s"), rs->buf.data ());
5839 rs->buf[0] = 0;
5840 }
5841 }
5842
5843 memset (seen, 0, sizeof (seen));
5844
5845 next = rs->buf.data ();
5846 while (*next)
5847 {
5848 enum packet_support is_supported;
5849 char *p, *end, *name_end, *value;
5850
5851 /* First separate out this item from the rest of the packet. If
5852 there's another item after this, we overwrite the separator
5853 (terminated strings are much easier to work with). */
5854 p = next;
5855 end = strchr (p, ';');
5856 if (end == NULL)
5857 {
5858 end = p + strlen (p);
5859 next = end;
5860 }
5861 else
5862 {
5863 *end = '\0';
5864 next = end + 1;
5865
5866 if (end == p)
5867 {
5868 warning (_("empty item in \"qSupported\" response"));
5869 continue;
5870 }
5871 }
5872
5873 name_end = strchr (p, '=');
5874 if (name_end)
5875 {
5876 /* This is a name=value entry. */
5877 is_supported = PACKET_ENABLE;
5878 value = name_end + 1;
5879 *name_end = '\0';
5880 }
5881 else
5882 {
5883 value = NULL;
5884 switch (end[-1])
5885 {
5886 case '+':
5887 is_supported = PACKET_ENABLE;
5888 break;
5889
5890 case '-':
5891 is_supported = PACKET_DISABLE;
5892 break;
5893
5894 case '?':
5895 is_supported = PACKET_SUPPORT_UNKNOWN;
5896 break;
5897
5898 default:
5899 warning (_("unrecognized item \"%s\" "
5900 "in \"qSupported\" response"), p);
5901 continue;
5902 }
5903 end[-1] = '\0';
5904 }
5905
5906 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5907 if (strcmp (remote_protocol_features[i].name, p) == 0)
5908 {
5909 const struct protocol_feature *feature;
5910
5911 seen[i] = 1;
5912 feature = &remote_protocol_features[i];
5913 feature->func (this, feature, is_supported, value);
5914 break;
5915 }
5916 }
5917
5918 /* If we increased the packet size, make sure to increase the global
5919 buffer size also. We delay this until after parsing the entire
5920 qSupported packet, because this is the same buffer we were
5921 parsing. */
5922 if (rs->buf.size () < rs->explicit_packet_size)
5923 rs->buf.resize (rs->explicit_packet_size);
5924
5925 /* Handle the defaults for unmentioned features. */
5926 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5927 if (!seen[i])
5928 {
5929 const struct protocol_feature *feature;
5930
5931 feature = &remote_protocol_features[i];
5932 feature->func (this, feature, feature->default_support, NULL);
5933 }
5934 }
5935
5936 /* Serial QUIT handler for the remote serial descriptor.
5937
5938 Defers handling a Ctrl-C until we're done with the current
5939 command/response packet sequence, unless:
5940
5941 - We're setting up the connection. Don't send a remote interrupt
5942 request, as we're not fully synced yet. Quit immediately
5943 instead.
5944
5945 - The target has been resumed in the foreground
5946 (target_terminal::is_ours is false) with a synchronous resume
5947 packet, and we're blocked waiting for the stop reply, thus a
5948 Ctrl-C should be immediately sent to the target.
5949
5950 - We get a second Ctrl-C while still within the same serial read or
5951 write. In that case the serial is seemingly wedged --- offer to
5952 quit/disconnect.
5953
5954 - We see a second Ctrl-C without target response, after having
5955 previously interrupted the target. In that case the target/stub
5956 is probably wedged --- offer to quit/disconnect.
5957 */
5958
5959 void
5960 remote_target::remote_serial_quit_handler ()
5961 {
5962 struct remote_state *rs = get_remote_state ();
5963
5964 if (check_quit_flag ())
5965 {
5966 /* If we're starting up, we're not fully synced yet. Quit
5967 immediately. */
5968 if (rs->starting_up)
5969 quit ();
5970 else if (rs->got_ctrlc_during_io)
5971 {
5972 if (query (_("The target is not responding to GDB commands.\n"
5973 "Stop debugging it? ")))
5974 remote_unpush_and_throw (this);
5975 }
5976 /* If ^C has already been sent once, offer to disconnect. */
5977 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5978 interrupt_query ();
5979 /* All-stop protocol, and blocked waiting for stop reply. Send
5980 an interrupt request. */
5981 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5982 target_interrupt ();
5983 else
5984 rs->got_ctrlc_during_io = 1;
5985 }
5986 }
5987
5988 /* The remote_target that is current while the quit handler is
5989 overridden with remote_serial_quit_handler. */
5990 static remote_target *curr_quit_handler_target;
5991
5992 static void
5993 remote_serial_quit_handler ()
5994 {
5995 curr_quit_handler_target->remote_serial_quit_handler ();
5996 }
5997
5998 /* Remove the remote target from the target stack of each inferior
5999 that is using it. Upper targets depend on it so remove them
6000 first. */
6001
6002 static void
6003 remote_unpush_target (remote_target *target)
6004 {
6005 /* We have to unpush the target from all inferiors, even those that
6006 aren't running. */
6007 scoped_restore_current_inferior restore_current_inferior;
6008
6009 for (inferior *inf : all_inferiors (target))
6010 {
6011 switch_to_inferior_no_thread (inf);
6012 inf->pop_all_targets_at_and_above (process_stratum);
6013 generic_mourn_inferior ();
6014 }
6015
6016 /* Don't rely on target_close doing this when the target is popped
6017 from the last remote inferior above, because something may be
6018 holding a reference to the target higher up on the stack, meaning
6019 target_close won't be called yet. We lost the connection to the
6020 target, so clear these now, otherwise we may later throw
6021 TARGET_CLOSE_ERROR while trying to tell the remote target to
6022 close the file. */
6023 fileio_handles_invalidate_target (target);
6024 }
6025
6026 static void
6027 remote_unpush_and_throw (remote_target *target)
6028 {
6029 remote_unpush_target (target);
6030 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6031 }
6032
6033 void
6034 remote_target::open_1 (const char *name, int from_tty, int extended_p)
6035 {
6036 remote_target *curr_remote = get_current_remote_target ();
6037
6038 if (name == 0)
6039 error (_("To open a remote debug connection, you need to specify what\n"
6040 "serial device is attached to the remote system\n"
6041 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6042
6043 /* If we're connected to a running target, target_preopen will kill it.
6044 Ask this question first, before target_preopen has a chance to kill
6045 anything. */
6046 if (curr_remote != NULL && !target_has_execution ())
6047 {
6048 if (from_tty
6049 && !query (_("Already connected to a remote target. Disconnect? ")))
6050 error (_("Still connected."));
6051 }
6052
6053 /* Here the possibly existing remote target gets unpushed. */
6054 target_preopen (from_tty);
6055
6056 remote_fileio_reset ();
6057 reopen_exec_file ();
6058 reread_symbols (from_tty);
6059
6060 remote_target *remote
6061 = (extended_p ? new extended_remote_target () : new remote_target ());
6062 target_ops_up target_holder (remote);
6063
6064 remote_state *rs = remote->get_remote_state ();
6065
6066 /* See FIXME above. */
6067 if (!target_async_permitted)
6068 rs->wait_forever_enabled_p = true;
6069
6070 rs->remote_desc = remote_serial_open (name);
6071 if (!rs->remote_desc)
6072 perror_with_name (name);
6073
6074 if (baud_rate != -1)
6075 {
6076 if (serial_setbaudrate (rs->remote_desc, baud_rate))
6077 {
6078 /* The requested speed could not be set. Error out to
6079 top level after closing remote_desc. Take care to
6080 set remote_desc to NULL to avoid closing remote_desc
6081 more than once. */
6082 serial_close (rs->remote_desc);
6083 rs->remote_desc = NULL;
6084 perror_with_name (name);
6085 }
6086 }
6087
6088 serial_setparity (rs->remote_desc, serial_parity);
6089 serial_raw (rs->remote_desc);
6090
6091 /* If there is something sitting in the buffer we might take it as a
6092 response to a command, which would be bad. */
6093 serial_flush_input (rs->remote_desc);
6094
6095 if (from_tty)
6096 {
6097 gdb_puts ("Remote debugging using ");
6098 gdb_puts (name);
6099 gdb_puts ("\n");
6100 }
6101
6102 /* Switch to using the remote target now. */
6103 current_inferior ()->push_target (std::move (target_holder));
6104
6105 /* Register extra event sources in the event loop. */
6106 rs->create_async_event_handler ();
6107
6108 rs->notif_state = remote_notif_state_allocate (remote);
6109
6110 /* Reset the target state; these things will be queried either by
6111 remote_query_supported or as they are needed. */
6112 remote->m_features.reset_all_packet_configs_support ();
6113 rs->explicit_packet_size = 0;
6114 rs->noack_mode = 0;
6115 rs->extended = extended_p;
6116 rs->waiting_for_stop_reply = 0;
6117 rs->ctrlc_pending_p = 0;
6118 rs->got_ctrlc_during_io = 0;
6119
6120 rs->general_thread = not_sent_ptid;
6121 rs->continue_thread = not_sent_ptid;
6122 rs->remote_traceframe_number = -1;
6123
6124 rs->last_resume_exec_dir = EXEC_FORWARD;
6125
6126 /* Probe for ability to use "ThreadInfo" query, as required. */
6127 rs->use_threadinfo_query = 1;
6128 rs->use_threadextra_query = 1;
6129
6130 rs->readahead_cache.invalidate ();
6131
6132 if (target_async_permitted)
6133 {
6134 /* FIXME: cagney/1999-09-23: During the initial connection it is
6135 assumed that the target is already ready and able to respond to
6136 requests. Unfortunately remote_start_remote() eventually calls
6137 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6138 around this. Eventually a mechanism that allows
6139 wait_for_inferior() to expect/get timeouts will be
6140 implemented. */
6141 rs->wait_forever_enabled_p = false;
6142 }
6143
6144 /* First delete any symbols previously loaded from shared libraries. */
6145 no_shared_libraries (NULL, 0);
6146
6147 /* Start the remote connection. If error() or QUIT, discard this
6148 target (we'd otherwise be in an inconsistent state) and then
6149 propogate the error on up the exception chain. This ensures that
6150 the caller doesn't stumble along blindly assuming that the
6151 function succeeded. The CLI doesn't have this problem but other
6152 UI's, such as MI do.
6153
6154 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6155 this function should return an error indication letting the
6156 caller restore the previous state. Unfortunately the command
6157 ``target remote'' is directly wired to this function making that
6158 impossible. On a positive note, the CLI side of this problem has
6159 been fixed - the function set_cmd_context() makes it possible for
6160 all the ``target ....'' commands to share a common callback
6161 function. See cli-dump.c. */
6162 {
6163
6164 try
6165 {
6166 remote->start_remote (from_tty, extended_p);
6167 }
6168 catch (const gdb_exception &ex)
6169 {
6170 /* Pop the partially set up target - unless something else did
6171 already before throwing the exception. */
6172 if (ex.error != TARGET_CLOSE_ERROR)
6173 remote_unpush_target (remote);
6174 throw;
6175 }
6176 }
6177
6178 remote_btrace_reset (rs);
6179
6180 if (target_async_permitted)
6181 rs->wait_forever_enabled_p = true;
6182 }
6183
6184 /* Determine if WS represents a fork status. */
6185
6186 static bool
6187 is_fork_status (target_waitkind kind)
6188 {
6189 return (kind == TARGET_WAITKIND_FORKED
6190 || kind == TARGET_WAITKIND_VFORKED);
6191 }
6192
6193 /* Return a reference to the field where a pending child status, if
6194 there's one, is recorded. If there's no child event pending, the
6195 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6196
6197 static const target_waitstatus &
6198 thread_pending_status (struct thread_info *thread)
6199 {
6200 return (thread->has_pending_waitstatus ()
6201 ? thread->pending_waitstatus ()
6202 : thread->pending_follow);
6203 }
6204
6205 /* Return THREAD's pending status if it is a pending fork/vfork (but
6206 not clone) parent, else return nullptr. */
6207
6208 static const target_waitstatus *
6209 thread_pending_fork_status (struct thread_info *thread)
6210 {
6211 const target_waitstatus &ws = thread_pending_status (thread);
6212
6213 if (!is_fork_status (ws.kind ()))
6214 return nullptr;
6215
6216 return &ws;
6217 }
6218
6219 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6220 event, else return nullptr. */
6221
6222 static const target_waitstatus *
6223 thread_pending_child_status (thread_info *thread)
6224 {
6225 const target_waitstatus &ws = thread_pending_status (thread);
6226
6227 if (!is_new_child_status (ws.kind ()))
6228 return nullptr;
6229
6230 return &ws;
6231 }
6232
6233 /* Detach the specified process. */
6234
6235 void
6236 remote_target::remote_detach_pid (int pid)
6237 {
6238 struct remote_state *rs = get_remote_state ();
6239
6240 /* This should not be necessary, but the handling for D;PID in
6241 GDBserver versions prior to 8.2 incorrectly assumes that the
6242 selected process points to the same process we're detaching,
6243 leading to misbehavior (and possibly GDBserver crashing) when it
6244 does not. Since it's easy and cheap, work around it by forcing
6245 GDBserver to select GDB's current process. */
6246 set_general_process ();
6247
6248 if (m_features.remote_multi_process_p ())
6249 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6250 else
6251 strcpy (rs->buf.data (), "D");
6252
6253 putpkt (rs->buf);
6254 getpkt (&rs->buf);
6255
6256 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6257 ;
6258 else if (rs->buf[0] == '\0')
6259 error (_("Remote doesn't know how to detach"));
6260 else
6261 {
6262 /* It is possible that we have an unprocessed exit event for this
6263 pid. If this is the case then we can ignore the failure to detach
6264 and just pretend that the detach worked, as far as the user is
6265 concerned, the process exited immediately after the detach. */
6266 bool process_has_already_exited = false;
6267 remote_notif_get_pending_events (&notif_client_stop);
6268 for (stop_reply_up &reply : rs->stop_reply_queue)
6269 {
6270 if (reply->ptid.pid () != pid)
6271 continue;
6272
6273 enum target_waitkind kind = reply->ws.kind ();
6274 if (kind == TARGET_WAITKIND_EXITED
6275 || kind == TARGET_WAITKIND_SIGNALLED)
6276 {
6277 process_has_already_exited = true;
6278 remote_debug_printf
6279 ("detach failed, but process already exited");
6280 break;
6281 }
6282 }
6283
6284 if (!process_has_already_exited)
6285 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6286 }
6287 }
6288
6289 /* This detaches a program to which we previously attached, using
6290 inferior_ptid to identify the process. After this is done, GDB
6291 can be used to debug some other program. We better not have left
6292 any breakpoints in the target program or it'll die when it hits
6293 one. */
6294
6295 void
6296 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6297 {
6298 int pid = inferior_ptid.pid ();
6299 struct remote_state *rs = get_remote_state ();
6300 int is_fork_parent;
6301
6302 if (!target_has_execution ())
6303 error (_("No process to detach from."));
6304
6305 target_announce_detach (from_tty);
6306
6307 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6308 {
6309 /* If we're in breakpoints-always-inserted mode, or the inferior
6310 is running, we have to remove breakpoints before detaching.
6311 We don't do this in common code instead because not all
6312 targets support removing breakpoints while the target is
6313 running. The remote target / gdbserver does, though. */
6314 remove_breakpoints_inf (current_inferior ());
6315 }
6316
6317 /* Tell the remote target to detach. */
6318 remote_detach_pid (pid);
6319
6320 /* Exit only if this is the only active inferior. */
6321 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6322 gdb_puts (_("Ending remote debugging.\n"));
6323
6324 /* See if any thread of the inferior we are detaching has a pending fork
6325 status. In that case, we must detach from the child resulting from
6326 that fork. */
6327 for (thread_info *thread : inf->non_exited_threads ())
6328 {
6329 const target_waitstatus *ws = thread_pending_fork_status (thread);
6330
6331 if (ws == nullptr)
6332 continue;
6333
6334 remote_detach_pid (ws->child_ptid ().pid ());
6335 }
6336
6337 /* Check also for any pending fork events in the stop reply queue. */
6338 remote_notif_get_pending_events (&notif_client_stop);
6339 for (stop_reply_up &reply : rs->stop_reply_queue)
6340 {
6341 if (reply->ptid.pid () != pid)
6342 continue;
6343
6344 if (!is_fork_status (reply->ws.kind ()))
6345 continue;
6346
6347 remote_detach_pid (reply->ws.child_ptid ().pid ());
6348 }
6349
6350 thread_info *tp = this->find_thread (inferior_ptid);
6351
6352 /* Check to see if we are detaching a fork parent. Note that if we
6353 are detaching a fork child, tp == NULL. */
6354 is_fork_parent = (tp != NULL
6355 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6356
6357 /* If doing detach-on-fork, we don't mourn, because that will delete
6358 breakpoints that should be available for the followed inferior. */
6359 if (!is_fork_parent)
6360 {
6361 /* Save the pid as a string before mourning, since that will
6362 unpush the remote target, and we need the string after. */
6363 std::string infpid = target_pid_to_str (ptid_t (pid));
6364
6365 target_mourn_inferior (inferior_ptid);
6366 if (print_inferior_events)
6367 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6368 inf->num, infpid.c_str ());
6369 }
6370 else
6371 {
6372 switch_to_no_thread ();
6373 detach_inferior (current_inferior ());
6374 }
6375 }
6376
6377 void
6378 remote_target::detach (inferior *inf, int from_tty)
6379 {
6380 remote_detach_1 (inf, from_tty);
6381 }
6382
6383 void
6384 extended_remote_target::detach (inferior *inf, int from_tty)
6385 {
6386 remote_detach_1 (inf, from_tty);
6387 }
6388
6389 /* Target follow-fork function for remote targets. On entry, and
6390 at return, the current inferior is the fork parent.
6391
6392 Note that although this is currently only used for extended-remote,
6393 it is named remote_follow_fork in anticipation of using it for the
6394 remote target as well. */
6395
6396 void
6397 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6398 target_waitkind fork_kind, bool follow_child,
6399 bool detach_fork)
6400 {
6401 process_stratum_target::follow_fork (child_inf, child_ptid,
6402 fork_kind, follow_child, detach_fork);
6403
6404 if ((fork_kind == TARGET_WAITKIND_FORKED
6405 && m_features.remote_fork_event_p ())
6406 || (fork_kind == TARGET_WAITKIND_VFORKED
6407 && m_features.remote_vfork_event_p ()))
6408 {
6409 /* When following the parent and detaching the child, we detach
6410 the child here. For the case of following the child and
6411 detaching the parent, the detach is done in the target-
6412 independent follow fork code in infrun.c. We can't use
6413 target_detach when detaching an unfollowed child because
6414 the client side doesn't know anything about the child. */
6415 if (detach_fork && !follow_child)
6416 {
6417 /* Detach the fork child. */
6418 remote_detach_pid (child_ptid.pid ());
6419 }
6420 }
6421 }
6422
6423 void
6424 remote_target::follow_clone (ptid_t child_ptid)
6425 {
6426 remote_add_thread (child_ptid, false, false, false);
6427 }
6428
6429 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6430 in the program space of the new inferior. */
6431
6432 void
6433 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6434 const char *execd_pathname)
6435 {
6436 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6437
6438 /* We know that this is a target file name, so if it has the "target:"
6439 prefix we strip it off before saving it in the program space. */
6440 if (is_target_filename (execd_pathname))
6441 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6442
6443 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6444 }
6445
6446 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6447
6448 void
6449 remote_target::disconnect (const char *args, int from_tty)
6450 {
6451 if (args)
6452 error (_("Argument given to \"disconnect\" when remotely debugging."));
6453
6454 /* Make sure we unpush even the extended remote targets. Calling
6455 target_mourn_inferior won't unpush, and
6456 remote_target::mourn_inferior won't unpush if there is more than
6457 one inferior left. */
6458 remote_unpush_target (this);
6459
6460 if (from_tty)
6461 gdb_puts ("Ending remote debugging.\n");
6462 }
6463
6464 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6465 be chatty about it. */
6466
6467 void
6468 extended_remote_target::attach (const char *args, int from_tty)
6469 {
6470 struct remote_state *rs = get_remote_state ();
6471 int pid;
6472 char *wait_status = NULL;
6473
6474 pid = parse_pid_to_attach (args);
6475
6476 /* Remote PID can be freely equal to getpid, do not check it here the same
6477 way as in other targets. */
6478
6479 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6480 error (_("This target does not support attaching to a process"));
6481
6482 target_announce_attach (from_tty, pid);
6483
6484 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6485 putpkt (rs->buf);
6486 getpkt (&rs->buf);
6487
6488 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6489 {
6490 case PACKET_OK:
6491 if (!target_is_non_stop_p ())
6492 {
6493 /* Save the reply for later. */
6494 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6495 strcpy (wait_status, rs->buf.data ());
6496 }
6497 else if (strcmp (rs->buf.data (), "OK") != 0)
6498 error (_("Attaching to %s failed with: %s"),
6499 target_pid_to_str (ptid_t (pid)).c_str (),
6500 rs->buf.data ());
6501 break;
6502 case PACKET_UNKNOWN:
6503 error (_("This target does not support attaching to a process"));
6504 default:
6505 error (_("Attaching to %s failed"),
6506 target_pid_to_str (ptid_t (pid)).c_str ());
6507 }
6508
6509 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6510
6511 inferior_ptid = ptid_t (pid);
6512
6513 if (target_is_non_stop_p ())
6514 {
6515 /* Get list of threads. */
6516 update_thread_list ();
6517
6518 thread_info *thread = first_thread_of_inferior (current_inferior ());
6519 if (thread != nullptr)
6520 switch_to_thread (thread);
6521
6522 /* Invalidate our notion of the remote current thread. */
6523 record_currthread (rs, minus_one_ptid);
6524 }
6525 else
6526 {
6527 /* Now, if we have thread information, update the main thread's
6528 ptid. */
6529 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6530
6531 /* Add the main thread to the thread list. We add the thread
6532 silently in this case (the final true parameter). */
6533 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6534
6535 switch_to_thread (thr);
6536 }
6537
6538 /* Next, if the target can specify a description, read it. We do
6539 this before anything involving memory or registers. */
6540 target_find_description ();
6541
6542 if (!target_is_non_stop_p ())
6543 {
6544 /* Use the previously fetched status. */
6545 gdb_assert (wait_status != NULL);
6546
6547 struct notif_event *reply
6548 = remote_notif_parse (this, &notif_client_stop, wait_status);
6549
6550 push_stop_reply ((struct stop_reply *) reply);
6551 }
6552 else
6553 {
6554 gdb_assert (wait_status == NULL);
6555
6556 gdb_assert (target_can_async_p ());
6557 }
6558 }
6559
6560 /* Implementation of the to_post_attach method. */
6561
6562 void
6563 extended_remote_target::post_attach (int pid)
6564 {
6565 /* Get text, data & bss offsets. */
6566 get_offsets ();
6567
6568 /* In certain cases GDB might not have had the chance to start
6569 symbol lookup up until now. This could happen if the debugged
6570 binary is not using shared libraries, the vsyscall page is not
6571 present (on Linux) and the binary itself hadn't changed since the
6572 debugging process was started. */
6573 if (current_program_space->symfile_object_file != NULL)
6574 remote_check_symbols();
6575 }
6576
6577 \f
6578 /* Check for the availability of vCont. This function should also check
6579 the response. */
6580
6581 void
6582 remote_target::remote_vcont_probe ()
6583 {
6584 remote_state *rs = get_remote_state ();
6585 char *buf;
6586
6587 strcpy (rs->buf.data (), "vCont?");
6588 putpkt (rs->buf);
6589 getpkt (&rs->buf);
6590 buf = rs->buf.data ();
6591
6592 /* Make sure that the features we assume are supported. */
6593 if (startswith (buf, "vCont"))
6594 {
6595 char *p = &buf[5];
6596 int support_c, support_C;
6597
6598 rs->supports_vCont.s = 0;
6599 rs->supports_vCont.S = 0;
6600 support_c = 0;
6601 support_C = 0;
6602 rs->supports_vCont.t = 0;
6603 rs->supports_vCont.r = 0;
6604 while (p && *p == ';')
6605 {
6606 p++;
6607 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6608 rs->supports_vCont.s = 1;
6609 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6610 rs->supports_vCont.S = 1;
6611 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6612 support_c = 1;
6613 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6614 support_C = 1;
6615 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6616 rs->supports_vCont.t = 1;
6617 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6618 rs->supports_vCont.r = 1;
6619
6620 p = strchr (p, ';');
6621 }
6622
6623 /* If c, and C are not all supported, we can't use vCont. Clearing
6624 BUF will make packet_ok disable the packet. */
6625 if (!support_c || !support_C)
6626 buf[0] = 0;
6627 }
6628
6629 m_features.packet_ok (rs->buf, PACKET_vCont);
6630 }
6631
6632 /* Helper function for building "vCont" resumptions. Write a
6633 resumption to P. ENDP points to one-passed-the-end of the buffer
6634 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6635 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6636 resumed thread should be single-stepped and/or signalled. If PTID
6637 equals minus_one_ptid, then all threads are resumed; if PTID
6638 represents a process, then all threads of the process are
6639 resumed. */
6640
6641 char *
6642 remote_target::append_resumption (char *p, char *endp,
6643 ptid_t ptid, int step, gdb_signal siggnal)
6644 {
6645 struct remote_state *rs = get_remote_state ();
6646
6647 if (step && siggnal != GDB_SIGNAL_0)
6648 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6649 else if (step
6650 /* GDB is willing to range step. */
6651 && use_range_stepping
6652 /* Target supports range stepping. */
6653 && rs->supports_vCont.r
6654 /* We don't currently support range stepping multiple
6655 threads with a wildcard (though the protocol allows it,
6656 so stubs shouldn't make an active effort to forbid
6657 it). */
6658 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6659 {
6660 struct thread_info *tp;
6661
6662 if (ptid == minus_one_ptid)
6663 {
6664 /* If we don't know about the target thread's tid, then
6665 we're resuming magic_null_ptid (see caller). */
6666 tp = this->find_thread (magic_null_ptid);
6667 }
6668 else
6669 tp = this->find_thread (ptid);
6670 gdb_assert (tp != NULL);
6671
6672 if (tp->control.may_range_step)
6673 {
6674 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6675
6676 p += xsnprintf (p, endp - p, ";r%s,%s",
6677 phex_nz (tp->control.step_range_start,
6678 addr_size),
6679 phex_nz (tp->control.step_range_end,
6680 addr_size));
6681 }
6682 else
6683 p += xsnprintf (p, endp - p, ";s");
6684 }
6685 else if (step)
6686 p += xsnprintf (p, endp - p, ";s");
6687 else if (siggnal != GDB_SIGNAL_0)
6688 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6689 else
6690 p += xsnprintf (p, endp - p, ";c");
6691
6692 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6693 {
6694 ptid_t nptid;
6695
6696 /* All (-1) threads of process. */
6697 nptid = ptid_t (ptid.pid (), -1);
6698
6699 p += xsnprintf (p, endp - p, ":");
6700 p = write_ptid (p, endp, nptid);
6701 }
6702 else if (ptid != minus_one_ptid)
6703 {
6704 p += xsnprintf (p, endp - p, ":");
6705 p = write_ptid (p, endp, ptid);
6706 }
6707
6708 return p;
6709 }
6710
6711 /* Clear the thread's private info on resume. */
6712
6713 static void
6714 resume_clear_thread_private_info (struct thread_info *thread)
6715 {
6716 if (thread->priv != NULL)
6717 {
6718 remote_thread_info *priv = get_remote_thread_info (thread);
6719
6720 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6721 priv->watch_data_address = 0;
6722 }
6723 }
6724
6725 /* Append a vCont continue-with-signal action for threads that have a
6726 non-zero stop signal. */
6727
6728 char *
6729 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6730 ptid_t ptid)
6731 {
6732 for (thread_info *thread : all_non_exited_threads (this, ptid))
6733 if (inferior_ptid != thread->ptid
6734 && thread->stop_signal () != GDB_SIGNAL_0)
6735 {
6736 p = append_resumption (p, endp, thread->ptid,
6737 0, thread->stop_signal ());
6738 thread->set_stop_signal (GDB_SIGNAL_0);
6739 resume_clear_thread_private_info (thread);
6740 }
6741
6742 return p;
6743 }
6744
6745 /* Set the target running, using the packets that use Hc
6746 (c/s/C/S). */
6747
6748 void
6749 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6750 gdb_signal siggnal)
6751 {
6752 struct remote_state *rs = get_remote_state ();
6753 char *buf;
6754
6755 rs->last_sent_signal = siggnal;
6756 rs->last_sent_step = step;
6757
6758 /* The c/s/C/S resume packets use Hc, so set the continue
6759 thread. */
6760 if (ptid == minus_one_ptid)
6761 set_continue_thread (any_thread_ptid);
6762 else
6763 set_continue_thread (ptid);
6764
6765 for (thread_info *thread : all_non_exited_threads (this))
6766 resume_clear_thread_private_info (thread);
6767
6768 buf = rs->buf.data ();
6769 if (::execution_direction == EXEC_REVERSE)
6770 {
6771 /* We don't pass signals to the target in reverse exec mode. */
6772 if (info_verbose && siggnal != GDB_SIGNAL_0)
6773 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6774 siggnal);
6775
6776 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6777 error (_("Remote reverse-step not supported."));
6778 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6779 error (_("Remote reverse-continue not supported."));
6780
6781 strcpy (buf, step ? "bs" : "bc");
6782 }
6783 else if (siggnal != GDB_SIGNAL_0)
6784 {
6785 buf[0] = step ? 'S' : 'C';
6786 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6787 buf[2] = tohex (((int) siggnal) & 0xf);
6788 buf[3] = '\0';
6789 }
6790 else
6791 strcpy (buf, step ? "s" : "c");
6792
6793 putpkt (buf);
6794 }
6795
6796 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6797 STEP, and SIGGNAL have the same meaning as in target_resume. This
6798 function returns non-zero iff it resumes the inferior.
6799
6800 This function issues a strict subset of all possible vCont commands
6801 at the moment. */
6802
6803 int
6804 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6805 enum gdb_signal siggnal)
6806 {
6807 struct remote_state *rs = get_remote_state ();
6808 char *p;
6809 char *endp;
6810
6811 /* No reverse execution actions defined for vCont. */
6812 if (::execution_direction == EXEC_REVERSE)
6813 return 0;
6814
6815 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6816 return 0;
6817
6818 p = rs->buf.data ();
6819 endp = p + get_remote_packet_size ();
6820
6821 /* If we could generate a wider range of packets, we'd have to worry
6822 about overflowing BUF. Should there be a generic
6823 "multi-part-packet" packet? */
6824
6825 p += xsnprintf (p, endp - p, "vCont");
6826
6827 if (scope_ptid == magic_null_ptid)
6828 {
6829 /* MAGIC_NULL_PTID means that we don't have any active threads,
6830 so we don't have any TID numbers the inferior will
6831 understand. Make sure to only send forms that do not specify
6832 a TID. */
6833 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6834 }
6835 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6836 {
6837 /* Resume all threads (of all processes, or of a single
6838 process), with preference for INFERIOR_PTID. This assumes
6839 inferior_ptid belongs to the set of all threads we are about
6840 to resume. */
6841 if (step || siggnal != GDB_SIGNAL_0)
6842 {
6843 /* Step inferior_ptid, with or without signal. */
6844 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6845 }
6846
6847 /* Also pass down any pending signaled resumption for other
6848 threads not the current. */
6849 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6850
6851 /* And continue others without a signal. */
6852 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6853 }
6854 else
6855 {
6856 /* Scheduler locking; resume only SCOPE_PTID. */
6857 append_resumption (p, endp, scope_ptid, step, siggnal);
6858 }
6859
6860 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6861 putpkt (rs->buf);
6862
6863 if (target_is_non_stop_p ())
6864 {
6865 /* In non-stop, the stub replies to vCont with "OK". The stop
6866 reply will be reported asynchronously by means of a `%Stop'
6867 notification. */
6868 getpkt (&rs->buf);
6869 if (strcmp (rs->buf.data (), "OK") != 0)
6870 error (_("Unexpected vCont reply in non-stop mode: %s"),
6871 rs->buf.data ());
6872 }
6873
6874 return 1;
6875 }
6876
6877 /* Tell the remote machine to resume. */
6878
6879 void
6880 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6881 {
6882 struct remote_state *rs = get_remote_state ();
6883
6884 /* When connected in non-stop mode, the core resumes threads
6885 individually. Resuming remote threads directly in target_resume
6886 would thus result in sending one packet per thread. Instead, to
6887 minimize roundtrip latency, here we just store the resume
6888 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6889 resumption will be done in remote_target::commit_resume, where we'll be
6890 able to do vCont action coalescing. */
6891 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6892 {
6893 remote_thread_info *remote_thr
6894 = get_remote_thread_info (inferior_thread ());
6895
6896 /* We don't expect the core to ask to resume an already resumed (from
6897 its point of view) thread. */
6898 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6899
6900 remote_thr->set_resumed_pending_vcont (step, siggnal);
6901
6902 /* There's actually nothing that says that the core can't
6903 request a wildcard resume in non-stop mode, though. It's
6904 just that we know it doesn't currently, so we don't bother
6905 with it. */
6906 gdb_assert (scope_ptid == inferior_ptid);
6907 return;
6908 }
6909
6910 commit_requested_thread_options ();
6911
6912 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6913 (explained in remote-notif.c:handle_notification) so
6914 remote_notif_process is not called. We need find a place where
6915 it is safe to start a 'vNotif' sequence. It is good to do it
6916 before resuming inferior, because inferior was stopped and no RSP
6917 traffic at that moment. */
6918 if (!target_is_non_stop_p ())
6919 remote_notif_process (rs->notif_state, &notif_client_stop);
6920
6921 rs->last_resume_exec_dir = ::execution_direction;
6922
6923 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6924 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6925 remote_resume_with_hc (scope_ptid, step, siggnal);
6926
6927 /* Update resumed state tracked by the remote target. */
6928 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6929 get_remote_thread_info (tp)->set_resumed ();
6930
6931 /* We've just told the target to resume. The remote server will
6932 wait for the inferior to stop, and then send a stop reply. In
6933 the mean time, we can't start another command/query ourselves
6934 because the stub wouldn't be ready to process it. This applies
6935 only to the base all-stop protocol, however. In non-stop (which
6936 only supports vCont), the stub replies with an "OK", and is
6937 immediate able to process further serial input. */
6938 if (!target_is_non_stop_p ())
6939 rs->waiting_for_stop_reply = 1;
6940 }
6941
6942 /* Private per-inferior info for target remote processes. */
6943
6944 struct remote_inferior : public private_inferior
6945 {
6946 /* Whether we can send a wildcard vCont for this process. */
6947 bool may_wildcard_vcont = true;
6948 };
6949
6950 /* Get the remote private inferior data associated to INF. */
6951
6952 static remote_inferior *
6953 get_remote_inferior (inferior *inf)
6954 {
6955 if (inf->priv == NULL)
6956 inf->priv.reset (new remote_inferior);
6957
6958 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6959 }
6960
6961 /* Class used to track the construction of a vCont packet in the
6962 outgoing packet buffer. This is used to send multiple vCont
6963 packets if we have more actions than would fit a single packet. */
6964
6965 class vcont_builder
6966 {
6967 public:
6968 explicit vcont_builder (remote_target *remote)
6969 : m_remote (remote)
6970 {
6971 restart ();
6972 }
6973
6974 void flush ();
6975 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6976
6977 private:
6978 void restart ();
6979
6980 /* The remote target. */
6981 remote_target *m_remote;
6982
6983 /* Pointer to the first action. P points here if no action has been
6984 appended yet. */
6985 char *m_first_action;
6986
6987 /* Where the next action will be appended. */
6988 char *m_p;
6989
6990 /* The end of the buffer. Must never write past this. */
6991 char *m_endp;
6992 };
6993
6994 /* Prepare the outgoing buffer for a new vCont packet. */
6995
6996 void
6997 vcont_builder::restart ()
6998 {
6999 struct remote_state *rs = m_remote->get_remote_state ();
7000
7001 m_p = rs->buf.data ();
7002 m_endp = m_p + m_remote->get_remote_packet_size ();
7003 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7004 m_first_action = m_p;
7005 }
7006
7007 /* If the vCont packet being built has any action, send it to the
7008 remote end. */
7009
7010 void
7011 vcont_builder::flush ()
7012 {
7013 struct remote_state *rs;
7014
7015 if (m_p == m_first_action)
7016 return;
7017
7018 rs = m_remote->get_remote_state ();
7019 m_remote->putpkt (rs->buf);
7020 m_remote->getpkt (&rs->buf);
7021 if (strcmp (rs->buf.data (), "OK") != 0)
7022 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7023 }
7024
7025 /* The largest action is range-stepping, with its two addresses. This
7026 is more than sufficient. If a new, bigger action is created, it'll
7027 quickly trigger a failed assertion in append_resumption (and we'll
7028 just bump this). */
7029 #define MAX_ACTION_SIZE 200
7030
7031 /* Append a new vCont action in the outgoing packet being built. If
7032 the action doesn't fit the packet along with previous actions, push
7033 what we've got so far to the remote end and start over a new vCont
7034 packet (with the new action). */
7035
7036 void
7037 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7038 {
7039 char buf[MAX_ACTION_SIZE + 1];
7040
7041 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7042 ptid, step, siggnal);
7043
7044 /* Check whether this new action would fit in the vCont packet along
7045 with previous actions. If not, send what we've got so far and
7046 start a new vCont packet. */
7047 size_t rsize = endp - buf;
7048 if (rsize > m_endp - m_p)
7049 {
7050 flush ();
7051 restart ();
7052
7053 /* Should now fit. */
7054 gdb_assert (rsize <= m_endp - m_p);
7055 }
7056
7057 memcpy (m_p, buf, rsize);
7058 m_p += rsize;
7059 *m_p = '\0';
7060 }
7061
7062 /* to_commit_resume implementation. */
7063
7064 void
7065 remote_target::commit_resumed ()
7066 {
7067 /* If connected in all-stop mode, we'd send the remote resume
7068 request directly from remote_resume. Likewise if
7069 reverse-debugging, as there are no defined vCont actions for
7070 reverse execution. */
7071 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7072 return;
7073
7074 commit_requested_thread_options ();
7075
7076 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7077 instead of resuming all threads of each process individually.
7078 However, if any thread of a process must remain halted, we can't
7079 send wildcard resumes and must send one action per thread.
7080
7081 Care must be taken to not resume threads/processes the server
7082 side already told us are stopped, but the core doesn't know about
7083 yet, because the events are still in the vStopped notification
7084 queue. For example:
7085
7086 #1 => vCont s:p1.1;c
7087 #2 <= OK
7088 #3 <= %Stopped T05 p1.1
7089 #4 => vStopped
7090 #5 <= T05 p1.2
7091 #6 => vStopped
7092 #7 <= OK
7093 #8 (infrun handles the stop for p1.1 and continues stepping)
7094 #9 => vCont s:p1.1;c
7095
7096 The last vCont above would resume thread p1.2 by mistake, because
7097 the server has no idea that the event for p1.2 had not been
7098 handled yet.
7099
7100 The server side must similarly ignore resume actions for the
7101 thread that has a pending %Stopped notification (and any other
7102 threads with events pending), until GDB acks the notification
7103 with vStopped. Otherwise, e.g., the following case is
7104 mishandled:
7105
7106 #1 => g (or any other packet)
7107 #2 <= [registers]
7108 #3 <= %Stopped T05 p1.2
7109 #4 => vCont s:p1.1;c
7110 #5 <= OK
7111
7112 Above, the server must not resume thread p1.2. GDB can't know
7113 that p1.2 stopped until it acks the %Stopped notification, and
7114 since from GDB's perspective all threads should be running, it
7115 sends a "c" action.
7116
7117 Finally, special care must also be given to handling fork/vfork
7118 events. A (v)fork event actually tells us that two processes
7119 stopped -- the parent and the child. Until we follow the fork,
7120 we must not resume the child. Therefore, if we have a pending
7121 fork follow, we must not send a global wildcard resume action
7122 (vCont;c). We can still send process-wide wildcards though. */
7123
7124 /* Start by assuming a global wildcard (vCont;c) is possible. */
7125 bool may_global_wildcard_vcont = true;
7126
7127 /* And assume every process is individually wildcard-able too. */
7128 for (inferior *inf : all_non_exited_inferiors (this))
7129 {
7130 remote_inferior *priv = get_remote_inferior (inf);
7131
7132 priv->may_wildcard_vcont = true;
7133 }
7134
7135 /* Check for any pending events (not reported or processed yet) and
7136 disable process and global wildcard resumes appropriately. */
7137 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7138
7139 bool any_pending_vcont_resume = false;
7140
7141 for (thread_info *tp : all_non_exited_threads (this))
7142 {
7143 remote_thread_info *priv = get_remote_thread_info (tp);
7144
7145 /* If a thread of a process is not meant to be resumed, then we
7146 can't wildcard that process. */
7147 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7148 {
7149 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7150
7151 /* And if we can't wildcard a process, we can't wildcard
7152 everything either. */
7153 may_global_wildcard_vcont = false;
7154 continue;
7155 }
7156
7157 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7158 any_pending_vcont_resume = true;
7159
7160 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7161 then we can't do a global wildcard, as that would resume the
7162 pending child. */
7163 if (thread_pending_child_status (tp) != nullptr)
7164 may_global_wildcard_vcont = false;
7165 }
7166
7167 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7168 do. */
7169 if (!any_pending_vcont_resume)
7170 return;
7171
7172 /* Now let's build the vCont packet(s). Actions must be appended
7173 from narrower to wider scopes (thread -> process -> global). If
7174 we end up with too many actions for a single packet vcont_builder
7175 flushes the current vCont packet to the remote side and starts a
7176 new one. */
7177 struct vcont_builder vcont_builder (this);
7178
7179 /* Threads first. */
7180 for (thread_info *tp : all_non_exited_threads (this))
7181 {
7182 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7183
7184 /* If the thread was previously vCont-resumed, no need to send a specific
7185 action for it. If we didn't receive a resume request for it, don't
7186 send an action for it either. */
7187 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7188 continue;
7189
7190 gdb_assert (!thread_is_in_step_over_chain (tp));
7191
7192 /* We should never be commit-resuming a thread that has a stop reply.
7193 Otherwise, we would end up reporting a stop event for a thread while
7194 it is running on the remote target. */
7195 remote_state *rs = get_remote_state ();
7196 for (const auto &stop_reply : rs->stop_reply_queue)
7197 gdb_assert (stop_reply->ptid != tp->ptid);
7198
7199 const resumed_pending_vcont_info &info
7200 = remote_thr->resumed_pending_vcont_info ();
7201
7202 /* Check if we need to send a specific action for this thread. If not,
7203 it will be included in a wildcard resume instead. */
7204 if (info.step || info.sig != GDB_SIGNAL_0
7205 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7206 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7207
7208 remote_thr->set_resumed ();
7209 }
7210
7211 /* Now check whether we can send any process-wide wildcard. This is
7212 to avoid sending a global wildcard in the case nothing is
7213 supposed to be resumed. */
7214 bool any_process_wildcard = false;
7215
7216 for (inferior *inf : all_non_exited_inferiors (this))
7217 {
7218 if (get_remote_inferior (inf)->may_wildcard_vcont)
7219 {
7220 any_process_wildcard = true;
7221 break;
7222 }
7223 }
7224
7225 if (any_process_wildcard)
7226 {
7227 /* If all processes are wildcard-able, then send a single "c"
7228 action, otherwise, send an "all (-1) threads of process"
7229 continue action for each running process, if any. */
7230 if (may_global_wildcard_vcont)
7231 {
7232 vcont_builder.push_action (minus_one_ptid,
7233 false, GDB_SIGNAL_0);
7234 }
7235 else
7236 {
7237 for (inferior *inf : all_non_exited_inferiors (this))
7238 {
7239 if (get_remote_inferior (inf)->may_wildcard_vcont)
7240 {
7241 vcont_builder.push_action (ptid_t (inf->pid),
7242 false, GDB_SIGNAL_0);
7243 }
7244 }
7245 }
7246 }
7247
7248 vcont_builder.flush ();
7249 }
7250
7251 /* Implementation of target_has_pending_events. */
7252
7253 bool
7254 remote_target::has_pending_events ()
7255 {
7256 if (target_can_async_p ())
7257 {
7258 remote_state *rs = get_remote_state ();
7259
7260 if (rs->async_event_handler_marked ())
7261 return true;
7262
7263 /* Note that BUFCNT can be negative, indicating sticky
7264 error. */
7265 if (rs->remote_desc->bufcnt != 0)
7266 return true;
7267 }
7268 return false;
7269 }
7270
7271 \f
7272
7273 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7274 thread, all threads of a remote process, or all threads of all
7275 processes. */
7276
7277 void
7278 remote_target::remote_stop_ns (ptid_t ptid)
7279 {
7280 struct remote_state *rs = get_remote_state ();
7281 char *p = rs->buf.data ();
7282 char *endp = p + get_remote_packet_size ();
7283
7284 /* If any thread that needs to stop was resumed but pending a vCont
7285 resume, generate a phony stop_reply. However, first check
7286 whether the thread wasn't resumed with a signal. Generating a
7287 phony stop in that case would result in losing the signal. */
7288 bool needs_commit = false;
7289 for (thread_info *tp : all_non_exited_threads (this, ptid))
7290 {
7291 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7292
7293 if (remote_thr->get_resume_state ()
7294 == resume_state::RESUMED_PENDING_VCONT)
7295 {
7296 const resumed_pending_vcont_info &info
7297 = remote_thr->resumed_pending_vcont_info ();
7298 if (info.sig != GDB_SIGNAL_0)
7299 {
7300 /* This signal must be forwarded to the inferior. We
7301 could commit-resume just this thread, but its simpler
7302 to just commit-resume everything. */
7303 needs_commit = true;
7304 break;
7305 }
7306 }
7307 }
7308
7309 if (needs_commit)
7310 commit_resumed ();
7311 else
7312 for (thread_info *tp : all_non_exited_threads (this, ptid))
7313 {
7314 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7315
7316 if (remote_thr->get_resume_state ()
7317 == resume_state::RESUMED_PENDING_VCONT)
7318 {
7319 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7320 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7321 tp->ptid.lwp (),
7322 pulongest (tp->ptid.tid ()));
7323
7324 /* Check that the thread wasn't resumed with a signal.
7325 Generating a phony stop would result in losing the
7326 signal. */
7327 const resumed_pending_vcont_info &info
7328 = remote_thr->resumed_pending_vcont_info ();
7329 gdb_assert (info.sig == GDB_SIGNAL_0);
7330
7331 stop_reply *sr = new stop_reply ();
7332 sr->ptid = tp->ptid;
7333 sr->rs = rs;
7334 sr->ws.set_stopped (GDB_SIGNAL_0);
7335 sr->arch = tp->inf->arch ();
7336 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7337 sr->watch_data_address = 0;
7338 sr->core = 0;
7339 this->push_stop_reply (sr);
7340
7341 /* Pretend that this thread was actually resumed on the
7342 remote target, then stopped. If we leave it in the
7343 RESUMED_PENDING_VCONT state and the commit_resumed
7344 method is called while the stop reply is still in the
7345 queue, we'll end up reporting a stop event to the core
7346 for that thread while it is running on the remote
7347 target... that would be bad. */
7348 remote_thr->set_resumed ();
7349 }
7350 }
7351
7352 if (!rs->supports_vCont.t)
7353 error (_("Remote server does not support stopping threads"));
7354
7355 if (ptid == minus_one_ptid
7356 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7357 p += xsnprintf (p, endp - p, "vCont;t");
7358 else
7359 {
7360 ptid_t nptid;
7361
7362 p += xsnprintf (p, endp - p, "vCont;t:");
7363
7364 if (ptid.is_pid ())
7365 /* All (-1) threads of process. */
7366 nptid = ptid_t (ptid.pid (), -1);
7367 else
7368 {
7369 /* Small optimization: if we already have a stop reply for
7370 this thread, no use in telling the stub we want this
7371 stopped. */
7372 if (peek_stop_reply (ptid))
7373 return;
7374
7375 nptid = ptid;
7376 }
7377
7378 write_ptid (p, endp, nptid);
7379 }
7380
7381 /* In non-stop, we get an immediate OK reply. The stop reply will
7382 come in asynchronously by notification. */
7383 putpkt (rs->buf);
7384 getpkt (&rs->buf);
7385 if (strcmp (rs->buf.data (), "OK") != 0)
7386 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7387 rs->buf.data ());
7388 }
7389
7390 /* All-stop version of target_interrupt. Sends a break or a ^C to
7391 interrupt the remote target. It is undefined which thread of which
7392 process reports the interrupt. */
7393
7394 void
7395 remote_target::remote_interrupt_as ()
7396 {
7397 struct remote_state *rs = get_remote_state ();
7398
7399 rs->ctrlc_pending_p = 1;
7400
7401 /* If the inferior is stopped already, but the core didn't know
7402 about it yet, just ignore the request. The pending stop events
7403 will be collected in remote_wait. */
7404 if (stop_reply_queue_length () > 0)
7405 return;
7406
7407 /* Send interrupt_sequence to remote target. */
7408 send_interrupt_sequence ();
7409 }
7410
7411 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7412 the remote target. It is undefined which thread of which process
7413 reports the interrupt. Throws an error if the packet is not
7414 supported by the server. */
7415
7416 void
7417 remote_target::remote_interrupt_ns ()
7418 {
7419 struct remote_state *rs = get_remote_state ();
7420 char *p = rs->buf.data ();
7421 char *endp = p + get_remote_packet_size ();
7422
7423 xsnprintf (p, endp - p, "vCtrlC");
7424
7425 /* In non-stop, we get an immediate OK reply. The stop reply will
7426 come in asynchronously by notification. */
7427 putpkt (rs->buf);
7428 getpkt (&rs->buf);
7429
7430 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7431 {
7432 case PACKET_OK:
7433 break;
7434 case PACKET_UNKNOWN:
7435 error (_("No support for interrupting the remote target."));
7436 case PACKET_ERROR:
7437 error (_("Interrupting target failed: %s"), rs->buf.data ());
7438 }
7439 }
7440
7441 /* Implement the to_stop function for the remote targets. */
7442
7443 void
7444 remote_target::stop (ptid_t ptid)
7445 {
7446 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7447
7448 if (target_is_non_stop_p ())
7449 remote_stop_ns (ptid);
7450 else
7451 {
7452 /* We don't currently have a way to transparently pause the
7453 remote target in all-stop mode. Interrupt it instead. */
7454 remote_interrupt_as ();
7455 }
7456 }
7457
7458 /* Implement the to_interrupt function for the remote targets. */
7459
7460 void
7461 remote_target::interrupt ()
7462 {
7463 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7464
7465 if (target_is_non_stop_p ())
7466 remote_interrupt_ns ();
7467 else
7468 remote_interrupt_as ();
7469 }
7470
7471 /* Implement the to_pass_ctrlc function for the remote targets. */
7472
7473 void
7474 remote_target::pass_ctrlc ()
7475 {
7476 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7477
7478 struct remote_state *rs = get_remote_state ();
7479
7480 /* If we're starting up, we're not fully synced yet. Quit
7481 immediately. */
7482 if (rs->starting_up)
7483 quit ();
7484 /* If ^C has already been sent once, offer to disconnect. */
7485 else if (rs->ctrlc_pending_p)
7486 interrupt_query ();
7487 else
7488 target_interrupt ();
7489 }
7490
7491 /* Ask the user what to do when an interrupt is received. */
7492
7493 void
7494 remote_target::interrupt_query ()
7495 {
7496 struct remote_state *rs = get_remote_state ();
7497
7498 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7499 {
7500 if (query (_("The target is not responding to interrupt requests.\n"
7501 "Stop debugging it? ")))
7502 {
7503 remote_unpush_target (this);
7504 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7505 }
7506 }
7507 else
7508 {
7509 if (query (_("Interrupted while waiting for the program.\n"
7510 "Give up waiting? ")))
7511 quit ();
7512 }
7513 }
7514
7515 /* Enable/disable target terminal ownership. Most targets can use
7516 terminal groups to control terminal ownership. Remote targets are
7517 different in that explicit transfer of ownership to/from GDB/target
7518 is required. */
7519
7520 void
7521 remote_target::terminal_inferior ()
7522 {
7523 /* NOTE: At this point we could also register our selves as the
7524 recipient of all input. Any characters typed could then be
7525 passed on down to the target. */
7526 }
7527
7528 void
7529 remote_target::terminal_ours ()
7530 {
7531 }
7532
7533 static void
7534 remote_console_output (const char *msg)
7535 {
7536 const char *p;
7537
7538 for (p = msg; p[0] && p[1]; p += 2)
7539 {
7540 char tb[2];
7541 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7542
7543 tb[0] = c;
7544 tb[1] = 0;
7545 gdb_stdtarg->puts (tb);
7546 }
7547 gdb_stdtarg->flush ();
7548 }
7549
7550 /* Return the length of the stop reply queue. */
7551
7552 int
7553 remote_target::stop_reply_queue_length ()
7554 {
7555 remote_state *rs = get_remote_state ();
7556 return rs->stop_reply_queue.size ();
7557 }
7558
7559 static void
7560 remote_notif_stop_parse (remote_target *remote,
7561 const notif_client *self, const char *buf,
7562 struct notif_event *event)
7563 {
7564 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7565 }
7566
7567 static void
7568 remote_notif_stop_ack (remote_target *remote,
7569 const notif_client *self, const char *buf,
7570 struct notif_event *event)
7571 {
7572 struct stop_reply *stop_reply = (struct stop_reply *) event;
7573
7574 /* acknowledge */
7575 putpkt (remote, self->ack_command);
7576
7577 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7578 the notification. It was left in the queue because we need to
7579 acknowledge it and pull the rest of the notifications out. */
7580 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7581 remote->push_stop_reply (stop_reply);
7582 }
7583
7584 static int
7585 remote_notif_stop_can_get_pending_events (remote_target *remote,
7586 const notif_client *self)
7587 {
7588 /* We can't get pending events in remote_notif_process for
7589 notification stop, and we have to do this in remote_wait_ns
7590 instead. If we fetch all queued events from stub, remote stub
7591 may exit and we have no chance to process them back in
7592 remote_wait_ns. */
7593 remote_state *rs = remote->get_remote_state ();
7594 rs->mark_async_event_handler ();
7595 return 0;
7596 }
7597
7598 stop_reply::~stop_reply ()
7599 {
7600 for (cached_reg_t &reg : regcache)
7601 xfree (reg.data);
7602 }
7603
7604 static notif_event_up
7605 remote_notif_stop_alloc_reply ()
7606 {
7607 return notif_event_up (new struct stop_reply ());
7608 }
7609
7610 /* A client of notification Stop. */
7611
7612 const notif_client notif_client_stop =
7613 {
7614 "Stop",
7615 "vStopped",
7616 remote_notif_stop_parse,
7617 remote_notif_stop_ack,
7618 remote_notif_stop_can_get_pending_events,
7619 remote_notif_stop_alloc_reply,
7620 REMOTE_NOTIF_STOP,
7621 };
7622
7623 /* If CONTEXT contains any fork/vfork/clone child threads that have
7624 not been reported yet, remove them from the CONTEXT list. If such
7625 a thread exists it is because we are stopped at a fork/vfork/clone
7626 catchpoint and have not yet called follow_fork/follow_clone, which
7627 will set up the host-side data structures for the new child. */
7628
7629 void
7630 remote_target::remove_new_children (threads_listing_context *context)
7631 {
7632 const notif_client *notif = &notif_client_stop;
7633
7634 /* For any threads stopped at a (v)fork/clone event, remove the
7635 corresponding child threads from the CONTEXT list. */
7636 for (thread_info *thread : all_non_exited_threads (this))
7637 {
7638 const target_waitstatus *ws = thread_pending_child_status (thread);
7639
7640 if (ws == nullptr)
7641 continue;
7642
7643 context->remove_thread (ws->child_ptid ());
7644 }
7645
7646 /* Check for any pending (v)fork/clone events (not reported or
7647 processed yet) in process PID and remove those child threads from
7648 the CONTEXT list as well. */
7649 remote_notif_get_pending_events (notif);
7650 for (auto &event : get_remote_state ()->stop_reply_queue)
7651 if (is_new_child_status (event->ws.kind ()))
7652 context->remove_thread (event->ws.child_ptid ());
7653 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7654 context->remove_thread (event->ptid);
7655 }
7656
7657 /* Check whether any event pending in the vStopped queue would prevent a
7658 global or process wildcard vCont action. Set *may_global_wildcard to
7659 false if we can't do a global wildcard (vCont;c), and clear the event
7660 inferior's may_wildcard_vcont flag if we can't do a process-wide
7661 wildcard resume (vCont;c:pPID.-1). */
7662
7663 void
7664 remote_target::check_pending_events_prevent_wildcard_vcont
7665 (bool *may_global_wildcard)
7666 {
7667 const notif_client *notif = &notif_client_stop;
7668
7669 remote_notif_get_pending_events (notif);
7670 for (auto &event : get_remote_state ()->stop_reply_queue)
7671 {
7672 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7673 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7674 continue;
7675
7676 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7677 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7678 *may_global_wildcard = false;
7679
7680 /* This may be the first time we heard about this process.
7681 Regardless, we must not do a global wildcard resume, otherwise
7682 we'd resume this process too. */
7683 *may_global_wildcard = false;
7684 if (event->ptid != null_ptid)
7685 {
7686 inferior *inf = find_inferior_ptid (this, event->ptid);
7687 if (inf != NULL)
7688 get_remote_inferior (inf)->may_wildcard_vcont = false;
7689 }
7690 }
7691 }
7692
7693 /* Discard all pending stop replies of inferior INF. */
7694
7695 void
7696 remote_target::discard_pending_stop_replies (struct inferior *inf)
7697 {
7698 struct stop_reply *reply;
7699 struct remote_state *rs = get_remote_state ();
7700 struct remote_notif_state *rns = rs->notif_state;
7701
7702 /* This function can be notified when an inferior exists. When the
7703 target is not remote, the notification state is NULL. */
7704 if (rs->remote_desc == NULL)
7705 return;
7706
7707 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7708
7709 /* Discard the in-flight notification. */
7710 if (reply != NULL && reply->ptid.pid () == inf->pid)
7711 {
7712 /* Leave the notification pending, since the server expects that
7713 we acknowledge it with vStopped. But clear its contents, so
7714 that later on when we acknowledge it, we also discard it. */
7715 remote_debug_printf
7716 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7717 reply->ptid.to_string().c_str(),
7718 reply->ws.to_string ().c_str ());
7719 reply->ws.set_ignore ();
7720 }
7721
7722 /* Discard the stop replies we have already pulled with
7723 vStopped. */
7724 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7725 rs->stop_reply_queue.end (),
7726 [=] (const stop_reply_up &event)
7727 {
7728 return event->ptid.pid () == inf->pid;
7729 });
7730 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7731 remote_debug_printf
7732 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7733 (*it)->ptid.to_string().c_str(),
7734 (*it)->ws.to_string ().c_str ());
7735 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7736 }
7737
7738 /* Discard the stop replies for RS in stop_reply_queue. */
7739
7740 void
7741 remote_target::discard_pending_stop_replies_in_queue ()
7742 {
7743 remote_state *rs = get_remote_state ();
7744
7745 /* Discard the stop replies we have already pulled with
7746 vStopped. */
7747 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7748 rs->stop_reply_queue.end (),
7749 [=] (const stop_reply_up &event)
7750 {
7751 return event->rs == rs;
7752 });
7753 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7754 }
7755
7756 /* Remove the first reply in 'stop_reply_queue' which matches
7757 PTID. */
7758
7759 struct stop_reply *
7760 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7761 {
7762 remote_state *rs = get_remote_state ();
7763
7764 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7765 rs->stop_reply_queue.end (),
7766 [=] (const stop_reply_up &event)
7767 {
7768 return event->ptid.matches (ptid);
7769 });
7770 struct stop_reply *result;
7771 if (iter == rs->stop_reply_queue.end ())
7772 result = nullptr;
7773 else
7774 {
7775 result = iter->release ();
7776 rs->stop_reply_queue.erase (iter);
7777 }
7778
7779 if (notif_debug)
7780 gdb_printf (gdb_stdlog,
7781 "notif: discard queued event: 'Stop' in %s\n",
7782 ptid.to_string ().c_str ());
7783
7784 return result;
7785 }
7786
7787 /* Look for a queued stop reply belonging to PTID. If one is found,
7788 remove it from the queue, and return it. Returns NULL if none is
7789 found. If there are still queued events left to process, tell the
7790 event loop to get back to target_wait soon. */
7791
7792 struct stop_reply *
7793 remote_target::queued_stop_reply (ptid_t ptid)
7794 {
7795 remote_state *rs = get_remote_state ();
7796 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7797
7798 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7799 {
7800 /* There's still at least an event left. */
7801 rs->mark_async_event_handler ();
7802 }
7803
7804 return r;
7805 }
7806
7807 /* Push a fully parsed stop reply in the stop reply queue. Since we
7808 know that we now have at least one queued event left to pass to the
7809 core side, tell the event loop to get back to target_wait soon. */
7810
7811 void
7812 remote_target::push_stop_reply (struct stop_reply *new_event)
7813 {
7814 remote_state *rs = get_remote_state ();
7815 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7816
7817 if (notif_debug)
7818 gdb_printf (gdb_stdlog,
7819 "notif: push 'Stop' %s to queue %d\n",
7820 new_event->ptid.to_string ().c_str (),
7821 int (rs->stop_reply_queue.size ()));
7822
7823 /* Mark the pending event queue only if async mode is currently enabled.
7824 If async mode is not currently enabled, then, if it later becomes
7825 enabled, and there are events in this queue, we will mark the event
7826 token at that point, see remote_target::async. */
7827 if (target_is_async_p ())
7828 rs->mark_async_event_handler ();
7829 }
7830
7831 /* Returns true if we have a stop reply for PTID. */
7832
7833 int
7834 remote_target::peek_stop_reply (ptid_t ptid)
7835 {
7836 remote_state *rs = get_remote_state ();
7837 for (auto &event : rs->stop_reply_queue)
7838 if (ptid == event->ptid
7839 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7840 return 1;
7841 return 0;
7842 }
7843
7844 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7845 starting with P and ending with PEND matches PREFIX. */
7846
7847 static int
7848 strprefix (const char *p, const char *pend, const char *prefix)
7849 {
7850 for ( ; p < pend; p++, prefix++)
7851 if (*p != *prefix)
7852 return 0;
7853 return *prefix == '\0';
7854 }
7855
7856 /* Parse the stop reply in BUF. Either the function succeeds, and the
7857 result is stored in EVENT, or throws an error. */
7858
7859 void
7860 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7861 {
7862 remote_arch_state *rsa = NULL;
7863 ULONGEST addr;
7864 const char *p;
7865 int skipregs = 0;
7866
7867 event->ptid = null_ptid;
7868 event->rs = get_remote_state ();
7869 event->ws.set_ignore ();
7870 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7871 event->regcache.clear ();
7872 event->core = -1;
7873
7874 switch (buf[0])
7875 {
7876 case 'T': /* Status with PC, SP, FP, ... */
7877 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7878 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7879 ss = signal number
7880 n... = register number
7881 r... = register contents
7882 */
7883
7884 p = &buf[3]; /* after Txx */
7885 while (*p)
7886 {
7887 const char *p1;
7888 int fieldsize;
7889
7890 p1 = strchr (p, ':');
7891 if (p1 == NULL)
7892 error (_("Malformed packet(a) (missing colon): %s\n\
7893 Packet: '%s'\n"),
7894 p, buf);
7895 if (p == p1)
7896 error (_("Malformed packet(a) (missing register number): %s\n\
7897 Packet: '%s'\n"),
7898 p, buf);
7899
7900 /* Some "registers" are actually extended stop information.
7901 Note if you're adding a new entry here: GDB 7.9 and
7902 earlier assume that all register "numbers" that start
7903 with an hex digit are real register numbers. Make sure
7904 the server only sends such a packet if it knows the
7905 client understands it. */
7906
7907 if (strprefix (p, p1, "thread"))
7908 event->ptid = read_ptid (++p1, &p);
7909 else if (strprefix (p, p1, "syscall_entry"))
7910 {
7911 ULONGEST sysno;
7912
7913 p = unpack_varlen_hex (++p1, &sysno);
7914 event->ws.set_syscall_entry ((int) sysno);
7915 }
7916 else if (strprefix (p, p1, "syscall_return"))
7917 {
7918 ULONGEST sysno;
7919
7920 p = unpack_varlen_hex (++p1, &sysno);
7921 event->ws.set_syscall_return ((int) sysno);
7922 }
7923 else if (strprefix (p, p1, "watch")
7924 || strprefix (p, p1, "rwatch")
7925 || strprefix (p, p1, "awatch"))
7926 {
7927 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7928 p = unpack_varlen_hex (++p1, &addr);
7929 event->watch_data_address = (CORE_ADDR) addr;
7930 }
7931 else if (strprefix (p, p1, "swbreak"))
7932 {
7933 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7934
7935 /* Make sure the stub doesn't forget to indicate support
7936 with qSupported. */
7937 if (m_features.packet_support (PACKET_swbreak_feature)
7938 != PACKET_ENABLE)
7939 error (_("Unexpected swbreak stop reason"));
7940
7941 /* The value part is documented as "must be empty",
7942 though we ignore it, in case we ever decide to make
7943 use of it in a backward compatible way. */
7944 p = strchrnul (p1 + 1, ';');
7945 }
7946 else if (strprefix (p, p1, "hwbreak"))
7947 {
7948 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7949
7950 /* Make sure the stub doesn't forget to indicate support
7951 with qSupported. */
7952 if (m_features.packet_support (PACKET_hwbreak_feature)
7953 != PACKET_ENABLE)
7954 error (_("Unexpected hwbreak stop reason"));
7955
7956 /* See above. */
7957 p = strchrnul (p1 + 1, ';');
7958 }
7959 else if (strprefix (p, p1, "library"))
7960 {
7961 event->ws.set_loaded ();
7962 p = strchrnul (p1 + 1, ';');
7963 }
7964 else if (strprefix (p, p1, "replaylog"))
7965 {
7966 event->ws.set_no_history ();
7967 /* p1 will indicate "begin" or "end", but it makes
7968 no difference for now, so ignore it. */
7969 p = strchrnul (p1 + 1, ';');
7970 }
7971 else if (strprefix (p, p1, "core"))
7972 {
7973 ULONGEST c;
7974
7975 p = unpack_varlen_hex (++p1, &c);
7976 event->core = c;
7977 }
7978 else if (strprefix (p, p1, "fork"))
7979 event->ws.set_forked (read_ptid (++p1, &p));
7980 else if (strprefix (p, p1, "vfork"))
7981 event->ws.set_vforked (read_ptid (++p1, &p));
7982 else if (strprefix (p, p1, "clone"))
7983 event->ws.set_thread_cloned (read_ptid (++p1, &p));
7984 else if (strprefix (p, p1, "vforkdone"))
7985 {
7986 event->ws.set_vfork_done ();
7987 p = strchrnul (p1 + 1, ';');
7988 }
7989 else if (strprefix (p, p1, "exec"))
7990 {
7991 ULONGEST ignored;
7992 int pathlen;
7993
7994 /* Determine the length of the execd pathname. */
7995 p = unpack_varlen_hex (++p1, &ignored);
7996 pathlen = (p - p1) / 2;
7997
7998 /* Save the pathname for event reporting and for
7999 the next run command. */
8000 gdb::unique_xmalloc_ptr<char> pathname
8001 ((char *) xmalloc (pathlen + 1));
8002 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8003 pathname.get ()[pathlen] = '\0';
8004
8005 /* This is freed during event handling. */
8006 event->ws.set_execd (std::move (pathname));
8007
8008 /* Skip the registers included in this packet, since
8009 they may be for an architecture different from the
8010 one used by the original program. */
8011 skipregs = 1;
8012 }
8013 else if (strprefix (p, p1, "create"))
8014 {
8015 event->ws.set_thread_created ();
8016 p = strchrnul (p1 + 1, ';');
8017 }
8018 else
8019 {
8020 ULONGEST pnum;
8021 const char *p_temp;
8022
8023 if (skipregs)
8024 {
8025 p = strchrnul (p1 + 1, ';');
8026 p++;
8027 continue;
8028 }
8029
8030 /* Maybe a real ``P'' register number. */
8031 p_temp = unpack_varlen_hex (p, &pnum);
8032 /* If the first invalid character is the colon, we got a
8033 register number. Otherwise, it's an unknown stop
8034 reason. */
8035 if (p_temp == p1)
8036 {
8037 /* If we haven't parsed the event's thread yet, find
8038 it now, in order to find the architecture of the
8039 reported expedited registers. */
8040 if (event->ptid == null_ptid)
8041 {
8042 /* If there is no thread-id information then leave
8043 the event->ptid as null_ptid. Later in
8044 process_stop_reply we will pick a suitable
8045 thread. */
8046 const char *thr = strstr (p1 + 1, ";thread:");
8047 if (thr != NULL)
8048 event->ptid = read_ptid (thr + strlen (";thread:"),
8049 NULL);
8050 }
8051
8052 if (rsa == NULL)
8053 {
8054 inferior *inf
8055 = (event->ptid == null_ptid
8056 ? NULL
8057 : find_inferior_ptid (this, event->ptid));
8058 /* If this is the first time we learn anything
8059 about this process, skip the registers
8060 included in this packet, since we don't yet
8061 know which architecture to use to parse them.
8062 We'll determine the architecture later when
8063 we process the stop reply and retrieve the
8064 target description, via
8065 remote_notice_new_inferior ->
8066 post_create_inferior. */
8067 if (inf == NULL)
8068 {
8069 p = strchrnul (p1 + 1, ';');
8070 p++;
8071 continue;
8072 }
8073
8074 event->arch = inf->arch ();
8075 rsa = event->rs->get_remote_arch_state (event->arch);
8076 }
8077
8078 packet_reg *reg
8079 = packet_reg_from_pnum (event->arch, rsa, pnum);
8080 cached_reg_t cached_reg;
8081
8082 if (reg == NULL)
8083 error (_("Remote sent bad register number %s: %s\n\
8084 Packet: '%s'\n"),
8085 hex_string (pnum), p, buf);
8086
8087 cached_reg.num = reg->regnum;
8088 cached_reg.data = (gdb_byte *)
8089 xmalloc (register_size (event->arch, reg->regnum));
8090
8091 p = p1 + 1;
8092 fieldsize = hex2bin (p, cached_reg.data,
8093 register_size (event->arch, reg->regnum));
8094 p += 2 * fieldsize;
8095 if (fieldsize < register_size (event->arch, reg->regnum))
8096 warning (_("Remote reply is too short: %s"), buf);
8097
8098 event->regcache.push_back (cached_reg);
8099 }
8100 else
8101 {
8102 /* Not a number. Silently skip unknown optional
8103 info. */
8104 p = strchrnul (p1 + 1, ';');
8105 }
8106 }
8107
8108 if (*p != ';')
8109 error (_("Remote register badly formatted: %s\nhere: %s"),
8110 buf, p);
8111 ++p;
8112 }
8113
8114 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8115 break;
8116
8117 /* fall through */
8118 case 'S': /* Old style status, just signal only. */
8119 {
8120 int sig;
8121
8122 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8123 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8124 event->ws.set_stopped ((enum gdb_signal) sig);
8125 else
8126 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8127 }
8128 break;
8129 case 'w': /* Thread exited. */
8130 {
8131 ULONGEST value;
8132
8133 p = unpack_varlen_hex (&buf[1], &value);
8134 event->ws.set_thread_exited (value);
8135 if (*p != ';')
8136 error (_("stop reply packet badly formatted: %s"), buf);
8137 event->ptid = read_ptid (++p, NULL);
8138 break;
8139 }
8140 case 'W': /* Target exited. */
8141 case 'X':
8142 {
8143 ULONGEST value;
8144
8145 /* GDB used to accept only 2 hex chars here. Stubs should
8146 only send more if they detect GDB supports multi-process
8147 support. */
8148 p = unpack_varlen_hex (&buf[1], &value);
8149
8150 if (buf[0] == 'W')
8151 {
8152 /* The remote process exited. */
8153 event->ws.set_exited (value);
8154 }
8155 else
8156 {
8157 /* The remote process exited with a signal. */
8158 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8159 event->ws.set_signalled ((enum gdb_signal) value);
8160 else
8161 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8162 }
8163
8164 /* If no process is specified, return null_ptid, and let the
8165 caller figure out the right process to use. */
8166 int pid = 0;
8167 if (*p == '\0')
8168 ;
8169 else if (*p == ';')
8170 {
8171 p++;
8172
8173 if (*p == '\0')
8174 ;
8175 else if (startswith (p, "process:"))
8176 {
8177 ULONGEST upid;
8178
8179 p += sizeof ("process:") - 1;
8180 unpack_varlen_hex (p, &upid);
8181 pid = upid;
8182 }
8183 else
8184 error (_("unknown stop reply packet: %s"), buf);
8185 }
8186 else
8187 error (_("unknown stop reply packet: %s"), buf);
8188 event->ptid = ptid_t (pid);
8189 }
8190 break;
8191 case 'N':
8192 event->ws.set_no_resumed ();
8193 event->ptid = minus_one_ptid;
8194 break;
8195 }
8196 }
8197
8198 /* When the stub wants to tell GDB about a new notification reply, it
8199 sends a notification (%Stop, for example). Those can come it at
8200 any time, hence, we have to make sure that any pending
8201 putpkt/getpkt sequence we're making is finished, before querying
8202 the stub for more events with the corresponding ack command
8203 (vStopped, for example). E.g., if we started a vStopped sequence
8204 immediately upon receiving the notification, something like this
8205 could happen:
8206
8207 1.1) --> Hg 1
8208 1.2) <-- OK
8209 1.3) --> g
8210 1.4) <-- %Stop
8211 1.5) --> vStopped
8212 1.6) <-- (registers reply to step #1.3)
8213
8214 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8215 query.
8216
8217 To solve this, whenever we parse a %Stop notification successfully,
8218 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8219 doing whatever we were doing:
8220
8221 2.1) --> Hg 1
8222 2.2) <-- OK
8223 2.3) --> g
8224 2.4) <-- %Stop
8225 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8226 2.5) <-- (registers reply to step #2.3)
8227
8228 Eventually after step #2.5, we return to the event loop, which
8229 notices there's an event on the
8230 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8231 associated callback --- the function below. At this point, we're
8232 always safe to start a vStopped sequence. :
8233
8234 2.6) --> vStopped
8235 2.7) <-- T05 thread:2
8236 2.8) --> vStopped
8237 2.9) --> OK
8238 */
8239
8240 void
8241 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8242 {
8243 struct remote_state *rs = get_remote_state ();
8244
8245 if (rs->notif_state->pending_event[nc->id] != NULL)
8246 {
8247 if (notif_debug)
8248 gdb_printf (gdb_stdlog,
8249 "notif: process: '%s' ack pending event\n",
8250 nc->name);
8251
8252 /* acknowledge */
8253 nc->ack (this, nc, rs->buf.data (),
8254 rs->notif_state->pending_event[nc->id]);
8255 rs->notif_state->pending_event[nc->id] = NULL;
8256
8257 while (1)
8258 {
8259 getpkt (&rs->buf);
8260 if (strcmp (rs->buf.data (), "OK") == 0)
8261 break;
8262 else
8263 remote_notif_ack (this, nc, rs->buf.data ());
8264 }
8265 }
8266 else
8267 {
8268 if (notif_debug)
8269 gdb_printf (gdb_stdlog,
8270 "notif: process: '%s' no pending reply\n",
8271 nc->name);
8272 }
8273 }
8274
8275 /* Wrapper around remote_target::remote_notif_get_pending_events to
8276 avoid having to export the whole remote_target class. */
8277
8278 void
8279 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8280 {
8281 remote->remote_notif_get_pending_events (nc);
8282 }
8283
8284 /* Called from process_stop_reply when the stop packet we are responding
8285 to didn't include a process-id or thread-id. STATUS is the stop event
8286 we are responding to.
8287
8288 It is the task of this function to select a suitable thread (or process)
8289 and return its ptid, this is the thread (or process) we will assume the
8290 stop event came from.
8291
8292 In some cases there isn't really any choice about which thread (or
8293 process) is selected, a basic remote with a single process containing a
8294 single thread might choose not to send any process-id or thread-id in
8295 its stop packets, this function will select and return the one and only
8296 thread.
8297
8298 However, if a target supports multiple threads (or processes) and still
8299 doesn't include a thread-id (or process-id) in its stop packet then
8300 first, this is a badly behaving target, and second, we're going to have
8301 to select a thread (or process) at random and use that. This function
8302 will print a warning to the user if it detects that there is the
8303 possibility that GDB is guessing which thread (or process) to
8304 report.
8305
8306 Note that this is called before GDB fetches the updated thread list from the
8307 target. So it's possible for the stop reply to be ambiguous and for GDB to
8308 not realize it. For example, if there's initially one thread, the target
8309 spawns a second thread, and then sends a stop reply without an id that
8310 concerns the first thread. GDB will assume the stop reply is about the
8311 first thread - the only thread it knows about - without printing a warning.
8312 Anyway, if the remote meant for the stop reply to be about the second thread,
8313 then it would be really broken, because GDB doesn't know about that thread
8314 yet. */
8315
8316 ptid_t
8317 remote_target::select_thread_for_ambiguous_stop_reply
8318 (const target_waitstatus &status)
8319 {
8320 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8321
8322 /* Some stop events apply to all threads in an inferior, while others
8323 only apply to a single thread. */
8324 bool process_wide_stop
8325 = (status.kind () == TARGET_WAITKIND_EXITED
8326 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8327
8328 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8329
8330 thread_info *first_resumed_thread = nullptr;
8331 bool ambiguous = false;
8332
8333 /* Consider all non-exited threads of the target, find the first resumed
8334 one. */
8335 for (thread_info *thr : all_non_exited_threads (this))
8336 {
8337 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8338
8339 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8340 continue;
8341
8342 if (first_resumed_thread == nullptr)
8343 first_resumed_thread = thr;
8344 else if (!process_wide_stop
8345 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8346 ambiguous = true;
8347 }
8348
8349 gdb_assert (first_resumed_thread != nullptr);
8350
8351 remote_debug_printf ("first resumed thread is %s",
8352 pid_to_str (first_resumed_thread->ptid).c_str ());
8353 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8354
8355 /* Warn if the remote target is sending ambiguous stop replies. */
8356 if (ambiguous)
8357 {
8358 static bool warned = false;
8359
8360 if (!warned)
8361 {
8362 /* If you are seeing this warning then the remote target has
8363 stopped without specifying a thread-id, but the target
8364 does have multiple threads (or inferiors), and so GDB is
8365 having to guess which thread stopped.
8366
8367 Examples of what might cause this are the target sending
8368 and 'S' stop packet, or a 'T' stop packet and not
8369 including a thread-id.
8370
8371 Additionally, the target might send a 'W' or 'X packet
8372 without including a process-id, when the target has
8373 multiple running inferiors. */
8374 if (process_wide_stop)
8375 warning (_("multi-inferior target stopped without "
8376 "sending a process-id, using first "
8377 "non-exited inferior"));
8378 else
8379 warning (_("multi-threaded target stopped without "
8380 "sending a thread-id, using first "
8381 "non-exited thread"));
8382 warned = true;
8383 }
8384 }
8385
8386 /* If this is a stop for all threads then don't use a particular threads
8387 ptid, instead create a new ptid where only the pid field is set. */
8388 if (process_wide_stop)
8389 return ptid_t (first_resumed_thread->ptid.pid ());
8390 else
8391 return first_resumed_thread->ptid;
8392 }
8393
8394 /* Called when it is decided that STOP_REPLY holds the info of the
8395 event that is to be returned to the core. This function always
8396 destroys STOP_REPLY. */
8397
8398 ptid_t
8399 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8400 struct target_waitstatus *status)
8401 {
8402 *status = stop_reply->ws;
8403 ptid_t ptid = stop_reply->ptid;
8404
8405 /* If no thread/process was reported by the stub then select a suitable
8406 thread/process. */
8407 if (ptid == null_ptid)
8408 ptid = select_thread_for_ambiguous_stop_reply (*status);
8409 gdb_assert (ptid != null_ptid);
8410
8411 if (status->kind () != TARGET_WAITKIND_EXITED
8412 && status->kind () != TARGET_WAITKIND_SIGNALLED
8413 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8414 {
8415 /* Expedited registers. */
8416 if (!stop_reply->regcache.empty ())
8417 {
8418 struct regcache *regcache
8419 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8420
8421 for (cached_reg_t &reg : stop_reply->regcache)
8422 {
8423 regcache->raw_supply (reg.num, reg.data);
8424 xfree (reg.data);
8425 }
8426
8427 stop_reply->regcache.clear ();
8428 }
8429
8430 remote_notice_new_inferior (ptid, false);
8431 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8432 remote_thr->core = stop_reply->core;
8433 remote_thr->stop_reason = stop_reply->stop_reason;
8434 remote_thr->watch_data_address = stop_reply->watch_data_address;
8435
8436 if (target_is_non_stop_p ())
8437 {
8438 /* If the target works in non-stop mode, a stop-reply indicates that
8439 only this thread stopped. */
8440 remote_thr->set_not_resumed ();
8441 }
8442 else
8443 {
8444 /* If the target works in all-stop mode, a stop-reply indicates that
8445 all the target's threads stopped. */
8446 for (thread_info *tp : all_non_exited_threads (this))
8447 get_remote_thread_info (tp)->set_not_resumed ();
8448 }
8449 }
8450
8451 delete stop_reply;
8452 return ptid;
8453 }
8454
8455 /* The non-stop mode version of target_wait. */
8456
8457 ptid_t
8458 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8459 target_wait_flags options)
8460 {
8461 struct remote_state *rs = get_remote_state ();
8462 struct stop_reply *stop_reply;
8463 int ret;
8464 bool is_notif = false;
8465
8466 /* If in non-stop mode, get out of getpkt even if a
8467 notification is received. */
8468
8469 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8470 while (1)
8471 {
8472 if (ret != -1 && !is_notif)
8473 switch (rs->buf[0])
8474 {
8475 case 'E': /* Error of some sort. */
8476 /* We're out of sync with the target now. Did it continue
8477 or not? We can't tell which thread it was in non-stop,
8478 so just ignore this. */
8479 warning (_("Remote failure reply: %s"), rs->buf.data ());
8480 break;
8481 case 'O': /* Console output. */
8482 remote_console_output (&rs->buf[1]);
8483 break;
8484 default:
8485 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8486 break;
8487 }
8488
8489 /* Acknowledge a pending stop reply that may have arrived in the
8490 mean time. */
8491 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8492 remote_notif_get_pending_events (&notif_client_stop);
8493
8494 /* If indeed we noticed a stop reply, we're done. */
8495 stop_reply = queued_stop_reply (ptid);
8496 if (stop_reply != NULL)
8497 return process_stop_reply (stop_reply, status);
8498
8499 /* Still no event. If we're just polling for an event, then
8500 return to the event loop. */
8501 if (options & TARGET_WNOHANG)
8502 {
8503 status->set_ignore ();
8504 return minus_one_ptid;
8505 }
8506
8507 /* Otherwise do a blocking wait. */
8508 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8509 }
8510 }
8511
8512 /* Return the first resumed thread. */
8513
8514 static ptid_t
8515 first_remote_resumed_thread (remote_target *target)
8516 {
8517 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8518 if (tp->resumed ())
8519 return tp->ptid;
8520 return null_ptid;
8521 }
8522
8523 /* Wait until the remote machine stops, then return, storing status in
8524 STATUS just as `wait' would. */
8525
8526 ptid_t
8527 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8528 target_wait_flags options)
8529 {
8530 struct remote_state *rs = get_remote_state ();
8531 ptid_t event_ptid = null_ptid;
8532 char *buf;
8533 struct stop_reply *stop_reply;
8534
8535 again:
8536
8537 status->set_ignore ();
8538
8539 stop_reply = queued_stop_reply (ptid);
8540 if (stop_reply != NULL)
8541 {
8542 /* None of the paths that push a stop reply onto the queue should
8543 have set the waiting_for_stop_reply flag. */
8544 gdb_assert (!rs->waiting_for_stop_reply);
8545 event_ptid = process_stop_reply (stop_reply, status);
8546 }
8547 else
8548 {
8549 bool forever = ((options & TARGET_WNOHANG) == 0
8550 && rs->wait_forever_enabled_p);
8551
8552 if (!rs->waiting_for_stop_reply)
8553 {
8554 status->set_no_resumed ();
8555 return minus_one_ptid;
8556 }
8557
8558 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8559 _never_ wait for ever -> test on target_is_async_p().
8560 However, before we do that we need to ensure that the caller
8561 knows how to take the target into/out of async mode. */
8562 bool is_notif;
8563 int ret = getpkt (&rs->buf, forever, &is_notif);
8564
8565 /* GDB gets a notification. Return to core as this event is
8566 not interesting. */
8567 if (ret != -1 && is_notif)
8568 return minus_one_ptid;
8569
8570 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8571 return minus_one_ptid;
8572
8573 buf = rs->buf.data ();
8574
8575 /* Assume that the target has acknowledged Ctrl-C unless we receive
8576 an 'F' or 'O' packet. */
8577 if (buf[0] != 'F' && buf[0] != 'O')
8578 rs->ctrlc_pending_p = 0;
8579
8580 switch (buf[0])
8581 {
8582 case 'E': /* Error of some sort. */
8583 /* We're out of sync with the target now. Did it continue or
8584 not? Not is more likely, so report a stop. */
8585 rs->waiting_for_stop_reply = 0;
8586
8587 warning (_("Remote failure reply: %s"), buf);
8588 status->set_stopped (GDB_SIGNAL_0);
8589 break;
8590 case 'F': /* File-I/O request. */
8591 /* GDB may access the inferior memory while handling the File-I/O
8592 request, but we don't want GDB accessing memory while waiting
8593 for a stop reply. See the comments in putpkt_binary. Set
8594 waiting_for_stop_reply to 0 temporarily. */
8595 rs->waiting_for_stop_reply = 0;
8596 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8597 rs->ctrlc_pending_p = 0;
8598 /* GDB handled the File-I/O request, and the target is running
8599 again. Keep waiting for events. */
8600 rs->waiting_for_stop_reply = 1;
8601 break;
8602 case 'N': case 'T': case 'S': case 'X': case 'W':
8603 {
8604 /* There is a stop reply to handle. */
8605 rs->waiting_for_stop_reply = 0;
8606
8607 stop_reply
8608 = (struct stop_reply *) remote_notif_parse (this,
8609 &notif_client_stop,
8610 rs->buf.data ());
8611
8612 event_ptid = process_stop_reply (stop_reply, status);
8613 break;
8614 }
8615 case 'O': /* Console output. */
8616 remote_console_output (buf + 1);
8617 break;
8618 case '\0':
8619 if (rs->last_sent_signal != GDB_SIGNAL_0)
8620 {
8621 /* Zero length reply means that we tried 'S' or 'C' and the
8622 remote system doesn't support it. */
8623 target_terminal::ours_for_output ();
8624 gdb_printf
8625 ("Can't send signals to this remote system. %s not sent.\n",
8626 gdb_signal_to_name (rs->last_sent_signal));
8627 rs->last_sent_signal = GDB_SIGNAL_0;
8628 target_terminal::inferior ();
8629
8630 strcpy (buf, rs->last_sent_step ? "s" : "c");
8631 putpkt (buf);
8632 break;
8633 }
8634 /* fallthrough */
8635 default:
8636 warning (_("Invalid remote reply: %s"), buf);
8637 break;
8638 }
8639 }
8640
8641 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8642 return minus_one_ptid;
8643 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8644 {
8645 /* Nothing interesting happened. If we're doing a non-blocking
8646 poll, we're done. Otherwise, go back to waiting. */
8647 if (options & TARGET_WNOHANG)
8648 return minus_one_ptid;
8649 else
8650 goto again;
8651 }
8652 else if (status->kind () != TARGET_WAITKIND_EXITED
8653 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8654 {
8655 if (event_ptid != null_ptid)
8656 record_currthread (rs, event_ptid);
8657 else
8658 event_ptid = first_remote_resumed_thread (this);
8659 }
8660 else
8661 {
8662 /* A process exit. Invalidate our notion of current thread. */
8663 record_currthread (rs, minus_one_ptid);
8664 /* It's possible that the packet did not include a pid. */
8665 if (event_ptid == null_ptid)
8666 event_ptid = first_remote_resumed_thread (this);
8667 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8668 if (event_ptid == null_ptid)
8669 event_ptid = magic_null_ptid;
8670 }
8671
8672 return event_ptid;
8673 }
8674
8675 /* Wait until the remote machine stops, then return, storing status in
8676 STATUS just as `wait' would. */
8677
8678 ptid_t
8679 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8680 target_wait_flags options)
8681 {
8682 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8683
8684 remote_state *rs = get_remote_state ();
8685
8686 /* Start by clearing the flag that asks for our wait method to be called,
8687 we'll mark it again at the end if needed. If the target is not in
8688 async mode then the async token should not be marked. */
8689 if (target_is_async_p ())
8690 rs->clear_async_event_handler ();
8691 else
8692 gdb_assert (!rs->async_event_handler_marked ());
8693
8694 ptid_t event_ptid;
8695
8696 if (target_is_non_stop_p ())
8697 event_ptid = wait_ns (ptid, status, options);
8698 else
8699 event_ptid = wait_as (ptid, status, options);
8700
8701 if (target_is_async_p ())
8702 {
8703 /* If there are events left in the queue, or unacknowledged
8704 notifications, then tell the event loop to call us again. */
8705 if (!rs->stop_reply_queue.empty ()
8706 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8707 rs->mark_async_event_handler ();
8708 }
8709
8710 return event_ptid;
8711 }
8712
8713 /* Fetch a single register using a 'p' packet. */
8714
8715 int
8716 remote_target::fetch_register_using_p (struct regcache *regcache,
8717 packet_reg *reg)
8718 {
8719 struct gdbarch *gdbarch = regcache->arch ();
8720 struct remote_state *rs = get_remote_state ();
8721 char *buf, *p;
8722 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8723 int i;
8724
8725 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8726 return 0;
8727
8728 if (reg->pnum == -1)
8729 return 0;
8730
8731 p = rs->buf.data ();
8732 *p++ = 'p';
8733 p += hexnumstr (p, reg->pnum);
8734 *p++ = '\0';
8735 putpkt (rs->buf);
8736 getpkt (&rs->buf);
8737
8738 buf = rs->buf.data ();
8739
8740 switch (m_features.packet_ok (rs->buf, PACKET_p))
8741 {
8742 case PACKET_OK:
8743 break;
8744 case PACKET_UNKNOWN:
8745 return 0;
8746 case PACKET_ERROR:
8747 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8748 gdbarch_register_name (regcache->arch (), reg->regnum),
8749 buf);
8750 }
8751
8752 /* If this register is unfetchable, tell the regcache. */
8753 if (buf[0] == 'x')
8754 {
8755 regcache->raw_supply (reg->regnum, NULL);
8756 return 1;
8757 }
8758
8759 /* Otherwise, parse and supply the value. */
8760 p = buf;
8761 i = 0;
8762 while (p[0] != 0)
8763 {
8764 if (p[1] == 0)
8765 error (_("fetch_register_using_p: early buf termination"));
8766
8767 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8768 p += 2;
8769 }
8770 regcache->raw_supply (reg->regnum, regp);
8771 return 1;
8772 }
8773
8774 /* Fetch the registers included in the target's 'g' packet. */
8775
8776 int
8777 remote_target::send_g_packet ()
8778 {
8779 struct remote_state *rs = get_remote_state ();
8780 int buf_len;
8781
8782 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8783 putpkt (rs->buf);
8784 getpkt (&rs->buf);
8785 if (packet_check_result (rs->buf) == PACKET_ERROR)
8786 error (_("Could not read registers; remote failure reply '%s'"),
8787 rs->buf.data ());
8788
8789 /* We can get out of synch in various cases. If the first character
8790 in the buffer is not a hex character, assume that has happened
8791 and try to fetch another packet to read. */
8792 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8793 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8794 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8795 && rs->buf[0] != 'x') /* New: unavailable register value. */
8796 {
8797 remote_debug_printf ("Bad register packet; fetching a new packet");
8798 getpkt (&rs->buf);
8799 }
8800
8801 buf_len = strlen (rs->buf.data ());
8802
8803 /* Sanity check the received packet. */
8804 if (buf_len % 2 != 0)
8805 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8806
8807 return buf_len / 2;
8808 }
8809
8810 void
8811 remote_target::process_g_packet (struct regcache *regcache)
8812 {
8813 struct gdbarch *gdbarch = regcache->arch ();
8814 struct remote_state *rs = get_remote_state ();
8815 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8816 int i, buf_len;
8817 char *p;
8818 char *regs;
8819
8820 buf_len = strlen (rs->buf.data ());
8821
8822 /* Further sanity checks, with knowledge of the architecture. */
8823 if (buf_len > 2 * rsa->sizeof_g_packet)
8824 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8825 "bytes): %s"),
8826 rsa->sizeof_g_packet, buf_len / 2,
8827 rs->buf.data ());
8828
8829 /* Save the size of the packet sent to us by the target. It is used
8830 as a heuristic when determining the max size of packets that the
8831 target can safely receive. */
8832 if (rsa->actual_register_packet_size == 0)
8833 rsa->actual_register_packet_size = buf_len;
8834
8835 /* If this is smaller than we guessed the 'g' packet would be,
8836 update our records. A 'g' reply that doesn't include a register's
8837 value implies either that the register is not available, or that
8838 the 'p' packet must be used. */
8839 if (buf_len < 2 * rsa->sizeof_g_packet)
8840 {
8841 long sizeof_g_packet = buf_len / 2;
8842
8843 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8844 {
8845 long offset = rsa->regs[i].offset;
8846 long reg_size = register_size (gdbarch, i);
8847
8848 if (rsa->regs[i].pnum == -1)
8849 continue;
8850
8851 if (offset >= sizeof_g_packet)
8852 rsa->regs[i].in_g_packet = 0;
8853 else if (offset + reg_size > sizeof_g_packet)
8854 error (_("Truncated register %d in remote 'g' packet"), i);
8855 else
8856 rsa->regs[i].in_g_packet = 1;
8857 }
8858
8859 /* Looks valid enough, we can assume this is the correct length
8860 for a 'g' packet. It's important not to adjust
8861 rsa->sizeof_g_packet if we have truncated registers otherwise
8862 this "if" won't be run the next time the method is called
8863 with a packet of the same size and one of the internal errors
8864 below will trigger instead. */
8865 rsa->sizeof_g_packet = sizeof_g_packet;
8866 }
8867
8868 regs = (char *) alloca (rsa->sizeof_g_packet);
8869
8870 /* Unimplemented registers read as all bits zero. */
8871 memset (regs, 0, rsa->sizeof_g_packet);
8872
8873 /* Reply describes registers byte by byte, each byte encoded as two
8874 hex characters. Suck them all up, then supply them to the
8875 register cacheing/storage mechanism. */
8876
8877 p = rs->buf.data ();
8878 for (i = 0; i < rsa->sizeof_g_packet; i++)
8879 {
8880 if (p[0] == 0 || p[1] == 0)
8881 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8882 internal_error (_("unexpected end of 'g' packet reply"));
8883
8884 if (p[0] == 'x' && p[1] == 'x')
8885 regs[i] = 0; /* 'x' */
8886 else
8887 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8888 p += 2;
8889 }
8890
8891 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8892 {
8893 struct packet_reg *r = &rsa->regs[i];
8894 long reg_size = register_size (gdbarch, i);
8895
8896 if (r->in_g_packet)
8897 {
8898 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8899 /* This shouldn't happen - we adjusted in_g_packet above. */
8900 internal_error (_("unexpected end of 'g' packet reply"));
8901 else if (rs->buf[r->offset * 2] == 'x')
8902 {
8903 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8904 /* The register isn't available, mark it as such (at
8905 the same time setting the value to zero). */
8906 regcache->raw_supply (r->regnum, NULL);
8907 }
8908 else
8909 regcache->raw_supply (r->regnum, regs + r->offset);
8910 }
8911 }
8912 }
8913
8914 void
8915 remote_target::fetch_registers_using_g (struct regcache *regcache)
8916 {
8917 send_g_packet ();
8918 process_g_packet (regcache);
8919 }
8920
8921 /* Make the remote selected traceframe match GDB's selected
8922 traceframe. */
8923
8924 void
8925 remote_target::set_remote_traceframe ()
8926 {
8927 int newnum;
8928 struct remote_state *rs = get_remote_state ();
8929
8930 if (rs->remote_traceframe_number == get_traceframe_number ())
8931 return;
8932
8933 /* Avoid recursion, remote_trace_find calls us again. */
8934 rs->remote_traceframe_number = get_traceframe_number ();
8935
8936 newnum = target_trace_find (tfind_number,
8937 get_traceframe_number (), 0, 0, NULL);
8938
8939 /* Should not happen. If it does, all bets are off. */
8940 if (newnum != get_traceframe_number ())
8941 warning (_("could not set remote traceframe"));
8942 }
8943
8944 void
8945 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8946 {
8947 struct gdbarch *gdbarch = regcache->arch ();
8948 struct remote_state *rs = get_remote_state ();
8949 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8950 int i;
8951
8952 set_remote_traceframe ();
8953 set_general_thread (regcache->ptid ());
8954
8955 if (regnum >= 0)
8956 {
8957 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8958
8959 gdb_assert (reg != NULL);
8960
8961 /* If this register might be in the 'g' packet, try that first -
8962 we are likely to read more than one register. If this is the
8963 first 'g' packet, we might be overly optimistic about its
8964 contents, so fall back to 'p'. */
8965 if (reg->in_g_packet)
8966 {
8967 fetch_registers_using_g (regcache);
8968 if (reg->in_g_packet)
8969 return;
8970 }
8971
8972 if (fetch_register_using_p (regcache, reg))
8973 return;
8974
8975 /* This register is not available. */
8976 regcache->raw_supply (reg->regnum, NULL);
8977
8978 return;
8979 }
8980
8981 fetch_registers_using_g (regcache);
8982
8983 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8984 if (!rsa->regs[i].in_g_packet)
8985 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8986 {
8987 /* This register is not available. */
8988 regcache->raw_supply (i, NULL);
8989 }
8990 }
8991
8992 /* Prepare to store registers. Since we may send them all (using a
8993 'G' request), we have to read out the ones we don't want to change
8994 first. */
8995
8996 void
8997 remote_target::prepare_to_store (struct regcache *regcache)
8998 {
8999 struct remote_state *rs = get_remote_state ();
9000 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9001 int i;
9002
9003 /* Make sure the entire registers array is valid. */
9004 switch (m_features.packet_support (PACKET_P))
9005 {
9006 case PACKET_DISABLE:
9007 case PACKET_SUPPORT_UNKNOWN:
9008 /* Make sure all the necessary registers are cached. */
9009 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9010 if (rsa->regs[i].in_g_packet)
9011 regcache->raw_update (rsa->regs[i].regnum);
9012 break;
9013 case PACKET_ENABLE:
9014 break;
9015 }
9016 }
9017
9018 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9019 packet was not recognized. */
9020
9021 int
9022 remote_target::store_register_using_P (const struct regcache *regcache,
9023 packet_reg *reg)
9024 {
9025 struct gdbarch *gdbarch = regcache->arch ();
9026 struct remote_state *rs = get_remote_state ();
9027 /* Try storing a single register. */
9028 char *buf = rs->buf.data ();
9029 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9030 char *p;
9031
9032 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9033 return 0;
9034
9035 if (reg->pnum == -1)
9036 return 0;
9037
9038 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9039 p = buf + strlen (buf);
9040 regcache->raw_collect (reg->regnum, regp);
9041 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9042 putpkt (rs->buf);
9043 getpkt (&rs->buf);
9044
9045 switch (m_features.packet_ok (rs->buf, PACKET_P))
9046 {
9047 case PACKET_OK:
9048 return 1;
9049 case PACKET_ERROR:
9050 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9051 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
9052 case PACKET_UNKNOWN:
9053 return 0;
9054 default:
9055 internal_error (_("Bad result from packet_ok"));
9056 }
9057 }
9058
9059 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9060 contents of the register cache buffer. FIXME: ignores errors. */
9061
9062 void
9063 remote_target::store_registers_using_G (const struct regcache *regcache)
9064 {
9065 struct remote_state *rs = get_remote_state ();
9066 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9067 gdb_byte *regs;
9068 char *p;
9069
9070 /* Extract all the registers in the regcache copying them into a
9071 local buffer. */
9072 {
9073 int i;
9074
9075 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9076 memset (regs, 0, rsa->sizeof_g_packet);
9077 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9078 {
9079 struct packet_reg *r = &rsa->regs[i];
9080
9081 if (r->in_g_packet)
9082 regcache->raw_collect (r->regnum, regs + r->offset);
9083 }
9084 }
9085
9086 /* Command describes registers byte by byte,
9087 each byte encoded as two hex characters. */
9088 p = rs->buf.data ();
9089 *p++ = 'G';
9090 bin2hex (regs, p, rsa->sizeof_g_packet);
9091 putpkt (rs->buf);
9092 getpkt (&rs->buf);
9093 if (packet_check_result (rs->buf) == PACKET_ERROR)
9094 error (_("Could not write registers; remote failure reply '%s'"),
9095 rs->buf.data ());
9096 }
9097
9098 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9099 of the register cache buffer. FIXME: ignores errors. */
9100
9101 void
9102 remote_target::store_registers (struct regcache *regcache, int regnum)
9103 {
9104 struct gdbarch *gdbarch = regcache->arch ();
9105 struct remote_state *rs = get_remote_state ();
9106 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9107 int i;
9108
9109 set_remote_traceframe ();
9110 set_general_thread (regcache->ptid ());
9111
9112 if (regnum >= 0)
9113 {
9114 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9115
9116 gdb_assert (reg != NULL);
9117
9118 /* Always prefer to store registers using the 'P' packet if
9119 possible; we often change only a small number of registers.
9120 Sometimes we change a larger number; we'd need help from a
9121 higher layer to know to use 'G'. */
9122 if (store_register_using_P (regcache, reg))
9123 return;
9124
9125 /* For now, don't complain if we have no way to write the
9126 register. GDB loses track of unavailable registers too
9127 easily. Some day, this may be an error. We don't have
9128 any way to read the register, either... */
9129 if (!reg->in_g_packet)
9130 return;
9131
9132 store_registers_using_G (regcache);
9133 return;
9134 }
9135
9136 store_registers_using_G (regcache);
9137
9138 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9139 if (!rsa->regs[i].in_g_packet)
9140 if (!store_register_using_P (regcache, &rsa->regs[i]))
9141 /* See above for why we do not issue an error here. */
9142 continue;
9143 }
9144 \f
9145
9146 /* Return the number of hex digits in num. */
9147
9148 static int
9149 hexnumlen (ULONGEST num)
9150 {
9151 int i;
9152
9153 for (i = 0; num != 0; i++)
9154 num >>= 4;
9155
9156 return std::max (i, 1);
9157 }
9158
9159 /* Set BUF to the minimum number of hex digits representing NUM. */
9160
9161 static int
9162 hexnumstr (char *buf, ULONGEST num)
9163 {
9164 int len = hexnumlen (num);
9165
9166 return hexnumnstr (buf, num, len);
9167 }
9168
9169
9170 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9171
9172 static int
9173 hexnumnstr (char *buf, ULONGEST num, int width)
9174 {
9175 int i;
9176
9177 buf[width] = '\0';
9178
9179 for (i = width - 1; i >= 0; i--)
9180 {
9181 buf[i] = "0123456789abcdef"[(num & 0xf)];
9182 num >>= 4;
9183 }
9184
9185 return width;
9186 }
9187
9188 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9189
9190 static CORE_ADDR
9191 remote_address_masked (CORE_ADDR addr)
9192 {
9193 unsigned int address_size = remote_address_size;
9194
9195 /* If "remoteaddresssize" was not set, default to target address size. */
9196 if (!address_size)
9197 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9198
9199 if (address_size > 0
9200 && address_size < (sizeof (ULONGEST) * 8))
9201 {
9202 /* Only create a mask when that mask can safely be constructed
9203 in a ULONGEST variable. */
9204 ULONGEST mask = 1;
9205
9206 mask = (mask << address_size) - 1;
9207 addr &= mask;
9208 }
9209 return addr;
9210 }
9211
9212 /* Determine whether the remote target supports binary downloading.
9213 This is accomplished by sending a no-op memory write of zero length
9214 to the target at the specified address. It does not suffice to send
9215 the whole packet, since many stubs strip the eighth bit and
9216 subsequently compute a wrong checksum, which causes real havoc with
9217 remote_write_bytes.
9218
9219 NOTE: This can still lose if the serial line is not eight-bit
9220 clean. In cases like this, the user should clear "remote
9221 X-packet". */
9222
9223 void
9224 remote_target::check_binary_download (CORE_ADDR addr)
9225 {
9226 struct remote_state *rs = get_remote_state ();
9227
9228 switch (m_features.packet_support (PACKET_X))
9229 {
9230 case PACKET_DISABLE:
9231 break;
9232 case PACKET_ENABLE:
9233 break;
9234 case PACKET_SUPPORT_UNKNOWN:
9235 {
9236 char *p;
9237
9238 p = rs->buf.data ();
9239 *p++ = 'X';
9240 p += hexnumstr (p, (ULONGEST) addr);
9241 *p++ = ',';
9242 p += hexnumstr (p, (ULONGEST) 0);
9243 *p++ = ':';
9244 *p = '\0';
9245
9246 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9247 getpkt (&rs->buf);
9248
9249 if (rs->buf[0] == '\0')
9250 {
9251 remote_debug_printf ("binary downloading NOT supported by target");
9252 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9253 }
9254 else
9255 {
9256 remote_debug_printf ("binary downloading supported by target");
9257 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9258 }
9259 break;
9260 }
9261 }
9262 }
9263
9264 /* Helper function to resize the payload in order to try to get a good
9265 alignment. We try to write an amount of data such that the next write will
9266 start on an address aligned on REMOTE_ALIGN_WRITES. */
9267
9268 static int
9269 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9270 {
9271 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9272 }
9273
9274 /* Write memory data directly to the remote machine.
9275 This does not inform the data cache; the data cache uses this.
9276 HEADER is the starting part of the packet.
9277 MEMADDR is the address in the remote memory space.
9278 MYADDR is the address of the buffer in our space.
9279 LEN_UNITS is the number of addressable units to write.
9280 UNIT_SIZE is the length in bytes of an addressable unit.
9281 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9282 should send data as binary ('X'), or hex-encoded ('M').
9283
9284 The function creates packet of the form
9285 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9286
9287 where encoding of <DATA> is terminated by PACKET_FORMAT.
9288
9289 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9290 are omitted.
9291
9292 Return the transferred status, error or OK (an
9293 'enum target_xfer_status' value). Save the number of addressable units
9294 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9295
9296 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9297 exchange between gdb and the stub could look like (?? in place of the
9298 checksum):
9299
9300 -> $m1000,4#??
9301 <- aaaabbbbccccdddd
9302
9303 -> $M1000,3:eeeeffffeeee#??
9304 <- OK
9305
9306 -> $m1000,4#??
9307 <- eeeeffffeeeedddd */
9308
9309 target_xfer_status
9310 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9311 const gdb_byte *myaddr,
9312 ULONGEST len_units,
9313 int unit_size,
9314 ULONGEST *xfered_len_units,
9315 char packet_format, int use_length)
9316 {
9317 struct remote_state *rs = get_remote_state ();
9318 char *p;
9319 char *plen = NULL;
9320 int plenlen = 0;
9321 int todo_units;
9322 int units_written;
9323 int payload_capacity_bytes;
9324 int payload_length_bytes;
9325
9326 if (packet_format != 'X' && packet_format != 'M')
9327 internal_error (_("remote_write_bytes_aux: bad packet format"));
9328
9329 if (len_units == 0)
9330 return TARGET_XFER_EOF;
9331
9332 payload_capacity_bytes = get_memory_write_packet_size ();
9333
9334 /* The packet buffer will be large enough for the payload;
9335 get_memory_packet_size ensures this. */
9336 rs->buf[0] = '\0';
9337
9338 /* Compute the size of the actual payload by subtracting out the
9339 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9340
9341 payload_capacity_bytes -= strlen ("$,:#NN");
9342 if (!use_length)
9343 /* The comma won't be used. */
9344 payload_capacity_bytes += 1;
9345 payload_capacity_bytes -= strlen (header);
9346 payload_capacity_bytes -= hexnumlen (memaddr);
9347
9348 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9349
9350 strcat (rs->buf.data (), header);
9351 p = rs->buf.data () + strlen (header);
9352
9353 /* Compute a best guess of the number of bytes actually transfered. */
9354 if (packet_format == 'X')
9355 {
9356 /* Best guess at number of bytes that will fit. */
9357 todo_units = std::min (len_units,
9358 (ULONGEST) payload_capacity_bytes / unit_size);
9359 if (use_length)
9360 payload_capacity_bytes -= hexnumlen (todo_units);
9361 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9362 }
9363 else
9364 {
9365 /* Number of bytes that will fit. */
9366 todo_units
9367 = std::min (len_units,
9368 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9369 if (use_length)
9370 payload_capacity_bytes -= hexnumlen (todo_units);
9371 todo_units = std::min (todo_units,
9372 (payload_capacity_bytes / unit_size) / 2);
9373 }
9374
9375 if (todo_units <= 0)
9376 internal_error (_("minimum packet size too small to write data"));
9377
9378 /* If we already need another packet, then try to align the end
9379 of this packet to a useful boundary. */
9380 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9381 todo_units = align_for_efficient_write (todo_units, memaddr);
9382
9383 /* Append "<memaddr>". */
9384 memaddr = remote_address_masked (memaddr);
9385 p += hexnumstr (p, (ULONGEST) memaddr);
9386
9387 if (use_length)
9388 {
9389 /* Append ",". */
9390 *p++ = ',';
9391
9392 /* Append the length and retain its location and size. It may need to be
9393 adjusted once the packet body has been created. */
9394 plen = p;
9395 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9396 p += plenlen;
9397 }
9398
9399 /* Append ":". */
9400 *p++ = ':';
9401 *p = '\0';
9402
9403 /* Append the packet body. */
9404 if (packet_format == 'X')
9405 {
9406 /* Binary mode. Send target system values byte by byte, in
9407 increasing byte addresses. Only escape certain critical
9408 characters. */
9409 payload_length_bytes =
9410 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9411 &units_written, payload_capacity_bytes);
9412
9413 /* If not all TODO units fit, then we'll need another packet. Make
9414 a second try to keep the end of the packet aligned. Don't do
9415 this if the packet is tiny. */
9416 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9417 {
9418 int new_todo_units;
9419
9420 new_todo_units = align_for_efficient_write (units_written, memaddr);
9421
9422 if (new_todo_units != units_written)
9423 payload_length_bytes =
9424 remote_escape_output (myaddr, new_todo_units, unit_size,
9425 (gdb_byte *) p, &units_written,
9426 payload_capacity_bytes);
9427 }
9428
9429 p += payload_length_bytes;
9430 if (use_length && units_written < todo_units)
9431 {
9432 /* Escape chars have filled up the buffer prematurely,
9433 and we have actually sent fewer units than planned.
9434 Fix-up the length field of the packet. Use the same
9435 number of characters as before. */
9436 plen += hexnumnstr (plen, (ULONGEST) units_written,
9437 plenlen);
9438 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9439 }
9440 }
9441 else
9442 {
9443 /* Normal mode: Send target system values byte by byte, in
9444 increasing byte addresses. Each byte is encoded as a two hex
9445 value. */
9446 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9447 units_written = todo_units;
9448 }
9449
9450 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9451 getpkt (&rs->buf);
9452
9453 if (rs->buf[0] == 'E')
9454 return TARGET_XFER_E_IO;
9455
9456 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9457 send fewer units than we'd planned. */
9458 *xfered_len_units = (ULONGEST) units_written;
9459 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9460 }
9461
9462 /* Write memory data directly to the remote machine.
9463 This does not inform the data cache; the data cache uses this.
9464 MEMADDR is the address in the remote memory space.
9465 MYADDR is the address of the buffer in our space.
9466 LEN is the number of bytes.
9467
9468 Return the transferred status, error or OK (an
9469 'enum target_xfer_status' value). Save the number of bytes
9470 transferred in *XFERED_LEN. Only transfer a single packet. */
9471
9472 target_xfer_status
9473 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9474 ULONGEST len, int unit_size,
9475 ULONGEST *xfered_len)
9476 {
9477 const char *packet_format = NULL;
9478
9479 /* Check whether the target supports binary download. */
9480 check_binary_download (memaddr);
9481
9482 switch (m_features.packet_support (PACKET_X))
9483 {
9484 case PACKET_ENABLE:
9485 packet_format = "X";
9486 break;
9487 case PACKET_DISABLE:
9488 packet_format = "M";
9489 break;
9490 case PACKET_SUPPORT_UNKNOWN:
9491 internal_error (_("remote_write_bytes: bad internal state"));
9492 default:
9493 internal_error (_("bad switch"));
9494 }
9495
9496 return remote_write_bytes_aux (packet_format,
9497 memaddr, myaddr, len, unit_size, xfered_len,
9498 packet_format[0], 1);
9499 }
9500
9501 /* Read memory data directly from the remote machine.
9502 This does not use the data cache; the data cache uses this.
9503 MEMADDR is the address in the remote memory space.
9504 MYADDR is the address of the buffer in our space.
9505 LEN_UNITS is the number of addressable memory units to read..
9506 UNIT_SIZE is the length in bytes of an addressable unit.
9507
9508 Return the transferred status, error or OK (an
9509 'enum target_xfer_status' value). Save the number of bytes
9510 transferred in *XFERED_LEN_UNITS.
9511
9512 See the comment of remote_write_bytes_aux for an example of
9513 memory read/write exchange between gdb and the stub. */
9514
9515 target_xfer_status
9516 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9517 ULONGEST len_units,
9518 int unit_size, ULONGEST *xfered_len_units)
9519 {
9520 struct remote_state *rs = get_remote_state ();
9521 int buf_size_bytes; /* Max size of packet output buffer. */
9522 char *p;
9523 int todo_units;
9524 int decoded_bytes;
9525
9526 buf_size_bytes = get_memory_read_packet_size ();
9527 /* The packet buffer will be large enough for the payload;
9528 get_memory_packet_size ensures this. */
9529
9530 /* Number of units that will fit. */
9531 todo_units = std::min (len_units,
9532 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9533
9534 /* Construct "m"<memaddr>","<len>". */
9535 memaddr = remote_address_masked (memaddr);
9536 p = rs->buf.data ();
9537 *p++ = 'm';
9538 p += hexnumstr (p, (ULONGEST) memaddr);
9539 *p++ = ',';
9540 p += hexnumstr (p, (ULONGEST) todo_units);
9541 *p = '\0';
9542 putpkt (rs->buf);
9543 getpkt (&rs->buf);
9544 if (rs->buf[0] == 'E'
9545 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9546 && rs->buf[3] == '\0')
9547 return TARGET_XFER_E_IO;
9548 /* Reply describes memory byte by byte, each byte encoded as two hex
9549 characters. */
9550 p = rs->buf.data ();
9551 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9552 /* Return what we have. Let higher layers handle partial reads. */
9553 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9554 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9555 }
9556
9557 /* Using the set of read-only target sections of remote, read live
9558 read-only memory.
9559
9560 For interface/parameters/return description see target.h,
9561 to_xfer_partial. */
9562
9563 target_xfer_status
9564 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9565 ULONGEST memaddr,
9566 ULONGEST len,
9567 int unit_size,
9568 ULONGEST *xfered_len)
9569 {
9570 const struct target_section *secp;
9571
9572 secp = target_section_by_addr (this, memaddr);
9573 if (secp != NULL
9574 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9575 {
9576 ULONGEST memend = memaddr + len;
9577
9578 const std::vector<target_section> *table
9579 = target_get_section_table (this);
9580 for (const target_section &p : *table)
9581 {
9582 if (memaddr >= p.addr)
9583 {
9584 if (memend <= p.endaddr)
9585 {
9586 /* Entire transfer is within this section. */
9587 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9588 xfered_len);
9589 }
9590 else if (memaddr >= p.endaddr)
9591 {
9592 /* This section ends before the transfer starts. */
9593 continue;
9594 }
9595 else
9596 {
9597 /* This section overlaps the transfer. Just do half. */
9598 len = p.endaddr - memaddr;
9599 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9600 xfered_len);
9601 }
9602 }
9603 }
9604 }
9605
9606 return TARGET_XFER_EOF;
9607 }
9608
9609 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9610 first if the requested memory is unavailable in traceframe.
9611 Otherwise, fall back to remote_read_bytes_1. */
9612
9613 target_xfer_status
9614 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9615 gdb_byte *myaddr, ULONGEST len, int unit_size,
9616 ULONGEST *xfered_len)
9617 {
9618 if (len == 0)
9619 return TARGET_XFER_EOF;
9620
9621 if (get_traceframe_number () != -1)
9622 {
9623 std::vector<mem_range> available;
9624
9625 /* If we fail to get the set of available memory, then the
9626 target does not support querying traceframe info, and so we
9627 attempt reading from the traceframe anyway (assuming the
9628 target implements the old QTro packet then). */
9629 if (traceframe_available_memory (&available, memaddr, len))
9630 {
9631 if (available.empty () || available[0].start != memaddr)
9632 {
9633 enum target_xfer_status res;
9634
9635 /* Don't read into the traceframe's available
9636 memory. */
9637 if (!available.empty ())
9638 {
9639 LONGEST oldlen = len;
9640
9641 len = available[0].start - memaddr;
9642 gdb_assert (len <= oldlen);
9643 }
9644
9645 /* This goes through the topmost target again. */
9646 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9647 len, unit_size, xfered_len);
9648 if (res == TARGET_XFER_OK)
9649 return TARGET_XFER_OK;
9650 else
9651 {
9652 /* No use trying further, we know some memory starting
9653 at MEMADDR isn't available. */
9654 *xfered_len = len;
9655 return (*xfered_len != 0) ?
9656 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9657 }
9658 }
9659
9660 /* Don't try to read more than how much is available, in
9661 case the target implements the deprecated QTro packet to
9662 cater for older GDBs (the target's knowledge of read-only
9663 sections may be outdated by now). */
9664 len = available[0].length;
9665 }
9666 }
9667
9668 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9669 }
9670
9671 \f
9672
9673 /* Sends a packet with content determined by the printf format string
9674 FORMAT and the remaining arguments, then gets the reply. Returns
9675 whether the packet was a success, a failure, or unknown. */
9676
9677 packet_result
9678 remote_target::remote_send_printf (const char *format, ...)
9679 {
9680 struct remote_state *rs = get_remote_state ();
9681 int max_size = get_remote_packet_size ();
9682 va_list ap;
9683
9684 va_start (ap, format);
9685
9686 rs->buf[0] = '\0';
9687 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9688
9689 va_end (ap);
9690
9691 if (size >= max_size)
9692 internal_error (_("Too long remote packet."));
9693
9694 if (putpkt (rs->buf) < 0)
9695 error (_("Communication problem with target."));
9696
9697 rs->buf[0] = '\0';
9698 getpkt (&rs->buf);
9699
9700 return packet_check_result (rs->buf);
9701 }
9702
9703 /* Flash writing can take quite some time. We'll set
9704 effectively infinite timeout for flash operations.
9705 In future, we'll need to decide on a better approach. */
9706 static const int remote_flash_timeout = 1000;
9707
9708 void
9709 remote_target::flash_erase (ULONGEST address, LONGEST length)
9710 {
9711 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9712 enum packet_result ret;
9713 scoped_restore restore_timeout
9714 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9715
9716 ret = remote_send_printf ("vFlashErase:%s,%s",
9717 phex (address, addr_size),
9718 phex (length, 4));
9719 switch (ret)
9720 {
9721 case PACKET_UNKNOWN:
9722 error (_("Remote target does not support flash erase"));
9723 case PACKET_ERROR:
9724 error (_("Error erasing flash with vFlashErase packet"));
9725 default:
9726 break;
9727 }
9728 }
9729
9730 target_xfer_status
9731 remote_target::remote_flash_write (ULONGEST address,
9732 ULONGEST length, ULONGEST *xfered_len,
9733 const gdb_byte *data)
9734 {
9735 scoped_restore restore_timeout
9736 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9737 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9738 xfered_len,'X', 0);
9739 }
9740
9741 void
9742 remote_target::flash_done ()
9743 {
9744 int ret;
9745
9746 scoped_restore restore_timeout
9747 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9748
9749 ret = remote_send_printf ("vFlashDone");
9750
9751 switch (ret)
9752 {
9753 case PACKET_UNKNOWN:
9754 error (_("Remote target does not support vFlashDone"));
9755 case PACKET_ERROR:
9756 error (_("Error finishing flash operation"));
9757 default:
9758 break;
9759 }
9760 }
9761
9762 \f
9763 /* Stuff for dealing with the packets which are part of this protocol.
9764 See comment at top of file for details. */
9765
9766 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9767 error to higher layers. Called when a serial error is detected.
9768 The exception message is STRING, followed by a colon and a blank,
9769 the system error message for errno at function entry and final dot
9770 for output compatibility with throw_perror_with_name. */
9771
9772 static void
9773 unpush_and_perror (remote_target *target, const char *string)
9774 {
9775 int saved_errno = errno;
9776
9777 remote_unpush_target (target);
9778 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9779 safe_strerror (saved_errno));
9780 }
9781
9782 /* Read a single character from the remote end. The current quit
9783 handler is overridden to avoid quitting in the middle of packet
9784 sequence, as that would break communication with the remote server.
9785 See remote_serial_quit_handler for more detail. */
9786
9787 int
9788 remote_target::readchar (int timeout)
9789 {
9790 int ch;
9791 struct remote_state *rs = get_remote_state ();
9792
9793 {
9794 scoped_restore restore_quit_target
9795 = make_scoped_restore (&curr_quit_handler_target, this);
9796 scoped_restore restore_quit
9797 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9798
9799 rs->got_ctrlc_during_io = 0;
9800
9801 ch = serial_readchar (rs->remote_desc, timeout);
9802
9803 if (rs->got_ctrlc_during_io)
9804 set_quit_flag ();
9805 }
9806
9807 if (ch >= 0)
9808 return ch;
9809
9810 switch ((enum serial_rc) ch)
9811 {
9812 case SERIAL_EOF:
9813 remote_unpush_target (this);
9814 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9815 /* no return */
9816 case SERIAL_ERROR:
9817 unpush_and_perror (this, _("Remote communication error. "
9818 "Target disconnected"));
9819 /* no return */
9820 case SERIAL_TIMEOUT:
9821 break;
9822 }
9823 return ch;
9824 }
9825
9826 /* Wrapper for serial_write that closes the target and throws if
9827 writing fails. The current quit handler is overridden to avoid
9828 quitting in the middle of packet sequence, as that would break
9829 communication with the remote server. See
9830 remote_serial_quit_handler for more detail. */
9831
9832 void
9833 remote_target::remote_serial_write (const char *str, int len)
9834 {
9835 struct remote_state *rs = get_remote_state ();
9836
9837 scoped_restore restore_quit_target
9838 = make_scoped_restore (&curr_quit_handler_target, this);
9839 scoped_restore restore_quit
9840 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9841
9842 rs->got_ctrlc_during_io = 0;
9843
9844 if (serial_write (rs->remote_desc, str, len))
9845 {
9846 unpush_and_perror (this, _("Remote communication error. "
9847 "Target disconnected"));
9848 }
9849
9850 if (rs->got_ctrlc_during_io)
9851 set_quit_flag ();
9852 }
9853
9854 /* Return a string representing an escaped version of BUF, of len N.
9855 E.g. \n is converted to \\n, \t to \\t, etc. */
9856
9857 static std::string
9858 escape_buffer (const char *buf, int n)
9859 {
9860 string_file stb;
9861
9862 stb.putstrn (buf, n, '\\');
9863 return stb.release ();
9864 }
9865
9866 int
9867 remote_target::putpkt (const char *buf)
9868 {
9869 return putpkt_binary (buf, strlen (buf));
9870 }
9871
9872 /* Wrapper around remote_target::putpkt to avoid exporting
9873 remote_target. */
9874
9875 int
9876 putpkt (remote_target *remote, const char *buf)
9877 {
9878 return remote->putpkt (buf);
9879 }
9880
9881 /* Send a packet to the remote machine, with error checking. The data
9882 of the packet is in BUF. The string in BUF can be at most
9883 get_remote_packet_size () - 5 to account for the $, # and checksum,
9884 and for a possible /0 if we are debugging (remote_debug) and want
9885 to print the sent packet as a string. */
9886
9887 int
9888 remote_target::putpkt_binary (const char *buf, int cnt)
9889 {
9890 struct remote_state *rs = get_remote_state ();
9891 int i;
9892 unsigned char csum = 0;
9893 gdb::def_vector<char> data (cnt + 6);
9894 char *buf2 = data.data ();
9895
9896 int ch;
9897 int tcount = 0;
9898 char *p;
9899
9900 /* Catch cases like trying to read memory or listing threads while
9901 we're waiting for a stop reply. The remote server wouldn't be
9902 ready to handle this request, so we'd hang and timeout. We don't
9903 have to worry about this in synchronous mode, because in that
9904 case it's not possible to issue a command while the target is
9905 running. This is not a problem in non-stop mode, because in that
9906 case, the stub is always ready to process serial input. */
9907 if (!target_is_non_stop_p ()
9908 && target_is_async_p ()
9909 && rs->waiting_for_stop_reply)
9910 {
9911 error (_("Cannot execute this command while the target is running.\n"
9912 "Use the \"interrupt\" command to stop the target\n"
9913 "and then try again."));
9914 }
9915
9916 /* Copy the packet into buffer BUF2, encapsulating it
9917 and giving it a checksum. */
9918
9919 p = buf2;
9920 *p++ = '$';
9921
9922 for (i = 0; i < cnt; i++)
9923 {
9924 csum += buf[i];
9925 *p++ = buf[i];
9926 }
9927 *p++ = '#';
9928 *p++ = tohex ((csum >> 4) & 0xf);
9929 *p++ = tohex (csum & 0xf);
9930
9931 /* Send it over and over until we get a positive ack. */
9932
9933 while (1)
9934 {
9935 if (remote_debug)
9936 {
9937 *p = '\0';
9938
9939 int len = (int) (p - buf2);
9940 int max_chars;
9941
9942 if (remote_packet_max_chars < 0)
9943 max_chars = len;
9944 else
9945 max_chars = remote_packet_max_chars;
9946
9947 std::string str
9948 = escape_buffer (buf2, std::min (len, max_chars));
9949
9950 if (len > max_chars)
9951 remote_debug_printf_nofunc
9952 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9953 len - max_chars);
9954 else
9955 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9956 }
9957 remote_serial_write (buf2, p - buf2);
9958
9959 /* If this is a no acks version of the remote protocol, send the
9960 packet and move on. */
9961 if (rs->noack_mode)
9962 break;
9963
9964 /* Read until either a timeout occurs (-2) or '+' is read.
9965 Handle any notification that arrives in the mean time. */
9966 while (1)
9967 {
9968 ch = readchar (remote_timeout);
9969
9970 switch (ch)
9971 {
9972 case '+':
9973 remote_debug_printf_nofunc ("Received Ack");
9974 return 1;
9975 case '-':
9976 remote_debug_printf_nofunc ("Received Nak");
9977 /* FALLTHROUGH */
9978 case SERIAL_TIMEOUT:
9979 tcount++;
9980 if (tcount > 3)
9981 return 0;
9982 break; /* Retransmit buffer. */
9983 case '$':
9984 {
9985 remote_debug_printf ("Packet instead of Ack, ignoring it");
9986 /* It's probably an old response sent because an ACK
9987 was lost. Gobble up the packet and ack it so it
9988 doesn't get retransmitted when we resend this
9989 packet. */
9990 skip_frame ();
9991 remote_serial_write ("+", 1);
9992 continue; /* Now, go look for +. */
9993 }
9994
9995 case '%':
9996 {
9997 int val;
9998
9999 /* If we got a notification, handle it, and go back to looking
10000 for an ack. */
10001 /* We've found the start of a notification. Now
10002 collect the data. */
10003 val = read_frame (&rs->buf);
10004 if (val >= 0)
10005 {
10006 remote_debug_printf_nofunc
10007 (" Notification received: %s",
10008 escape_buffer (rs->buf.data (), val).c_str ());
10009
10010 handle_notification (rs->notif_state, rs->buf.data ());
10011 /* We're in sync now, rewait for the ack. */
10012 tcount = 0;
10013 }
10014 else
10015 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10016 rs->buf.data ());
10017 continue;
10018 }
10019 /* fall-through */
10020 default:
10021 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10022 rs->buf.data ());
10023 continue;
10024 }
10025 break; /* Here to retransmit. */
10026 }
10027
10028 #if 0
10029 /* This is wrong. If doing a long backtrace, the user should be
10030 able to get out next time we call QUIT, without anything as
10031 violent as interrupt_query. If we want to provide a way out of
10032 here without getting to the next QUIT, it should be based on
10033 hitting ^C twice as in remote_wait. */
10034 if (quit_flag)
10035 {
10036 quit_flag = 0;
10037 interrupt_query ();
10038 }
10039 #endif
10040 }
10041
10042 return 0;
10043 }
10044
10045 /* Come here after finding the start of a frame when we expected an
10046 ack. Do our best to discard the rest of this packet. */
10047
10048 void
10049 remote_target::skip_frame ()
10050 {
10051 int c;
10052
10053 while (1)
10054 {
10055 c = readchar (remote_timeout);
10056 switch (c)
10057 {
10058 case SERIAL_TIMEOUT:
10059 /* Nothing we can do. */
10060 return;
10061 case '#':
10062 /* Discard the two bytes of checksum and stop. */
10063 c = readchar (remote_timeout);
10064 if (c >= 0)
10065 c = readchar (remote_timeout);
10066
10067 return;
10068 case '*': /* Run length encoding. */
10069 /* Discard the repeat count. */
10070 c = readchar (remote_timeout);
10071 if (c < 0)
10072 return;
10073 break;
10074 default:
10075 /* A regular character. */
10076 break;
10077 }
10078 }
10079 }
10080
10081 /* Come here after finding the start of the frame. Collect the rest
10082 into *BUF, verifying the checksum, length, and handling run-length
10083 compression. NUL terminate the buffer. If there is not enough room,
10084 expand *BUF.
10085
10086 Returns -1 on error, number of characters in buffer (ignoring the
10087 trailing NULL) on success. (could be extended to return one of the
10088 SERIAL status indications). */
10089
10090 long
10091 remote_target::read_frame (gdb::char_vector *buf_p)
10092 {
10093 unsigned char csum;
10094 long bc;
10095 int c;
10096 char *buf = buf_p->data ();
10097 struct remote_state *rs = get_remote_state ();
10098
10099 csum = 0;
10100 bc = 0;
10101
10102 while (1)
10103 {
10104 c = readchar (remote_timeout);
10105 switch (c)
10106 {
10107 case SERIAL_TIMEOUT:
10108 remote_debug_printf ("Timeout in mid-packet, retrying");
10109 return -1;
10110
10111 case '$':
10112 remote_debug_printf ("Saw new packet start in middle of old one");
10113 return -1; /* Start a new packet, count retries. */
10114
10115 case '#':
10116 {
10117 unsigned char pktcsum;
10118 int check_0 = 0;
10119 int check_1 = 0;
10120
10121 buf[bc] = '\0';
10122
10123 check_0 = readchar (remote_timeout);
10124 if (check_0 >= 0)
10125 check_1 = readchar (remote_timeout);
10126
10127 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10128 {
10129 remote_debug_printf ("Timeout in checksum, retrying");
10130 return -1;
10131 }
10132 else if (check_0 < 0 || check_1 < 0)
10133 {
10134 remote_debug_printf ("Communication error in checksum");
10135 return -1;
10136 }
10137
10138 /* Don't recompute the checksum; with no ack packets we
10139 don't have any way to indicate a packet retransmission
10140 is necessary. */
10141 if (rs->noack_mode)
10142 return bc;
10143
10144 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10145 if (csum == pktcsum)
10146 return bc;
10147
10148 remote_debug_printf
10149 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10150 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10151
10152 /* Number of characters in buffer ignoring trailing
10153 NULL. */
10154 return -1;
10155 }
10156 case '*': /* Run length encoding. */
10157 {
10158 int repeat;
10159
10160 csum += c;
10161 c = readchar (remote_timeout);
10162 csum += c;
10163 repeat = c - ' ' + 3; /* Compute repeat count. */
10164
10165 /* The character before ``*'' is repeated. */
10166
10167 if (repeat > 0 && repeat <= 255 && bc > 0)
10168 {
10169 if (bc + repeat - 1 >= buf_p->size () - 1)
10170 {
10171 /* Make some more room in the buffer. */
10172 buf_p->resize (buf_p->size () + repeat);
10173 buf = buf_p->data ();
10174 }
10175
10176 memset (&buf[bc], buf[bc - 1], repeat);
10177 bc += repeat;
10178 continue;
10179 }
10180
10181 buf[bc] = '\0';
10182 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10183 return -1;
10184 }
10185 default:
10186 if (bc >= buf_p->size () - 1)
10187 {
10188 /* Make some more room in the buffer. */
10189 buf_p->resize (buf_p->size () * 2);
10190 buf = buf_p->data ();
10191 }
10192
10193 buf[bc++] = c;
10194 csum += c;
10195 continue;
10196 }
10197 }
10198 }
10199
10200 /* Set this to the maximum number of seconds to wait instead of waiting forever
10201 in target_wait(). If this timer times out, then it generates an error and
10202 the command is aborted. This replaces most of the need for timeouts in the
10203 GDB test suite, and makes it possible to distinguish between a hung target
10204 and one with slow communications. */
10205
10206 static int watchdog = 0;
10207 static void
10208 show_watchdog (struct ui_file *file, int from_tty,
10209 struct cmd_list_element *c, const char *value)
10210 {
10211 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10212 }
10213
10214 /* Read a packet from the remote machine, with error checking, and
10215 store it in *BUF. Resize *BUF if necessary to hold the result. If
10216 FOREVER, wait forever rather than timing out; this is used (in
10217 synchronous mode) to wait for a target that is is executing user
10218 code to stop. If FOREVER == false, this function is allowed to time
10219 out gracefully and return an indication of this to the caller.
10220 Otherwise return the number of bytes read. If IS_NOTIF is not
10221 NULL, then consider receiving a notification enough reason to
10222 return to the caller. In this case, *IS_NOTIF is an output boolean
10223 that indicates whether *BUF holds a notification or not (a regular
10224 packet). */
10225
10226 int
10227 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10228 {
10229 struct remote_state *rs = get_remote_state ();
10230 int c;
10231 int tries;
10232 int timeout;
10233 int val = -1;
10234
10235 strcpy (buf->data (), "timeout");
10236
10237 if (forever)
10238 timeout = watchdog > 0 ? watchdog : -1;
10239 else if (is_notif != nullptr)
10240 timeout = 0; /* There should already be a char in the buffer. If
10241 not, bail out. */
10242 else
10243 timeout = remote_timeout;
10244
10245 #define MAX_TRIES 3
10246
10247 /* Process any number of notifications, and then return when
10248 we get a packet. */
10249 for (;;)
10250 {
10251 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10252 times. */
10253 for (tries = 1; tries <= MAX_TRIES; tries++)
10254 {
10255 /* This can loop forever if the remote side sends us
10256 characters continuously, but if it pauses, we'll get
10257 SERIAL_TIMEOUT from readchar because of timeout. Then
10258 we'll count that as a retry.
10259
10260 Note that even when forever is set, we will only wait
10261 forever prior to the start of a packet. After that, we
10262 expect characters to arrive at a brisk pace. They should
10263 show up within remote_timeout intervals. */
10264 do
10265 c = readchar (timeout);
10266 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10267
10268 if (c == SERIAL_TIMEOUT)
10269 {
10270 if (is_notif != nullptr)
10271 return -1; /* Don't complain, it's normal to not get
10272 anything in this case. */
10273
10274 if (forever) /* Watchdog went off? Kill the target. */
10275 {
10276 remote_unpush_target (this);
10277 throw_error (TARGET_CLOSE_ERROR,
10278 _("Watchdog timeout has expired. "
10279 "Target detached."));
10280 }
10281
10282 remote_debug_printf ("Timed out.");
10283 }
10284 else
10285 {
10286 /* We've found the start of a packet or notification.
10287 Now collect the data. */
10288 val = read_frame (buf);
10289 if (val >= 0)
10290 break;
10291 }
10292
10293 remote_serial_write ("-", 1);
10294 }
10295
10296 if (tries > MAX_TRIES)
10297 {
10298 /* We have tried hard enough, and just can't receive the
10299 packet/notification. Give up. */
10300 gdb_printf (_("Ignoring packet error, continuing...\n"));
10301
10302 /* Skip the ack char if we're in no-ack mode. */
10303 if (!rs->noack_mode)
10304 remote_serial_write ("+", 1);
10305 return -1;
10306 }
10307
10308 /* If we got an ordinary packet, return that to our caller. */
10309 if (c == '$')
10310 {
10311 if (remote_debug)
10312 {
10313 int max_chars;
10314
10315 if (remote_packet_max_chars < 0)
10316 max_chars = val;
10317 else
10318 max_chars = remote_packet_max_chars;
10319
10320 std::string str
10321 = escape_buffer (buf->data (),
10322 std::min (val, max_chars));
10323
10324 if (val > max_chars)
10325 remote_debug_printf_nofunc
10326 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10327 val - max_chars);
10328 else
10329 remote_debug_printf_nofunc ("Packet received: %s",
10330 str.c_str ());
10331 }
10332
10333 /* Skip the ack char if we're in no-ack mode. */
10334 if (!rs->noack_mode)
10335 remote_serial_write ("+", 1);
10336 if (is_notif != NULL)
10337 *is_notif = false;
10338 return val;
10339 }
10340
10341 /* If we got a notification, handle it, and go back to looking
10342 for a packet. */
10343 else
10344 {
10345 gdb_assert (c == '%');
10346
10347 remote_debug_printf_nofunc
10348 (" Notification received: %s",
10349 escape_buffer (buf->data (), val).c_str ());
10350
10351 if (is_notif != NULL)
10352 *is_notif = true;
10353
10354 handle_notification (rs->notif_state, buf->data ());
10355
10356 /* Notifications require no acknowledgement. */
10357
10358 if (is_notif != nullptr)
10359 return val;
10360 }
10361 }
10362 }
10363
10364 /* Kill any new fork children of inferior INF that haven't been
10365 processed by follow_fork. */
10366
10367 void
10368 remote_target::kill_new_fork_children (inferior *inf)
10369 {
10370 remote_state *rs = get_remote_state ();
10371 const notif_client *notif = &notif_client_stop;
10372
10373 /* Kill the fork child threads of any threads in inferior INF that are stopped
10374 at a fork event. */
10375 for (thread_info *thread : inf->non_exited_threads ())
10376 {
10377 const target_waitstatus *ws = thread_pending_fork_status (thread);
10378
10379 if (ws == nullptr)
10380 continue;
10381
10382 int child_pid = ws->child_ptid ().pid ();
10383 int res = remote_vkill (child_pid);
10384
10385 if (res != 0)
10386 error (_("Can't kill fork child process %d"), child_pid);
10387 }
10388
10389 /* Check for any pending fork events (not reported or processed yet)
10390 in inferior INF and kill those fork child threads as well. */
10391 remote_notif_get_pending_events (notif);
10392 for (auto &event : rs->stop_reply_queue)
10393 {
10394 if (event->ptid.pid () != inf->pid)
10395 continue;
10396
10397 if (!is_fork_status (event->ws.kind ()))
10398 continue;
10399
10400 int child_pid = event->ws.child_ptid ().pid ();
10401 int res = remote_vkill (child_pid);
10402
10403 if (res != 0)
10404 error (_("Can't kill fork child process %d"), child_pid);
10405 }
10406 }
10407
10408 \f
10409 /* Target hook to kill the current inferior. */
10410
10411 void
10412 remote_target::kill ()
10413 {
10414 int res = -1;
10415 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10416
10417 gdb_assert (inf != nullptr);
10418
10419 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10420 {
10421 /* If we're stopped while forking and we haven't followed yet,
10422 kill the child task. We need to do this before killing the
10423 parent task because if this is a vfork then the parent will
10424 be sleeping. */
10425 kill_new_fork_children (inf);
10426
10427 res = remote_vkill (inf->pid);
10428 if (res == 0)
10429 {
10430 target_mourn_inferior (inferior_ptid);
10431 return;
10432 }
10433 }
10434
10435 /* If we are in 'target remote' mode and we are killing the only
10436 inferior, then we will tell gdbserver to exit and unpush the
10437 target. */
10438 if (res == -1 && !m_features.remote_multi_process_p ()
10439 && number_of_live_inferiors (this) == 1)
10440 {
10441 remote_kill_k ();
10442
10443 /* We've killed the remote end, we get to mourn it. If we are
10444 not in extended mode, mourning the inferior also unpushes
10445 remote_ops from the target stack, which closes the remote
10446 connection. */
10447 target_mourn_inferior (inferior_ptid);
10448
10449 return;
10450 }
10451
10452 error (_("Can't kill process"));
10453 }
10454
10455 /* Send a kill request to the target using the 'vKill' packet. */
10456
10457 int
10458 remote_target::remote_vkill (int pid)
10459 {
10460 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10461 return -1;
10462
10463 remote_state *rs = get_remote_state ();
10464
10465 /* Tell the remote target to detach. */
10466 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10467 putpkt (rs->buf);
10468 getpkt (&rs->buf);
10469
10470 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10471 {
10472 case PACKET_OK:
10473 return 0;
10474 case PACKET_ERROR:
10475 return 1;
10476 case PACKET_UNKNOWN:
10477 return -1;
10478 default:
10479 internal_error (_("Bad result from packet_ok"));
10480 }
10481 }
10482
10483 /* Send a kill request to the target using the 'k' packet. */
10484
10485 void
10486 remote_target::remote_kill_k ()
10487 {
10488 /* Catch errors so the user can quit from gdb even when we
10489 aren't on speaking terms with the remote system. */
10490 try
10491 {
10492 putpkt ("k");
10493 }
10494 catch (const gdb_exception_error &ex)
10495 {
10496 if (ex.error == TARGET_CLOSE_ERROR)
10497 {
10498 /* If we got an (EOF) error that caused the target
10499 to go away, then we're done, that's what we wanted.
10500 "k" is susceptible to cause a premature EOF, given
10501 that the remote server isn't actually required to
10502 reply to "k", and it can happen that it doesn't
10503 even get to reply ACK to the "k". */
10504 return;
10505 }
10506
10507 /* Otherwise, something went wrong. We didn't actually kill
10508 the target. Just propagate the exception, and let the
10509 user or higher layers decide what to do. */
10510 throw;
10511 }
10512 }
10513
10514 void
10515 remote_target::mourn_inferior ()
10516 {
10517 struct remote_state *rs = get_remote_state ();
10518
10519 /* We're no longer interested in notification events of an inferior
10520 that exited or was killed/detached. */
10521 discard_pending_stop_replies (current_inferior ());
10522
10523 /* In 'target remote' mode with one inferior, we close the connection. */
10524 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10525 {
10526 remote_unpush_target (this);
10527 return;
10528 }
10529
10530 /* In case we got here due to an error, but we're going to stay
10531 connected. */
10532 rs->waiting_for_stop_reply = 0;
10533
10534 /* If the current general thread belonged to the process we just
10535 detached from or has exited, the remote side current general
10536 thread becomes undefined. Considering a case like this:
10537
10538 - We just got here due to a detach.
10539 - The process that we're detaching from happens to immediately
10540 report a global breakpoint being hit in non-stop mode, in the
10541 same thread we had selected before.
10542 - GDB attaches to this process again.
10543 - This event happens to be the next event we handle.
10544
10545 GDB would consider that the current general thread didn't need to
10546 be set on the stub side (with Hg), since for all it knew,
10547 GENERAL_THREAD hadn't changed.
10548
10549 Notice that although in all-stop mode, the remote server always
10550 sets the current thread to the thread reporting the stop event,
10551 that doesn't happen in non-stop mode; in non-stop, the stub *must
10552 not* change the current thread when reporting a breakpoint hit,
10553 due to the decoupling of event reporting and event handling.
10554
10555 To keep things simple, we always invalidate our notion of the
10556 current thread. */
10557 record_currthread (rs, minus_one_ptid);
10558
10559 /* Call common code to mark the inferior as not running. */
10560 generic_mourn_inferior ();
10561 }
10562
10563 bool
10564 extended_remote_target::supports_disable_randomization ()
10565 {
10566 return (m_features.packet_support (PACKET_QDisableRandomization)
10567 == PACKET_ENABLE);
10568 }
10569
10570 void
10571 remote_target::extended_remote_disable_randomization (int val)
10572 {
10573 struct remote_state *rs = get_remote_state ();
10574 char *reply;
10575
10576 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10577 "QDisableRandomization:%x", val);
10578 putpkt (rs->buf);
10579 reply = remote_get_noisy_reply ();
10580 if (*reply == '\0')
10581 error (_("Target does not support QDisableRandomization."));
10582 if (strcmp (reply, "OK") != 0)
10583 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10584 }
10585
10586 int
10587 remote_target::extended_remote_run (const std::string &args)
10588 {
10589 struct remote_state *rs = get_remote_state ();
10590 int len;
10591 const char *remote_exec_file = get_remote_exec_file ();
10592
10593 /* If the user has disabled vRun support, or we have detected that
10594 support is not available, do not try it. */
10595 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10596 return -1;
10597
10598 strcpy (rs->buf.data (), "vRun;");
10599 len = strlen (rs->buf.data ());
10600
10601 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10602 error (_("Remote file name too long for run packet"));
10603 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10604 strlen (remote_exec_file));
10605
10606 if (!args.empty ())
10607 {
10608 int i;
10609
10610 gdb_argv argv (args.c_str ());
10611 for (i = 0; argv[i] != NULL; i++)
10612 {
10613 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10614 error (_("Argument list too long for run packet"));
10615 rs->buf[len++] = ';';
10616 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10617 strlen (argv[i]));
10618 }
10619 }
10620
10621 rs->buf[len++] = '\0';
10622
10623 putpkt (rs->buf);
10624 getpkt (&rs->buf);
10625
10626 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10627 {
10628 case PACKET_OK:
10629 /* We have a wait response. All is well. */
10630 return 0;
10631 case PACKET_UNKNOWN:
10632 return -1;
10633 case PACKET_ERROR:
10634 if (remote_exec_file[0] == '\0')
10635 error (_("Running the default executable on the remote target failed; "
10636 "try \"set remote exec-file\"?"));
10637 else
10638 error (_("Running \"%s\" on the remote target failed"),
10639 remote_exec_file);
10640 default:
10641 gdb_assert_not_reached ("bad switch");
10642 }
10643 }
10644
10645 /* Helper function to send set/unset environment packets. ACTION is
10646 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10647 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10648 sent. */
10649
10650 void
10651 remote_target::send_environment_packet (const char *action,
10652 const char *packet,
10653 const char *value)
10654 {
10655 remote_state *rs = get_remote_state ();
10656
10657 /* Convert the environment variable to an hex string, which
10658 is the best format to be transmitted over the wire. */
10659 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10660 strlen (value));
10661
10662 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10663 "%s:%s", packet, encoded_value.c_str ());
10664
10665 putpkt (rs->buf);
10666 getpkt (&rs->buf);
10667 if (strcmp (rs->buf.data (), "OK") != 0)
10668 warning (_("Unable to %s environment variable '%s' on remote."),
10669 action, value);
10670 }
10671
10672 /* Helper function to handle the QEnvironment* packets. */
10673
10674 void
10675 remote_target::extended_remote_environment_support ()
10676 {
10677 remote_state *rs = get_remote_state ();
10678
10679 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10680 {
10681 putpkt ("QEnvironmentReset");
10682 getpkt (&rs->buf);
10683 if (strcmp (rs->buf.data (), "OK") != 0)
10684 warning (_("Unable to reset environment on remote."));
10685 }
10686
10687 gdb_environ *e = &current_inferior ()->environment;
10688
10689 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10690 != PACKET_DISABLE)
10691 {
10692 for (const std::string &el : e->user_set_env ())
10693 send_environment_packet ("set", "QEnvironmentHexEncoded",
10694 el.c_str ());
10695 }
10696
10697
10698 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10699 for (const std::string &el : e->user_unset_env ())
10700 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10701 }
10702
10703 /* Helper function to set the current working directory for the
10704 inferior in the remote target. */
10705
10706 void
10707 remote_target::extended_remote_set_inferior_cwd ()
10708 {
10709 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10710 {
10711 const std::string &inferior_cwd = current_inferior ()->cwd ();
10712 remote_state *rs = get_remote_state ();
10713
10714 if (!inferior_cwd.empty ())
10715 {
10716 std::string hexpath
10717 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10718 inferior_cwd.size ());
10719
10720 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10721 "QSetWorkingDir:%s", hexpath.c_str ());
10722 }
10723 else
10724 {
10725 /* An empty inferior_cwd means that the user wants us to
10726 reset the remote server's inferior's cwd. */
10727 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10728 "QSetWorkingDir:");
10729 }
10730
10731 putpkt (rs->buf);
10732 getpkt (&rs->buf);
10733 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10734 error (_("\
10735 Remote replied unexpectedly while setting the inferior's working\n\
10736 directory: %s"),
10737 rs->buf.data ());
10738
10739 }
10740 }
10741
10742 /* In the extended protocol we want to be able to do things like
10743 "run" and have them basically work as expected. So we need
10744 a special create_inferior function. We support changing the
10745 executable file and the command line arguments, but not the
10746 environment. */
10747
10748 void
10749 extended_remote_target::create_inferior (const char *exec_file,
10750 const std::string &args,
10751 char **env, int from_tty)
10752 {
10753 int run_worked;
10754 char *stop_reply;
10755 struct remote_state *rs = get_remote_state ();
10756 const char *remote_exec_file = get_remote_exec_file ();
10757
10758 /* If running asynchronously, register the target file descriptor
10759 with the event loop. */
10760 if (target_can_async_p ())
10761 target_async (true);
10762
10763 /* Disable address space randomization if requested (and supported). */
10764 if (supports_disable_randomization ())
10765 extended_remote_disable_randomization (disable_randomization);
10766
10767 /* If startup-with-shell is on, we inform gdbserver to start the
10768 remote inferior using a shell. */
10769 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10770 {
10771 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10772 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10773 putpkt (rs->buf);
10774 getpkt (&rs->buf);
10775 if (strcmp (rs->buf.data (), "OK") != 0)
10776 error (_("\
10777 Remote replied unexpectedly while setting startup-with-shell: %s"),
10778 rs->buf.data ());
10779 }
10780
10781 extended_remote_environment_support ();
10782
10783 extended_remote_set_inferior_cwd ();
10784
10785 /* Now restart the remote server. */
10786 run_worked = extended_remote_run (args) != -1;
10787 if (!run_worked)
10788 {
10789 /* vRun was not supported. Fail if we need it to do what the
10790 user requested. */
10791 if (remote_exec_file[0])
10792 error (_("Remote target does not support \"set remote exec-file\""));
10793 if (!args.empty ())
10794 error (_("Remote target does not support \"set args\" or run ARGS"));
10795
10796 /* Fall back to "R". */
10797 extended_remote_restart ();
10798 }
10799
10800 /* vRun's success return is a stop reply. */
10801 stop_reply = run_worked ? rs->buf.data () : NULL;
10802 add_current_inferior_and_thread (stop_reply);
10803
10804 /* Get updated offsets, if the stub uses qOffsets. */
10805 get_offsets ();
10806 }
10807 \f
10808
10809 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10810 the list of conditions (in agent expression bytecode format), if any, the
10811 target needs to evaluate. The output is placed into the packet buffer
10812 started from BUF and ended at BUF_END. */
10813
10814 static int
10815 remote_add_target_side_condition (struct gdbarch *gdbarch,
10816 struct bp_target_info *bp_tgt, char *buf,
10817 char *buf_end)
10818 {
10819 if (bp_tgt->conditions.empty ())
10820 return 0;
10821
10822 buf += strlen (buf);
10823 xsnprintf (buf, buf_end - buf, "%s", ";");
10824 buf++;
10825
10826 /* Send conditions to the target. */
10827 for (agent_expr *aexpr : bp_tgt->conditions)
10828 {
10829 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10830 buf += strlen (buf);
10831 for (int i = 0; i < aexpr->buf.size (); ++i)
10832 buf = pack_hex_byte (buf, aexpr->buf[i]);
10833 *buf = '\0';
10834 }
10835 return 0;
10836 }
10837
10838 static void
10839 remote_add_target_side_commands (struct gdbarch *gdbarch,
10840 struct bp_target_info *bp_tgt, char *buf)
10841 {
10842 if (bp_tgt->tcommands.empty ())
10843 return;
10844
10845 buf += strlen (buf);
10846
10847 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10848 buf += strlen (buf);
10849
10850 /* Concatenate all the agent expressions that are commands into the
10851 cmds parameter. */
10852 for (agent_expr *aexpr : bp_tgt->tcommands)
10853 {
10854 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10855 buf += strlen (buf);
10856 for (int i = 0; i < aexpr->buf.size (); ++i)
10857 buf = pack_hex_byte (buf, aexpr->buf[i]);
10858 *buf = '\0';
10859 }
10860 }
10861
10862 /* Insert a breakpoint. On targets that have software breakpoint
10863 support, we ask the remote target to do the work; on targets
10864 which don't, we insert a traditional memory breakpoint. */
10865
10866 int
10867 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10868 struct bp_target_info *bp_tgt)
10869 {
10870 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10871 If it succeeds, then set the support to PACKET_ENABLE. If it
10872 fails, and the user has explicitly requested the Z support then
10873 report an error, otherwise, mark it disabled and go on. */
10874
10875 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10876 {
10877 CORE_ADDR addr = bp_tgt->reqstd_address;
10878 struct remote_state *rs;
10879 char *p, *endbuf;
10880
10881 /* Make sure the remote is pointing at the right process, if
10882 necessary. */
10883 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10884 set_general_process ();
10885
10886 rs = get_remote_state ();
10887 p = rs->buf.data ();
10888 endbuf = p + get_remote_packet_size ();
10889
10890 *(p++) = 'Z';
10891 *(p++) = '0';
10892 *(p++) = ',';
10893 addr = (ULONGEST) remote_address_masked (addr);
10894 p += hexnumstr (p, addr);
10895 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10896
10897 if (supports_evaluation_of_breakpoint_conditions ())
10898 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10899
10900 if (can_run_breakpoint_commands ())
10901 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10902
10903 putpkt (rs->buf);
10904 getpkt (&rs->buf);
10905
10906 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10907 {
10908 case PACKET_ERROR:
10909 return -1;
10910 case PACKET_OK:
10911 return 0;
10912 case PACKET_UNKNOWN:
10913 break;
10914 }
10915 }
10916
10917 /* If this breakpoint has target-side commands but this stub doesn't
10918 support Z0 packets, throw error. */
10919 if (!bp_tgt->tcommands.empty ())
10920 throw_error (NOT_SUPPORTED_ERROR, _("\
10921 Target doesn't support breakpoints that have target side commands."));
10922
10923 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10924 }
10925
10926 int
10927 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10928 struct bp_target_info *bp_tgt,
10929 enum remove_bp_reason reason)
10930 {
10931 CORE_ADDR addr = bp_tgt->placed_address;
10932 struct remote_state *rs = get_remote_state ();
10933
10934 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10935 {
10936 char *p = rs->buf.data ();
10937 char *endbuf = p + get_remote_packet_size ();
10938
10939 /* Make sure the remote is pointing at the right process, if
10940 necessary. */
10941 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10942 set_general_process ();
10943
10944 *(p++) = 'z';
10945 *(p++) = '0';
10946 *(p++) = ',';
10947
10948 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10949 p += hexnumstr (p, addr);
10950 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10951
10952 putpkt (rs->buf);
10953 getpkt (&rs->buf);
10954
10955 return (rs->buf[0] == 'E');
10956 }
10957
10958 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10959 }
10960
10961 static enum Z_packet_type
10962 watchpoint_to_Z_packet (int type)
10963 {
10964 switch (type)
10965 {
10966 case hw_write:
10967 return Z_PACKET_WRITE_WP;
10968 break;
10969 case hw_read:
10970 return Z_PACKET_READ_WP;
10971 break;
10972 case hw_access:
10973 return Z_PACKET_ACCESS_WP;
10974 break;
10975 default:
10976 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10977 }
10978 }
10979
10980 int
10981 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10982 enum target_hw_bp_type type, struct expression *cond)
10983 {
10984 struct remote_state *rs = get_remote_state ();
10985 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10986 char *p;
10987 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10988
10989 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10990 + to_underlying (packet))) == PACKET_DISABLE)
10991 return 1;
10992
10993 /* Make sure the remote is pointing at the right process, if
10994 necessary. */
10995 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10996 set_general_process ();
10997
10998 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10999 p = strchr (rs->buf.data (), '\0');
11000 addr = remote_address_masked (addr);
11001 p += hexnumstr (p, (ULONGEST) addr);
11002 xsnprintf (p, endbuf - p, ",%x", len);
11003
11004 putpkt (rs->buf);
11005 getpkt (&rs->buf);
11006
11007 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11008 + to_underlying (packet))))
11009 {
11010 case PACKET_ERROR:
11011 return -1;
11012 case PACKET_UNKNOWN:
11013 return 1;
11014 case PACKET_OK:
11015 return 0;
11016 }
11017 internal_error (_("remote_insert_watchpoint: reached end of function"));
11018 }
11019
11020 bool
11021 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11022 CORE_ADDR start, int length)
11023 {
11024 CORE_ADDR diff = remote_address_masked (addr - start);
11025
11026 return diff < length;
11027 }
11028
11029
11030 int
11031 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11032 enum target_hw_bp_type type, struct expression *cond)
11033 {
11034 struct remote_state *rs = get_remote_state ();
11035 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11036 char *p;
11037 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11038
11039 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11040 + to_underlying (packet))) == PACKET_DISABLE)
11041 return -1;
11042
11043 /* Make sure the remote is pointing at the right process, if
11044 necessary. */
11045 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11046 set_general_process ();
11047
11048 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11049 p = strchr (rs->buf.data (), '\0');
11050 addr = remote_address_masked (addr);
11051 p += hexnumstr (p, (ULONGEST) addr);
11052 xsnprintf (p, endbuf - p, ",%x", len);
11053 putpkt (rs->buf);
11054 getpkt (&rs->buf);
11055
11056 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11057 + to_underlying (packet))))
11058 {
11059 case PACKET_ERROR:
11060 case PACKET_UNKNOWN:
11061 return -1;
11062 case PACKET_OK:
11063 return 0;
11064 }
11065 internal_error (_("remote_remove_watchpoint: reached end of function"));
11066 }
11067
11068
11069 static int remote_hw_watchpoint_limit = -1;
11070 static int remote_hw_watchpoint_length_limit = -1;
11071 static int remote_hw_breakpoint_limit = -1;
11072
11073 int
11074 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11075 {
11076 if (remote_hw_watchpoint_length_limit == 0)
11077 return 0;
11078 else if (remote_hw_watchpoint_length_limit < 0)
11079 return 1;
11080 else if (len <= remote_hw_watchpoint_length_limit)
11081 return 1;
11082 else
11083 return 0;
11084 }
11085
11086 int
11087 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11088 {
11089 if (type == bp_hardware_breakpoint)
11090 {
11091 if (remote_hw_breakpoint_limit == 0)
11092 return 0;
11093 else if (remote_hw_breakpoint_limit < 0)
11094 return 1;
11095 else if (cnt <= remote_hw_breakpoint_limit)
11096 return 1;
11097 }
11098 else
11099 {
11100 if (remote_hw_watchpoint_limit == 0)
11101 return 0;
11102 else if (remote_hw_watchpoint_limit < 0)
11103 return 1;
11104 else if (ot)
11105 return -1;
11106 else if (cnt <= remote_hw_watchpoint_limit)
11107 return 1;
11108 }
11109 return -1;
11110 }
11111
11112 /* The to_stopped_by_sw_breakpoint method of target remote. */
11113
11114 bool
11115 remote_target::stopped_by_sw_breakpoint ()
11116 {
11117 struct thread_info *thread = inferior_thread ();
11118
11119 return (thread->priv != NULL
11120 && (get_remote_thread_info (thread)->stop_reason
11121 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11122 }
11123
11124 /* The to_supports_stopped_by_sw_breakpoint method of target
11125 remote. */
11126
11127 bool
11128 remote_target::supports_stopped_by_sw_breakpoint ()
11129 {
11130 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11131 }
11132
11133 /* The to_stopped_by_hw_breakpoint method of target remote. */
11134
11135 bool
11136 remote_target::stopped_by_hw_breakpoint ()
11137 {
11138 struct thread_info *thread = inferior_thread ();
11139
11140 return (thread->priv != NULL
11141 && (get_remote_thread_info (thread)->stop_reason
11142 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11143 }
11144
11145 /* The to_supports_stopped_by_hw_breakpoint method of target
11146 remote. */
11147
11148 bool
11149 remote_target::supports_stopped_by_hw_breakpoint ()
11150 {
11151 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11152 }
11153
11154 bool
11155 remote_target::stopped_by_watchpoint ()
11156 {
11157 struct thread_info *thread = inferior_thread ();
11158
11159 return (thread->priv != NULL
11160 && (get_remote_thread_info (thread)->stop_reason
11161 == TARGET_STOPPED_BY_WATCHPOINT));
11162 }
11163
11164 bool
11165 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11166 {
11167 struct thread_info *thread = inferior_thread ();
11168
11169 if (thread->priv != NULL
11170 && (get_remote_thread_info (thread)->stop_reason
11171 == TARGET_STOPPED_BY_WATCHPOINT))
11172 {
11173 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11174 return true;
11175 }
11176
11177 return false;
11178 }
11179
11180
11181 int
11182 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11183 struct bp_target_info *bp_tgt)
11184 {
11185 CORE_ADDR addr = bp_tgt->reqstd_address;
11186 struct remote_state *rs;
11187 char *p, *endbuf;
11188 char *message;
11189
11190 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11191 return -1;
11192
11193 /* Make sure the remote is pointing at the right process, if
11194 necessary. */
11195 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11196 set_general_process ();
11197
11198 rs = get_remote_state ();
11199 p = rs->buf.data ();
11200 endbuf = p + get_remote_packet_size ();
11201
11202 *(p++) = 'Z';
11203 *(p++) = '1';
11204 *(p++) = ',';
11205
11206 addr = remote_address_masked (addr);
11207 p += hexnumstr (p, (ULONGEST) addr);
11208 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11209
11210 if (supports_evaluation_of_breakpoint_conditions ())
11211 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11212
11213 if (can_run_breakpoint_commands ())
11214 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11215
11216 putpkt (rs->buf);
11217 getpkt (&rs->buf);
11218
11219 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11220 {
11221 case PACKET_ERROR:
11222 if (rs->buf[1] == '.')
11223 {
11224 message = strchr (&rs->buf[2], '.');
11225 if (message)
11226 error (_("Remote failure reply: %s"), message + 1);
11227 }
11228 return -1;
11229 case PACKET_UNKNOWN:
11230 return -1;
11231 case PACKET_OK:
11232 return 0;
11233 }
11234 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11235 }
11236
11237
11238 int
11239 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11240 struct bp_target_info *bp_tgt)
11241 {
11242 CORE_ADDR addr;
11243 struct remote_state *rs = get_remote_state ();
11244 char *p = rs->buf.data ();
11245 char *endbuf = p + get_remote_packet_size ();
11246
11247 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11248 return -1;
11249
11250 /* Make sure the remote is pointing at the right process, if
11251 necessary. */
11252 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11253 set_general_process ();
11254
11255 *(p++) = 'z';
11256 *(p++) = '1';
11257 *(p++) = ',';
11258
11259 addr = remote_address_masked (bp_tgt->placed_address);
11260 p += hexnumstr (p, (ULONGEST) addr);
11261 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11262
11263 putpkt (rs->buf);
11264 getpkt (&rs->buf);
11265
11266 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11267 {
11268 case PACKET_ERROR:
11269 case PACKET_UNKNOWN:
11270 return -1;
11271 case PACKET_OK:
11272 return 0;
11273 }
11274 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11275 }
11276
11277 /* Verify memory using the "qCRC:" request. */
11278
11279 int
11280 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11281 {
11282 struct remote_state *rs = get_remote_state ();
11283 unsigned long host_crc, target_crc;
11284 char *tmp;
11285
11286 /* It doesn't make sense to use qCRC if the remote target is
11287 connected but not running. */
11288 if (target_has_execution ()
11289 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11290 {
11291 enum packet_result result;
11292
11293 /* Make sure the remote is pointing at the right process. */
11294 set_general_process ();
11295
11296 /* FIXME: assumes lma can fit into long. */
11297 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11298 (long) lma, (long) size);
11299 putpkt (rs->buf);
11300
11301 /* Be clever; compute the host_crc before waiting for target
11302 reply. */
11303 host_crc = xcrc32 (data, size, 0xffffffff);
11304
11305 getpkt (&rs->buf);
11306
11307 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11308 if (result == PACKET_ERROR)
11309 return -1;
11310 else if (result == PACKET_OK)
11311 {
11312 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11313 target_crc = target_crc * 16 + fromhex (*tmp);
11314
11315 return (host_crc == target_crc);
11316 }
11317 }
11318
11319 return simple_verify_memory (this, data, lma, size);
11320 }
11321
11322 /* compare-sections command
11323
11324 With no arguments, compares each loadable section in the exec bfd
11325 with the same memory range on the target, and reports mismatches.
11326 Useful for verifying the image on the target against the exec file. */
11327
11328 static void
11329 compare_sections_command (const char *args, int from_tty)
11330 {
11331 asection *s;
11332 const char *sectname;
11333 bfd_size_type size;
11334 bfd_vma lma;
11335 int matched = 0;
11336 int mismatched = 0;
11337 int res;
11338 int read_only = 0;
11339
11340 if (!current_program_space->exec_bfd ())
11341 error (_("command cannot be used without an exec file"));
11342
11343 if (args != NULL && strcmp (args, "-r") == 0)
11344 {
11345 read_only = 1;
11346 args = NULL;
11347 }
11348
11349 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11350 {
11351 if (!(s->flags & SEC_LOAD))
11352 continue; /* Skip non-loadable section. */
11353
11354 if (read_only && (s->flags & SEC_READONLY) == 0)
11355 continue; /* Skip writeable sections */
11356
11357 size = bfd_section_size (s);
11358 if (size == 0)
11359 continue; /* Skip zero-length section. */
11360
11361 sectname = bfd_section_name (s);
11362 if (args && strcmp (args, sectname) != 0)
11363 continue; /* Not the section selected by user. */
11364
11365 matched = 1; /* Do this section. */
11366 lma = s->lma;
11367
11368 gdb::byte_vector sectdata (size);
11369 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11370 sectdata.data (), 0, size);
11371
11372 res = target_verify_memory (sectdata.data (), lma, size);
11373
11374 if (res == -1)
11375 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11376 paddress (current_inferior ()->arch (), lma),
11377 paddress (current_inferior ()->arch (), lma + size));
11378
11379 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11380 paddress (current_inferior ()->arch (), lma),
11381 paddress (current_inferior ()->arch (), lma + size));
11382 if (res)
11383 gdb_printf ("matched.\n");
11384 else
11385 {
11386 gdb_printf ("MIS-MATCHED!\n");
11387 mismatched++;
11388 }
11389 }
11390 if (mismatched > 0)
11391 warning (_("One or more sections of the target image does "
11392 "not match the loaded file"));
11393 if (args && !matched)
11394 gdb_printf (_("No loaded section named '%s'.\n"), args);
11395 }
11396
11397 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11398 into remote target. The number of bytes written to the remote
11399 target is returned, or -1 for error. */
11400
11401 target_xfer_status
11402 remote_target::remote_write_qxfer (const char *object_name,
11403 const char *annex, const gdb_byte *writebuf,
11404 ULONGEST offset, LONGEST len,
11405 ULONGEST *xfered_len,
11406 const unsigned int which_packet)
11407 {
11408 int i, buf_len;
11409 ULONGEST n;
11410 struct remote_state *rs = get_remote_state ();
11411 int max_size = get_memory_write_packet_size ();
11412
11413 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11414 return TARGET_XFER_E_IO;
11415
11416 /* Insert header. */
11417 i = snprintf (rs->buf.data (), max_size,
11418 "qXfer:%s:write:%s:%s:",
11419 object_name, annex ? annex : "",
11420 phex_nz (offset, sizeof offset));
11421 max_size -= (i + 1);
11422
11423 /* Escape as much data as fits into rs->buf. */
11424 buf_len = remote_escape_output
11425 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11426
11427 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11428 || getpkt (&rs->buf) < 0
11429 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11430 return TARGET_XFER_E_IO;
11431
11432 unpack_varlen_hex (rs->buf.data (), &n);
11433
11434 *xfered_len = n;
11435 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11436 }
11437
11438 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11439 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11440 number of bytes read is returned, or 0 for EOF, or -1 for error.
11441 The number of bytes read may be less than LEN without indicating an
11442 EOF. PACKET is checked and updated to indicate whether the remote
11443 target supports this object. */
11444
11445 target_xfer_status
11446 remote_target::remote_read_qxfer (const char *object_name,
11447 const char *annex,
11448 gdb_byte *readbuf, ULONGEST offset,
11449 LONGEST len,
11450 ULONGEST *xfered_len,
11451 const unsigned int which_packet)
11452 {
11453 struct remote_state *rs = get_remote_state ();
11454 LONGEST i, n, packet_len;
11455
11456 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11457 return TARGET_XFER_E_IO;
11458
11459 /* Check whether we've cached an end-of-object packet that matches
11460 this request. */
11461 if (rs->finished_object)
11462 {
11463 if (strcmp (object_name, rs->finished_object) == 0
11464 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11465 && offset == rs->finished_offset)
11466 return TARGET_XFER_EOF;
11467
11468
11469 /* Otherwise, we're now reading something different. Discard
11470 the cache. */
11471 xfree (rs->finished_object);
11472 xfree (rs->finished_annex);
11473 rs->finished_object = NULL;
11474 rs->finished_annex = NULL;
11475 }
11476
11477 /* Request only enough to fit in a single packet. The actual data
11478 may not, since we don't know how much of it will need to be escaped;
11479 the target is free to respond with slightly less data. We subtract
11480 five to account for the response type and the protocol frame. */
11481 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11482 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11483 "qXfer:%s:read:%s:%s,%s",
11484 object_name, annex ? annex : "",
11485 phex_nz (offset, sizeof offset),
11486 phex_nz (n, sizeof n));
11487 i = putpkt (rs->buf);
11488 if (i < 0)
11489 return TARGET_XFER_E_IO;
11490
11491 rs->buf[0] = '\0';
11492 packet_len = getpkt (&rs->buf);
11493 if (packet_len < 0
11494 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11495 return TARGET_XFER_E_IO;
11496
11497 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11498 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11499
11500 /* 'm' means there is (or at least might be) more data after this
11501 batch. That does not make sense unless there's at least one byte
11502 of data in this reply. */
11503 if (rs->buf[0] == 'm' && packet_len == 1)
11504 error (_("Remote qXfer reply contained no data."));
11505
11506 /* Got some data. */
11507 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11508 packet_len - 1, readbuf, n);
11509
11510 /* 'l' is an EOF marker, possibly including a final block of data,
11511 or possibly empty. If we have the final block of a non-empty
11512 object, record this fact to bypass a subsequent partial read. */
11513 if (rs->buf[0] == 'l' && offset + i > 0)
11514 {
11515 rs->finished_object = xstrdup (object_name);
11516 rs->finished_annex = xstrdup (annex ? annex : "");
11517 rs->finished_offset = offset + i;
11518 }
11519
11520 if (i == 0)
11521 return TARGET_XFER_EOF;
11522 else
11523 {
11524 *xfered_len = i;
11525 return TARGET_XFER_OK;
11526 }
11527 }
11528
11529 enum target_xfer_status
11530 remote_target::xfer_partial (enum target_object object,
11531 const char *annex, gdb_byte *readbuf,
11532 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11533 ULONGEST *xfered_len)
11534 {
11535 struct remote_state *rs;
11536 int i;
11537 char *p2;
11538 char query_type;
11539 int unit_size
11540 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11541
11542 set_remote_traceframe ();
11543 set_general_thread (inferior_ptid);
11544
11545 rs = get_remote_state ();
11546
11547 /* Handle memory using the standard memory routines. */
11548 if (object == TARGET_OBJECT_MEMORY)
11549 {
11550 /* If the remote target is connected but not running, we should
11551 pass this request down to a lower stratum (e.g. the executable
11552 file). */
11553 if (!target_has_execution ())
11554 return TARGET_XFER_EOF;
11555
11556 if (writebuf != NULL)
11557 return remote_write_bytes (offset, writebuf, len, unit_size,
11558 xfered_len);
11559 else
11560 return remote_read_bytes (offset, readbuf, len, unit_size,
11561 xfered_len);
11562 }
11563
11564 /* Handle extra signal info using qxfer packets. */
11565 if (object == TARGET_OBJECT_SIGNAL_INFO)
11566 {
11567 if (readbuf)
11568 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11569 xfered_len, PACKET_qXfer_siginfo_read);
11570 else
11571 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11572 xfered_len, PACKET_qXfer_siginfo_write);
11573 }
11574
11575 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11576 {
11577 if (readbuf)
11578 return remote_read_qxfer ("statictrace", annex,
11579 readbuf, offset, len, xfered_len,
11580 PACKET_qXfer_statictrace_read);
11581 else
11582 return TARGET_XFER_E_IO;
11583 }
11584
11585 /* Only handle flash writes. */
11586 if (writebuf != NULL)
11587 {
11588 switch (object)
11589 {
11590 case TARGET_OBJECT_FLASH:
11591 return remote_flash_write (offset, len, xfered_len,
11592 writebuf);
11593
11594 default:
11595 return TARGET_XFER_E_IO;
11596 }
11597 }
11598
11599 /* Map pre-existing objects onto letters. DO NOT do this for new
11600 objects!!! Instead specify new query packets. */
11601 switch (object)
11602 {
11603 case TARGET_OBJECT_AVR:
11604 query_type = 'R';
11605 break;
11606
11607 case TARGET_OBJECT_AUXV:
11608 gdb_assert (annex == NULL);
11609 return remote_read_qxfer
11610 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11611
11612 case TARGET_OBJECT_AVAILABLE_FEATURES:
11613 return remote_read_qxfer
11614 ("features", annex, readbuf, offset, len, xfered_len,
11615 PACKET_qXfer_features);
11616
11617 case TARGET_OBJECT_LIBRARIES:
11618 return remote_read_qxfer
11619 ("libraries", annex, readbuf, offset, len, xfered_len,
11620 PACKET_qXfer_libraries);
11621
11622 case TARGET_OBJECT_LIBRARIES_SVR4:
11623 return remote_read_qxfer
11624 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11625 PACKET_qXfer_libraries_svr4);
11626
11627 case TARGET_OBJECT_MEMORY_MAP:
11628 gdb_assert (annex == NULL);
11629 return remote_read_qxfer
11630 ("memory-map", annex, readbuf, offset, len, xfered_len,
11631 PACKET_qXfer_memory_map);
11632
11633 case TARGET_OBJECT_OSDATA:
11634 /* Should only get here if we're connected. */
11635 gdb_assert (rs->remote_desc);
11636 return remote_read_qxfer
11637 ("osdata", annex, readbuf, offset, len, xfered_len,
11638 PACKET_qXfer_osdata);
11639
11640 case TARGET_OBJECT_THREADS:
11641 gdb_assert (annex == NULL);
11642 return remote_read_qxfer
11643 ("threads", annex, readbuf, offset, len, xfered_len,
11644 PACKET_qXfer_threads);
11645
11646 case TARGET_OBJECT_TRACEFRAME_INFO:
11647 gdb_assert (annex == NULL);
11648 return remote_read_qxfer
11649 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11650 PACKET_qXfer_traceframe_info);
11651
11652 case TARGET_OBJECT_FDPIC:
11653 return remote_read_qxfer
11654 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11655
11656 case TARGET_OBJECT_OPENVMS_UIB:
11657 return remote_read_qxfer
11658 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11659
11660 case TARGET_OBJECT_BTRACE:
11661 return remote_read_qxfer
11662 ("btrace", annex, readbuf, offset, len, xfered_len,
11663 PACKET_qXfer_btrace);
11664
11665 case TARGET_OBJECT_BTRACE_CONF:
11666 return remote_read_qxfer
11667 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11668 PACKET_qXfer_btrace_conf);
11669
11670 case TARGET_OBJECT_EXEC_FILE:
11671 return remote_read_qxfer
11672 ("exec-file", annex, readbuf, offset, len, xfered_len,
11673 PACKET_qXfer_exec_file);
11674
11675 default:
11676 return TARGET_XFER_E_IO;
11677 }
11678
11679 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11680 large enough let the caller deal with it. */
11681 if (len < get_remote_packet_size ())
11682 return TARGET_XFER_E_IO;
11683 len = get_remote_packet_size ();
11684
11685 /* Except for querying the minimum buffer size, target must be open. */
11686 if (!rs->remote_desc)
11687 error (_("remote query is only available after target open"));
11688
11689 gdb_assert (annex != NULL);
11690 gdb_assert (readbuf != NULL);
11691
11692 p2 = rs->buf.data ();
11693 *p2++ = 'q';
11694 *p2++ = query_type;
11695
11696 /* We used one buffer char for the remote protocol q command and
11697 another for the query type. As the remote protocol encapsulation
11698 uses 4 chars plus one extra in case we are debugging
11699 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11700 string. */
11701 i = 0;
11702 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11703 {
11704 /* Bad caller may have sent forbidden characters. */
11705 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11706 *p2++ = annex[i];
11707 i++;
11708 }
11709 *p2 = '\0';
11710 gdb_assert (annex[i] == '\0');
11711
11712 i = putpkt (rs->buf);
11713 if (i < 0)
11714 return TARGET_XFER_E_IO;
11715
11716 getpkt (&rs->buf);
11717 strcpy ((char *) readbuf, rs->buf.data ());
11718
11719 *xfered_len = strlen ((char *) readbuf);
11720 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11721 }
11722
11723 /* Implementation of to_get_memory_xfer_limit. */
11724
11725 ULONGEST
11726 remote_target::get_memory_xfer_limit ()
11727 {
11728 return get_memory_write_packet_size ();
11729 }
11730
11731 int
11732 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11733 const gdb_byte *pattern, ULONGEST pattern_len,
11734 CORE_ADDR *found_addrp)
11735 {
11736 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11737 struct remote_state *rs = get_remote_state ();
11738 int max_size = get_memory_write_packet_size ();
11739
11740 /* Number of packet bytes used to encode the pattern;
11741 this could be more than PATTERN_LEN due to escape characters. */
11742 int escaped_pattern_len;
11743 /* Amount of pattern that was encodable in the packet. */
11744 int used_pattern_len;
11745 int i;
11746 int found;
11747 ULONGEST found_addr;
11748
11749 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11750 {
11751 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11752 == len);
11753 };
11754
11755 /* Don't go to the target if we don't have to. This is done before
11756 checking packet_support to avoid the possibility that a success for this
11757 edge case means the facility works in general. */
11758 if (pattern_len > search_space_len)
11759 return 0;
11760 if (pattern_len == 0)
11761 {
11762 *found_addrp = start_addr;
11763 return 1;
11764 }
11765
11766 /* If we already know the packet isn't supported, fall back to the simple
11767 way of searching memory. */
11768
11769 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11770 {
11771 /* Target doesn't provided special support, fall back and use the
11772 standard support (copy memory and do the search here). */
11773 return simple_search_memory (read_memory, start_addr, search_space_len,
11774 pattern, pattern_len, found_addrp);
11775 }
11776
11777 /* Make sure the remote is pointing at the right process. */
11778 set_general_process ();
11779
11780 /* Insert header. */
11781 i = snprintf (rs->buf.data (), max_size,
11782 "qSearch:memory:%s;%s;",
11783 phex_nz (start_addr, addr_size),
11784 phex_nz (search_space_len, sizeof (search_space_len)));
11785 max_size -= (i + 1);
11786
11787 /* Escape as much data as fits into rs->buf. */
11788 escaped_pattern_len =
11789 remote_escape_output (pattern, pattern_len, 1,
11790 (gdb_byte *) rs->buf.data () + i,
11791 &used_pattern_len, max_size);
11792
11793 /* Bail if the pattern is too large. */
11794 if (used_pattern_len != pattern_len)
11795 error (_("Pattern is too large to transmit to remote target."));
11796
11797 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11798 || getpkt (&rs->buf) < 0
11799 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11800 {
11801 /* The request may not have worked because the command is not
11802 supported. If so, fall back to the simple way. */
11803 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11804 {
11805 return simple_search_memory (read_memory, start_addr, search_space_len,
11806 pattern, pattern_len, found_addrp);
11807 }
11808 return -1;
11809 }
11810
11811 if (rs->buf[0] == '0')
11812 found = 0;
11813 else if (rs->buf[0] == '1')
11814 {
11815 found = 1;
11816 if (rs->buf[1] != ',')
11817 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11818 unpack_varlen_hex (&rs->buf[2], &found_addr);
11819 *found_addrp = found_addr;
11820 }
11821 else
11822 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11823
11824 return found;
11825 }
11826
11827 void
11828 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11829 {
11830 struct remote_state *rs = get_remote_state ();
11831 char *p = rs->buf.data ();
11832
11833 if (!rs->remote_desc)
11834 error (_("remote rcmd is only available after target open"));
11835
11836 /* Send a NULL command across as an empty command. */
11837 if (command == NULL)
11838 command = "";
11839
11840 /* The query prefix. */
11841 strcpy (rs->buf.data (), "qRcmd,");
11842 p = strchr (rs->buf.data (), '\0');
11843
11844 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11845 > get_remote_packet_size ())
11846 error (_("\"monitor\" command ``%s'' is too long."), command);
11847
11848 /* Encode the actual command. */
11849 bin2hex ((const gdb_byte *) command, p, strlen (command));
11850
11851 if (putpkt (rs->buf) < 0)
11852 error (_("Communication problem with target."));
11853
11854 /* get/display the response */
11855 while (1)
11856 {
11857 char *buf;
11858
11859 /* XXX - see also remote_get_noisy_reply(). */
11860 QUIT; /* Allow user to bail out with ^C. */
11861 rs->buf[0] = '\0';
11862 if (getpkt (&rs->buf) == -1)
11863 {
11864 /* Timeout. Continue to (try to) read responses.
11865 This is better than stopping with an error, assuming the stub
11866 is still executing the (long) monitor command.
11867 If needed, the user can interrupt gdb using C-c, obtaining
11868 an effect similar to stop on timeout. */
11869 continue;
11870 }
11871 buf = rs->buf.data ();
11872 if (buf[0] == '\0')
11873 error (_("Target does not support this command."));
11874 if (buf[0] == 'O' && buf[1] != 'K')
11875 {
11876 remote_console_output (buf + 1); /* 'O' message from stub. */
11877 continue;
11878 }
11879 if (strcmp (buf, "OK") == 0)
11880 break;
11881 if (strlen (buf) == 3 && buf[0] == 'E'
11882 && isxdigit (buf[1]) && isxdigit (buf[2]))
11883 {
11884 error (_("Protocol error with Rcmd"));
11885 }
11886 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11887 {
11888 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11889
11890 gdb_putc (c, outbuf);
11891 }
11892 break;
11893 }
11894 }
11895
11896 std::vector<mem_region>
11897 remote_target::memory_map ()
11898 {
11899 std::vector<mem_region> result;
11900 gdb::optional<gdb::char_vector> text
11901 = target_read_stralloc (current_inferior ()->top_target (),
11902 TARGET_OBJECT_MEMORY_MAP, NULL);
11903
11904 if (text)
11905 result = parse_memory_map (text->data ());
11906
11907 return result;
11908 }
11909
11910 /* Set of callbacks used to implement the 'maint packet' command. */
11911
11912 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11913 {
11914 /* Called before the packet is sent. BUF is the packet content before
11915 the protocol specific prefix, suffix, and escaping is added. */
11916
11917 void sending (gdb::array_view<const char> &buf) override
11918 {
11919 gdb_puts ("sending: ");
11920 print_packet (buf);
11921 gdb_puts ("\n");
11922 }
11923
11924 /* Called with BUF, the reply from the remote target. */
11925
11926 void received (gdb::array_view<const char> &buf) override
11927 {
11928 gdb_puts ("received: \"");
11929 print_packet (buf);
11930 gdb_puts ("\"\n");
11931 }
11932
11933 private:
11934
11935 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11936 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11937
11938 static void
11939 print_packet (gdb::array_view<const char> &buf)
11940 {
11941 string_file stb;
11942
11943 for (int i = 0; i < buf.size (); ++i)
11944 {
11945 gdb_byte c = buf[i];
11946 if (isprint (c))
11947 gdb_putc (c, &stb);
11948 else
11949 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11950 }
11951
11952 gdb_puts (stb.string ().c_str ());
11953 }
11954 };
11955
11956 /* See remote.h. */
11957
11958 void
11959 send_remote_packet (gdb::array_view<const char> &buf,
11960 send_remote_packet_callbacks *callbacks)
11961 {
11962 if (buf.size () == 0 || buf.data ()[0] == '\0')
11963 error (_("a remote packet must not be empty"));
11964
11965 remote_target *remote = get_current_remote_target ();
11966 if (remote == nullptr)
11967 error (_("packets can only be sent to a remote target"));
11968
11969 callbacks->sending (buf);
11970
11971 remote->putpkt_binary (buf.data (), buf.size ());
11972 remote_state *rs = remote->get_remote_state ();
11973 int bytes = remote->getpkt (&rs->buf);
11974
11975 if (bytes < 0)
11976 error (_("error while fetching packet from remote target"));
11977
11978 gdb::array_view<const char> view (&rs->buf[0], bytes);
11979 callbacks->received (view);
11980 }
11981
11982 /* Entry point for the 'maint packet' command. */
11983
11984 static void
11985 cli_packet_command (const char *args, int from_tty)
11986 {
11987 cli_packet_command_callbacks cb;
11988 gdb::array_view<const char> view
11989 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11990 send_remote_packet (view, &cb);
11991 }
11992
11993 #if 0
11994 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11995
11996 static void display_thread_info (struct gdb_ext_thread_info *info);
11997
11998 static void threadset_test_cmd (char *cmd, int tty);
11999
12000 static void threadalive_test (char *cmd, int tty);
12001
12002 static void threadlist_test_cmd (char *cmd, int tty);
12003
12004 int get_and_display_threadinfo (threadref *ref);
12005
12006 static void threadinfo_test_cmd (char *cmd, int tty);
12007
12008 static int thread_display_step (threadref *ref, void *context);
12009
12010 static void threadlist_update_test_cmd (char *cmd, int tty);
12011
12012 static void init_remote_threadtests (void);
12013
12014 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12015
12016 static void
12017 threadset_test_cmd (const char *cmd, int tty)
12018 {
12019 int sample_thread = SAMPLE_THREAD;
12020
12021 gdb_printf (_("Remote threadset test\n"));
12022 set_general_thread (sample_thread);
12023 }
12024
12025
12026 static void
12027 threadalive_test (const char *cmd, int tty)
12028 {
12029 int sample_thread = SAMPLE_THREAD;
12030 int pid = inferior_ptid.pid ();
12031 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12032
12033 if (remote_thread_alive (ptid))
12034 gdb_printf ("PASS: Thread alive test\n");
12035 else
12036 gdb_printf ("FAIL: Thread alive test\n");
12037 }
12038
12039 void output_threadid (char *title, threadref *ref);
12040
12041 void
12042 output_threadid (char *title, threadref *ref)
12043 {
12044 char hexid[20];
12045
12046 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12047 hexid[16] = 0;
12048 gdb_printf ("%s %s\n", title, (&hexid[0]));
12049 }
12050
12051 static void
12052 threadlist_test_cmd (const char *cmd, int tty)
12053 {
12054 int startflag = 1;
12055 threadref nextthread;
12056 int done, result_count;
12057 threadref threadlist[3];
12058
12059 gdb_printf ("Remote Threadlist test\n");
12060 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12061 &result_count, &threadlist[0]))
12062 gdb_printf ("FAIL: threadlist test\n");
12063 else
12064 {
12065 threadref *scan = threadlist;
12066 threadref *limit = scan + result_count;
12067
12068 while (scan < limit)
12069 output_threadid (" thread ", scan++);
12070 }
12071 }
12072
12073 void
12074 display_thread_info (struct gdb_ext_thread_info *info)
12075 {
12076 output_threadid ("Threadid: ", &info->threadid);
12077 gdb_printf ("Name: %s\n ", info->shortname);
12078 gdb_printf ("State: %s\n", info->display);
12079 gdb_printf ("other: %s\n\n", info->more_display);
12080 }
12081
12082 int
12083 get_and_display_threadinfo (threadref *ref)
12084 {
12085 int result;
12086 int set;
12087 struct gdb_ext_thread_info threadinfo;
12088
12089 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12090 | TAG_MOREDISPLAY | TAG_DISPLAY;
12091 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12092 display_thread_info (&threadinfo);
12093 return result;
12094 }
12095
12096 static void
12097 threadinfo_test_cmd (const char *cmd, int tty)
12098 {
12099 int athread = SAMPLE_THREAD;
12100 threadref thread;
12101 int set;
12102
12103 int_to_threadref (&thread, athread);
12104 gdb_printf ("Remote Threadinfo test\n");
12105 if (!get_and_display_threadinfo (&thread))
12106 gdb_printf ("FAIL cannot get thread info\n");
12107 }
12108
12109 static int
12110 thread_display_step (threadref *ref, void *context)
12111 {
12112 /* output_threadid(" threadstep ",ref); *//* simple test */
12113 return get_and_display_threadinfo (ref);
12114 }
12115
12116 static void
12117 threadlist_update_test_cmd (const char *cmd, int tty)
12118 {
12119 gdb_printf ("Remote Threadlist update test\n");
12120 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12121 }
12122
12123 static void
12124 init_remote_threadtests (void)
12125 {
12126 add_com ("tlist", class_obscure, threadlist_test_cmd,
12127 _("Fetch and print the remote list of "
12128 "thread identifiers, one pkt only."));
12129 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12130 _("Fetch and display info about one thread."));
12131 add_com ("tset", class_obscure, threadset_test_cmd,
12132 _("Test setting to a different thread."));
12133 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12134 _("Iterate through updating all remote thread info."));
12135 add_com ("talive", class_obscure, threadalive_test,
12136 _("Remote thread alive test."));
12137 }
12138
12139 #endif /* 0 */
12140
12141 /* Convert a thread ID to a string. */
12142
12143 std::string
12144 remote_target::pid_to_str (ptid_t ptid)
12145 {
12146 if (ptid == null_ptid)
12147 return normal_pid_to_str (ptid);
12148 else if (ptid.is_pid ())
12149 {
12150 /* Printing an inferior target id. */
12151
12152 /* When multi-process extensions are off, there's no way in the
12153 remote protocol to know the remote process id, if there's any
12154 at all. There's one exception --- when we're connected with
12155 target extended-remote, and we manually attached to a process
12156 with "attach PID". We don't record anywhere a flag that
12157 allows us to distinguish that case from the case of
12158 connecting with extended-remote and the stub already being
12159 attached to a process, and reporting yes to qAttached, hence
12160 no smart special casing here. */
12161 if (!m_features.remote_multi_process_p ())
12162 return "Remote target";
12163
12164 return normal_pid_to_str (ptid);
12165 }
12166 else
12167 {
12168 if (magic_null_ptid == ptid)
12169 return "Thread <main>";
12170 else if (m_features.remote_multi_process_p ())
12171 if (ptid.lwp () == 0)
12172 return normal_pid_to_str (ptid);
12173 else
12174 return string_printf ("Thread %d.%ld",
12175 ptid.pid (), ptid.lwp ());
12176 else
12177 return string_printf ("Thread %ld", ptid.lwp ());
12178 }
12179 }
12180
12181 /* Get the address of the thread local variable in OBJFILE which is
12182 stored at OFFSET within the thread local storage for thread PTID. */
12183
12184 CORE_ADDR
12185 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12186 CORE_ADDR offset)
12187 {
12188 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12189 {
12190 struct remote_state *rs = get_remote_state ();
12191 char *p = rs->buf.data ();
12192 char *endp = p + get_remote_packet_size ();
12193 enum packet_result result;
12194
12195 strcpy (p, "qGetTLSAddr:");
12196 p += strlen (p);
12197 p = write_ptid (p, endp, ptid);
12198 *p++ = ',';
12199 p += hexnumstr (p, offset);
12200 *p++ = ',';
12201 p += hexnumstr (p, lm);
12202 *p++ = '\0';
12203
12204 putpkt (rs->buf);
12205 getpkt (&rs->buf);
12206 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12207 if (result == PACKET_OK)
12208 {
12209 ULONGEST addr;
12210
12211 unpack_varlen_hex (rs->buf.data (), &addr);
12212 return addr;
12213 }
12214 else if (result == PACKET_UNKNOWN)
12215 throw_error (TLS_GENERIC_ERROR,
12216 _("Remote target doesn't support qGetTLSAddr packet"));
12217 else
12218 throw_error (TLS_GENERIC_ERROR,
12219 _("Remote target failed to process qGetTLSAddr request"));
12220 }
12221 else
12222 throw_error (TLS_GENERIC_ERROR,
12223 _("TLS not supported or disabled on this target"));
12224 /* Not reached. */
12225 return 0;
12226 }
12227
12228 /* Provide thread local base, i.e. Thread Information Block address.
12229 Returns 1 if ptid is found and thread_local_base is non zero. */
12230
12231 bool
12232 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12233 {
12234 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12235 {
12236 struct remote_state *rs = get_remote_state ();
12237 char *p = rs->buf.data ();
12238 char *endp = p + get_remote_packet_size ();
12239 enum packet_result result;
12240
12241 strcpy (p, "qGetTIBAddr:");
12242 p += strlen (p);
12243 p = write_ptid (p, endp, ptid);
12244 *p++ = '\0';
12245
12246 putpkt (rs->buf);
12247 getpkt (&rs->buf);
12248 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12249 if (result == PACKET_OK)
12250 {
12251 ULONGEST val;
12252 unpack_varlen_hex (rs->buf.data (), &val);
12253 if (addr)
12254 *addr = (CORE_ADDR) val;
12255 return true;
12256 }
12257 else if (result == PACKET_UNKNOWN)
12258 error (_("Remote target doesn't support qGetTIBAddr packet"));
12259 else
12260 error (_("Remote target failed to process qGetTIBAddr request"));
12261 }
12262 else
12263 error (_("qGetTIBAddr not supported or disabled on this target"));
12264 /* Not reached. */
12265 return false;
12266 }
12267
12268 /* Support for inferring a target description based on the current
12269 architecture and the size of a 'g' packet. While the 'g' packet
12270 can have any size (since optional registers can be left off the
12271 end), some sizes are easily recognizable given knowledge of the
12272 approximate architecture. */
12273
12274 struct remote_g_packet_guess
12275 {
12276 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12277 : bytes (bytes_),
12278 tdesc (tdesc_)
12279 {
12280 }
12281
12282 int bytes;
12283 const struct target_desc *tdesc;
12284 };
12285
12286 struct remote_g_packet_data
12287 {
12288 std::vector<remote_g_packet_guess> guesses;
12289 };
12290
12291 static const registry<gdbarch>::key<struct remote_g_packet_data>
12292 remote_g_packet_data_handle;
12293
12294 static struct remote_g_packet_data *
12295 get_g_packet_data (struct gdbarch *gdbarch)
12296 {
12297 struct remote_g_packet_data *data
12298 = remote_g_packet_data_handle.get (gdbarch);
12299 if (data == nullptr)
12300 data = remote_g_packet_data_handle.emplace (gdbarch);
12301 return data;
12302 }
12303
12304 void
12305 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12306 const struct target_desc *tdesc)
12307 {
12308 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12309
12310 gdb_assert (tdesc != NULL);
12311
12312 for (const remote_g_packet_guess &guess : data->guesses)
12313 if (guess.bytes == bytes)
12314 internal_error (_("Duplicate g packet description added for size %d"),
12315 bytes);
12316
12317 data->guesses.emplace_back (bytes, tdesc);
12318 }
12319
12320 /* Return true if remote_read_description would do anything on this target
12321 and architecture, false otherwise. */
12322
12323 static bool
12324 remote_read_description_p (struct target_ops *target)
12325 {
12326 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12327
12328 return !data->guesses.empty ();
12329 }
12330
12331 const struct target_desc *
12332 remote_target::read_description ()
12333 {
12334 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12335
12336 /* Do not try this during initial connection, when we do not know
12337 whether there is a running but stopped thread. */
12338 if (!target_has_execution () || inferior_ptid == null_ptid)
12339 return beneath ()->read_description ();
12340
12341 if (!data->guesses.empty ())
12342 {
12343 int bytes = send_g_packet ();
12344
12345 for (const remote_g_packet_guess &guess : data->guesses)
12346 if (guess.bytes == bytes)
12347 return guess.tdesc;
12348
12349 /* We discard the g packet. A minor optimization would be to
12350 hold on to it, and fill the register cache once we have selected
12351 an architecture, but it's too tricky to do safely. */
12352 }
12353
12354 return beneath ()->read_description ();
12355 }
12356
12357 /* Remote file transfer support. This is host-initiated I/O, not
12358 target-initiated; for target-initiated, see remote-fileio.c. */
12359
12360 /* If *LEFT is at least the length of STRING, copy STRING to
12361 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12362 decrease *LEFT. Otherwise raise an error. */
12363
12364 static void
12365 remote_buffer_add_string (char **buffer, int *left, const char *string)
12366 {
12367 int len = strlen (string);
12368
12369 if (len > *left)
12370 error (_("Packet too long for target."));
12371
12372 memcpy (*buffer, string, len);
12373 *buffer += len;
12374 *left -= len;
12375
12376 /* NUL-terminate the buffer as a convenience, if there is
12377 room. */
12378 if (*left)
12379 **buffer = '\0';
12380 }
12381
12382 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12383 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12384 decrease *LEFT. Otherwise raise an error. */
12385
12386 static void
12387 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12388 int len)
12389 {
12390 if (2 * len > *left)
12391 error (_("Packet too long for target."));
12392
12393 bin2hex (bytes, *buffer, len);
12394 *buffer += 2 * len;
12395 *left -= 2 * len;
12396
12397 /* NUL-terminate the buffer as a convenience, if there is
12398 room. */
12399 if (*left)
12400 **buffer = '\0';
12401 }
12402
12403 /* If *LEFT is large enough, convert VALUE to hex and add it to
12404 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12405 decrease *LEFT. Otherwise raise an error. */
12406
12407 static void
12408 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12409 {
12410 int len = hexnumlen (value);
12411
12412 if (len > *left)
12413 error (_("Packet too long for target."));
12414
12415 hexnumstr (*buffer, value);
12416 *buffer += len;
12417 *left -= len;
12418
12419 /* NUL-terminate the buffer as a convenience, if there is
12420 room. */
12421 if (*left)
12422 **buffer = '\0';
12423 }
12424
12425 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12426 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12427 was included, and *ATTACHMENT to point to the start of the annex
12428 if any. The length of the packet isn't needed here; there may
12429 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12430
12431 Return 0 if the packet could be parsed, -1 if it could not. If
12432 -1 is returned, the other variables may not be initialized. */
12433
12434 static int
12435 remote_hostio_parse_result (const char *buffer, int *retcode,
12436 fileio_error *remote_errno, const char **attachment)
12437 {
12438 char *p, *p2;
12439
12440 *remote_errno = FILEIO_SUCCESS;
12441 *attachment = NULL;
12442
12443 if (buffer[0] != 'F')
12444 return -1;
12445
12446 errno = 0;
12447 *retcode = strtol (&buffer[1], &p, 16);
12448 if (errno != 0 || p == &buffer[1])
12449 return -1;
12450
12451 /* Check for ",errno". */
12452 if (*p == ',')
12453 {
12454 errno = 0;
12455 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12456 if (errno != 0 || p + 1 == p2)
12457 return -1;
12458 p = p2;
12459 }
12460
12461 /* Check for ";attachment". If there is no attachment, the
12462 packet should end here. */
12463 if (*p == ';')
12464 {
12465 *attachment = p + 1;
12466 return 0;
12467 }
12468 else if (*p == '\0')
12469 return 0;
12470 else
12471 return -1;
12472 }
12473
12474 /* Send a prepared I/O packet to the target and read its response.
12475 The prepared packet is in the global RS->BUF before this function
12476 is called, and the answer is there when we return.
12477
12478 COMMAND_BYTES is the length of the request to send, which may include
12479 binary data. WHICH_PACKET is the packet configuration to check
12480 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12481 is set to the error number and -1 is returned. Otherwise the value
12482 returned by the function is returned.
12483
12484 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12485 attachment is expected; an error will be reported if there's a
12486 mismatch. If one is found, *ATTACHMENT will be set to point into
12487 the packet buffer and *ATTACHMENT_LEN will be set to the
12488 attachment's length. */
12489
12490 int
12491 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12492 fileio_error *remote_errno, const char **attachment,
12493 int *attachment_len)
12494 {
12495 struct remote_state *rs = get_remote_state ();
12496 int ret, bytes_read;
12497 const char *attachment_tmp;
12498
12499 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12500 {
12501 *remote_errno = FILEIO_ENOSYS;
12502 return -1;
12503 }
12504
12505 putpkt_binary (rs->buf.data (), command_bytes);
12506 bytes_read = getpkt (&rs->buf);
12507
12508 /* If it timed out, something is wrong. Don't try to parse the
12509 buffer. */
12510 if (bytes_read < 0)
12511 {
12512 *remote_errno = FILEIO_EINVAL;
12513 return -1;
12514 }
12515
12516 switch (m_features.packet_ok (rs->buf, which_packet))
12517 {
12518 case PACKET_ERROR:
12519 *remote_errno = FILEIO_EINVAL;
12520 return -1;
12521 case PACKET_UNKNOWN:
12522 *remote_errno = FILEIO_ENOSYS;
12523 return -1;
12524 case PACKET_OK:
12525 break;
12526 }
12527
12528 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12529 &attachment_tmp))
12530 {
12531 *remote_errno = FILEIO_EINVAL;
12532 return -1;
12533 }
12534
12535 /* Make sure we saw an attachment if and only if we expected one. */
12536 if ((attachment_tmp == NULL && attachment != NULL)
12537 || (attachment_tmp != NULL && attachment == NULL))
12538 {
12539 *remote_errno = FILEIO_EINVAL;
12540 return -1;
12541 }
12542
12543 /* If an attachment was found, it must point into the packet buffer;
12544 work out how many bytes there were. */
12545 if (attachment_tmp != NULL)
12546 {
12547 *attachment = attachment_tmp;
12548 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12549 }
12550
12551 return ret;
12552 }
12553
12554 /* See declaration.h. */
12555
12556 void
12557 readahead_cache::invalidate ()
12558 {
12559 this->fd = -1;
12560 }
12561
12562 /* See declaration.h. */
12563
12564 void
12565 readahead_cache::invalidate_fd (int fd)
12566 {
12567 if (this->fd == fd)
12568 this->fd = -1;
12569 }
12570
12571 /* Set the filesystem remote_hostio functions that take FILENAME
12572 arguments will use. Return 0 on success, or -1 if an error
12573 occurs (and set *REMOTE_ERRNO). */
12574
12575 int
12576 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12577 fileio_error *remote_errno)
12578 {
12579 struct remote_state *rs = get_remote_state ();
12580 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12581 char *p = rs->buf.data ();
12582 int left = get_remote_packet_size () - 1;
12583 char arg[9];
12584 int ret;
12585
12586 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12587 return 0;
12588
12589 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12590 return 0;
12591
12592 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12593
12594 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12595 remote_buffer_add_string (&p, &left, arg);
12596
12597 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12598 remote_errno, NULL, NULL);
12599
12600 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12601 return 0;
12602
12603 if (ret == 0)
12604 rs->fs_pid = required_pid;
12605
12606 return ret;
12607 }
12608
12609 /* Implementation of to_fileio_open. */
12610
12611 int
12612 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12613 int flags, int mode, int warn_if_slow,
12614 fileio_error *remote_errno)
12615 {
12616 struct remote_state *rs = get_remote_state ();
12617 char *p = rs->buf.data ();
12618 int left = get_remote_packet_size () - 1;
12619
12620 if (warn_if_slow)
12621 {
12622 static int warning_issued = 0;
12623
12624 gdb_printf (_("Reading %s from remote target...\n"),
12625 filename);
12626
12627 if (!warning_issued)
12628 {
12629 warning (_("File transfers from remote targets can be slow."
12630 " Use \"set sysroot\" to access files locally"
12631 " instead."));
12632 warning_issued = 1;
12633 }
12634 }
12635
12636 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12637 return -1;
12638
12639 remote_buffer_add_string (&p, &left, "vFile:open:");
12640
12641 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12642 strlen (filename));
12643 remote_buffer_add_string (&p, &left, ",");
12644
12645 remote_buffer_add_int (&p, &left, flags);
12646 remote_buffer_add_string (&p, &left, ",");
12647
12648 remote_buffer_add_int (&p, &left, mode);
12649
12650 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12651 remote_errno, NULL, NULL);
12652 }
12653
12654 int
12655 remote_target::fileio_open (struct inferior *inf, const char *filename,
12656 int flags, int mode, int warn_if_slow,
12657 fileio_error *remote_errno)
12658 {
12659 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12660 remote_errno);
12661 }
12662
12663 /* Implementation of to_fileio_pwrite. */
12664
12665 int
12666 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12667 ULONGEST offset, fileio_error *remote_errno)
12668 {
12669 struct remote_state *rs = get_remote_state ();
12670 char *p = rs->buf.data ();
12671 int left = get_remote_packet_size ();
12672 int out_len;
12673
12674 rs->readahead_cache.invalidate_fd (fd);
12675
12676 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12677
12678 remote_buffer_add_int (&p, &left, fd);
12679 remote_buffer_add_string (&p, &left, ",");
12680
12681 remote_buffer_add_int (&p, &left, offset);
12682 remote_buffer_add_string (&p, &left, ",");
12683
12684 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12685 (get_remote_packet_size ()
12686 - (p - rs->buf.data ())));
12687
12688 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12689 remote_errno, NULL, NULL);
12690 }
12691
12692 int
12693 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12694 ULONGEST offset, fileio_error *remote_errno)
12695 {
12696 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12697 }
12698
12699 /* Helper for the implementation of to_fileio_pread. Read the file
12700 from the remote side with vFile:pread. */
12701
12702 int
12703 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12704 ULONGEST offset, fileio_error *remote_errno)
12705 {
12706 struct remote_state *rs = get_remote_state ();
12707 char *p = rs->buf.data ();
12708 const char *attachment;
12709 int left = get_remote_packet_size ();
12710 int ret, attachment_len;
12711 int read_len;
12712
12713 remote_buffer_add_string (&p, &left, "vFile:pread:");
12714
12715 remote_buffer_add_int (&p, &left, fd);
12716 remote_buffer_add_string (&p, &left, ",");
12717
12718 remote_buffer_add_int (&p, &left, len);
12719 remote_buffer_add_string (&p, &left, ",");
12720
12721 remote_buffer_add_int (&p, &left, offset);
12722
12723 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12724 remote_errno, &attachment,
12725 &attachment_len);
12726
12727 if (ret < 0)
12728 return ret;
12729
12730 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12731 read_buf, len);
12732 if (read_len != ret)
12733 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12734
12735 return ret;
12736 }
12737
12738 /* See declaration.h. */
12739
12740 int
12741 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12742 ULONGEST offset)
12743 {
12744 if (this->fd == fd
12745 && this->offset <= offset
12746 && offset < this->offset + this->buf.size ())
12747 {
12748 ULONGEST max = this->offset + this->buf.size ();
12749
12750 if (offset + len > max)
12751 len = max - offset;
12752
12753 memcpy (read_buf, &this->buf[offset - this->offset], len);
12754 return len;
12755 }
12756
12757 return 0;
12758 }
12759
12760 /* Implementation of to_fileio_pread. */
12761
12762 int
12763 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12764 ULONGEST offset, fileio_error *remote_errno)
12765 {
12766 int ret;
12767 struct remote_state *rs = get_remote_state ();
12768 readahead_cache *cache = &rs->readahead_cache;
12769
12770 ret = cache->pread (fd, read_buf, len, offset);
12771 if (ret > 0)
12772 {
12773 cache->hit_count++;
12774
12775 remote_debug_printf ("readahead cache hit %s",
12776 pulongest (cache->hit_count));
12777 return ret;
12778 }
12779
12780 cache->miss_count++;
12781
12782 remote_debug_printf ("readahead cache miss %s",
12783 pulongest (cache->miss_count));
12784
12785 cache->fd = fd;
12786 cache->offset = offset;
12787 cache->buf.resize (get_remote_packet_size ());
12788
12789 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12790 cache->buf.size (),
12791 cache->offset, remote_errno);
12792 if (ret <= 0)
12793 {
12794 cache->invalidate_fd (fd);
12795 return ret;
12796 }
12797
12798 cache->buf.resize (ret);
12799 return cache->pread (fd, read_buf, len, offset);
12800 }
12801
12802 int
12803 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12804 ULONGEST offset, fileio_error *remote_errno)
12805 {
12806 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12807 }
12808
12809 /* Implementation of to_fileio_close. */
12810
12811 int
12812 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12813 {
12814 struct remote_state *rs = get_remote_state ();
12815 char *p = rs->buf.data ();
12816 int left = get_remote_packet_size () - 1;
12817
12818 rs->readahead_cache.invalidate_fd (fd);
12819
12820 remote_buffer_add_string (&p, &left, "vFile:close:");
12821
12822 remote_buffer_add_int (&p, &left, fd);
12823
12824 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12825 remote_errno, NULL, NULL);
12826 }
12827
12828 int
12829 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12830 {
12831 return remote_hostio_close (fd, remote_errno);
12832 }
12833
12834 /* Implementation of to_fileio_unlink. */
12835
12836 int
12837 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12838 fileio_error *remote_errno)
12839 {
12840 struct remote_state *rs = get_remote_state ();
12841 char *p = rs->buf.data ();
12842 int left = get_remote_packet_size () - 1;
12843
12844 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12845 return -1;
12846
12847 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12848
12849 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12850 strlen (filename));
12851
12852 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12853 remote_errno, NULL, NULL);
12854 }
12855
12856 int
12857 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12858 fileio_error *remote_errno)
12859 {
12860 return remote_hostio_unlink (inf, filename, remote_errno);
12861 }
12862
12863 /* Implementation of to_fileio_readlink. */
12864
12865 gdb::optional<std::string>
12866 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12867 fileio_error *remote_errno)
12868 {
12869 struct remote_state *rs = get_remote_state ();
12870 char *p = rs->buf.data ();
12871 const char *attachment;
12872 int left = get_remote_packet_size ();
12873 int len, attachment_len;
12874 int read_len;
12875
12876 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12877 return {};
12878
12879 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12880
12881 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12882 strlen (filename));
12883
12884 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12885 remote_errno, &attachment,
12886 &attachment_len);
12887
12888 if (len < 0)
12889 return {};
12890
12891 std::string ret (len, '\0');
12892
12893 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12894 (gdb_byte *) &ret[0], len);
12895 if (read_len != len)
12896 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12897
12898 return ret;
12899 }
12900
12901 /* Implementation of to_fileio_fstat. */
12902
12903 int
12904 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12905 {
12906 struct remote_state *rs = get_remote_state ();
12907 char *p = rs->buf.data ();
12908 int left = get_remote_packet_size ();
12909 int attachment_len, ret;
12910 const char *attachment;
12911 struct fio_stat fst;
12912 int read_len;
12913
12914 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12915
12916 remote_buffer_add_int (&p, &left, fd);
12917
12918 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12919 remote_errno, &attachment,
12920 &attachment_len);
12921 if (ret < 0)
12922 {
12923 if (*remote_errno != FILEIO_ENOSYS)
12924 return ret;
12925
12926 /* Strictly we should return -1, ENOSYS here, but when
12927 "set sysroot remote:" was implemented in August 2008
12928 BFD's need for a stat function was sidestepped with
12929 this hack. This was not remedied until March 2015
12930 so we retain the previous behavior to avoid breaking
12931 compatibility.
12932
12933 Note that the memset is a March 2015 addition; older
12934 GDBs set st_size *and nothing else* so the structure
12935 would have garbage in all other fields. This might
12936 break something but retaining the previous behavior
12937 here would be just too wrong. */
12938
12939 memset (st, 0, sizeof (struct stat));
12940 st->st_size = INT_MAX;
12941 return 0;
12942 }
12943
12944 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12945 (gdb_byte *) &fst, sizeof (fst));
12946
12947 if (read_len != ret)
12948 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12949
12950 if (read_len != sizeof (fst))
12951 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12952 read_len, (int) sizeof (fst));
12953
12954 remote_fileio_to_host_stat (&fst, st);
12955
12956 return 0;
12957 }
12958
12959 /* Implementation of to_filesystem_is_local. */
12960
12961 bool
12962 remote_target::filesystem_is_local ()
12963 {
12964 /* Valgrind GDB presents itself as a remote target but works
12965 on the local filesystem: it does not implement remote get
12966 and users are not expected to set a sysroot. To handle
12967 this case we treat the remote filesystem as local if the
12968 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12969 does not support vFile:open. */
12970 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12971 {
12972 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12973
12974 if (ps == PACKET_SUPPORT_UNKNOWN)
12975 {
12976 int fd;
12977 fileio_error remote_errno;
12978
12979 /* Try opening a file to probe support. The supplied
12980 filename is irrelevant, we only care about whether
12981 the stub recognizes the packet or not. */
12982 fd = remote_hostio_open (NULL, "just probing",
12983 FILEIO_O_RDONLY, 0700, 0,
12984 &remote_errno);
12985
12986 if (fd >= 0)
12987 remote_hostio_close (fd, &remote_errno);
12988
12989 ps = m_features.packet_support (PACKET_vFile_open);
12990 }
12991
12992 if (ps == PACKET_DISABLE)
12993 {
12994 static int warning_issued = 0;
12995
12996 if (!warning_issued)
12997 {
12998 warning (_("remote target does not support file"
12999 " transfer, attempting to access files"
13000 " from local filesystem."));
13001 warning_issued = 1;
13002 }
13003
13004 return true;
13005 }
13006 }
13007
13008 return false;
13009 }
13010
13011 static char *
13012 remote_hostio_error (fileio_error errnum)
13013 {
13014 int host_error = fileio_error_to_host (errnum);
13015
13016 if (host_error == -1)
13017 error (_("Unknown remote I/O error %d"), errnum);
13018 else
13019 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13020 }
13021
13022 /* A RAII wrapper around a remote file descriptor. */
13023
13024 class scoped_remote_fd
13025 {
13026 public:
13027 scoped_remote_fd (remote_target *remote, int fd)
13028 : m_remote (remote), m_fd (fd)
13029 {
13030 }
13031
13032 ~scoped_remote_fd ()
13033 {
13034 if (m_fd != -1)
13035 {
13036 try
13037 {
13038 fileio_error remote_errno;
13039 m_remote->remote_hostio_close (m_fd, &remote_errno);
13040 }
13041 catch (...)
13042 {
13043 /* Swallow exception before it escapes the dtor. If
13044 something goes wrong, likely the connection is gone,
13045 and there's nothing else that can be done. */
13046 }
13047 }
13048 }
13049
13050 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13051
13052 /* Release ownership of the file descriptor, and return it. */
13053 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13054 {
13055 int fd = m_fd;
13056 m_fd = -1;
13057 return fd;
13058 }
13059
13060 /* Return the owned file descriptor. */
13061 int get () const noexcept
13062 {
13063 return m_fd;
13064 }
13065
13066 private:
13067 /* The remote target. */
13068 remote_target *m_remote;
13069
13070 /* The owned remote I/O file descriptor. */
13071 int m_fd;
13072 };
13073
13074 void
13075 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13076 {
13077 remote_target *remote = get_current_remote_target ();
13078
13079 if (remote == nullptr)
13080 error (_("command can only be used with remote target"));
13081
13082 remote->remote_file_put (local_file, remote_file, from_tty);
13083 }
13084
13085 void
13086 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13087 int from_tty)
13088 {
13089 int retcode, bytes, io_size;
13090 fileio_error remote_errno;
13091 int bytes_in_buffer;
13092 int saw_eof;
13093 ULONGEST offset;
13094
13095 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13096 if (file == NULL)
13097 perror_with_name (local_file);
13098
13099 scoped_remote_fd fd
13100 (this, remote_hostio_open (NULL,
13101 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13102 | FILEIO_O_TRUNC),
13103 0700, 0, &remote_errno));
13104 if (fd.get () == -1)
13105 remote_hostio_error (remote_errno);
13106
13107 /* Send up to this many bytes at once. They won't all fit in the
13108 remote packet limit, so we'll transfer slightly fewer. */
13109 io_size = get_remote_packet_size ();
13110 gdb::byte_vector buffer (io_size);
13111
13112 bytes_in_buffer = 0;
13113 saw_eof = 0;
13114 offset = 0;
13115 while (bytes_in_buffer || !saw_eof)
13116 {
13117 if (!saw_eof)
13118 {
13119 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13120 io_size - bytes_in_buffer,
13121 file.get ());
13122 if (bytes == 0)
13123 {
13124 if (ferror (file.get ()))
13125 error (_("Error reading %s."), local_file);
13126 else
13127 {
13128 /* EOF. Unless there is something still in the
13129 buffer from the last iteration, we are done. */
13130 saw_eof = 1;
13131 if (bytes_in_buffer == 0)
13132 break;
13133 }
13134 }
13135 }
13136 else
13137 bytes = 0;
13138
13139 bytes += bytes_in_buffer;
13140 bytes_in_buffer = 0;
13141
13142 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13143 offset, &remote_errno);
13144
13145 if (retcode < 0)
13146 remote_hostio_error (remote_errno);
13147 else if (retcode == 0)
13148 error (_("Remote write of %d bytes returned 0!"), bytes);
13149 else if (retcode < bytes)
13150 {
13151 /* Short write. Save the rest of the read data for the next
13152 write. */
13153 bytes_in_buffer = bytes - retcode;
13154 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13155 }
13156
13157 offset += retcode;
13158 }
13159
13160 if (remote_hostio_close (fd.release (), &remote_errno))
13161 remote_hostio_error (remote_errno);
13162
13163 if (from_tty)
13164 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13165 }
13166
13167 void
13168 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13169 {
13170 remote_target *remote = get_current_remote_target ();
13171
13172 if (remote == nullptr)
13173 error (_("command can only be used with remote target"));
13174
13175 remote->remote_file_get (remote_file, local_file, from_tty);
13176 }
13177
13178 void
13179 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13180 int from_tty)
13181 {
13182 fileio_error remote_errno;
13183 int bytes, io_size;
13184 ULONGEST offset;
13185
13186 scoped_remote_fd fd
13187 (this, remote_hostio_open (NULL,
13188 remote_file, FILEIO_O_RDONLY, 0, 0,
13189 &remote_errno));
13190 if (fd.get () == -1)
13191 remote_hostio_error (remote_errno);
13192
13193 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13194 if (file == NULL)
13195 perror_with_name (local_file);
13196
13197 /* Send up to this many bytes at once. They won't all fit in the
13198 remote packet limit, so we'll transfer slightly fewer. */
13199 io_size = get_remote_packet_size ();
13200 gdb::byte_vector buffer (io_size);
13201
13202 offset = 0;
13203 while (1)
13204 {
13205 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13206 &remote_errno);
13207 if (bytes == 0)
13208 /* Success, but no bytes, means end-of-file. */
13209 break;
13210 if (bytes == -1)
13211 remote_hostio_error (remote_errno);
13212
13213 offset += bytes;
13214
13215 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13216 if (bytes == 0)
13217 perror_with_name (local_file);
13218 }
13219
13220 if (remote_hostio_close (fd.release (), &remote_errno))
13221 remote_hostio_error (remote_errno);
13222
13223 if (from_tty)
13224 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13225 }
13226
13227 void
13228 remote_file_delete (const char *remote_file, int from_tty)
13229 {
13230 remote_target *remote = get_current_remote_target ();
13231
13232 if (remote == nullptr)
13233 error (_("command can only be used with remote target"));
13234
13235 remote->remote_file_delete (remote_file, from_tty);
13236 }
13237
13238 void
13239 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13240 {
13241 int retcode;
13242 fileio_error remote_errno;
13243
13244 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13245 if (retcode == -1)
13246 remote_hostio_error (remote_errno);
13247
13248 if (from_tty)
13249 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13250 }
13251
13252 static void
13253 remote_put_command (const char *args, int from_tty)
13254 {
13255 if (args == NULL)
13256 error_no_arg (_("file to put"));
13257
13258 gdb_argv argv (args);
13259 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13260 error (_("Invalid parameters to remote put"));
13261
13262 remote_file_put (argv[0], argv[1], from_tty);
13263 }
13264
13265 static void
13266 remote_get_command (const char *args, int from_tty)
13267 {
13268 if (args == NULL)
13269 error_no_arg (_("file to get"));
13270
13271 gdb_argv argv (args);
13272 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13273 error (_("Invalid parameters to remote get"));
13274
13275 remote_file_get (argv[0], argv[1], from_tty);
13276 }
13277
13278 static void
13279 remote_delete_command (const char *args, int from_tty)
13280 {
13281 if (args == NULL)
13282 error_no_arg (_("file to delete"));
13283
13284 gdb_argv argv (args);
13285 if (argv[0] == NULL || argv[1] != NULL)
13286 error (_("Invalid parameters to remote delete"));
13287
13288 remote_file_delete (argv[0], from_tty);
13289 }
13290
13291 bool
13292 remote_target::can_execute_reverse ()
13293 {
13294 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13295 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13296 return true;
13297 else
13298 return false;
13299 }
13300
13301 bool
13302 remote_target::supports_non_stop ()
13303 {
13304 return true;
13305 }
13306
13307 bool
13308 remote_target::supports_disable_randomization ()
13309 {
13310 /* Only supported in extended mode. */
13311 return false;
13312 }
13313
13314 bool
13315 remote_target::supports_multi_process ()
13316 {
13317 return m_features.remote_multi_process_p ();
13318 }
13319
13320 int
13321 remote_target::remote_supports_cond_tracepoints ()
13322 {
13323 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13324 == PACKET_ENABLE);
13325 }
13326
13327 bool
13328 remote_target::supports_evaluation_of_breakpoint_conditions ()
13329 {
13330 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13331 == PACKET_ENABLE);
13332 }
13333
13334 int
13335 remote_target::remote_supports_fast_tracepoints ()
13336 {
13337 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13338 }
13339
13340 int
13341 remote_target::remote_supports_static_tracepoints ()
13342 {
13343 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13344 }
13345
13346 int
13347 remote_target::remote_supports_install_in_trace ()
13348 {
13349 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13350 }
13351
13352 bool
13353 remote_target::supports_enable_disable_tracepoint ()
13354 {
13355 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13356 == PACKET_ENABLE);
13357 }
13358
13359 bool
13360 remote_target::supports_string_tracing ()
13361 {
13362 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13363 }
13364
13365 bool
13366 remote_target::can_run_breakpoint_commands ()
13367 {
13368 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13369 }
13370
13371 void
13372 remote_target::trace_init ()
13373 {
13374 struct remote_state *rs = get_remote_state ();
13375
13376 putpkt ("QTinit");
13377 remote_get_noisy_reply ();
13378 if (strcmp (rs->buf.data (), "OK") != 0)
13379 error (_("Target does not support this command."));
13380 }
13381
13382 /* Recursive routine to walk through command list including loops, and
13383 download packets for each command. */
13384
13385 void
13386 remote_target::remote_download_command_source (int num, ULONGEST addr,
13387 struct command_line *cmds)
13388 {
13389 struct remote_state *rs = get_remote_state ();
13390 struct command_line *cmd;
13391
13392 for (cmd = cmds; cmd; cmd = cmd->next)
13393 {
13394 QUIT; /* Allow user to bail out with ^C. */
13395 strcpy (rs->buf.data (), "QTDPsrc:");
13396 encode_source_string (num, addr, "cmd", cmd->line,
13397 rs->buf.data () + strlen (rs->buf.data ()),
13398 rs->buf.size () - strlen (rs->buf.data ()));
13399 putpkt (rs->buf);
13400 remote_get_noisy_reply ();
13401 if (strcmp (rs->buf.data (), "OK"))
13402 warning (_("Target does not support source download."));
13403
13404 if (cmd->control_type == while_control
13405 || cmd->control_type == while_stepping_control)
13406 {
13407 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13408
13409 QUIT; /* Allow user to bail out with ^C. */
13410 strcpy (rs->buf.data (), "QTDPsrc:");
13411 encode_source_string (num, addr, "cmd", "end",
13412 rs->buf.data () + strlen (rs->buf.data ()),
13413 rs->buf.size () - strlen (rs->buf.data ()));
13414 putpkt (rs->buf);
13415 remote_get_noisy_reply ();
13416 if (strcmp (rs->buf.data (), "OK"))
13417 warning (_("Target does not support source download."));
13418 }
13419 }
13420 }
13421
13422 void
13423 remote_target::download_tracepoint (struct bp_location *loc)
13424 {
13425 CORE_ADDR tpaddr;
13426 char addrbuf[40];
13427 std::vector<std::string> tdp_actions;
13428 std::vector<std::string> stepping_actions;
13429 char *pkt;
13430 struct breakpoint *b = loc->owner;
13431 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13432 struct remote_state *rs = get_remote_state ();
13433 int ret;
13434 const char *err_msg = _("Tracepoint packet too large for target.");
13435 size_t size_left;
13436
13437 /* We use a buffer other than rs->buf because we'll build strings
13438 across multiple statements, and other statements in between could
13439 modify rs->buf. */
13440 gdb::char_vector buf (get_remote_packet_size ());
13441
13442 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13443
13444 tpaddr = loc->address;
13445 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13446 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13447 b->number, addrbuf, /* address */
13448 (b->enable_state == bp_enabled ? 'E' : 'D'),
13449 t->step_count, t->pass_count);
13450
13451 if (ret < 0 || ret >= buf.size ())
13452 error ("%s", err_msg);
13453
13454 /* Fast tracepoints are mostly handled by the target, but we can
13455 tell the target how big of an instruction block should be moved
13456 around. */
13457 if (b->type == bp_fast_tracepoint)
13458 {
13459 /* Only test for support at download time; we may not know
13460 target capabilities at definition time. */
13461 if (remote_supports_fast_tracepoints ())
13462 {
13463 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13464 NULL))
13465 {
13466 size_left = buf.size () - strlen (buf.data ());
13467 ret = snprintf (buf.data () + strlen (buf.data ()),
13468 size_left, ":F%x",
13469 gdb_insn_length (loc->gdbarch, tpaddr));
13470
13471 if (ret < 0 || ret >= size_left)
13472 error ("%s", err_msg);
13473 }
13474 else
13475 /* If it passed validation at definition but fails now,
13476 something is very wrong. */
13477 internal_error (_("Fast tracepoint not valid during download"));
13478 }
13479 else
13480 /* Fast tracepoints are functionally identical to regular
13481 tracepoints, so don't take lack of support as a reason to
13482 give up on the trace run. */
13483 warning (_("Target does not support fast tracepoints, "
13484 "downloading %d as regular tracepoint"), b->number);
13485 }
13486 else if (b->type == bp_static_tracepoint
13487 || b->type == bp_static_marker_tracepoint)
13488 {
13489 /* Only test for support at download time; we may not know
13490 target capabilities at definition time. */
13491 if (remote_supports_static_tracepoints ())
13492 {
13493 struct static_tracepoint_marker marker;
13494
13495 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13496 {
13497 size_left = buf.size () - strlen (buf.data ());
13498 ret = snprintf (buf.data () + strlen (buf.data ()),
13499 size_left, ":S");
13500
13501 if (ret < 0 || ret >= size_left)
13502 error ("%s", err_msg);
13503 }
13504 else
13505 error (_("Static tracepoint not valid during download"));
13506 }
13507 else
13508 /* Fast tracepoints are functionally identical to regular
13509 tracepoints, so don't take lack of support as a reason
13510 to give up on the trace run. */
13511 error (_("Target does not support static tracepoints"));
13512 }
13513 /* If the tracepoint has a conditional, make it into an agent
13514 expression and append to the definition. */
13515 if (loc->cond)
13516 {
13517 /* Only test support at download time, we may not know target
13518 capabilities at definition time. */
13519 if (remote_supports_cond_tracepoints ())
13520 {
13521 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13522 loc->cond.get ());
13523
13524 size_left = buf.size () - strlen (buf.data ());
13525
13526 ret = snprintf (buf.data () + strlen (buf.data ()),
13527 size_left, ":X%x,", (int) aexpr->buf.size ());
13528
13529 if (ret < 0 || ret >= size_left)
13530 error ("%s", err_msg);
13531
13532 size_left = buf.size () - strlen (buf.data ());
13533
13534 /* Two bytes to encode each aexpr byte, plus the terminating
13535 null byte. */
13536 if (aexpr->buf.size () * 2 + 1 > size_left)
13537 error ("%s", err_msg);
13538
13539 pkt = buf.data () + strlen (buf.data ());
13540
13541 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13542 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13543 *pkt = '\0';
13544 }
13545 else
13546 warning (_("Target does not support conditional tracepoints, "
13547 "ignoring tp %d cond"), b->number);
13548 }
13549
13550 if (b->commands || !default_collect.empty ())
13551 {
13552 size_left = buf.size () - strlen (buf.data ());
13553
13554 ret = snprintf (buf.data () + strlen (buf.data ()),
13555 size_left, "-");
13556
13557 if (ret < 0 || ret >= size_left)
13558 error ("%s", err_msg);
13559 }
13560
13561 putpkt (buf.data ());
13562 remote_get_noisy_reply ();
13563 if (strcmp (rs->buf.data (), "OK"))
13564 error (_("Target does not support tracepoints."));
13565
13566 /* do_single_steps (t); */
13567 for (auto action_it = tdp_actions.begin ();
13568 action_it != tdp_actions.end (); action_it++)
13569 {
13570 QUIT; /* Allow user to bail out with ^C. */
13571
13572 bool has_more = ((action_it + 1) != tdp_actions.end ()
13573 || !stepping_actions.empty ());
13574
13575 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13576 b->number, addrbuf, /* address */
13577 action_it->c_str (),
13578 has_more ? '-' : 0);
13579
13580 if (ret < 0 || ret >= buf.size ())
13581 error ("%s", err_msg);
13582
13583 putpkt (buf.data ());
13584 remote_get_noisy_reply ();
13585 if (strcmp (rs->buf.data (), "OK"))
13586 error (_("Error on target while setting tracepoints."));
13587 }
13588
13589 for (auto action_it = stepping_actions.begin ();
13590 action_it != stepping_actions.end (); action_it++)
13591 {
13592 QUIT; /* Allow user to bail out with ^C. */
13593
13594 bool is_first = action_it == stepping_actions.begin ();
13595 bool has_more = (action_it + 1) != stepping_actions.end ();
13596
13597 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13598 b->number, addrbuf, /* address */
13599 is_first ? "S" : "",
13600 action_it->c_str (),
13601 has_more ? "-" : "");
13602
13603 if (ret < 0 || ret >= buf.size ())
13604 error ("%s", err_msg);
13605
13606 putpkt (buf.data ());
13607 remote_get_noisy_reply ();
13608 if (strcmp (rs->buf.data (), "OK"))
13609 error (_("Error on target while setting tracepoints."));
13610 }
13611
13612 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13613 {
13614 if (b->locspec != nullptr)
13615 {
13616 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13617
13618 if (ret < 0 || ret >= buf.size ())
13619 error ("%s", err_msg);
13620
13621 const char *str = b->locspec->to_string ();
13622 encode_source_string (b->number, loc->address, "at", str,
13623 buf.data () + strlen (buf.data ()),
13624 buf.size () - strlen (buf.data ()));
13625 putpkt (buf.data ());
13626 remote_get_noisy_reply ();
13627 if (strcmp (rs->buf.data (), "OK"))
13628 warning (_("Target does not support source download."));
13629 }
13630 if (b->cond_string)
13631 {
13632 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13633
13634 if (ret < 0 || ret >= buf.size ())
13635 error ("%s", err_msg);
13636
13637 encode_source_string (b->number, loc->address,
13638 "cond", b->cond_string.get (),
13639 buf.data () + strlen (buf.data ()),
13640 buf.size () - strlen (buf.data ()));
13641 putpkt (buf.data ());
13642 remote_get_noisy_reply ();
13643 if (strcmp (rs->buf.data (), "OK"))
13644 warning (_("Target does not support source download."));
13645 }
13646 remote_download_command_source (b->number, loc->address,
13647 breakpoint_commands (b));
13648 }
13649 }
13650
13651 bool
13652 remote_target::can_download_tracepoint ()
13653 {
13654 struct remote_state *rs = get_remote_state ();
13655 struct trace_status *ts;
13656 int status;
13657
13658 /* Don't try to install tracepoints until we've relocated our
13659 symbols, and fetched and merged the target's tracepoint list with
13660 ours. */
13661 if (rs->starting_up)
13662 return false;
13663
13664 ts = current_trace_status ();
13665 status = get_trace_status (ts);
13666
13667 if (status == -1 || !ts->running_known || !ts->running)
13668 return false;
13669
13670 /* If we are in a tracing experiment, but remote stub doesn't support
13671 installing tracepoint in trace, we have to return. */
13672 if (!remote_supports_install_in_trace ())
13673 return false;
13674
13675 return true;
13676 }
13677
13678
13679 void
13680 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13681 {
13682 struct remote_state *rs = get_remote_state ();
13683 char *p;
13684
13685 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13686 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13687 tsv.builtin);
13688 p = rs->buf.data () + strlen (rs->buf.data ());
13689 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13690 >= get_remote_packet_size ())
13691 error (_("Trace state variable name too long for tsv definition packet"));
13692 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13693 *p++ = '\0';
13694 putpkt (rs->buf);
13695 remote_get_noisy_reply ();
13696 if (rs->buf[0] == '\0')
13697 error (_("Target does not support this command."));
13698 if (strcmp (rs->buf.data (), "OK") != 0)
13699 error (_("Error on target while downloading trace state variable."));
13700 }
13701
13702 void
13703 remote_target::enable_tracepoint (struct bp_location *location)
13704 {
13705 struct remote_state *rs = get_remote_state ();
13706
13707 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13708 location->owner->number,
13709 phex (location->address, sizeof (CORE_ADDR)));
13710 putpkt (rs->buf);
13711 remote_get_noisy_reply ();
13712 if (rs->buf[0] == '\0')
13713 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13714 if (strcmp (rs->buf.data (), "OK") != 0)
13715 error (_("Error on target while enabling tracepoint."));
13716 }
13717
13718 void
13719 remote_target::disable_tracepoint (struct bp_location *location)
13720 {
13721 struct remote_state *rs = get_remote_state ();
13722
13723 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13724 location->owner->number,
13725 phex (location->address, sizeof (CORE_ADDR)));
13726 putpkt (rs->buf);
13727 remote_get_noisy_reply ();
13728 if (rs->buf[0] == '\0')
13729 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13730 if (strcmp (rs->buf.data (), "OK") != 0)
13731 error (_("Error on target while disabling tracepoint."));
13732 }
13733
13734 void
13735 remote_target::trace_set_readonly_regions ()
13736 {
13737 asection *s;
13738 bfd_size_type size;
13739 bfd_vma vma;
13740 int anysecs = 0;
13741 int offset = 0;
13742 bfd *abfd = current_program_space->exec_bfd ();
13743
13744 if (!abfd)
13745 return; /* No information to give. */
13746
13747 struct remote_state *rs = get_remote_state ();
13748
13749 strcpy (rs->buf.data (), "QTro");
13750 offset = strlen (rs->buf.data ());
13751 for (s = abfd->sections; s; s = s->next)
13752 {
13753 char tmp1[40], tmp2[40];
13754 int sec_length;
13755
13756 if ((s->flags & SEC_LOAD) == 0
13757 /* || (s->flags & SEC_CODE) == 0 */
13758 || (s->flags & SEC_READONLY) == 0)
13759 continue;
13760
13761 anysecs = 1;
13762 vma = bfd_section_vma (s);
13763 size = bfd_section_size (s);
13764 bfd_sprintf_vma (abfd, tmp1, vma);
13765 bfd_sprintf_vma (abfd, tmp2, vma + size);
13766 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13767 if (offset + sec_length + 1 > rs->buf.size ())
13768 {
13769 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13770 != PACKET_ENABLE)
13771 warning (_("\
13772 Too many sections for read-only sections definition packet."));
13773 break;
13774 }
13775 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13776 tmp1, tmp2);
13777 offset += sec_length;
13778 }
13779 if (anysecs)
13780 {
13781 putpkt (rs->buf);
13782 getpkt (&rs->buf);
13783 }
13784 }
13785
13786 void
13787 remote_target::trace_start ()
13788 {
13789 struct remote_state *rs = get_remote_state ();
13790
13791 putpkt ("QTStart");
13792 remote_get_noisy_reply ();
13793 if (rs->buf[0] == '\0')
13794 error (_("Target does not support this command."));
13795 if (strcmp (rs->buf.data (), "OK") != 0)
13796 error (_("Bogus reply from target: %s"), rs->buf.data ());
13797 }
13798
13799 int
13800 remote_target::get_trace_status (struct trace_status *ts)
13801 {
13802 /* Initialize it just to avoid a GCC false warning. */
13803 char *p = NULL;
13804 enum packet_result result;
13805 struct remote_state *rs = get_remote_state ();
13806
13807 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13808 return -1;
13809
13810 /* FIXME we need to get register block size some other way. */
13811 trace_regblock_size
13812 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13813
13814 putpkt ("qTStatus");
13815
13816 try
13817 {
13818 p = remote_get_noisy_reply ();
13819 }
13820 catch (const gdb_exception_error &ex)
13821 {
13822 if (ex.error != TARGET_CLOSE_ERROR)
13823 {
13824 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13825 return -1;
13826 }
13827 throw;
13828 }
13829
13830 result = m_features.packet_ok (p, PACKET_qTStatus);
13831
13832 /* If the remote target doesn't do tracing, flag it. */
13833 if (result == PACKET_UNKNOWN)
13834 return -1;
13835
13836 /* We're working with a live target. */
13837 ts->filename = NULL;
13838
13839 if (*p++ != 'T')
13840 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13841
13842 /* Function 'parse_trace_status' sets default value of each field of
13843 'ts' at first, so we don't have to do it here. */
13844 parse_trace_status (p, ts);
13845
13846 return ts->running;
13847 }
13848
13849 void
13850 remote_target::get_tracepoint_status (tracepoint *tp,
13851 struct uploaded_tp *utp)
13852 {
13853 struct remote_state *rs = get_remote_state ();
13854 char *reply;
13855 size_t size = get_remote_packet_size ();
13856
13857 if (tp)
13858 {
13859 tp->hit_count = 0;
13860 tp->traceframe_usage = 0;
13861 for (bp_location &loc : tp->locations ())
13862 {
13863 /* If the tracepoint was never downloaded, don't go asking for
13864 any status. */
13865 if (tp->number_on_target == 0)
13866 continue;
13867 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13868 phex_nz (loc.address, 0));
13869 putpkt (rs->buf);
13870 reply = remote_get_noisy_reply ();
13871 if (reply && *reply)
13872 {
13873 if (*reply == 'V')
13874 parse_tracepoint_status (reply + 1, tp, utp);
13875 }
13876 }
13877 }
13878 else if (utp)
13879 {
13880 utp->hit_count = 0;
13881 utp->traceframe_usage = 0;
13882 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13883 phex_nz (utp->addr, 0));
13884 putpkt (rs->buf);
13885 reply = remote_get_noisy_reply ();
13886 if (reply && *reply)
13887 {
13888 if (*reply == 'V')
13889 parse_tracepoint_status (reply + 1, tp, utp);
13890 }
13891 }
13892 }
13893
13894 void
13895 remote_target::trace_stop ()
13896 {
13897 struct remote_state *rs = get_remote_state ();
13898
13899 putpkt ("QTStop");
13900 remote_get_noisy_reply ();
13901 if (rs->buf[0] == '\0')
13902 error (_("Target does not support this command."));
13903 if (strcmp (rs->buf.data (), "OK") != 0)
13904 error (_("Bogus reply from target: %s"), rs->buf.data ());
13905 }
13906
13907 int
13908 remote_target::trace_find (enum trace_find_type type, int num,
13909 CORE_ADDR addr1, CORE_ADDR addr2,
13910 int *tpp)
13911 {
13912 struct remote_state *rs = get_remote_state ();
13913 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13914 char *p, *reply;
13915 int target_frameno = -1, target_tracept = -1;
13916
13917 /* Lookups other than by absolute frame number depend on the current
13918 trace selected, so make sure it is correct on the remote end
13919 first. */
13920 if (type != tfind_number)
13921 set_remote_traceframe ();
13922
13923 p = rs->buf.data ();
13924 strcpy (p, "QTFrame:");
13925 p = strchr (p, '\0');
13926 switch (type)
13927 {
13928 case tfind_number:
13929 xsnprintf (p, endbuf - p, "%x", num);
13930 break;
13931 case tfind_pc:
13932 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13933 break;
13934 case tfind_tp:
13935 xsnprintf (p, endbuf - p, "tdp:%x", num);
13936 break;
13937 case tfind_range:
13938 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13939 phex_nz (addr2, 0));
13940 break;
13941 case tfind_outside:
13942 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13943 phex_nz (addr2, 0));
13944 break;
13945 default:
13946 error (_("Unknown trace find type %d"), type);
13947 }
13948
13949 putpkt (rs->buf);
13950 reply = remote_get_noisy_reply ();
13951 if (*reply == '\0')
13952 error (_("Target does not support this command."));
13953
13954 while (reply && *reply)
13955 switch (*reply)
13956 {
13957 case 'F':
13958 p = ++reply;
13959 target_frameno = (int) strtol (p, &reply, 16);
13960 if (reply == p)
13961 error (_("Unable to parse trace frame number"));
13962 /* Don't update our remote traceframe number cache on failure
13963 to select a remote traceframe. */
13964 if (target_frameno == -1)
13965 return -1;
13966 break;
13967 case 'T':
13968 p = ++reply;
13969 target_tracept = (int) strtol (p, &reply, 16);
13970 if (reply == p)
13971 error (_("Unable to parse tracepoint number"));
13972 break;
13973 case 'O': /* "OK"? */
13974 if (reply[1] == 'K' && reply[2] == '\0')
13975 reply += 2;
13976 else
13977 error (_("Bogus reply from target: %s"), reply);
13978 break;
13979 default:
13980 error (_("Bogus reply from target: %s"), reply);
13981 }
13982 if (tpp)
13983 *tpp = target_tracept;
13984
13985 rs->remote_traceframe_number = target_frameno;
13986 return target_frameno;
13987 }
13988
13989 bool
13990 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13991 {
13992 struct remote_state *rs = get_remote_state ();
13993 char *reply;
13994 ULONGEST uval;
13995
13996 set_remote_traceframe ();
13997
13998 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13999 putpkt (rs->buf);
14000 reply = remote_get_noisy_reply ();
14001 if (reply && *reply)
14002 {
14003 if (*reply == 'V')
14004 {
14005 unpack_varlen_hex (reply + 1, &uval);
14006 *val = (LONGEST) uval;
14007 return true;
14008 }
14009 }
14010 return false;
14011 }
14012
14013 int
14014 remote_target::save_trace_data (const char *filename)
14015 {
14016 struct remote_state *rs = get_remote_state ();
14017 char *p, *reply;
14018
14019 p = rs->buf.data ();
14020 strcpy (p, "QTSave:");
14021 p += strlen (p);
14022 if ((p - rs->buf.data ()) + strlen (filename) * 2
14023 >= get_remote_packet_size ())
14024 error (_("Remote file name too long for trace save packet"));
14025 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14026 *p++ = '\0';
14027 putpkt (rs->buf);
14028 reply = remote_get_noisy_reply ();
14029 if (*reply == '\0')
14030 error (_("Target does not support this command."));
14031 if (strcmp (reply, "OK") != 0)
14032 error (_("Bogus reply from target: %s"), reply);
14033 return 0;
14034 }
14035
14036 /* This is basically a memory transfer, but needs to be its own packet
14037 because we don't know how the target actually organizes its trace
14038 memory, plus we want to be able to ask for as much as possible, but
14039 not be unhappy if we don't get as much as we ask for. */
14040
14041 LONGEST
14042 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14043 {
14044 struct remote_state *rs = get_remote_state ();
14045 char *reply;
14046 char *p;
14047 int rslt;
14048
14049 p = rs->buf.data ();
14050 strcpy (p, "qTBuffer:");
14051 p += strlen (p);
14052 p += hexnumstr (p, offset);
14053 *p++ = ',';
14054 p += hexnumstr (p, len);
14055 *p++ = '\0';
14056
14057 putpkt (rs->buf);
14058 reply = remote_get_noisy_reply ();
14059 if (reply && *reply)
14060 {
14061 /* 'l' by itself means we're at the end of the buffer and
14062 there is nothing more to get. */
14063 if (*reply == 'l')
14064 return 0;
14065
14066 /* Convert the reply into binary. Limit the number of bytes to
14067 convert according to our passed-in buffer size, rather than
14068 what was returned in the packet; if the target is
14069 unexpectedly generous and gives us a bigger reply than we
14070 asked for, we don't want to crash. */
14071 rslt = hex2bin (reply, buf, len);
14072 return rslt;
14073 }
14074
14075 /* Something went wrong, flag as an error. */
14076 return -1;
14077 }
14078
14079 void
14080 remote_target::set_disconnected_tracing (int val)
14081 {
14082 struct remote_state *rs = get_remote_state ();
14083
14084 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14085 == PACKET_ENABLE)
14086 {
14087 char *reply;
14088
14089 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14090 "QTDisconnected:%x", val);
14091 putpkt (rs->buf);
14092 reply = remote_get_noisy_reply ();
14093 if (*reply == '\0')
14094 error (_("Target does not support this command."));
14095 if (strcmp (reply, "OK") != 0)
14096 error (_("Bogus reply from target: %s"), reply);
14097 }
14098 else if (val)
14099 warning (_("Target does not support disconnected tracing."));
14100 }
14101
14102 int
14103 remote_target::core_of_thread (ptid_t ptid)
14104 {
14105 thread_info *info = this->find_thread (ptid);
14106
14107 if (info != NULL && info->priv != NULL)
14108 return get_remote_thread_info (info)->core;
14109
14110 return -1;
14111 }
14112
14113 void
14114 remote_target::set_circular_trace_buffer (int val)
14115 {
14116 struct remote_state *rs = get_remote_state ();
14117 char *reply;
14118
14119 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14120 "QTBuffer:circular:%x", val);
14121 putpkt (rs->buf);
14122 reply = remote_get_noisy_reply ();
14123 if (*reply == '\0')
14124 error (_("Target does not support this command."));
14125 if (strcmp (reply, "OK") != 0)
14126 error (_("Bogus reply from target: %s"), reply);
14127 }
14128
14129 traceframe_info_up
14130 remote_target::traceframe_info ()
14131 {
14132 gdb::optional<gdb::char_vector> text
14133 = target_read_stralloc (current_inferior ()->top_target (),
14134 TARGET_OBJECT_TRACEFRAME_INFO,
14135 NULL);
14136 if (text)
14137 return parse_traceframe_info (text->data ());
14138
14139 return NULL;
14140 }
14141
14142 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14143 instruction on which a fast tracepoint may be placed. Returns -1
14144 if the packet is not supported, and 0 if the minimum instruction
14145 length is unknown. */
14146
14147 int
14148 remote_target::get_min_fast_tracepoint_insn_len ()
14149 {
14150 struct remote_state *rs = get_remote_state ();
14151 char *reply;
14152
14153 /* If we're not debugging a process yet, the IPA can't be
14154 loaded. */
14155 if (!target_has_execution ())
14156 return 0;
14157
14158 /* Make sure the remote is pointing at the right process. */
14159 set_general_process ();
14160
14161 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14162 putpkt (rs->buf);
14163 reply = remote_get_noisy_reply ();
14164 if (*reply == '\0')
14165 return -1;
14166 else
14167 {
14168 ULONGEST min_insn_len;
14169
14170 unpack_varlen_hex (reply, &min_insn_len);
14171
14172 return (int) min_insn_len;
14173 }
14174 }
14175
14176 void
14177 remote_target::set_trace_buffer_size (LONGEST val)
14178 {
14179 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14180 {
14181 struct remote_state *rs = get_remote_state ();
14182 char *buf = rs->buf.data ();
14183 char *endbuf = buf + get_remote_packet_size ();
14184 enum packet_result result;
14185
14186 gdb_assert (val >= 0 || val == -1);
14187 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14188 /* Send -1 as literal "-1" to avoid host size dependency. */
14189 if (val < 0)
14190 {
14191 *buf++ = '-';
14192 buf += hexnumstr (buf, (ULONGEST) -val);
14193 }
14194 else
14195 buf += hexnumstr (buf, (ULONGEST) val);
14196
14197 putpkt (rs->buf);
14198 remote_get_noisy_reply ();
14199 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14200
14201 if (result != PACKET_OK)
14202 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14203 }
14204 }
14205
14206 bool
14207 remote_target::set_trace_notes (const char *user, const char *notes,
14208 const char *stop_notes)
14209 {
14210 struct remote_state *rs = get_remote_state ();
14211 char *reply;
14212 char *buf = rs->buf.data ();
14213 char *endbuf = buf + get_remote_packet_size ();
14214 int nbytes;
14215
14216 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14217 if (user)
14218 {
14219 buf += xsnprintf (buf, endbuf - buf, "user:");
14220 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14221 buf += 2 * nbytes;
14222 *buf++ = ';';
14223 }
14224 if (notes)
14225 {
14226 buf += xsnprintf (buf, endbuf - buf, "notes:");
14227 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14228 buf += 2 * nbytes;
14229 *buf++ = ';';
14230 }
14231 if (stop_notes)
14232 {
14233 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14234 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14235 buf += 2 * nbytes;
14236 *buf++ = ';';
14237 }
14238 /* Ensure the buffer is terminated. */
14239 *buf = '\0';
14240
14241 putpkt (rs->buf);
14242 reply = remote_get_noisy_reply ();
14243 if (*reply == '\0')
14244 return false;
14245
14246 if (strcmp (reply, "OK") != 0)
14247 error (_("Bogus reply from target: %s"), reply);
14248
14249 return true;
14250 }
14251
14252 bool
14253 remote_target::use_agent (bool use)
14254 {
14255 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14256 {
14257 struct remote_state *rs = get_remote_state ();
14258
14259 /* If the stub supports QAgent. */
14260 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14261 putpkt (rs->buf);
14262 getpkt (&rs->buf);
14263
14264 if (strcmp (rs->buf.data (), "OK") == 0)
14265 {
14266 ::use_agent = use;
14267 return true;
14268 }
14269 }
14270
14271 return false;
14272 }
14273
14274 bool
14275 remote_target::can_use_agent ()
14276 {
14277 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14278 }
14279
14280 #if defined (HAVE_LIBEXPAT)
14281
14282 /* Check the btrace document version. */
14283
14284 static void
14285 check_xml_btrace_version (struct gdb_xml_parser *parser,
14286 const struct gdb_xml_element *element,
14287 void *user_data,
14288 std::vector<gdb_xml_value> &attributes)
14289 {
14290 const char *version
14291 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14292
14293 if (strcmp (version, "1.0") != 0)
14294 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14295 }
14296
14297 /* Parse a btrace "block" xml record. */
14298
14299 static void
14300 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14301 const struct gdb_xml_element *element,
14302 void *user_data,
14303 std::vector<gdb_xml_value> &attributes)
14304 {
14305 struct btrace_data *btrace;
14306 ULONGEST *begin, *end;
14307
14308 btrace = (struct btrace_data *) user_data;
14309
14310 switch (btrace->format)
14311 {
14312 case BTRACE_FORMAT_BTS:
14313 break;
14314
14315 case BTRACE_FORMAT_NONE:
14316 btrace->format = BTRACE_FORMAT_BTS;
14317 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14318 break;
14319
14320 default:
14321 gdb_xml_error (parser, _("Btrace format error."));
14322 }
14323
14324 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14325 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14326 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14327 }
14328
14329 /* Parse a "raw" xml record. */
14330
14331 static void
14332 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14333 gdb_byte **pdata, size_t *psize)
14334 {
14335 gdb_byte *bin;
14336 size_t len, size;
14337
14338 len = strlen (body_text);
14339 if (len % 2 != 0)
14340 gdb_xml_error (parser, _("Bad raw data size."));
14341
14342 size = len / 2;
14343
14344 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14345 bin = data.get ();
14346
14347 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14348 while (len > 0)
14349 {
14350 char hi, lo;
14351
14352 hi = *body_text++;
14353 lo = *body_text++;
14354
14355 if (hi == 0 || lo == 0)
14356 gdb_xml_error (parser, _("Bad hex encoding."));
14357
14358 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14359 len -= 2;
14360 }
14361
14362 *pdata = data.release ();
14363 *psize = size;
14364 }
14365
14366 /* Parse a btrace pt-config "cpu" xml record. */
14367
14368 static void
14369 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14370 const struct gdb_xml_element *element,
14371 void *user_data,
14372 std::vector<gdb_xml_value> &attributes)
14373 {
14374 struct btrace_data *btrace;
14375 const char *vendor;
14376 ULONGEST *family, *model, *stepping;
14377
14378 vendor
14379 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14380 family
14381 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14382 model
14383 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14384 stepping
14385 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14386
14387 btrace = (struct btrace_data *) user_data;
14388
14389 if (strcmp (vendor, "GenuineIntel") == 0)
14390 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14391
14392 btrace->variant.pt.config.cpu.family = *family;
14393 btrace->variant.pt.config.cpu.model = *model;
14394 btrace->variant.pt.config.cpu.stepping = *stepping;
14395 }
14396
14397 /* Parse a btrace pt "raw" xml record. */
14398
14399 static void
14400 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14401 const struct gdb_xml_element *element,
14402 void *user_data, const char *body_text)
14403 {
14404 struct btrace_data *btrace;
14405
14406 btrace = (struct btrace_data *) user_data;
14407 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14408 &btrace->variant.pt.size);
14409 }
14410
14411 /* Parse a btrace "pt" xml record. */
14412
14413 static void
14414 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14415 const struct gdb_xml_element *element,
14416 void *user_data,
14417 std::vector<gdb_xml_value> &attributes)
14418 {
14419 struct btrace_data *btrace;
14420
14421 btrace = (struct btrace_data *) user_data;
14422 btrace->format = BTRACE_FORMAT_PT;
14423 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14424 btrace->variant.pt.data = NULL;
14425 btrace->variant.pt.size = 0;
14426 }
14427
14428 static const struct gdb_xml_attribute block_attributes[] = {
14429 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14430 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14431 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14432 };
14433
14434 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14435 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14436 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14437 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14438 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14439 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14440 };
14441
14442 static const struct gdb_xml_element btrace_pt_config_children[] = {
14443 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14444 parse_xml_btrace_pt_config_cpu, NULL },
14445 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14446 };
14447
14448 static const struct gdb_xml_element btrace_pt_children[] = {
14449 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14450 NULL },
14451 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14452 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14453 };
14454
14455 static const struct gdb_xml_attribute btrace_attributes[] = {
14456 { "version", GDB_XML_AF_NONE, NULL, NULL },
14457 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14458 };
14459
14460 static const struct gdb_xml_element btrace_children[] = {
14461 { "block", block_attributes, NULL,
14462 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14463 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14464 NULL },
14465 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14466 };
14467
14468 static const struct gdb_xml_element btrace_elements[] = {
14469 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14470 check_xml_btrace_version, NULL },
14471 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14472 };
14473
14474 #endif /* defined (HAVE_LIBEXPAT) */
14475
14476 /* Parse a branch trace xml document XML into DATA. */
14477
14478 static void
14479 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14480 {
14481 #if defined (HAVE_LIBEXPAT)
14482
14483 int errcode;
14484 btrace_data result;
14485 result.format = BTRACE_FORMAT_NONE;
14486
14487 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14488 buffer, &result);
14489 if (errcode != 0)
14490 error (_("Error parsing branch trace."));
14491
14492 /* Keep parse results. */
14493 *btrace = std::move (result);
14494
14495 #else /* !defined (HAVE_LIBEXPAT) */
14496
14497 error (_("Cannot process branch trace. XML support was disabled at "
14498 "compile time."));
14499
14500 #endif /* !defined (HAVE_LIBEXPAT) */
14501 }
14502
14503 #if defined (HAVE_LIBEXPAT)
14504
14505 /* Parse a btrace-conf "bts" xml record. */
14506
14507 static void
14508 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14509 const struct gdb_xml_element *element,
14510 void *user_data,
14511 std::vector<gdb_xml_value> &attributes)
14512 {
14513 struct btrace_config *conf;
14514 struct gdb_xml_value *size;
14515
14516 conf = (struct btrace_config *) user_data;
14517 conf->format = BTRACE_FORMAT_BTS;
14518 conf->bts.size = 0;
14519
14520 size = xml_find_attribute (attributes, "size");
14521 if (size != NULL)
14522 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14523 }
14524
14525 /* Parse a btrace-conf "pt" xml record. */
14526
14527 static void
14528 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14529 const struct gdb_xml_element *element,
14530 void *user_data,
14531 std::vector<gdb_xml_value> &attributes)
14532 {
14533 struct btrace_config *conf;
14534 struct gdb_xml_value *size;
14535
14536 conf = (struct btrace_config *) user_data;
14537 conf->format = BTRACE_FORMAT_PT;
14538 conf->pt.size = 0;
14539
14540 size = xml_find_attribute (attributes, "size");
14541 if (size != NULL)
14542 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14543 }
14544
14545 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14546 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14547 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14548 };
14549
14550 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14551 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14552 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14553 };
14554
14555 static const struct gdb_xml_element btrace_conf_children[] = {
14556 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14557 parse_xml_btrace_conf_bts, NULL },
14558 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14559 parse_xml_btrace_conf_pt, NULL },
14560 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14561 };
14562
14563 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14564 { "version", GDB_XML_AF_NONE, NULL, NULL },
14565 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14566 };
14567
14568 static const struct gdb_xml_element btrace_conf_elements[] = {
14569 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14570 GDB_XML_EF_NONE, NULL, NULL },
14571 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14572 };
14573
14574 #endif /* defined (HAVE_LIBEXPAT) */
14575
14576 /* Parse a branch trace configuration xml document XML into CONF. */
14577
14578 static void
14579 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14580 {
14581 #if defined (HAVE_LIBEXPAT)
14582
14583 int errcode;
14584 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14585 btrace_conf_elements, xml, conf);
14586 if (errcode != 0)
14587 error (_("Error parsing branch trace configuration."));
14588
14589 #else /* !defined (HAVE_LIBEXPAT) */
14590
14591 error (_("Cannot process the branch trace configuration. XML support "
14592 "was disabled at compile time."));
14593
14594 #endif /* !defined (HAVE_LIBEXPAT) */
14595 }
14596
14597 /* Reset our idea of our target's btrace configuration. */
14598
14599 static void
14600 remote_btrace_reset (remote_state *rs)
14601 {
14602 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14603 }
14604
14605 /* Synchronize the configuration with the target. */
14606
14607 void
14608 remote_target::btrace_sync_conf (const btrace_config *conf)
14609 {
14610 struct remote_state *rs;
14611 char *buf, *pos, *endbuf;
14612
14613 rs = get_remote_state ();
14614 buf = rs->buf.data ();
14615 endbuf = buf + get_remote_packet_size ();
14616
14617 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14618 && conf->bts.size != rs->btrace_config.bts.size)
14619 {
14620 pos = buf;
14621 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14622 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14623 conf->bts.size);
14624
14625 putpkt (buf);
14626 getpkt (&rs->buf);
14627
14628 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14629 == PACKET_ERROR)
14630 {
14631 if (buf[0] == 'E' && buf[1] == '.')
14632 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14633 else
14634 error (_("Failed to configure the BTS buffer size."));
14635 }
14636
14637 rs->btrace_config.bts.size = conf->bts.size;
14638 }
14639
14640 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14641 && conf->pt.size != rs->btrace_config.pt.size)
14642 {
14643 pos = buf;
14644 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14645 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14646 conf->pt.size);
14647
14648 putpkt (buf);
14649 getpkt (&rs->buf);
14650
14651 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14652 == PACKET_ERROR)
14653 {
14654 if (buf[0] == 'E' && buf[1] == '.')
14655 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14656 else
14657 error (_("Failed to configure the trace buffer size."));
14658 }
14659
14660 rs->btrace_config.pt.size = conf->pt.size;
14661 }
14662 }
14663
14664 /* Read TP's btrace configuration from the target and store it into CONF. */
14665
14666 static void
14667 btrace_read_config (thread_info *tp, btrace_config *conf)
14668 {
14669 /* target_read_stralloc relies on INFERIOR_PTID. */
14670 scoped_restore_current_thread restore_thread;
14671 switch_to_thread (tp);
14672
14673 gdb::optional<gdb::char_vector> xml
14674 = target_read_stralloc (current_inferior ()->top_target (),
14675 TARGET_OBJECT_BTRACE_CONF, "");
14676 if (xml)
14677 parse_xml_btrace_conf (conf, xml->data ());
14678 }
14679
14680 /* Maybe reopen target btrace. */
14681
14682 void
14683 remote_target::remote_btrace_maybe_reopen ()
14684 {
14685 struct remote_state *rs = get_remote_state ();
14686 int btrace_target_pushed = 0;
14687 #if !defined (HAVE_LIBIPT)
14688 int warned = 0;
14689 #endif
14690
14691 /* Don't bother walking the entirety of the remote thread list when
14692 we know the feature isn't supported by the remote. */
14693 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14694 return;
14695
14696 for (thread_info *tp : all_non_exited_threads (this))
14697 {
14698 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14699 btrace_read_config (tp, &rs->btrace_config);
14700
14701 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14702 continue;
14703
14704 #if !defined (HAVE_LIBIPT)
14705 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14706 {
14707 if (!warned)
14708 {
14709 warned = 1;
14710 warning (_("Target is recording using Intel Processor Trace "
14711 "but support was disabled at compile time."));
14712 }
14713
14714 continue;
14715 }
14716 #endif /* !defined (HAVE_LIBIPT) */
14717
14718 /* Push target, once, but before anything else happens. This way our
14719 changes to the threads will be cleaned up by unpushing the target
14720 in case btrace_read_config () throws. */
14721 if (!btrace_target_pushed)
14722 {
14723 btrace_target_pushed = 1;
14724 record_btrace_push_target ();
14725 gdb_printf (_("Target is recording using %s.\n"),
14726 btrace_format_string (rs->btrace_config.format));
14727 }
14728
14729 tp->btrace.target
14730 = new btrace_target_info { tp->ptid, rs->btrace_config };
14731 }
14732 }
14733
14734 /* Enable branch tracing. */
14735
14736 struct btrace_target_info *
14737 remote_target::enable_btrace (thread_info *tp,
14738 const struct btrace_config *conf)
14739 {
14740 struct packet_config *packet = NULL;
14741 struct remote_state *rs = get_remote_state ();
14742 char *buf = rs->buf.data ();
14743 char *endbuf = buf + get_remote_packet_size ();
14744
14745 unsigned int which_packet;
14746 switch (conf->format)
14747 {
14748 case BTRACE_FORMAT_BTS:
14749 which_packet = PACKET_Qbtrace_bts;
14750 break;
14751 case BTRACE_FORMAT_PT:
14752 which_packet = PACKET_Qbtrace_pt;
14753 break;
14754 default:
14755 internal_error (_("Bad branch btrace format: %u."),
14756 (unsigned int) conf->format);
14757 }
14758
14759 packet = &m_features.m_protocol_packets[which_packet];
14760 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14761 error (_("Target does not support branch tracing."));
14762
14763 btrace_sync_conf (conf);
14764
14765 ptid_t ptid = tp->ptid;
14766 set_general_thread (ptid);
14767
14768 buf += xsnprintf (buf, endbuf - buf, "%s",
14769 packets_descriptions[which_packet].name);
14770 putpkt (rs->buf);
14771 getpkt (&rs->buf);
14772
14773 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14774 {
14775 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14776 error (_("Could not enable branch tracing for %s: %s"),
14777 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14778 else
14779 error (_("Could not enable branch tracing for %s."),
14780 target_pid_to_str (ptid).c_str ());
14781 }
14782
14783 btrace_target_info *tinfo = new btrace_target_info { ptid };
14784
14785 /* If we fail to read the configuration, we lose some information, but the
14786 tracing itself is not impacted. */
14787 try
14788 {
14789 btrace_read_config (tp, &tinfo->conf);
14790 }
14791 catch (const gdb_exception_error &err)
14792 {
14793 if (err.message != NULL)
14794 warning ("%s", err.what ());
14795 }
14796
14797 return tinfo;
14798 }
14799
14800 /* Disable branch tracing. */
14801
14802 void
14803 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14804 {
14805 struct remote_state *rs = get_remote_state ();
14806 char *buf = rs->buf.data ();
14807 char *endbuf = buf + get_remote_packet_size ();
14808
14809 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14810 error (_("Target does not support branch tracing."));
14811
14812 set_general_thread (tinfo->ptid);
14813
14814 buf += xsnprintf (buf, endbuf - buf, "%s",
14815 packets_descriptions[PACKET_Qbtrace_off].name);
14816 putpkt (rs->buf);
14817 getpkt (&rs->buf);
14818
14819 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14820 {
14821 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14822 error (_("Could not disable branch tracing for %s: %s"),
14823 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14824 else
14825 error (_("Could not disable branch tracing for %s."),
14826 target_pid_to_str (tinfo->ptid).c_str ());
14827 }
14828
14829 delete tinfo;
14830 }
14831
14832 /* Teardown branch tracing. */
14833
14834 void
14835 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14836 {
14837 /* We must not talk to the target during teardown. */
14838 delete tinfo;
14839 }
14840
14841 /* Read the branch trace. */
14842
14843 enum btrace_error
14844 remote_target::read_btrace (struct btrace_data *btrace,
14845 struct btrace_target_info *tinfo,
14846 enum btrace_read_type type)
14847 {
14848 const char *annex;
14849
14850 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14851 error (_("Target does not support branch tracing."));
14852
14853 #if !defined(HAVE_LIBEXPAT)
14854 error (_("Cannot process branch tracing result. XML parsing not supported."));
14855 #endif
14856
14857 switch (type)
14858 {
14859 case BTRACE_READ_ALL:
14860 annex = "all";
14861 break;
14862 case BTRACE_READ_NEW:
14863 annex = "new";
14864 break;
14865 case BTRACE_READ_DELTA:
14866 annex = "delta";
14867 break;
14868 default:
14869 internal_error (_("Bad branch tracing read type: %u."),
14870 (unsigned int) type);
14871 }
14872
14873 gdb::optional<gdb::char_vector> xml
14874 = target_read_stralloc (current_inferior ()->top_target (),
14875 TARGET_OBJECT_BTRACE, annex);
14876 if (!xml)
14877 return BTRACE_ERR_UNKNOWN;
14878
14879 parse_xml_btrace (btrace, xml->data ());
14880
14881 return BTRACE_ERR_NONE;
14882 }
14883
14884 const struct btrace_config *
14885 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14886 {
14887 return &tinfo->conf;
14888 }
14889
14890 bool
14891 remote_target::augmented_libraries_svr4_read ()
14892 {
14893 return
14894 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14895 == PACKET_ENABLE);
14896 }
14897
14898 /* Implementation of to_load. */
14899
14900 void
14901 remote_target::load (const char *name, int from_tty)
14902 {
14903 generic_load (name, from_tty);
14904 }
14905
14906 /* Accepts an integer PID; returns a string representing a file that
14907 can be opened on the remote side to get the symbols for the child
14908 process. Returns NULL if the operation is not supported. */
14909
14910 const char *
14911 remote_target::pid_to_exec_file (int pid)
14912 {
14913 static gdb::optional<gdb::char_vector> filename;
14914 char *annex = NULL;
14915
14916 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14917 return NULL;
14918
14919 inferior *inf = find_inferior_pid (this, pid);
14920 if (inf == NULL)
14921 internal_error (_("not currently attached to process %d"), pid);
14922
14923 if (!inf->fake_pid_p)
14924 {
14925 const int annex_size = 9;
14926
14927 annex = (char *) alloca (annex_size);
14928 xsnprintf (annex, annex_size, "%x", pid);
14929 }
14930
14931 filename = target_read_stralloc (current_inferior ()->top_target (),
14932 TARGET_OBJECT_EXEC_FILE, annex);
14933
14934 return filename ? filename->data () : nullptr;
14935 }
14936
14937 /* Implement the to_can_do_single_step target_ops method. */
14938
14939 int
14940 remote_target::can_do_single_step ()
14941 {
14942 /* We can only tell whether target supports single step or not by
14943 supported s and S vCont actions if the stub supports vContSupported
14944 feature. If the stub doesn't support vContSupported feature,
14945 we have conservatively to think target doesn't supports single
14946 step. */
14947 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14948 {
14949 struct remote_state *rs = get_remote_state ();
14950
14951 return rs->supports_vCont.s && rs->supports_vCont.S;
14952 }
14953 else
14954 return 0;
14955 }
14956
14957 /* Implementation of the to_execution_direction method for the remote
14958 target. */
14959
14960 enum exec_direction_kind
14961 remote_target::execution_direction ()
14962 {
14963 struct remote_state *rs = get_remote_state ();
14964
14965 return rs->last_resume_exec_dir;
14966 }
14967
14968 /* Return pointer to the thread_info struct which corresponds to
14969 THREAD_HANDLE (having length HANDLE_LEN). */
14970
14971 thread_info *
14972 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14973 int handle_len,
14974 inferior *inf)
14975 {
14976 for (thread_info *tp : all_non_exited_threads (this))
14977 {
14978 remote_thread_info *priv = get_remote_thread_info (tp);
14979
14980 if (tp->inf == inf && priv != NULL)
14981 {
14982 if (handle_len != priv->thread_handle.size ())
14983 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14984 handle_len, priv->thread_handle.size ());
14985 if (memcmp (thread_handle, priv->thread_handle.data (),
14986 handle_len) == 0)
14987 return tp;
14988 }
14989 }
14990
14991 return NULL;
14992 }
14993
14994 gdb::array_view<const gdb_byte>
14995 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14996 {
14997 remote_thread_info *priv = get_remote_thread_info (tp);
14998 return priv->thread_handle;
14999 }
15000
15001 bool
15002 remote_target::can_async_p ()
15003 {
15004 /* This flag should be checked in the common target.c code. */
15005 gdb_assert (target_async_permitted);
15006
15007 /* We're async whenever the serial device can. */
15008 return get_remote_state ()->can_async_p ();
15009 }
15010
15011 bool
15012 remote_target::is_async_p ()
15013 {
15014 /* We're async whenever the serial device is. */
15015 return get_remote_state ()->is_async_p ();
15016 }
15017
15018 /* Pass the SERIAL event on and up to the client. One day this code
15019 will be able to delay notifying the client of an event until the
15020 point where an entire packet has been received. */
15021
15022 static serial_event_ftype remote_async_serial_handler;
15023
15024 static void
15025 remote_async_serial_handler (struct serial *scb, void *context)
15026 {
15027 /* Don't propogate error information up to the client. Instead let
15028 the client find out about the error by querying the target. */
15029 inferior_event_handler (INF_REG_EVENT);
15030 }
15031
15032 int
15033 remote_target::async_wait_fd ()
15034 {
15035 struct remote_state *rs = get_remote_state ();
15036 return rs->remote_desc->fd;
15037 }
15038
15039 void
15040 remote_target::async (bool enable)
15041 {
15042 struct remote_state *rs = get_remote_state ();
15043
15044 if (enable)
15045 {
15046 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15047
15048 /* If there are pending events in the stop reply queue tell the
15049 event loop to process them. */
15050 if (!rs->stop_reply_queue.empty ())
15051 rs->mark_async_event_handler ();
15052
15053 /* For simplicity, below we clear the pending events token
15054 without remembering whether it is marked, so here we always
15055 mark it. If there's actually no pending notification to
15056 process, this ends up being a no-op (other than a spurious
15057 event-loop wakeup). */
15058 if (target_is_non_stop_p ())
15059 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15060 }
15061 else
15062 {
15063 serial_async (rs->remote_desc, NULL, NULL);
15064 /* If the core is disabling async, it doesn't want to be
15065 disturbed with target events. Clear all async event sources
15066 too. */
15067 rs->clear_async_event_handler ();
15068
15069 if (target_is_non_stop_p ())
15070 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15071 }
15072 }
15073
15074 /* Implementation of the to_thread_events method. */
15075
15076 void
15077 remote_target::thread_events (int enable)
15078 {
15079 struct remote_state *rs = get_remote_state ();
15080 size_t size = get_remote_packet_size ();
15081
15082 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15083 return;
15084
15085 if (rs->last_thread_events == enable)
15086 return;
15087
15088 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15089 putpkt (rs->buf);
15090 getpkt (&rs->buf);
15091
15092 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
15093 {
15094 case PACKET_OK:
15095 if (strcmp (rs->buf.data (), "OK") != 0)
15096 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15097 rs->last_thread_events = enable;
15098 break;
15099 case PACKET_ERROR:
15100 warning (_("Remote failure reply: %s"), rs->buf.data ());
15101 break;
15102 case PACKET_UNKNOWN:
15103 break;
15104 }
15105 }
15106
15107 /* Implementation of the supports_set_thread_options target
15108 method. */
15109
15110 bool
15111 remote_target::supports_set_thread_options (gdb_thread_options options)
15112 {
15113 remote_state *rs = get_remote_state ();
15114 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15115 && (rs->supported_thread_options & options) == options);
15116 }
15117
15118 /* For coalescing reasons, actually sending the options to the target
15119 happens at resume time, via this function. See target_resume for
15120 all-stop, and target_commit_resumed for non-stop. */
15121
15122 void
15123 remote_target::commit_requested_thread_options ()
15124 {
15125 struct remote_state *rs = get_remote_state ();
15126
15127 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15128 return;
15129
15130 char *p = rs->buf.data ();
15131 char *endp = p + get_remote_packet_size ();
15132
15133 /* Clear options for all threads by default. Note that unlike
15134 vCont, the rightmost options that match a thread apply, so we
15135 don't have to worry about whether we can use wildcard ptids. */
15136 strcpy (p, "QThreadOptions;0");
15137 p += strlen (p);
15138
15139 /* Send the QThreadOptions packet stored in P. */
15140 auto flush = [&] ()
15141 {
15142 *p++ = '\0';
15143
15144 putpkt (rs->buf);
15145 getpkt (&rs->buf, 0);
15146
15147 switch (m_features.packet_ok (rs->buf, PACKET_QThreadOptions))
15148 {
15149 case PACKET_OK:
15150 if (strcmp (rs->buf.data (), "OK") != 0)
15151 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15152 break;
15153 case PACKET_ERROR:
15154 error (_("Remote failure reply: %s"), rs->buf.data ());
15155 case PACKET_UNKNOWN:
15156 gdb_assert_not_reached ("PACKET_UNKNOWN");
15157 break;
15158 }
15159 };
15160
15161 /* Prepare P for another QThreadOptions packet. */
15162 auto restart = [&] ()
15163 {
15164 p = rs->buf.data ();
15165 strcpy (p, "QThreadOptions");
15166 p += strlen (p);
15167 };
15168
15169 /* Now set non-zero options for threads that need them. We don't
15170 bother with the case of all threads of a process wanting the same
15171 non-zero options as that's not an expected scenario. */
15172 for (thread_info *tp : all_non_exited_threads (this))
15173 {
15174 gdb_thread_options options = tp->thread_options ();
15175
15176 if (options == 0)
15177 continue;
15178
15179 /* It might be possible to we have more threads with options
15180 than can fit a single QThreadOptions packet. So build each
15181 options/thread pair in this separate buffer to make sure it
15182 fits. */
15183 constexpr size_t max_options_size = 100;
15184 char obuf[max_options_size];
15185 char *obuf_p = obuf;
15186 char *obuf_endp = obuf + max_options_size;
15187
15188 *obuf_p++ = ';';
15189 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15190 phex_nz (options, sizeof (options)));
15191 if (tp->ptid != magic_null_ptid)
15192 {
15193 *obuf_p++ = ':';
15194 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15195 }
15196
15197 size_t osize = obuf_p - obuf;
15198 if (osize > endp - p)
15199 {
15200 /* This new options/thread pair doesn't fit the packet
15201 buffer. Send what we have already. */
15202 flush ();
15203 restart ();
15204
15205 /* Should now fit. */
15206 gdb_assert (osize <= endp - p);
15207 }
15208
15209 memcpy (p, obuf, osize);
15210 p += osize;
15211 }
15212
15213 flush ();
15214 }
15215
15216 static void
15217 show_remote_cmd (const char *args, int from_tty)
15218 {
15219 /* We can't just use cmd_show_list here, because we want to skip
15220 the redundant "show remote Z-packet" and the legacy aliases. */
15221 struct cmd_list_element *list = remote_show_cmdlist;
15222 struct ui_out *uiout = current_uiout;
15223
15224 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15225 for (; list != NULL; list = list->next)
15226 if (strcmp (list->name, "Z-packet") == 0)
15227 continue;
15228 else if (list->type == not_set_cmd)
15229 /* Alias commands are exactly like the original, except they
15230 don't have the normal type. */
15231 continue;
15232 else
15233 {
15234 ui_out_emit_tuple option_emitter (uiout, "option");
15235
15236 uiout->field_string ("name", list->name);
15237 uiout->text (": ");
15238 if (list->type == show_cmd)
15239 do_show_command (NULL, from_tty, list);
15240 else
15241 cmd_func (list, NULL, from_tty);
15242 }
15243 }
15244
15245 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15246 offer all inferiors using that program space a change to look up symbols. */
15247
15248 static void
15249 remote_objfile_changed_check_symbols (program_space *pspace)
15250 {
15251 /* The affected program space is possibly shared by multiple inferiors.
15252 Consider sending a qSymbol packet for each of the inferiors using that
15253 program space. */
15254 for (inferior *inf : all_inferiors ())
15255 {
15256 if (inf->pspace != pspace)
15257 continue;
15258
15259 /* Check whether the inferior's process target is a remote target. */
15260 remote_target *remote = as_remote_target (inf->process_target ());
15261 if (remote == nullptr)
15262 continue;
15263
15264 /* When we are attaching or handling a fork child and the shared library
15265 subsystem reads the list of loaded libraries, we receive new objfile
15266 events in between each found library. The libraries are read in an
15267 undefined order, so if we gave the remote side a chance to look up
15268 symbols between each objfile, we might give it an inconsistent picture
15269 of the inferior. It could appear that a library A appears loaded but
15270 a library B does not, even though library A requires library B. That
15271 would present a state that couldn't normally exist in the inferior.
15272
15273 So, skip these events, we'll give the remote a chance to look up
15274 symbols once all the loaded libraries and their symbols are known to
15275 GDB. */
15276 if (inf->in_initial_library_scan)
15277 continue;
15278
15279 if (!remote->has_execution (inf))
15280 continue;
15281
15282 /* Need to switch to a specific thread, because remote_check_symbols will
15283 set the general thread using INFERIOR_PTID.
15284
15285 It's possible to have inferiors with no thread here, because we are
15286 called very early in the connection process, while the inferior is
15287 being set up, before threads are added. Just skip it, start_remote_1
15288 also calls remote_check_symbols when it's done setting things up. */
15289 thread_info *thread = any_thread_of_inferior (inf);
15290 if (thread != nullptr)
15291 {
15292 scoped_restore_current_thread restore_thread;
15293 switch_to_thread (thread);
15294 remote->remote_check_symbols ();
15295 }
15296 }
15297 }
15298
15299 /* Function to be called whenever a new objfile (shlib) is detected. */
15300
15301 static void
15302 remote_new_objfile (struct objfile *objfile)
15303 {
15304 remote_objfile_changed_check_symbols (objfile->pspace);
15305 }
15306
15307 /* Pull all the tracepoints defined on the target and create local
15308 data structures representing them. We don't want to create real
15309 tracepoints yet, we don't want to mess up the user's existing
15310 collection. */
15311
15312 int
15313 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15314 {
15315 struct remote_state *rs = get_remote_state ();
15316 char *p;
15317
15318 /* Ask for a first packet of tracepoint definition. */
15319 putpkt ("qTfP");
15320 getpkt (&rs->buf);
15321 p = rs->buf.data ();
15322 while (*p && *p != 'l')
15323 {
15324 parse_tracepoint_definition (p, utpp);
15325 /* Ask for another packet of tracepoint definition. */
15326 putpkt ("qTsP");
15327 getpkt (&rs->buf);
15328 p = rs->buf.data ();
15329 }
15330 return 0;
15331 }
15332
15333 int
15334 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15335 {
15336 struct remote_state *rs = get_remote_state ();
15337 char *p;
15338
15339 /* Ask for a first packet of variable definition. */
15340 putpkt ("qTfV");
15341 getpkt (&rs->buf);
15342 p = rs->buf.data ();
15343 while (*p && *p != 'l')
15344 {
15345 parse_tsv_definition (p, utsvp);
15346 /* Ask for another packet of variable definition. */
15347 putpkt ("qTsV");
15348 getpkt (&rs->buf);
15349 p = rs->buf.data ();
15350 }
15351 return 0;
15352 }
15353
15354 /* The "set/show range-stepping" show hook. */
15355
15356 static void
15357 show_range_stepping (struct ui_file *file, int from_tty,
15358 struct cmd_list_element *c,
15359 const char *value)
15360 {
15361 gdb_printf (file,
15362 _("Debugger's willingness to use range stepping "
15363 "is %s.\n"), value);
15364 }
15365
15366 /* Return true if the vCont;r action is supported by the remote
15367 stub. */
15368
15369 bool
15370 remote_target::vcont_r_supported ()
15371 {
15372 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15373 && get_remote_state ()->supports_vCont.r);
15374 }
15375
15376 /* The "set/show range-stepping" set hook. */
15377
15378 static void
15379 set_range_stepping (const char *ignore_args, int from_tty,
15380 struct cmd_list_element *c)
15381 {
15382 /* When enabling, check whether range stepping is actually supported
15383 by the target, and warn if not. */
15384 if (use_range_stepping)
15385 {
15386 remote_target *remote = get_current_remote_target ();
15387 if (remote == NULL
15388 || !remote->vcont_r_supported ())
15389 warning (_("Range stepping is not supported by the current target"));
15390 }
15391 }
15392
15393 static void
15394 show_remote_debug (struct ui_file *file, int from_tty,
15395 struct cmd_list_element *c, const char *value)
15396 {
15397 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15398 value);
15399 }
15400
15401 static void
15402 show_remote_timeout (struct ui_file *file, int from_tty,
15403 struct cmd_list_element *c, const char *value)
15404 {
15405 gdb_printf (file,
15406 _("Timeout limit to wait for target to respond is %s.\n"),
15407 value);
15408 }
15409
15410 /* Implement the "supports_memory_tagging" target_ops method. */
15411
15412 bool
15413 remote_target::supports_memory_tagging ()
15414 {
15415 return m_features.remote_memory_tagging_p ();
15416 }
15417
15418 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15419
15420 static void
15421 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15422 size_t len, int type)
15423 {
15424 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15425
15426 std::string request = string_printf ("qMemTags:%s,%s:%s",
15427 phex_nz (address, addr_size),
15428 phex_nz (len, sizeof (len)),
15429 phex_nz (type, sizeof (type)));
15430
15431 strcpy (packet.data (), request.c_str ());
15432 }
15433
15434 /* Parse the qMemTags packet reply into TAGS.
15435
15436 Return true if successful, false otherwise. */
15437
15438 static bool
15439 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15440 gdb::byte_vector &tags)
15441 {
15442 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15443 return false;
15444
15445 /* Copy the tag data. */
15446 tags = hex2bin (reply.data () + 1);
15447
15448 return true;
15449 }
15450
15451 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15452
15453 static void
15454 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15455 size_t len, int type,
15456 const gdb::byte_vector &tags)
15457 {
15458 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15459
15460 /* Put together the main packet, address and length. */
15461 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15462 phex_nz (address, addr_size),
15463 phex_nz (len, sizeof (len)),
15464 phex_nz (type, sizeof (type)));
15465 request += bin2hex (tags.data (), tags.size ());
15466
15467 /* Check if we have exceeded the maximum packet size. */
15468 if (packet.size () < request.length ())
15469 error (_("Contents too big for packet QMemTags."));
15470
15471 strcpy (packet.data (), request.c_str ());
15472 }
15473
15474 /* Implement the "fetch_memtags" target_ops method. */
15475
15476 bool
15477 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15478 gdb::byte_vector &tags, int type)
15479 {
15480 /* Make sure the qMemTags packet is supported. */
15481 if (!m_features.remote_memory_tagging_p ())
15482 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15483
15484 struct remote_state *rs = get_remote_state ();
15485
15486 create_fetch_memtags_request (rs->buf, address, len, type);
15487
15488 putpkt (rs->buf);
15489 getpkt (&rs->buf);
15490
15491 return parse_fetch_memtags_reply (rs->buf, tags);
15492 }
15493
15494 /* Implement the "store_memtags" target_ops method. */
15495
15496 bool
15497 remote_target::store_memtags (CORE_ADDR address, size_t len,
15498 const gdb::byte_vector &tags, int type)
15499 {
15500 /* Make sure the QMemTags packet is supported. */
15501 if (!m_features.remote_memory_tagging_p ())
15502 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15503
15504 struct remote_state *rs = get_remote_state ();
15505
15506 create_store_memtags_request (rs->buf, address, len, type, tags);
15507
15508 putpkt (rs->buf);
15509 getpkt (&rs->buf);
15510
15511 /* Verify if the request was successful. */
15512 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15513 }
15514
15515 /* Return true if remote target T is non-stop. */
15516
15517 bool
15518 remote_target_is_non_stop_p (remote_target *t)
15519 {
15520 scoped_restore_current_thread restore_thread;
15521 switch_to_target_no_thread (t);
15522
15523 return target_is_non_stop_p ();
15524 }
15525
15526 #if GDB_SELF_TEST
15527
15528 namespace selftests {
15529
15530 static void
15531 test_memory_tagging_functions ()
15532 {
15533 remote_target remote;
15534
15535 struct packet_config *config
15536 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15537
15538 scoped_restore restore_memtag_support_
15539 = make_scoped_restore (&config->support);
15540
15541 /* Test memory tagging packet support. */
15542 config->support = PACKET_SUPPORT_UNKNOWN;
15543 SELF_CHECK (remote.supports_memory_tagging () == false);
15544 config->support = PACKET_DISABLE;
15545 SELF_CHECK (remote.supports_memory_tagging () == false);
15546 config->support = PACKET_ENABLE;
15547 SELF_CHECK (remote.supports_memory_tagging () == true);
15548
15549 /* Setup testing. */
15550 gdb::char_vector packet;
15551 gdb::byte_vector tags, bv;
15552 std::string expected, reply;
15553 packet.resize (32000);
15554
15555 /* Test creating a qMemTags request. */
15556
15557 expected = "qMemTags:0,0:0";
15558 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15559 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15560
15561 expected = "qMemTags:deadbeef,10:1";
15562 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15563 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15564
15565 /* Test parsing a qMemTags reply. */
15566
15567 /* Error reply, tags vector unmodified. */
15568 reply = "E00";
15569 strcpy (packet.data (), reply.c_str ());
15570 tags.resize (0);
15571 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15572 SELF_CHECK (tags.size () == 0);
15573
15574 /* Valid reply, tags vector updated. */
15575 tags.resize (0);
15576 bv.resize (0);
15577
15578 for (int i = 0; i < 5; i++)
15579 bv.push_back (i);
15580
15581 reply = "m" + bin2hex (bv.data (), bv.size ());
15582 strcpy (packet.data (), reply.c_str ());
15583
15584 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15585 SELF_CHECK (tags.size () == 5);
15586
15587 for (int i = 0; i < 5; i++)
15588 SELF_CHECK (tags[i] == i);
15589
15590 /* Test creating a QMemTags request. */
15591
15592 /* Empty tag data. */
15593 tags.resize (0);
15594 expected = "QMemTags:0,0:0:";
15595 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15596 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15597 expected.length ()) == 0);
15598
15599 /* Non-empty tag data. */
15600 tags.resize (0);
15601 for (int i = 0; i < 5; i++)
15602 tags.push_back (i);
15603 expected = "QMemTags:deadbeef,ff:1:0001020304";
15604 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15605 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15606 expected.length ()) == 0);
15607 }
15608
15609 } // namespace selftests
15610 #endif /* GDB_SELF_TEST */
15611
15612 void _initialize_remote ();
15613 void
15614 _initialize_remote ()
15615 {
15616 add_target (remote_target_info, remote_target::open);
15617 add_target (extended_remote_target_info, extended_remote_target::open);
15618
15619 /* Hook into new objfile notification. */
15620 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15621 gdb::observers::all_objfiles_removed.attach
15622 (remote_objfile_changed_check_symbols, "remote");
15623
15624 #if 0
15625 init_remote_threadtests ();
15626 #endif
15627
15628 /* set/show remote ... */
15629
15630 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15631 Remote protocol specific variables.\n\
15632 Configure various remote-protocol specific variables such as\n\
15633 the packets being used."),
15634 &remote_set_cmdlist,
15635 0 /* allow-unknown */, &setlist);
15636 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15637 Remote protocol specific variables.\n\
15638 Configure various remote-protocol specific variables such as\n\
15639 the packets being used."),
15640 &remote_show_cmdlist,
15641 0 /* allow-unknown */, &showlist);
15642
15643 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15644 Compare section data on target to the exec file.\n\
15645 Argument is a single section name (default: all loaded sections).\n\
15646 To compare only read-only loaded sections, specify the -r option."),
15647 &cmdlist);
15648
15649 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15650 Send an arbitrary packet to a remote target.\n\
15651 maintenance packet TEXT\n\
15652 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15653 this command sends the string TEXT to the inferior, and displays the\n\
15654 response packet. GDB supplies the initial `$' character, and the\n\
15655 terminating `#' character and checksum."),
15656 &maintenancelist);
15657
15658 set_show_commands remotebreak_cmds
15659 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15660 Set whether to send break if interrupted."), _("\
15661 Show whether to send break if interrupted."), _("\
15662 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15663 set_remotebreak, show_remotebreak,
15664 &setlist, &showlist);
15665 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15666 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15667
15668 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15669 interrupt_sequence_modes, &interrupt_sequence_mode,
15670 _("\
15671 Set interrupt sequence to remote target."), _("\
15672 Show interrupt sequence to remote target."), _("\
15673 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15674 NULL, show_interrupt_sequence,
15675 &remote_set_cmdlist,
15676 &remote_show_cmdlist);
15677
15678 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15679 &interrupt_on_connect, _("\
15680 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15681 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15682 If set, interrupt sequence is sent to remote target."),
15683 NULL, NULL,
15684 &remote_set_cmdlist, &remote_show_cmdlist);
15685
15686 /* Install commands for configuring memory read/write packets. */
15687
15688 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15689 Set the maximum number of bytes per memory write packet (deprecated)."),
15690 &setlist);
15691 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15692 Show the maximum number of bytes per memory write packet (deprecated)."),
15693 &showlist);
15694 add_cmd ("memory-write-packet-size", no_class,
15695 set_memory_write_packet_size, _("\
15696 Set the maximum number of bytes per memory-write packet.\n\
15697 Specify the number of bytes in a packet or 0 (zero) for the\n\
15698 default packet size. The actual limit is further reduced\n\
15699 dependent on the target. Specify \"fixed\" to disable the\n\
15700 further restriction and \"limit\" to enable that restriction."),
15701 &remote_set_cmdlist);
15702 add_cmd ("memory-read-packet-size", no_class,
15703 set_memory_read_packet_size, _("\
15704 Set the maximum number of bytes per memory-read packet.\n\
15705 Specify the number of bytes in a packet or 0 (zero) for the\n\
15706 default packet size. The actual limit is further reduced\n\
15707 dependent on the target. Specify \"fixed\" to disable the\n\
15708 further restriction and \"limit\" to enable that restriction."),
15709 &remote_set_cmdlist);
15710 add_cmd ("memory-write-packet-size", no_class,
15711 show_memory_write_packet_size,
15712 _("Show the maximum number of bytes per memory-write packet."),
15713 &remote_show_cmdlist);
15714 add_cmd ("memory-read-packet-size", no_class,
15715 show_memory_read_packet_size,
15716 _("Show the maximum number of bytes per memory-read packet."),
15717 &remote_show_cmdlist);
15718
15719 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15720 &remote_hw_watchpoint_limit, _("\
15721 Set the maximum number of target hardware watchpoints."), _("\
15722 Show the maximum number of target hardware watchpoints."), _("\
15723 Specify \"unlimited\" for unlimited hardware watchpoints."),
15724 NULL, show_hardware_watchpoint_limit,
15725 &remote_set_cmdlist,
15726 &remote_show_cmdlist);
15727 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15728 no_class,
15729 &remote_hw_watchpoint_length_limit, _("\
15730 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15731 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15732 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15733 NULL, show_hardware_watchpoint_length_limit,
15734 &remote_set_cmdlist, &remote_show_cmdlist);
15735 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15736 &remote_hw_breakpoint_limit, _("\
15737 Set the maximum number of target hardware breakpoints."), _("\
15738 Show the maximum number of target hardware breakpoints."), _("\
15739 Specify \"unlimited\" for unlimited hardware breakpoints."),
15740 NULL, show_hardware_breakpoint_limit,
15741 &remote_set_cmdlist, &remote_show_cmdlist);
15742
15743 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15744 &remote_address_size, _("\
15745 Set the maximum size of the address (in bits) in a memory packet."), _("\
15746 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15747 NULL,
15748 NULL, /* FIXME: i18n: */
15749 &setlist, &showlist);
15750
15751 init_all_packet_configs ();
15752
15753 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15754
15755 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15756
15757 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15758 0);
15759
15760 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15761 "catch-syscalls", 0);
15762
15763 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15764 "program-signals", 0);
15765
15766 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15767 "set-working-dir", 0);
15768
15769 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15770 "startup-with-shell", 0);
15771
15772 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15773 "environment-hex-encoded", 0);
15774
15775 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15776 "environment-reset", 0);
15777
15778 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15779 "environment-unset", 0);
15780
15781 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15782
15783 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15784
15785 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15786
15787 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15788
15789 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15790
15791 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15792
15793 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15794
15795 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15796
15797 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15798 "read-aux-vector", 0);
15799
15800 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15801 "pid-to-exec-file", 0);
15802
15803 add_packet_config_cmd (PACKET_qXfer_features,
15804 "qXfer:features:read", "target-features", 0);
15805
15806 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15807 "library-info", 0);
15808
15809 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15810 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15811
15812 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15813 "memory-map", 0);
15814
15815 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15816
15817 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15818 0);
15819
15820 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15821 "read-siginfo-object", 0);
15822
15823 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15824 "write-siginfo-object", 0);
15825
15826 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15827 "qXfer:traceframe-info:read", "traceframe-info", 0);
15828
15829 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15830 "unwind-info-block", 0);
15831
15832 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15833 "get-thread-local-storage-address", 0);
15834
15835 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15836 "get-thread-information-block-address", 0);
15837
15838 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15839
15840 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15841
15842 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15843 0);
15844
15845 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15846 "search-memory", 0);
15847
15848 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15849
15850 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15851
15852 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15853
15854 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15855
15856 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15857 0);
15858
15859 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15860
15861 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15862 0);
15863
15864 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15865 "hostio-readlink", 0);
15866
15867 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15868
15869 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15870
15871 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15872
15873 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15874
15875 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15876
15877 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15878
15879 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15880 "ConditionalTracepoints", "conditional-tracepoints",
15881 0);
15882
15883 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15884 "ConditionalBreakpoints", "conditional-breakpoints",
15885 0);
15886
15887 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15888 "breakpoint-commands", 0);
15889
15890 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15891 "fast-tracepoints", 0);
15892
15893 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15894 "TracepointSource", 0);
15895
15896 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15897
15898 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15899 "static-tracepoints", 0);
15900
15901 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15902 "install-in-trace", 0);
15903
15904 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15905 "qXfer:statictrace:read", "read-sdata-object", 0);
15906
15907 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15908 "read-fdpic-loadmap", 0);
15909
15910 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15911 "disable-randomization", 0);
15912
15913 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15914
15915 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15916 "trace-buffer-size", 0);
15917
15918 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15919 0);
15920
15921 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15922 0);
15923
15924 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15925 0);
15926
15927 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15928
15929 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15930 "read-btrace-conf", 0);
15931
15932 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15933 "btrace-conf-bts-size", 0);
15934
15935 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15936 "multiprocess-feature", 0);
15937
15938 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15939 "swbreak-feature", 0);
15940
15941 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15942 "hwbreak-feature", 0);
15943
15944 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15945 "fork-event-feature", 0);
15946
15947 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15948 "vfork-event-feature", 0);
15949
15950 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15951 "btrace-conf-pt-size", 0);
15952
15953 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15954 "verbose-resume-supported", 0);
15955
15956 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15957 "exec-event-feature", 0);
15958
15959 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15960
15961 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15962 0);
15963
15964 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
15965 "thread-options", 0);
15966
15967 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15968 "no-resumed-stop-reply", 0);
15969
15970 add_packet_config_cmd (PACKET_memory_tagging_feature,
15971 "memory-tagging-feature", "memory-tagging-feature", 0);
15972
15973 /* Assert that we've registered "set remote foo-packet" commands
15974 for all packet configs. */
15975 {
15976 int i;
15977
15978 for (i = 0; i < PACKET_MAX; i++)
15979 {
15980 /* Ideally all configs would have a command associated. Some
15981 still don't though. */
15982 int excepted;
15983
15984 switch (i)
15985 {
15986 case PACKET_QNonStop:
15987 case PACKET_EnableDisableTracepoints_feature:
15988 case PACKET_tracenz_feature:
15989 case PACKET_DisconnectedTracing_feature:
15990 case PACKET_augmented_libraries_svr4_read_feature:
15991 case PACKET_qCRC:
15992 /* Additions to this list need to be well justified:
15993 pre-existing packets are OK; new packets are not. */
15994 excepted = 1;
15995 break;
15996 default:
15997 excepted = 0;
15998 break;
15999 }
16000
16001 /* This catches both forgetting to add a config command, and
16002 forgetting to remove a packet from the exception list. */
16003 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16004 }
16005 }
16006
16007 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16008 Z sub-packet has its own set and show commands, but users may
16009 have sets to this variable in their .gdbinit files (or in their
16010 documentation). */
16011 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16012 &remote_Z_packet_detect, _("\
16013 Set use of remote protocol `Z' packets."), _("\
16014 Show use of remote protocol `Z' packets."), _("\
16015 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16016 packets."),
16017 set_remote_protocol_Z_packet_cmd,
16018 show_remote_protocol_Z_packet_cmd,
16019 /* FIXME: i18n: Use of remote protocol
16020 `Z' packets is %s. */
16021 &remote_set_cmdlist, &remote_show_cmdlist);
16022
16023 add_basic_prefix_cmd ("remote", class_files, _("\
16024 Manipulate files on the remote system.\n\
16025 Transfer files to and from the remote target system."),
16026 &remote_cmdlist,
16027 0 /* allow-unknown */, &cmdlist);
16028
16029 add_cmd ("put", class_files, remote_put_command,
16030 _("Copy a local file to the remote system."),
16031 &remote_cmdlist);
16032
16033 add_cmd ("get", class_files, remote_get_command,
16034 _("Copy a remote file to the local system."),
16035 &remote_cmdlist);
16036
16037 add_cmd ("delete", class_files, remote_delete_command,
16038 _("Delete a remote file."),
16039 &remote_cmdlist);
16040
16041 add_setshow_string_noescape_cmd ("exec-file", class_files,
16042 &remote_exec_file_var, _("\
16043 Set the remote pathname for \"run\"."), _("\
16044 Show the remote pathname for \"run\"."), NULL,
16045 set_remote_exec_file,
16046 show_remote_exec_file,
16047 &remote_set_cmdlist,
16048 &remote_show_cmdlist);
16049
16050 add_setshow_boolean_cmd ("range-stepping", class_run,
16051 &use_range_stepping, _("\
16052 Enable or disable range stepping."), _("\
16053 Show whether target-assisted range stepping is enabled."), _("\
16054 If on, and the target supports it, when stepping a source line, GDB\n\
16055 tells the target to step the corresponding range of addresses itself instead\n\
16056 of issuing multiple single-steps. This speeds up source level\n\
16057 stepping. If off, GDB always issues single-steps, even if range\n\
16058 stepping is supported by the target. The default is on."),
16059 set_range_stepping,
16060 show_range_stepping,
16061 &setlist,
16062 &showlist);
16063
16064 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16065 Set watchdog timer."), _("\
16066 Show watchdog timer."), _("\
16067 When non-zero, this timeout is used instead of waiting forever for a target\n\
16068 to finish a low-level step or continue operation. If the specified amount\n\
16069 of time passes without a response from the target, an error occurs."),
16070 NULL,
16071 show_watchdog,
16072 &setlist, &showlist);
16073
16074 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16075 &remote_packet_max_chars, _("\
16076 Set the maximum number of characters to display for each remote packet."), _("\
16077 Show the maximum number of characters to display for each remote packet."), _("\
16078 Specify \"unlimited\" to display all the characters."),
16079 NULL, show_remote_packet_max_chars,
16080 &setdebuglist, &showdebuglist);
16081
16082 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16083 _("Set debugging of remote protocol."),
16084 _("Show debugging of remote protocol."),
16085 _("\
16086 When enabled, each packet sent or received with the remote target\n\
16087 is displayed."),
16088 NULL,
16089 show_remote_debug,
16090 &setdebuglist, &showdebuglist);
16091
16092 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16093 &remote_timeout, _("\
16094 Set timeout limit to wait for target to respond."), _("\
16095 Show timeout limit to wait for target to respond."), _("\
16096 This value is used to set the time limit for gdb to wait for a response\n\
16097 from the target."),
16098 NULL,
16099 show_remote_timeout,
16100 &setlist, &showlist);
16101
16102 /* Eventually initialize fileio. See fileio.c */
16103 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16104
16105 #if GDB_SELF_TEST
16106 selftests::register_test ("remote_memory_tagging",
16107 selftests::test_memory_tagging_functions);
16108 #endif
16109 }