8c7979ce6a64a336f6e232e2de9a10f3bad411cc
[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 multi-process extensions. */
252 PACKET_multiprocess_feature,
253
254 /* Support for enabling and disabling tracepoints while a trace
255 experiment is running. */
256 PACKET_EnableDisableTracepoints_feature,
257
258 /* Support for collecting strings using the tracenz bytecode. */
259 PACKET_tracenz_feature,
260
261 /* Support for continuing to run a trace experiment while GDB is
262 disconnected. */
263 PACKET_DisconnectedTracing_feature,
264
265 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
266 PACKET_augmented_libraries_svr4_read_feature,
267
268 /* Support for the qXfer:btrace-conf:read packet. */
269 PACKET_qXfer_btrace_conf,
270
271 /* Support for the Qbtrace-conf:bts:size packet. */
272 PACKET_Qbtrace_conf_bts_size,
273
274 /* Support for swbreak+ feature. */
275 PACKET_swbreak_feature,
276
277 /* Support for hwbreak+ feature. */
278 PACKET_hwbreak_feature,
279
280 /* Support for fork events. */
281 PACKET_fork_event_feature,
282
283 /* Support for vfork events. */
284 PACKET_vfork_event_feature,
285
286 /* Support for the Qbtrace-conf:pt:size packet. */
287 PACKET_Qbtrace_conf_pt_size,
288
289 /* Support for exec events. */
290 PACKET_exec_event_feature,
291
292 /* Support for query supported vCont actions. */
293 PACKET_vContSupported,
294
295 /* Support remote CTRL-C. */
296 PACKET_vCtrlC,
297
298 /* Support TARGET_WAITKIND_NO_RESUMED. */
299 PACKET_no_resumed,
300
301 /* Support for memory tagging, allocation tag fetch/store
302 packets and the tag violation stop replies. */
303 PACKET_memory_tagging_feature,
304
305 PACKET_MAX
306 };
307
308 struct threads_listing_context;
309
310 /* Stub vCont actions support.
311
312 Each field is a boolean flag indicating whether the stub reports
313 support for the corresponding action. */
314
315 struct vCont_action_support
316 {
317 /* vCont;t */
318 bool t = false;
319
320 /* vCont;r */
321 bool r = false;
322
323 /* vCont;s */
324 bool s = false;
325
326 /* vCont;S */
327 bool S = false;
328 };
329
330 /* About this many threadids fit in a packet. */
331
332 #define MAXTHREADLISTRESULTS 32
333
334 /* Data for the vFile:pread readahead cache. */
335
336 struct readahead_cache
337 {
338 /* Invalidate the readahead cache. */
339 void invalidate ();
340
341 /* Invalidate the readahead cache if it is holding data for FD. */
342 void invalidate_fd (int fd);
343
344 /* Serve pread from the readahead cache. Returns number of bytes
345 read, or 0 if the request can't be served from the cache. */
346 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
347
348 /* The file descriptor for the file that is being cached. -1 if the
349 cache is invalid. */
350 int fd = -1;
351
352 /* The offset into the file that the cache buffer corresponds
353 to. */
354 ULONGEST offset = 0;
355
356 /* The buffer holding the cache contents. */
357 gdb::byte_vector buf;
358
359 /* Cache hit and miss counters. */
360 ULONGEST hit_count = 0;
361 ULONGEST miss_count = 0;
362 };
363
364 /* Description of the remote protocol for a given architecture. */
365
366 struct packet_reg
367 {
368 long offset; /* Offset into G packet. */
369 long regnum; /* GDB's internal register number. */
370 LONGEST pnum; /* Remote protocol register number. */
371 int in_g_packet; /* Always part of G packet. */
372 /* long size in bytes; == register_size (arch, regnum);
373 at present. */
374 /* char *name; == gdbarch_register_name (arch, regnum);
375 at present. */
376 };
377
378 struct remote_arch_state
379 {
380 explicit remote_arch_state (struct gdbarch *gdbarch);
381
382 /* Description of the remote protocol registers. */
383 long sizeof_g_packet;
384
385 /* Description of the remote protocol registers indexed by REGNUM
386 (making an array gdbarch_num_regs in size). */
387 std::unique_ptr<packet_reg[]> regs;
388
389 /* This is the size (in chars) of the first response to the ``g''
390 packet. It is used as a heuristic when determining the maximum
391 size of memory-read and memory-write packets. A target will
392 typically only reserve a buffer large enough to hold the ``g''
393 packet. The size does not include packet overhead (headers and
394 trailers). */
395 long actual_register_packet_size;
396
397 /* This is the maximum size (in chars) of a non read/write packet.
398 It is also used as a cap on the size of read/write packets. */
399 long remote_packet_size;
400 };
401
402 /* Description of the remote protocol state for the currently
403 connected target. This is per-target state, and independent of the
404 selected architecture. */
405
406 class remote_state
407 {
408 public:
409
410 remote_state ();
411 ~remote_state ();
412
413 /* Get the remote arch state for GDBARCH. */
414 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
415
416 void create_async_event_handler ()
417 {
418 gdb_assert (m_async_event_handler_token == nullptr);
419 m_async_event_handler_token
420 = ::create_async_event_handler ([] (gdb_client_data data)
421 {
422 inferior_event_handler (INF_REG_EVENT);
423 },
424 nullptr, "remote");
425 }
426
427 void mark_async_event_handler ()
428 {
429 gdb_assert (this->is_async_p ());
430 ::mark_async_event_handler (m_async_event_handler_token);
431 }
432
433 void clear_async_event_handler ()
434 { ::clear_async_event_handler (m_async_event_handler_token); }
435
436 bool async_event_handler_marked () const
437 { return ::async_event_handler_marked (m_async_event_handler_token); }
438
439 void delete_async_event_handler ()
440 {
441 if (m_async_event_handler_token != nullptr)
442 ::delete_async_event_handler (&m_async_event_handler_token);
443 }
444
445 bool is_async_p () const
446 {
447 /* We're async whenever the serial device is. */
448 gdb_assert (this->remote_desc != nullptr);
449 return serial_is_async_p (this->remote_desc);
450 }
451
452 bool can_async_p () const
453 {
454 /* We can async whenever the serial device can. */
455 gdb_assert (this->remote_desc != nullptr);
456 return serial_can_async_p (this->remote_desc);
457 }
458
459 public: /* data */
460
461 /* A buffer to use for incoming packets, and its current size. The
462 buffer is grown dynamically for larger incoming packets.
463 Outgoing packets may also be constructed in this buffer.
464 The size of the buffer is always at least REMOTE_PACKET_SIZE;
465 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
466 packets. */
467 gdb::char_vector buf;
468
469 /* True if we're going through initial connection setup (finding out
470 about the remote side's threads, relocating symbols, etc.). */
471 bool starting_up = false;
472
473 /* If we negotiated packet size explicitly (and thus can bypass
474 heuristics for the largest packet size that will not overflow
475 a buffer in the stub), this will be set to that packet size.
476 Otherwise zero, meaning to use the guessed size. */
477 long explicit_packet_size = 0;
478
479 /* True, if in no ack mode. That is, neither GDB nor the stub will
480 expect acks from each other. The connection is assumed to be
481 reliable. */
482 bool noack_mode = false;
483
484 /* True if we're connected in extended remote mode. */
485 bool extended = false;
486
487 /* True if we resumed the target and we're waiting for the target to
488 stop. In the mean time, we can't start another command/query.
489 The remote server wouldn't be ready to process it, so we'd
490 timeout waiting for a reply that would never come and eventually
491 we'd close the connection. This can happen in asynchronous mode
492 because we allow GDB commands while the target is running. */
493 bool waiting_for_stop_reply = false;
494
495 /* The status of the stub support for the various vCont actions. */
496 vCont_action_support supports_vCont;
497
498 /* True if the user has pressed Ctrl-C, but the target hasn't
499 responded to that. */
500 bool ctrlc_pending_p = false;
501
502 /* True if we saw a Ctrl-C while reading or writing from/to the
503 remote descriptor. At that point it is not safe to send a remote
504 interrupt packet, so we instead remember we saw the Ctrl-C and
505 process it once we're done with sending/receiving the current
506 packet, which should be shortly. If however that takes too long,
507 and the user presses Ctrl-C again, we offer to disconnect. */
508 bool got_ctrlc_during_io = false;
509
510 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
511 remote_open knows that we don't have a file open when the program
512 starts. */
513 struct serial *remote_desc = nullptr;
514
515 /* These are the threads which we last sent to the remote system. The
516 TID member will be -1 for all or -2 for not sent yet. */
517 ptid_t general_thread = null_ptid;
518 ptid_t continue_thread = null_ptid;
519
520 /* This is the traceframe which we last selected on the remote system.
521 It will be -1 if no traceframe is selected. */
522 int remote_traceframe_number = -1;
523
524 char *last_pass_packet = nullptr;
525
526 /* The last QProgramSignals packet sent to the target. We bypass
527 sending a new program signals list down to the target if the new
528 packet is exactly the same as the last we sent. IOW, we only let
529 the target know about program signals list changes. */
530 char *last_program_signals_packet = nullptr;
531
532 gdb_signal last_sent_signal = GDB_SIGNAL_0;
533
534 bool last_sent_step = false;
535
536 /* The execution direction of the last resume we got. */
537 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
538
539 char *finished_object = nullptr;
540 char *finished_annex = nullptr;
541 ULONGEST finished_offset = 0;
542
543 /* Should we try the 'ThreadInfo' query packet?
544
545 This variable (NOT available to the user: auto-detect only!)
546 determines whether GDB will use the new, simpler "ThreadInfo"
547 query or the older, more complex syntax for thread queries.
548 This is an auto-detect variable (set to true at each connect,
549 and set to false when the target fails to recognize it). */
550 bool use_threadinfo_query = false;
551 bool use_threadextra_query = false;
552
553 threadref echo_nextthread {};
554 threadref nextthread {};
555 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
556
557 /* The state of remote notification. */
558 struct remote_notif_state *notif_state = nullptr;
559
560 /* The branch trace configuration. */
561 struct btrace_config btrace_config {};
562
563 /* The argument to the last "vFile:setfs:" packet we sent, used
564 to avoid sending repeated unnecessary "vFile:setfs:" packets.
565 Initialized to -1 to indicate that no "vFile:setfs:" packet
566 has yet been sent. */
567 int fs_pid = -1;
568
569 /* A readahead cache for vFile:pread. Often, reading a binary
570 involves a sequence of small reads. E.g., when parsing an ELF
571 file. A readahead cache helps mostly the case of remote
572 debugging on a connection with higher latency, due to the
573 request/reply nature of the RSP. We only cache data for a single
574 file descriptor at a time. */
575 struct readahead_cache readahead_cache;
576
577 /* The list of already fetched and acknowledged stop events. This
578 queue is used for notification Stop, and other notifications
579 don't need queue for their events, because the notification
580 events of Stop can't be consumed immediately, so that events
581 should be queued first, and be consumed by remote_wait_{ns,as}
582 one per time. Other notifications can consume their events
583 immediately, so queue is not needed for them. */
584 std::vector<stop_reply_up> stop_reply_queue;
585
586 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
587 ``forever'' still use the normal timeout mechanism. This is
588 currently used by the ASYNC code to guarentee that target reads
589 during the initial connect always time-out. Once getpkt has been
590 modified to return a timeout indication and, in turn
591 remote_wait()/wait_for_inferior() have gained a timeout parameter
592 this can go away. */
593 bool wait_forever_enabled_p = true;
594
595 private:
596 /* Asynchronous signal handle registered as event loop source for
597 when we have pending events ready to be passed to the core. */
598 async_event_handler *m_async_event_handler_token = nullptr;
599
600 /* Mapping of remote protocol data for each gdbarch. Usually there
601 is only one entry here, though we may see more with stubs that
602 support multi-process. */
603 std::unordered_map<struct gdbarch *, remote_arch_state>
604 m_arch_states;
605 };
606
607 static const target_info remote_target_info = {
608 "remote",
609 N_("Remote target using gdb-specific protocol"),
610 remote_doc
611 };
612
613 /* Description of a remote packet. */
614
615 struct packet_description
616 {
617 /* Name of the packet used for gdb output. */
618 const char *name;
619
620 /* Title of the packet, used by the set/show remote name-packet
621 commands to identify the individual packages and gdb output. */
622 const char *title;
623 };
624
625 /* Configuration of a remote packet. */
626
627 struct packet_config
628 {
629 /* If auto, GDB auto-detects support for this packet or feature,
630 either through qSupported, or by trying the packet and looking
631 at the response. If true, GDB assumes the target supports this
632 packet. If false, the packet is disabled. Configs that don't
633 have an associated command always have this set to auto. */
634 enum auto_boolean detect;
635
636 /* Does the target support this packet? */
637 enum packet_support support;
638 };
639
640 /* User configurable variables for the number of characters in a
641 memory read/write packet. MIN (rsa->remote_packet_size,
642 rsa->sizeof_g_packet) is the default. Some targets need smaller
643 values (fifo overruns, et.al.) and some users need larger values
644 (speed up transfers). The variables ``preferred_*'' (the user
645 request), ``current_*'' (what was actually set) and ``forced_*''
646 (Positive - a soft limit, negative - a hard limit). */
647
648 struct memory_packet_config
649 {
650 const char *name;
651 long size;
652 int fixed_p;
653 };
654
655 /* These global variables contain the default configuration for every new
656 remote_feature object. */
657 static memory_packet_config memory_read_packet_config =
658 {
659 "memory-read-packet-size",
660 };
661 static memory_packet_config memory_write_packet_config =
662 {
663 "memory-write-packet-size",
664 };
665
666 /* This global array contains packet descriptions (name and title). */
667 static packet_description packets_descriptions[PACKET_MAX];
668 /* This global array contains the default configuration for every new
669 per-remote target array. */
670 static packet_config remote_protocol_packets[PACKET_MAX];
671
672 /* Description of a remote target's features. It stores the configuration
673 and provides functions to determine supported features of the target. */
674
675 struct remote_features
676 {
677 remote_features ()
678 {
679 m_memory_read_packet_config = memory_read_packet_config;
680 m_memory_write_packet_config = memory_write_packet_config;
681
682 std::copy (std::begin (remote_protocol_packets),
683 std::end (remote_protocol_packets),
684 std::begin (m_protocol_packets));
685 }
686 ~remote_features () = default;
687
688 DISABLE_COPY_AND_ASSIGN (remote_features);
689
690 /* Returns whether a given packet defined by its enum value is supported. */
691 enum packet_support packet_support (int) const;
692
693 /* Returns the packet's corresponding "set remote foo-packet" command
694 state. See struct packet_config for more details. */
695 enum auto_boolean packet_set_cmd_state (int packet) const
696 { return m_protocol_packets[packet].detect; }
697
698 /* Returns true if the multi-process extensions are in effect. */
699 int remote_multi_process_p () const
700 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
701
702 /* Returns true if fork events are supported. */
703 int remote_fork_event_p () const
704 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
705
706 /* Returns true if vfork events are supported. */
707 int remote_vfork_event_p () const
708 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
709
710 /* Returns true if exec events are supported. */
711 int remote_exec_event_p () const
712 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
713
714 /* Returns true if memory tagging is supported, false otherwise. */
715 bool remote_memory_tagging_p () const
716 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
717
718 /* Reset all packets back to "unknown support". Called when opening a
719 new connection to a remote target. */
720 void reset_all_packet_configs_support ();
721
722 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
723 support configuration accordingly. */
724 packet_result packet_ok (const char *buf, const int which_packet);
725 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
726
727 /* Configuration of a remote target's memory read packet. */
728 memory_packet_config m_memory_read_packet_config;
729 /* Configuration of a remote target's memory write packet. */
730 memory_packet_config m_memory_write_packet_config;
731
732 /* The per-remote target array which stores a remote's packet
733 configurations. */
734 packet_config m_protocol_packets[PACKET_MAX];
735 };
736
737 class remote_target : public process_stratum_target
738 {
739 public:
740 remote_target () = default;
741 ~remote_target () override;
742
743 const target_info &info () const override
744 { return remote_target_info; }
745
746 const char *connection_string () override;
747
748 thread_control_capabilities get_thread_control_capabilities () override
749 { return tc_schedlock; }
750
751 /* Open a remote connection. */
752 static void open (const char *, int);
753
754 void close () override;
755
756 void detach (inferior *, int) override;
757 void disconnect (const char *, int) override;
758
759 void commit_resumed () override;
760 void resume (ptid_t, int, enum gdb_signal) override;
761 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
762 bool has_pending_events () override;
763
764 void fetch_registers (struct regcache *, int) override;
765 void store_registers (struct regcache *, int) override;
766 void prepare_to_store (struct regcache *) override;
767
768 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
769
770 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
771 enum remove_bp_reason) override;
772
773
774 bool stopped_by_sw_breakpoint () override;
775 bool supports_stopped_by_sw_breakpoint () override;
776
777 bool stopped_by_hw_breakpoint () override;
778
779 bool supports_stopped_by_hw_breakpoint () override;
780
781 bool stopped_by_watchpoint () override;
782
783 bool stopped_data_address (CORE_ADDR *) override;
784
785 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
786
787 int can_use_hw_breakpoint (enum bptype, int, int) override;
788
789 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
790
791 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
792
793 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
794
795 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
796 struct expression *) override;
797
798 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
799 struct expression *) override;
800
801 void kill () override;
802
803 void load (const char *, int) override;
804
805 void mourn_inferior () override;
806
807 void pass_signals (gdb::array_view<const unsigned char>) override;
808
809 int set_syscall_catchpoint (int, bool, int,
810 gdb::array_view<const int>) override;
811
812 void program_signals (gdb::array_view<const unsigned char>) override;
813
814 bool thread_alive (ptid_t ptid) override;
815
816 const char *thread_name (struct thread_info *) override;
817
818 void update_thread_list () override;
819
820 std::string pid_to_str (ptid_t) override;
821
822 const char *extra_thread_info (struct thread_info *) override;
823
824 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
825
826 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
827 int handle_len,
828 inferior *inf) override;
829
830 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
831 override;
832
833 void stop (ptid_t) override;
834
835 void interrupt () override;
836
837 void pass_ctrlc () override;
838
839 enum target_xfer_status xfer_partial (enum target_object object,
840 const char *annex,
841 gdb_byte *readbuf,
842 const gdb_byte *writebuf,
843 ULONGEST offset, ULONGEST len,
844 ULONGEST *xfered_len) override;
845
846 ULONGEST get_memory_xfer_limit () override;
847
848 void rcmd (const char *command, struct ui_file *output) override;
849
850 const char *pid_to_exec_file (int pid) override;
851
852 void log_command (const char *cmd) override
853 {
854 serial_log_command (this, cmd);
855 }
856
857 CORE_ADDR get_thread_local_address (ptid_t ptid,
858 CORE_ADDR load_module_addr,
859 CORE_ADDR offset) override;
860
861 bool can_execute_reverse () override;
862
863 std::vector<mem_region> memory_map () override;
864
865 void flash_erase (ULONGEST address, LONGEST length) override;
866
867 void flash_done () override;
868
869 const struct target_desc *read_description () override;
870
871 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
872 const gdb_byte *pattern, ULONGEST pattern_len,
873 CORE_ADDR *found_addrp) override;
874
875 bool can_async_p () override;
876
877 bool is_async_p () override;
878
879 void async (bool) override;
880
881 int async_wait_fd () override;
882
883 void thread_events (int) override;
884
885 int can_do_single_step () override;
886
887 void terminal_inferior () override;
888
889 void terminal_ours () override;
890
891 bool supports_non_stop () override;
892
893 bool supports_multi_process () override;
894
895 bool supports_disable_randomization () override;
896
897 bool filesystem_is_local () override;
898
899
900 int fileio_open (struct inferior *inf, const char *filename,
901 int flags, int mode, int warn_if_slow,
902 fileio_error *target_errno) override;
903
904 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
905 ULONGEST offset, fileio_error *target_errno) override;
906
907 int fileio_pread (int fd, gdb_byte *read_buf, int len,
908 ULONGEST offset, fileio_error *target_errno) override;
909
910 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
911
912 int fileio_close (int fd, fileio_error *target_errno) override;
913
914 int fileio_unlink (struct inferior *inf,
915 const char *filename,
916 fileio_error *target_errno) override;
917
918 gdb::optional<std::string>
919 fileio_readlink (struct inferior *inf,
920 const char *filename,
921 fileio_error *target_errno) override;
922
923 bool supports_enable_disable_tracepoint () override;
924
925 bool supports_string_tracing () override;
926
927 int remote_supports_cond_tracepoints ();
928
929 bool supports_evaluation_of_breakpoint_conditions () override;
930
931 int remote_supports_fast_tracepoints ();
932
933 int remote_supports_static_tracepoints ();
934
935 int remote_supports_install_in_trace ();
936
937 bool can_run_breakpoint_commands () override;
938
939 void trace_init () override;
940
941 void download_tracepoint (struct bp_location *location) override;
942
943 bool can_download_tracepoint () override;
944
945 void download_trace_state_variable (const trace_state_variable &tsv) override;
946
947 void enable_tracepoint (struct bp_location *location) override;
948
949 void disable_tracepoint (struct bp_location *location) override;
950
951 void trace_set_readonly_regions () override;
952
953 void trace_start () override;
954
955 int get_trace_status (struct trace_status *ts) override;
956
957 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
958 override;
959
960 void trace_stop () override;
961
962 int trace_find (enum trace_find_type type, int num,
963 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
964
965 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
966
967 int save_trace_data (const char *filename) override;
968
969 int upload_tracepoints (struct uploaded_tp **utpp) override;
970
971 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
972
973 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
974
975 int get_min_fast_tracepoint_insn_len () override;
976
977 void set_disconnected_tracing (int val) override;
978
979 void set_circular_trace_buffer (int val) override;
980
981 void set_trace_buffer_size (LONGEST val) override;
982
983 bool set_trace_notes (const char *user, const char *notes,
984 const char *stopnotes) override;
985
986 int core_of_thread (ptid_t ptid) override;
987
988 int verify_memory (const gdb_byte *data,
989 CORE_ADDR memaddr, ULONGEST size) override;
990
991
992 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
993
994 void set_permissions () override;
995
996 bool static_tracepoint_marker_at (CORE_ADDR,
997 struct static_tracepoint_marker *marker)
998 override;
999
1000 std::vector<static_tracepoint_marker>
1001 static_tracepoint_markers_by_strid (const char *id) override;
1002
1003 traceframe_info_up traceframe_info () override;
1004
1005 bool use_agent (bool use) override;
1006 bool can_use_agent () override;
1007
1008 struct btrace_target_info *
1009 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1010
1011 void disable_btrace (struct btrace_target_info *tinfo) override;
1012
1013 void teardown_btrace (struct btrace_target_info *tinfo) override;
1014
1015 enum btrace_error read_btrace (struct btrace_data *data,
1016 struct btrace_target_info *btinfo,
1017 enum btrace_read_type type) override;
1018
1019 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1020 bool augmented_libraries_svr4_read () override;
1021 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1022 void follow_clone (ptid_t child_ptid) override;
1023 void follow_exec (inferior *, ptid_t, const char *) override;
1024 int insert_fork_catchpoint (int) override;
1025 int remove_fork_catchpoint (int) override;
1026 int insert_vfork_catchpoint (int) override;
1027 int remove_vfork_catchpoint (int) override;
1028 int insert_exec_catchpoint (int) override;
1029 int remove_exec_catchpoint (int) override;
1030 enum exec_direction_kind execution_direction () override;
1031
1032 bool supports_memory_tagging () override;
1033
1034 bool fetch_memtags (CORE_ADDR address, size_t len,
1035 gdb::byte_vector &tags, int type) override;
1036
1037 bool store_memtags (CORE_ADDR address, size_t len,
1038 const gdb::byte_vector &tags, int type) override;
1039
1040 public: /* Remote specific methods. */
1041
1042 void remote_download_command_source (int num, ULONGEST addr,
1043 struct command_line *cmds);
1044
1045 void remote_file_put (const char *local_file, const char *remote_file,
1046 int from_tty);
1047 void remote_file_get (const char *remote_file, const char *local_file,
1048 int from_tty);
1049 void remote_file_delete (const char *remote_file, int from_tty);
1050
1051 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1052 ULONGEST offset, fileio_error *remote_errno);
1053 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1054 ULONGEST offset, fileio_error *remote_errno);
1055 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1056 ULONGEST offset, fileio_error *remote_errno);
1057
1058 int remote_hostio_send_command (int command_bytes, int which_packet,
1059 fileio_error *remote_errno, const char **attachment,
1060 int *attachment_len);
1061 int remote_hostio_set_filesystem (struct inferior *inf,
1062 fileio_error *remote_errno);
1063 /* We should get rid of this and use fileio_open directly. */
1064 int remote_hostio_open (struct inferior *inf, const char *filename,
1065 int flags, int mode, int warn_if_slow,
1066 fileio_error *remote_errno);
1067 int remote_hostio_close (int fd, fileio_error *remote_errno);
1068
1069 int remote_hostio_unlink (inferior *inf, const char *filename,
1070 fileio_error *remote_errno);
1071
1072 struct remote_state *get_remote_state ();
1073
1074 long get_remote_packet_size (void);
1075 long get_memory_packet_size (struct memory_packet_config *config);
1076
1077 long get_memory_write_packet_size ();
1078 long get_memory_read_packet_size ();
1079
1080 char *append_pending_thread_resumptions (char *p, char *endp,
1081 ptid_t ptid);
1082 static void open_1 (const char *name, int from_tty, int extended_p);
1083 void start_remote (int from_tty, int extended_p);
1084 void remote_detach_1 (struct inferior *inf, int from_tty);
1085
1086 char *append_resumption (char *p, char *endp,
1087 ptid_t ptid, int step, gdb_signal siggnal);
1088 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1089 gdb_signal siggnal);
1090
1091 thread_info *add_current_inferior_and_thread (const char *wait_status);
1092
1093 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1094 target_wait_flags options);
1095 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1096 target_wait_flags options);
1097
1098 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1099 target_waitstatus *status);
1100
1101 ptid_t select_thread_for_ambiguous_stop_reply
1102 (const struct target_waitstatus &status);
1103
1104 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1105
1106 void print_one_stopped_thread (thread_info *thread);
1107 void process_initial_stop_replies (int from_tty);
1108
1109 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1110 bool silent_p);
1111
1112 void btrace_sync_conf (const btrace_config *conf);
1113
1114 void remote_btrace_maybe_reopen ();
1115
1116 void remove_new_children (threads_listing_context *context);
1117 void kill_new_fork_children (inferior *inf);
1118 void discard_pending_stop_replies (struct inferior *inf);
1119 int stop_reply_queue_length ();
1120
1121 void check_pending_events_prevent_wildcard_vcont
1122 (bool *may_global_wildcard_vcont);
1123
1124 void discard_pending_stop_replies_in_queue ();
1125 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1126 struct stop_reply *queued_stop_reply (ptid_t ptid);
1127 int peek_stop_reply (ptid_t ptid);
1128 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1129
1130 void remote_stop_ns (ptid_t ptid);
1131 void remote_interrupt_as ();
1132 void remote_interrupt_ns ();
1133
1134 char *remote_get_noisy_reply ();
1135 int remote_query_attached (int pid);
1136 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1137 int try_open_exec);
1138
1139 ptid_t remote_current_thread (ptid_t oldpid);
1140 ptid_t get_current_thread (const char *wait_status);
1141
1142 void set_thread (ptid_t ptid, int gen);
1143 void set_general_thread (ptid_t ptid);
1144 void set_continue_thread (ptid_t ptid);
1145 void set_general_process ();
1146
1147 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1148
1149 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1150 gdb_ext_thread_info *info);
1151 int remote_get_threadinfo (threadref *threadid, int fieldset,
1152 gdb_ext_thread_info *info);
1153
1154 int parse_threadlist_response (const char *pkt, int result_limit,
1155 threadref *original_echo,
1156 threadref *resultlist,
1157 int *doneflag);
1158 int remote_get_threadlist (int startflag, threadref *nextthread,
1159 int result_limit, int *done, int *result_count,
1160 threadref *threadlist);
1161
1162 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1163 void *context, int looplimit);
1164
1165 int remote_get_threads_with_ql (threads_listing_context *context);
1166 int remote_get_threads_with_qxfer (threads_listing_context *context);
1167 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1168
1169 void extended_remote_restart ();
1170
1171 void get_offsets ();
1172
1173 void remote_check_symbols ();
1174
1175 void remote_supported_packet (const struct protocol_feature *feature,
1176 enum packet_support support,
1177 const char *argument);
1178
1179 void remote_query_supported ();
1180
1181 void remote_packet_size (const protocol_feature *feature,
1182 packet_support support, const char *value);
1183
1184 void remote_serial_quit_handler ();
1185
1186 void remote_detach_pid (int pid);
1187
1188 void remote_vcont_probe ();
1189
1190 void remote_resume_with_hc (ptid_t ptid, int step,
1191 gdb_signal siggnal);
1192
1193 void send_interrupt_sequence ();
1194 void interrupt_query ();
1195
1196 void remote_notif_get_pending_events (const notif_client *nc);
1197
1198 int fetch_register_using_p (struct regcache *regcache,
1199 packet_reg *reg);
1200 int send_g_packet ();
1201 void process_g_packet (struct regcache *regcache);
1202 void fetch_registers_using_g (struct regcache *regcache);
1203 int store_register_using_P (const struct regcache *regcache,
1204 packet_reg *reg);
1205 void store_registers_using_G (const struct regcache *regcache);
1206
1207 void set_remote_traceframe ();
1208
1209 void check_binary_download (CORE_ADDR addr);
1210
1211 target_xfer_status remote_write_bytes_aux (const char *header,
1212 CORE_ADDR memaddr,
1213 const gdb_byte *myaddr,
1214 ULONGEST len_units,
1215 int unit_size,
1216 ULONGEST *xfered_len_units,
1217 char packet_format,
1218 int use_length);
1219
1220 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1221 const gdb_byte *myaddr, ULONGEST len,
1222 int unit_size, ULONGEST *xfered_len);
1223
1224 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1225 ULONGEST len_units,
1226 int unit_size, ULONGEST *xfered_len_units);
1227
1228 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1229 ULONGEST memaddr,
1230 ULONGEST len,
1231 int unit_size,
1232 ULONGEST *xfered_len);
1233
1234 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1235 gdb_byte *myaddr, ULONGEST len,
1236 int unit_size,
1237 ULONGEST *xfered_len);
1238
1239 packet_result remote_send_printf (const char *format, ...)
1240 ATTRIBUTE_PRINTF (2, 3);
1241
1242 target_xfer_status remote_flash_write (ULONGEST address,
1243 ULONGEST length, ULONGEST *xfered_len,
1244 const gdb_byte *data);
1245
1246 int readchar (int timeout);
1247
1248 void remote_serial_write (const char *str, int len);
1249
1250 int putpkt (const char *buf);
1251 int putpkt_binary (const char *buf, int cnt);
1252
1253 int putpkt (const gdb::char_vector &buf)
1254 {
1255 return putpkt (buf.data ());
1256 }
1257
1258 void skip_frame ();
1259 long read_frame (gdb::char_vector *buf_p);
1260 int getpkt (gdb::char_vector *buf, bool forever = false,
1261 bool *is_notif = nullptr);
1262 int remote_vkill (int pid);
1263 void remote_kill_k ();
1264
1265 void extended_remote_disable_randomization (int val);
1266 int extended_remote_run (const std::string &args);
1267
1268 void send_environment_packet (const char *action,
1269 const char *packet,
1270 const char *value);
1271
1272 void extended_remote_environment_support ();
1273 void extended_remote_set_inferior_cwd ();
1274
1275 target_xfer_status remote_write_qxfer (const char *object_name,
1276 const char *annex,
1277 const gdb_byte *writebuf,
1278 ULONGEST offset, LONGEST len,
1279 ULONGEST *xfered_len,
1280 const unsigned int which_packet);
1281
1282 target_xfer_status remote_read_qxfer (const char *object_name,
1283 const char *annex,
1284 gdb_byte *readbuf, ULONGEST offset,
1285 LONGEST len,
1286 ULONGEST *xfered_len,
1287 const unsigned int which_packet);
1288
1289 void push_stop_reply (struct stop_reply *new_event);
1290
1291 bool vcont_r_supported ();
1292
1293 remote_features m_features;
1294
1295 private:
1296
1297 bool start_remote_1 (int from_tty, int extended_p);
1298
1299 /* The remote state. Don't reference this directly. Use the
1300 get_remote_state method instead. */
1301 remote_state m_remote_state;
1302 };
1303
1304 static const target_info extended_remote_target_info = {
1305 "extended-remote",
1306 N_("Extended remote target using gdb-specific protocol"),
1307 remote_doc
1308 };
1309
1310 /* Set up the extended remote target by extending the standard remote
1311 target and adding to it. */
1312
1313 class extended_remote_target final : public remote_target
1314 {
1315 public:
1316 const target_info &info () const override
1317 { return extended_remote_target_info; }
1318
1319 /* Open an extended-remote connection. */
1320 static void open (const char *, int);
1321
1322 bool can_create_inferior () override { return true; }
1323 void create_inferior (const char *, const std::string &,
1324 char **, int) override;
1325
1326 void detach (inferior *, int) override;
1327
1328 bool can_attach () override { return true; }
1329 void attach (const char *, int) override;
1330
1331 void post_attach (int) override;
1332 bool supports_disable_randomization () override;
1333 };
1334
1335 struct stop_reply : public notif_event
1336 {
1337 ~stop_reply ();
1338
1339 /* The identifier of the thread about this event */
1340 ptid_t ptid;
1341
1342 /* The remote state this event is associated with. When the remote
1343 connection, represented by a remote_state object, is closed,
1344 all the associated stop_reply events should be released. */
1345 struct remote_state *rs;
1346
1347 struct target_waitstatus ws;
1348
1349 /* The architecture associated with the expedited registers. */
1350 gdbarch *arch;
1351
1352 /* Expedited registers. This makes remote debugging a bit more
1353 efficient for those targets that provide critical registers as
1354 part of their normal status mechanism (as another roundtrip to
1355 fetch them is avoided). */
1356 std::vector<cached_reg_t> regcache;
1357
1358 enum target_stop_reason stop_reason;
1359
1360 CORE_ADDR watch_data_address;
1361
1362 int core;
1363 };
1364
1365 /* Return TARGET as a remote_target if it is one, else nullptr. */
1366
1367 static remote_target *
1368 as_remote_target (process_stratum_target *target)
1369 {
1370 return dynamic_cast<remote_target *> (target);
1371 }
1372
1373 /* See remote.h. */
1374
1375 bool
1376 is_remote_target (process_stratum_target *target)
1377 {
1378 return as_remote_target (target) != nullptr;
1379 }
1380
1381 /* Per-program-space data key. */
1382 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1383 remote_pspace_data;
1384
1385 /* The variable registered as the control variable used by the
1386 remote exec-file commands. While the remote exec-file setting is
1387 per-program-space, the set/show machinery uses this as the
1388 location of the remote exec-file value. */
1389 static std::string remote_exec_file_var;
1390
1391 /* The size to align memory write packets, when practical. The protocol
1392 does not guarantee any alignment, and gdb will generate short
1393 writes and unaligned writes, but even as a best-effort attempt this
1394 can improve bulk transfers. For instance, if a write is misaligned
1395 relative to the target's data bus, the stub may need to make an extra
1396 round trip fetching data from the target. This doesn't make a
1397 huge difference, but it's easy to do, so we try to be helpful.
1398
1399 The alignment chosen is arbitrary; usually data bus width is
1400 important here, not the possibly larger cache line size. */
1401 enum { REMOTE_ALIGN_WRITES = 16 };
1402
1403 /* Prototypes for local functions. */
1404
1405 static int hexnumlen (ULONGEST num);
1406
1407 static int stubhex (int ch);
1408
1409 static int hexnumstr (char *, ULONGEST);
1410
1411 static int hexnumnstr (char *, ULONGEST, int);
1412
1413 static CORE_ADDR remote_address_masked (CORE_ADDR);
1414
1415 static int stub_unpack_int (const char *buff, int fieldlength);
1416
1417 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1418 cmd_list_element *c);
1419
1420 static void show_packet_config_cmd (ui_file *file,
1421 const unsigned int which_packet,
1422 remote_target *remote);
1423
1424 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1425 int from_tty,
1426 struct cmd_list_element *c,
1427 const char *value);
1428
1429 static ptid_t read_ptid (const char *buf, const char **obuf);
1430
1431 static bool remote_read_description_p (struct target_ops *target);
1432
1433 static void remote_console_output (const char *msg);
1434
1435 static void remote_btrace_reset (remote_state *rs);
1436
1437 static void remote_unpush_and_throw (remote_target *target);
1438
1439 /* For "remote". */
1440
1441 static struct cmd_list_element *remote_cmdlist;
1442
1443 /* For "set remote" and "show remote". */
1444
1445 static struct cmd_list_element *remote_set_cmdlist;
1446 static struct cmd_list_element *remote_show_cmdlist;
1447
1448 /* Controls whether GDB is willing to use range stepping. */
1449
1450 static bool use_range_stepping = true;
1451
1452 /* From the remote target's point of view, each thread is in one of these three
1453 states. */
1454 enum class resume_state
1455 {
1456 /* Not resumed - we haven't been asked to resume this thread. */
1457 NOT_RESUMED,
1458
1459 /* We have been asked to resume this thread, but haven't sent a vCont action
1460 for it yet. We'll need to consider it next time commit_resume is
1461 called. */
1462 RESUMED_PENDING_VCONT,
1463
1464 /* We have been asked to resume this thread, and we have sent a vCont action
1465 for it. */
1466 RESUMED,
1467 };
1468
1469 /* Information about a thread's pending vCont-resume. Used when a thread is in
1470 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1471 stores this information which is then picked up by
1472 remote_target::commit_resume to know which is the proper action for this
1473 thread to include in the vCont packet. */
1474 struct resumed_pending_vcont_info
1475 {
1476 /* True if the last resume call for this thread was a step request, false
1477 if a continue request. */
1478 bool step;
1479
1480 /* The signal specified in the last resume call for this thread. */
1481 gdb_signal sig;
1482 };
1483
1484 /* Private data that we'll store in (struct thread_info)->priv. */
1485 struct remote_thread_info : public private_thread_info
1486 {
1487 std::string extra;
1488 std::string name;
1489 int core = -1;
1490
1491 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1492 sequence of bytes. */
1493 gdb::byte_vector thread_handle;
1494
1495 /* Whether the target stopped for a breakpoint/watchpoint. */
1496 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1497
1498 /* This is set to the data address of the access causing the target
1499 to stop for a watchpoint. */
1500 CORE_ADDR watch_data_address = 0;
1501
1502 /* Get the thread's resume state. */
1503 enum resume_state get_resume_state () const
1504 {
1505 return m_resume_state;
1506 }
1507
1508 /* Put the thread in the NOT_RESUMED state. */
1509 void set_not_resumed ()
1510 {
1511 m_resume_state = resume_state::NOT_RESUMED;
1512 }
1513
1514 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1515 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1516 {
1517 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1518 m_resumed_pending_vcont_info.step = step;
1519 m_resumed_pending_vcont_info.sig = sig;
1520 }
1521
1522 /* Get the information this thread's pending vCont-resumption.
1523
1524 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1525 state. */
1526 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1527 {
1528 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1529
1530 return m_resumed_pending_vcont_info;
1531 }
1532
1533 /* Put the thread in the VCONT_RESUMED state. */
1534 void set_resumed ()
1535 {
1536 m_resume_state = resume_state::RESUMED;
1537 }
1538
1539 private:
1540 /* Resume state for this thread. This is used to implement vCont action
1541 coalescing (only when the target operates in non-stop mode).
1542
1543 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1544 which notes that this thread must be considered in the next commit_resume
1545 call.
1546
1547 remote_target::commit_resume sends a vCont packet with actions for the
1548 threads in the RESUMED_PENDING_VCONT state and moves them to the
1549 VCONT_RESUMED state.
1550
1551 When reporting a stop to the core for a thread, that thread is moved back
1552 to the NOT_RESUMED state. */
1553 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1554
1555 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1556 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1557 };
1558
1559 remote_state::remote_state ()
1560 : buf (400)
1561 {
1562 }
1563
1564 remote_state::~remote_state ()
1565 {
1566 xfree (this->last_pass_packet);
1567 xfree (this->last_program_signals_packet);
1568 xfree (this->finished_object);
1569 xfree (this->finished_annex);
1570 }
1571
1572 /* Utility: generate error from an incoming stub packet. */
1573 static void
1574 trace_error (char *buf)
1575 {
1576 if (*buf++ != 'E')
1577 return; /* not an error msg */
1578 switch (*buf)
1579 {
1580 case '1': /* malformed packet error */
1581 if (*++buf == '0') /* general case: */
1582 error (_("remote.c: error in outgoing packet."));
1583 else
1584 error (_("remote.c: error in outgoing packet at field #%ld."),
1585 strtol (buf, NULL, 16));
1586 default:
1587 error (_("Target returns error code '%s'."), buf);
1588 }
1589 }
1590
1591 /* Utility: wait for reply from stub, while accepting "O" packets. */
1592
1593 char *
1594 remote_target::remote_get_noisy_reply ()
1595 {
1596 struct remote_state *rs = get_remote_state ();
1597
1598 do /* Loop on reply from remote stub. */
1599 {
1600 char *buf;
1601
1602 QUIT; /* Allow user to bail out with ^C. */
1603 getpkt (&rs->buf);
1604 buf = rs->buf.data ();
1605 if (buf[0] == 'E')
1606 trace_error (buf);
1607 else if (startswith (buf, "qRelocInsn:"))
1608 {
1609 ULONGEST ul;
1610 CORE_ADDR from, to, org_to;
1611 const char *p, *pp;
1612 int adjusted_size = 0;
1613 int relocated = 0;
1614
1615 p = buf + strlen ("qRelocInsn:");
1616 pp = unpack_varlen_hex (p, &ul);
1617 if (*pp != ';')
1618 error (_("invalid qRelocInsn packet: %s"), buf);
1619 from = ul;
1620
1621 p = pp + 1;
1622 unpack_varlen_hex (p, &ul);
1623 to = ul;
1624
1625 org_to = to;
1626
1627 try
1628 {
1629 gdbarch_relocate_instruction (current_inferior ()->arch (),
1630 &to, from);
1631 relocated = 1;
1632 }
1633 catch (const gdb_exception &ex)
1634 {
1635 if (ex.error == MEMORY_ERROR)
1636 {
1637 /* Propagate memory errors silently back to the
1638 target. The stub may have limited the range of
1639 addresses we can write to, for example. */
1640 }
1641 else
1642 {
1643 /* Something unexpectedly bad happened. Be verbose
1644 so we can tell what, and propagate the error back
1645 to the stub, so it doesn't get stuck waiting for
1646 a response. */
1647 exception_fprintf (gdb_stderr, ex,
1648 _("warning: relocating instruction: "));
1649 }
1650 putpkt ("E01");
1651 }
1652
1653 if (relocated)
1654 {
1655 adjusted_size = to - org_to;
1656
1657 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1658 putpkt (buf);
1659 }
1660 }
1661 else if (buf[0] == 'O' && buf[1] != 'K')
1662 remote_console_output (buf + 1); /* 'O' message from stub */
1663 else
1664 return buf; /* Here's the actual reply. */
1665 }
1666 while (1);
1667 }
1668
1669 struct remote_arch_state *
1670 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1671 {
1672 remote_arch_state *rsa;
1673
1674 auto it = this->m_arch_states.find (gdbarch);
1675 if (it == this->m_arch_states.end ())
1676 {
1677 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1678 std::forward_as_tuple (gdbarch),
1679 std::forward_as_tuple (gdbarch));
1680 rsa = &p.first->second;
1681
1682 /* Make sure that the packet buffer is plenty big enough for
1683 this architecture. */
1684 if (this->buf.size () < rsa->remote_packet_size)
1685 this->buf.resize (2 * rsa->remote_packet_size);
1686 }
1687 else
1688 rsa = &it->second;
1689
1690 return rsa;
1691 }
1692
1693 /* Fetch the global remote target state. */
1694
1695 remote_state *
1696 remote_target::get_remote_state ()
1697 {
1698 /* Make sure that the remote architecture state has been
1699 initialized, because doing so might reallocate rs->buf. Any
1700 function which calls getpkt also needs to be mindful of changes
1701 to rs->buf, but this call limits the number of places which run
1702 into trouble. */
1703 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1704
1705 return &m_remote_state;
1706 }
1707
1708 /* Fetch the remote exec-file from the current program space. */
1709
1710 static const char *
1711 get_remote_exec_file (void)
1712 {
1713 char *remote_exec_file;
1714
1715 remote_exec_file = remote_pspace_data.get (current_program_space);
1716 if (remote_exec_file == NULL)
1717 return "";
1718
1719 return remote_exec_file;
1720 }
1721
1722 /* Set the remote exec file for PSPACE. */
1723
1724 static void
1725 set_pspace_remote_exec_file (struct program_space *pspace,
1726 const char *remote_exec_file)
1727 {
1728 char *old_file = remote_pspace_data.get (pspace);
1729
1730 xfree (old_file);
1731 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1732 }
1733
1734 /* The "set/show remote exec-file" set command hook. */
1735
1736 static void
1737 set_remote_exec_file (const char *ignored, int from_tty,
1738 struct cmd_list_element *c)
1739 {
1740 set_pspace_remote_exec_file (current_program_space,
1741 remote_exec_file_var.c_str ());
1742 }
1743
1744 /* The "set/show remote exec-file" show command hook. */
1745
1746 static void
1747 show_remote_exec_file (struct ui_file *file, int from_tty,
1748 struct cmd_list_element *cmd, const char *value)
1749 {
1750 gdb_printf (file, "%s\n", get_remote_exec_file ());
1751 }
1752
1753 static int
1754 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1755 {
1756 int regnum, num_remote_regs, offset;
1757 struct packet_reg **remote_regs;
1758
1759 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1760 {
1761 struct packet_reg *r = &regs[regnum];
1762
1763 if (register_size (gdbarch, regnum) == 0)
1764 /* Do not try to fetch zero-sized (placeholder) registers. */
1765 r->pnum = -1;
1766 else
1767 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1768
1769 r->regnum = regnum;
1770 }
1771
1772 /* Define the g/G packet format as the contents of each register
1773 with a remote protocol number, in order of ascending protocol
1774 number. */
1775
1776 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1777 for (num_remote_regs = 0, regnum = 0;
1778 regnum < gdbarch_num_regs (gdbarch);
1779 regnum++)
1780 if (regs[regnum].pnum != -1)
1781 remote_regs[num_remote_regs++] = &regs[regnum];
1782
1783 std::sort (remote_regs, remote_regs + num_remote_regs,
1784 [] (const packet_reg *a, const packet_reg *b)
1785 { return a->pnum < b->pnum; });
1786
1787 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1788 {
1789 remote_regs[regnum]->in_g_packet = 1;
1790 remote_regs[regnum]->offset = offset;
1791 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1792 }
1793
1794 return offset;
1795 }
1796
1797 /* Given the architecture described by GDBARCH, return the remote
1798 protocol register's number and the register's offset in the g/G
1799 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1800 If the target does not have a mapping for REGNUM, return false,
1801 otherwise, return true. */
1802
1803 int
1804 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1805 int *pnum, int *poffset)
1806 {
1807 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1808
1809 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1810
1811 map_regcache_remote_table (gdbarch, regs.data ());
1812
1813 *pnum = regs[regnum].pnum;
1814 *poffset = regs[regnum].offset;
1815
1816 return *pnum != -1;
1817 }
1818
1819 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1820 {
1821 /* Use the architecture to build a regnum<->pnum table, which will be
1822 1:1 unless a feature set specifies otherwise. */
1823 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1824
1825 /* Record the maximum possible size of the g packet - it may turn out
1826 to be smaller. */
1827 this->sizeof_g_packet
1828 = map_regcache_remote_table (gdbarch, this->regs.get ());
1829
1830 /* Default maximum number of characters in a packet body. Many
1831 remote stubs have a hardwired buffer size of 400 bytes
1832 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1833 as the maximum packet-size to ensure that the packet and an extra
1834 NUL character can always fit in the buffer. This stops GDB
1835 trashing stubs that try to squeeze an extra NUL into what is
1836 already a full buffer (As of 1999-12-04 that was most stubs). */
1837 this->remote_packet_size = 400 - 1;
1838
1839 /* This one is filled in when a ``g'' packet is received. */
1840 this->actual_register_packet_size = 0;
1841
1842 /* Should rsa->sizeof_g_packet needs more space than the
1843 default, adjust the size accordingly. Remember that each byte is
1844 encoded as two characters. 32 is the overhead for the packet
1845 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1846 (``$NN:G...#NN'') is a better guess, the below has been padded a
1847 little. */
1848 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1849 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1850 }
1851
1852 /* Get a pointer to the current remote target. If not connected to a
1853 remote target, return NULL. */
1854
1855 static remote_target *
1856 get_current_remote_target ()
1857 {
1858 target_ops *proc_target = current_inferior ()->process_target ();
1859 return dynamic_cast<remote_target *> (proc_target);
1860 }
1861
1862 /* Return the current allowed size of a remote packet. This is
1863 inferred from the current architecture, and should be used to
1864 limit the length of outgoing packets. */
1865 long
1866 remote_target::get_remote_packet_size ()
1867 {
1868 struct remote_state *rs = get_remote_state ();
1869 remote_arch_state *rsa
1870 = rs->get_remote_arch_state (current_inferior ()->arch ());
1871
1872 if (rs->explicit_packet_size)
1873 return rs->explicit_packet_size;
1874
1875 return rsa->remote_packet_size;
1876 }
1877
1878 static struct packet_reg *
1879 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1880 long regnum)
1881 {
1882 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1883 return NULL;
1884 else
1885 {
1886 struct packet_reg *r = &rsa->regs[regnum];
1887
1888 gdb_assert (r->regnum == regnum);
1889 return r;
1890 }
1891 }
1892
1893 static struct packet_reg *
1894 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1895 LONGEST pnum)
1896 {
1897 int i;
1898
1899 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1900 {
1901 struct packet_reg *r = &rsa->regs[i];
1902
1903 if (r->pnum == pnum)
1904 return r;
1905 }
1906 return NULL;
1907 }
1908
1909 /* Allow the user to specify what sequence to send to the remote
1910 when he requests a program interruption: Although ^C is usually
1911 what remote systems expect (this is the default, here), it is
1912 sometimes preferable to send a break. On other systems such
1913 as the Linux kernel, a break followed by g, which is Magic SysRq g
1914 is required in order to interrupt the execution. */
1915 const char interrupt_sequence_control_c[] = "Ctrl-C";
1916 const char interrupt_sequence_break[] = "BREAK";
1917 const char interrupt_sequence_break_g[] = "BREAK-g";
1918 static const char *const interrupt_sequence_modes[] =
1919 {
1920 interrupt_sequence_control_c,
1921 interrupt_sequence_break,
1922 interrupt_sequence_break_g,
1923 NULL
1924 };
1925 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1926
1927 static void
1928 show_interrupt_sequence (struct ui_file *file, int from_tty,
1929 struct cmd_list_element *c,
1930 const char *value)
1931 {
1932 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1933 gdb_printf (file,
1934 _("Send the ASCII ETX character (Ctrl-c) "
1935 "to the remote target to interrupt the "
1936 "execution of the program.\n"));
1937 else if (interrupt_sequence_mode == interrupt_sequence_break)
1938 gdb_printf (file,
1939 _("send a break signal to the remote target "
1940 "to interrupt the execution of the program.\n"));
1941 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1942 gdb_printf (file,
1943 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1944 "the remote target to interrupt the execution "
1945 "of Linux kernel.\n"));
1946 else
1947 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1948 interrupt_sequence_mode);
1949 }
1950
1951 /* This boolean variable specifies whether interrupt_sequence is sent
1952 to the remote target when gdb connects to it.
1953 This is mostly needed when you debug the Linux kernel: The Linux kernel
1954 expects BREAK g which is Magic SysRq g for connecting gdb. */
1955 static bool interrupt_on_connect = false;
1956
1957 /* This variable is used to implement the "set/show remotebreak" commands.
1958 Since these commands are now deprecated in favor of "set/show remote
1959 interrupt-sequence", it no longer has any effect on the code. */
1960 static bool remote_break;
1961
1962 static void
1963 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1964 {
1965 if (remote_break)
1966 interrupt_sequence_mode = interrupt_sequence_break;
1967 else
1968 interrupt_sequence_mode = interrupt_sequence_control_c;
1969 }
1970
1971 static void
1972 show_remotebreak (struct ui_file *file, int from_tty,
1973 struct cmd_list_element *c,
1974 const char *value)
1975 {
1976 }
1977
1978 /* This variable sets the number of bits in an address that are to be
1979 sent in a memory ("M" or "m") packet. Normally, after stripping
1980 leading zeros, the entire address would be sent. This variable
1981 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1982 initial implementation of remote.c restricted the address sent in
1983 memory packets to ``host::sizeof long'' bytes - (typically 32
1984 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1985 address was never sent. Since fixing this bug may cause a break in
1986 some remote targets this variable is principally provided to
1987 facilitate backward compatibility. */
1988
1989 static unsigned int remote_address_size;
1990
1991 \f
1992 /* The default max memory-write-packet-size, when the setting is
1993 "fixed". The 16k is historical. (It came from older GDB's using
1994 alloca for buffers and the knowledge (folklore?) that some hosts
1995 don't cope very well with large alloca calls.) */
1996 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1997
1998 /* The minimum remote packet size for memory transfers. Ensures we
1999 can write at least one byte. */
2000 #define MIN_MEMORY_PACKET_SIZE 20
2001
2002 /* Get the memory packet size, assuming it is fixed. */
2003
2004 static long
2005 get_fixed_memory_packet_size (struct memory_packet_config *config)
2006 {
2007 gdb_assert (config->fixed_p);
2008
2009 if (config->size <= 0)
2010 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2011 else
2012 return config->size;
2013 }
2014
2015 /* Compute the current size of a read/write packet. Since this makes
2016 use of ``actual_register_packet_size'' the computation is dynamic. */
2017
2018 long
2019 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2020 {
2021 struct remote_state *rs = get_remote_state ();
2022 remote_arch_state *rsa
2023 = rs->get_remote_arch_state (current_inferior ()->arch ());
2024
2025 long what_they_get;
2026 if (config->fixed_p)
2027 what_they_get = get_fixed_memory_packet_size (config);
2028 else
2029 {
2030 what_they_get = get_remote_packet_size ();
2031 /* Limit the packet to the size specified by the user. */
2032 if (config->size > 0
2033 && what_they_get > config->size)
2034 what_they_get = config->size;
2035
2036 /* Limit it to the size of the targets ``g'' response unless we have
2037 permission from the stub to use a larger packet size. */
2038 if (rs->explicit_packet_size == 0
2039 && rsa->actual_register_packet_size > 0
2040 && what_they_get > rsa->actual_register_packet_size)
2041 what_they_get = rsa->actual_register_packet_size;
2042 }
2043 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2044 what_they_get = MIN_MEMORY_PACKET_SIZE;
2045
2046 /* Make sure there is room in the global buffer for this packet
2047 (including its trailing NUL byte). */
2048 if (rs->buf.size () < what_they_get + 1)
2049 rs->buf.resize (2 * what_they_get);
2050
2051 return what_they_get;
2052 }
2053
2054 /* Update the size of a read/write packet. If they user wants
2055 something really big then do a sanity check. */
2056
2057 static void
2058 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2059 bool target_connected)
2060 {
2061 int fixed_p = config->fixed_p;
2062 long size = config->size;
2063
2064 if (args == NULL)
2065 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2066 else if (strcmp (args, "hard") == 0
2067 || strcmp (args, "fixed") == 0)
2068 fixed_p = 1;
2069 else if (strcmp (args, "soft") == 0
2070 || strcmp (args, "limit") == 0)
2071 fixed_p = 0;
2072 else
2073 {
2074 char *end;
2075
2076 size = strtoul (args, &end, 0);
2077 if (args == end)
2078 error (_("Invalid %s (bad syntax)."), config->name);
2079
2080 /* Instead of explicitly capping the size of a packet to or
2081 disallowing it, the user is allowed to set the size to
2082 something arbitrarily large. */
2083 }
2084
2085 /* Extra checks? */
2086 if (fixed_p && !config->fixed_p)
2087 {
2088 /* So that the query shows the correct value. */
2089 long query_size = (size <= 0
2090 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2091 : size);
2092
2093 if (target_connected
2094 && !query (_("The target may not be able to correctly handle a %s\n"
2095 "of %ld bytes. Change the packet size? "),
2096 config->name, query_size))
2097 error (_("Packet size not changed."));
2098 else if (!target_connected
2099 && !query (_("Future remote targets may not be able to "
2100 "correctly handle a %s\nof %ld bytes. Change the "
2101 "packet size for future remote targets? "),
2102 config->name, query_size))
2103 error (_("Packet size not changed."));
2104 }
2105 /* Update the config. */
2106 config->fixed_p = fixed_p;
2107 config->size = size;
2108
2109 const char *target_type = get_target_type_name (target_connected);
2110 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2111 args);
2112
2113 }
2114
2115 /* Show the memory-read or write-packet size configuration CONFIG of the
2116 target REMOTE. If REMOTE is nullptr, the default configuration for future
2117 remote targets should be passed in CONFIG. */
2118
2119 static void
2120 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2121 {
2122 const char *target_type = get_target_type_name (remote != nullptr);
2123
2124 if (config->size == 0)
2125 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2126 else
2127 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2128 config->size);
2129
2130 if (config->fixed_p)
2131 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2132 get_fixed_memory_packet_size (config));
2133 else
2134 {
2135 if (remote != nullptr)
2136 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2137 remote->get_memory_packet_size (config));
2138 else
2139 gdb_puts ("The actual limit will be further reduced "
2140 "dependent on the target.\n");
2141 }
2142 }
2143
2144 /* Configure the memory-write-packet size of the currently selected target. If
2145 no target is available, the default configuration for future remote targets
2146 is configured. */
2147
2148 static void
2149 set_memory_write_packet_size (const char *args, int from_tty)
2150 {
2151 remote_target *remote = get_current_remote_target ();
2152 if (remote != nullptr)
2153 {
2154 set_memory_packet_size
2155 (args, &remote->m_features.m_memory_write_packet_config, true);
2156 }
2157 else
2158 {
2159 memory_packet_config* config = &memory_write_packet_config;
2160 set_memory_packet_size (args, config, false);
2161 }
2162 }
2163
2164 /* Display the memory-write-packet size of the currently selected target. If
2165 no target is available, the default configuration for future remote targets
2166 is shown. */
2167
2168 static void
2169 show_memory_write_packet_size (const char *args, int from_tty)
2170 {
2171 remote_target *remote = get_current_remote_target ();
2172 if (remote != nullptr)
2173 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2174 remote);
2175 else
2176 show_memory_packet_size (&memory_write_packet_config, nullptr);
2177 }
2178
2179 /* Show the number of hardware watchpoints that can be used. */
2180
2181 static void
2182 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2183 struct cmd_list_element *c,
2184 const char *value)
2185 {
2186 gdb_printf (file, _("The maximum number of target hardware "
2187 "watchpoints is %s.\n"), value);
2188 }
2189
2190 /* Show the length limit (in bytes) for hardware watchpoints. */
2191
2192 static void
2193 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2194 struct cmd_list_element *c,
2195 const char *value)
2196 {
2197 gdb_printf (file, _("The maximum length (in bytes) of a target "
2198 "hardware watchpoint is %s.\n"), value);
2199 }
2200
2201 /* Show the number of hardware breakpoints that can be used. */
2202
2203 static void
2204 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2205 struct cmd_list_element *c,
2206 const char *value)
2207 {
2208 gdb_printf (file, _("The maximum number of target hardware "
2209 "breakpoints is %s.\n"), value);
2210 }
2211
2212 /* Controls the maximum number of characters to display in the debug output
2213 for each remote packet. The remaining characters are omitted. */
2214
2215 static int remote_packet_max_chars = 512;
2216
2217 /* Show the maximum number of characters to display for each remote packet
2218 when remote debugging is enabled. */
2219
2220 static void
2221 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2222 struct cmd_list_element *c,
2223 const char *value)
2224 {
2225 gdb_printf (file, _("Number of remote packet characters to "
2226 "display is %s.\n"), value);
2227 }
2228
2229 long
2230 remote_target::get_memory_write_packet_size ()
2231 {
2232 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2233 }
2234
2235 /* Configure the memory-read-packet size of the currently selected target. If
2236 no target is available, the default configuration for future remote targets
2237 is adapted. */
2238
2239 static void
2240 set_memory_read_packet_size (const char *args, int from_tty)
2241 {
2242 remote_target *remote = get_current_remote_target ();
2243 if (remote != nullptr)
2244 set_memory_packet_size
2245 (args, &remote->m_features.m_memory_read_packet_config, true);
2246 else
2247 {
2248 memory_packet_config* config = &memory_read_packet_config;
2249 set_memory_packet_size (args, config, false);
2250 }
2251
2252 }
2253
2254 /* Display the memory-read-packet size of the currently selected target. If
2255 no target is available, the default configuration for future remote targets
2256 is shown. */
2257
2258 static void
2259 show_memory_read_packet_size (const char *args, int from_tty)
2260 {
2261 remote_target *remote = get_current_remote_target ();
2262 if (remote != nullptr)
2263 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2264 remote);
2265 else
2266 show_memory_packet_size (&memory_read_packet_config, nullptr);
2267 }
2268
2269 long
2270 remote_target::get_memory_read_packet_size ()
2271 {
2272 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2273
2274 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2275 extra buffer size argument before the memory read size can be
2276 increased beyond this. */
2277 if (size > get_remote_packet_size ())
2278 size = get_remote_packet_size ();
2279 return size;
2280 }
2281
2282 static enum packet_support packet_config_support (const packet_config *config);
2283
2284
2285 static void
2286 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2287 cmd_list_element *c)
2288 {
2289 remote_target *remote = get_current_remote_target ();
2290 gdb_assert (c->var.has_value ());
2291
2292 auto *default_config = static_cast<packet_config *> (c->context ());
2293 const int packet_idx = std::distance (remote_protocol_packets,
2294 default_config);
2295
2296 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2297 {
2298 const char *name = packets_descriptions[packet_idx].name;
2299 const auto_boolean value = c->var->get<auto_boolean> ();
2300 const char *support = get_packet_support_name (value);
2301 const char *target_type = get_target_type_name (remote != nullptr);
2302
2303 if (remote != nullptr)
2304 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2305 else
2306 remote_protocol_packets[packet_idx].detect = value;
2307
2308 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2309 target_type, support);
2310 return;
2311 }
2312
2313 internal_error (_("Could not find config for %s"), c->name);
2314 }
2315
2316 static void
2317 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2318 remote_target *remote)
2319 {
2320 const char *support = "internal-error";
2321 const char *target_type = get_target_type_name (remote != nullptr);
2322
2323 packet_config *config;
2324 if (remote != nullptr)
2325 config = &remote->m_features.m_protocol_packets[which_packet];
2326 else
2327 config = &remote_protocol_packets[which_packet];
2328
2329 switch (packet_config_support (config))
2330 {
2331 case PACKET_ENABLE:
2332 support = "enabled";
2333 break;
2334 case PACKET_DISABLE:
2335 support = "disabled";
2336 break;
2337 case PACKET_SUPPORT_UNKNOWN:
2338 support = "unknown";
2339 break;
2340 }
2341 switch (config->detect)
2342 {
2343 case AUTO_BOOLEAN_AUTO:
2344 gdb_printf (file,
2345 _("Support for the '%s' packet %s is \"auto\", "
2346 "currently %s.\n"),
2347 packets_descriptions[which_packet].name, target_type,
2348 support);
2349 break;
2350 case AUTO_BOOLEAN_TRUE:
2351 case AUTO_BOOLEAN_FALSE:
2352 gdb_printf (file,
2353 _("Support for the '%s' packet %s is \"%s\".\n"),
2354 packets_descriptions[which_packet].name, target_type,
2355 get_packet_support_name (config->detect));
2356 break;
2357 }
2358 }
2359
2360 static void
2361 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2362 const char *title, int legacy)
2363 {
2364 packets_descriptions[which_packet].name = name;
2365 packets_descriptions[which_packet].title = title;
2366
2367 packet_config *config = &remote_protocol_packets[which_packet];
2368
2369 gdb::unique_xmalloc_ptr<char> set_doc
2370 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2371 name, title);
2372 gdb::unique_xmalloc_ptr<char> show_doc
2373 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2374 name, title);
2375 /* set/show TITLE-packet {auto,on,off} */
2376 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2377 set_show_commands cmds
2378 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2379 &config->detect, set_doc.get (),
2380 show_doc.get (), NULL, /* help_doc */
2381 set_remote_protocol_packet_cmd,
2382 show_remote_protocol_packet_cmd,
2383 &remote_set_cmdlist, &remote_show_cmdlist);
2384 cmds.show->set_context (config);
2385 cmds.set->set_context (config);
2386
2387 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2388 if (legacy)
2389 {
2390 /* It's not clear who should take ownership of the LEGACY_NAME string
2391 created below, so, for now, place the string into a static vector
2392 which ensures the strings is released when GDB exits. */
2393 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2394 gdb::unique_xmalloc_ptr<char> legacy_name
2395 = xstrprintf ("%s-packet", name);
2396 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2397 &remote_set_cmdlist);
2398 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2399 &remote_show_cmdlist);
2400 legacy_names.emplace_back (std::move (legacy_name));
2401 }
2402 }
2403
2404 static enum packet_result
2405 packet_check_result (const char *buf)
2406 {
2407 if (buf[0] != '\0')
2408 {
2409 /* The stub recognized the packet request. Check that the
2410 operation succeeded. */
2411 if (buf[0] == 'E'
2412 && isxdigit (buf[1]) && isxdigit (buf[2])
2413 && buf[3] == '\0')
2414 /* "Enn" - definitely an error. */
2415 return PACKET_ERROR;
2416
2417 /* Always treat "E." as an error. This will be used for
2418 more verbose error messages, such as E.memtypes. */
2419 if (buf[0] == 'E' && buf[1] == '.')
2420 return PACKET_ERROR;
2421
2422 /* The packet may or may not be OK. Just assume it is. */
2423 return PACKET_OK;
2424 }
2425 else
2426 /* The stub does not support the packet. */
2427 return PACKET_UNKNOWN;
2428 }
2429
2430 static enum packet_result
2431 packet_check_result (const gdb::char_vector &buf)
2432 {
2433 return packet_check_result (buf.data ());
2434 }
2435
2436 packet_result
2437 remote_features::packet_ok (const char *buf, const int which_packet)
2438 {
2439 packet_config *config = &m_protocol_packets[which_packet];
2440 packet_description *descr = &packets_descriptions[which_packet];
2441
2442 enum packet_result result;
2443
2444 if (config->detect != AUTO_BOOLEAN_TRUE
2445 && config->support == PACKET_DISABLE)
2446 internal_error (_("packet_ok: attempt to use a disabled packet"));
2447
2448 result = packet_check_result (buf);
2449 switch (result)
2450 {
2451 case PACKET_OK:
2452 case PACKET_ERROR:
2453 /* The stub recognized the packet request. */
2454 if (config->support == PACKET_SUPPORT_UNKNOWN)
2455 {
2456 remote_debug_printf ("Packet %s (%s) is supported",
2457 descr->name, descr->title);
2458 config->support = PACKET_ENABLE;
2459 }
2460 break;
2461 case PACKET_UNKNOWN:
2462 /* The stub does not support the packet. */
2463 if (config->detect == AUTO_BOOLEAN_AUTO
2464 && config->support == PACKET_ENABLE)
2465 {
2466 /* If the stub previously indicated that the packet was
2467 supported then there is a protocol error. */
2468 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2469 descr->name, descr->title);
2470 }
2471 else if (config->detect == AUTO_BOOLEAN_TRUE)
2472 {
2473 /* The user set it wrong. */
2474 error (_("Enabled packet %s (%s) not recognized by stub"),
2475 descr->name, descr->title);
2476 }
2477
2478 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2479 descr->title);
2480 config->support = PACKET_DISABLE;
2481 break;
2482 }
2483
2484 return result;
2485 }
2486
2487 packet_result
2488 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2489 {
2490 return packet_ok (buf.data (), which_packet);
2491 }
2492
2493 /* Returns whether a given packet or feature is supported. This takes
2494 into account the state of the corresponding "set remote foo-packet"
2495 command, which may be used to bypass auto-detection. */
2496
2497 static enum packet_support
2498 packet_config_support (const packet_config *config)
2499 {
2500 switch (config->detect)
2501 {
2502 case AUTO_BOOLEAN_TRUE:
2503 return PACKET_ENABLE;
2504 case AUTO_BOOLEAN_FALSE:
2505 return PACKET_DISABLE;
2506 case AUTO_BOOLEAN_AUTO:
2507 return config->support;
2508 default:
2509 gdb_assert_not_reached ("bad switch");
2510 }
2511 }
2512
2513 packet_support
2514 remote_features::packet_support (int packet) const
2515 {
2516 const packet_config *config = &m_protocol_packets[packet];
2517 return packet_config_support (config);
2518 }
2519
2520 static void
2521 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2522 struct cmd_list_element *c,
2523 const char *value)
2524 {
2525 remote_target *remote = get_current_remote_target ();
2526 gdb_assert (c->var.has_value ());
2527
2528 auto *default_config = static_cast<packet_config *> (c->context ());
2529 const int packet_idx = std::distance (remote_protocol_packets,
2530 default_config);
2531
2532 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2533 {
2534 show_packet_config_cmd (file, packet_idx, remote);
2535 return;
2536 }
2537 internal_error (_("Could not find config for %s"), c->name);
2538 }
2539
2540 /* Should we try one of the 'Z' requests? */
2541
2542 enum Z_packet_type
2543 {
2544 Z_PACKET_SOFTWARE_BP,
2545 Z_PACKET_HARDWARE_BP,
2546 Z_PACKET_WRITE_WP,
2547 Z_PACKET_READ_WP,
2548 Z_PACKET_ACCESS_WP,
2549 NR_Z_PACKET_TYPES
2550 };
2551
2552 /* For compatibility with older distributions. Provide a ``set remote
2553 Z-packet ...'' command that updates all the Z packet types. */
2554
2555 static enum auto_boolean remote_Z_packet_detect;
2556
2557 static void
2558 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2559 struct cmd_list_element *c)
2560 {
2561 remote_target *remote = get_current_remote_target ();
2562 int i;
2563
2564 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2565 {
2566 if (remote != nullptr)
2567 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2568 = remote_Z_packet_detect;
2569 else
2570 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2571 }
2572
2573 const char *support = get_packet_support_name (remote_Z_packet_detect);
2574 const char *target_type = get_target_type_name (remote != nullptr);
2575 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2576 support);
2577
2578 }
2579
2580 static void
2581 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2582 struct cmd_list_element *c,
2583 const char *value)
2584 {
2585 remote_target *remote = get_current_remote_target ();
2586 int i;
2587
2588 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2589 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2590 }
2591
2592 /* Insert fork catchpoint target routine. If fork events are enabled
2593 then return success, nothing more to do. */
2594
2595 int
2596 remote_target::insert_fork_catchpoint (int pid)
2597 {
2598 return !m_features.remote_fork_event_p ();
2599 }
2600
2601 /* Remove fork catchpoint target routine. Nothing to do, just
2602 return success. */
2603
2604 int
2605 remote_target::remove_fork_catchpoint (int pid)
2606 {
2607 return 0;
2608 }
2609
2610 /* Insert vfork catchpoint target routine. If vfork events are enabled
2611 then return success, nothing more to do. */
2612
2613 int
2614 remote_target::insert_vfork_catchpoint (int pid)
2615 {
2616 return !m_features.remote_vfork_event_p ();
2617 }
2618
2619 /* Remove vfork catchpoint target routine. Nothing to do, just
2620 return success. */
2621
2622 int
2623 remote_target::remove_vfork_catchpoint (int pid)
2624 {
2625 return 0;
2626 }
2627
2628 /* Insert exec catchpoint target routine. If exec events are
2629 enabled, just return success. */
2630
2631 int
2632 remote_target::insert_exec_catchpoint (int pid)
2633 {
2634 return !m_features.remote_exec_event_p ();
2635 }
2636
2637 /* Remove exec catchpoint target routine. Nothing to do, just
2638 return success. */
2639
2640 int
2641 remote_target::remove_exec_catchpoint (int pid)
2642 {
2643 return 0;
2644 }
2645
2646 \f
2647
2648 /* Take advantage of the fact that the TID field is not used, to tag
2649 special ptids with it set to != 0. */
2650 static const ptid_t magic_null_ptid (42000, -1, 1);
2651 static const ptid_t not_sent_ptid (42000, -2, 1);
2652 static const ptid_t any_thread_ptid (42000, 0, 1);
2653
2654 /* Find out if the stub attached to PID (and hence GDB should offer to
2655 detach instead of killing it when bailing out). */
2656
2657 int
2658 remote_target::remote_query_attached (int pid)
2659 {
2660 struct remote_state *rs = get_remote_state ();
2661 size_t size = get_remote_packet_size ();
2662
2663 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2664 return 0;
2665
2666 if (m_features.remote_multi_process_p ())
2667 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2668 else
2669 xsnprintf (rs->buf.data (), size, "qAttached");
2670
2671 putpkt (rs->buf);
2672 getpkt (&rs->buf);
2673
2674 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2675 {
2676 case PACKET_OK:
2677 if (strcmp (rs->buf.data (), "1") == 0)
2678 return 1;
2679 break;
2680 case PACKET_ERROR:
2681 warning (_("Remote failure reply: %s"), rs->buf.data ());
2682 break;
2683 case PACKET_UNKNOWN:
2684 break;
2685 }
2686
2687 return 0;
2688 }
2689
2690 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2691 has been invented by GDB, instead of reported by the target. Since
2692 we can be connected to a remote system before before knowing about
2693 any inferior, mark the target with execution when we find the first
2694 inferior. If ATTACHED is 1, then we had just attached to this
2695 inferior. If it is 0, then we just created this inferior. If it
2696 is -1, then try querying the remote stub to find out if it had
2697 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2698 attempt to open this inferior's executable as the main executable
2699 if no main executable is open already. */
2700
2701 inferior *
2702 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2703 int try_open_exec)
2704 {
2705 struct inferior *inf;
2706
2707 /* Check whether this process we're learning about is to be
2708 considered attached, or if is to be considered to have been
2709 spawned by the stub. */
2710 if (attached == -1)
2711 attached = remote_query_attached (pid);
2712
2713 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2714 {
2715 /* If the target shares code across all inferiors, then every
2716 attach adds a new inferior. */
2717 inf = add_inferior (pid);
2718
2719 /* ... and every inferior is bound to the same program space.
2720 However, each inferior may still have its own address
2721 space. */
2722 inf->aspace = maybe_new_address_space ();
2723 inf->pspace = current_program_space;
2724 }
2725 else
2726 {
2727 /* In the traditional debugging scenario, there's a 1-1 match
2728 between program/address spaces. We simply bind the inferior
2729 to the program space's address space. */
2730 inf = current_inferior ();
2731
2732 /* However, if the current inferior is already bound to a
2733 process, find some other empty inferior. */
2734 if (inf->pid != 0)
2735 {
2736 inf = nullptr;
2737 for (inferior *it : all_inferiors ())
2738 if (it->pid == 0)
2739 {
2740 inf = it;
2741 break;
2742 }
2743 }
2744 if (inf == nullptr)
2745 {
2746 /* Since all inferiors were already bound to a process, add
2747 a new inferior. */
2748 inf = add_inferior_with_spaces ();
2749 }
2750 switch_to_inferior_no_thread (inf);
2751 inf->push_target (this);
2752 inferior_appeared (inf, pid);
2753 }
2754
2755 inf->attach_flag = attached;
2756 inf->fake_pid_p = fake_pid_p;
2757
2758 /* If no main executable is currently open then attempt to
2759 open the file that was executed to create this inferior. */
2760 if (try_open_exec && get_exec_file (0) == NULL)
2761 exec_file_locate_attach (pid, 0, 1);
2762
2763 /* Check for exec file mismatch, and let the user solve it. */
2764 validate_exec_file (1);
2765
2766 return inf;
2767 }
2768
2769 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2770 static remote_thread_info *get_remote_thread_info (remote_target *target,
2771 ptid_t ptid);
2772
2773 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2774 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2775 remote_state::starting_up flag) is true then the new thread is added
2776 silently, otherwise the new thread will be announced to the user. */
2777
2778 thread_info *
2779 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2780 bool silent_p)
2781 {
2782 struct remote_state *rs = get_remote_state ();
2783 struct thread_info *thread;
2784
2785 /* GDB historically didn't pull threads in the initial connection
2786 setup. If the remote target doesn't even have a concept of
2787 threads (e.g., a bare-metal target), even if internally we
2788 consider that a single-threaded target, mentioning a new thread
2789 might be confusing to the user. Be silent then, preserving the
2790 age old behavior. */
2791 if (rs->starting_up || silent_p)
2792 thread = add_thread_silent (this, ptid);
2793 else
2794 thread = add_thread (this, ptid);
2795
2796 if (executing)
2797 get_remote_thread_info (thread)->set_resumed ();
2798 set_executing (this, ptid, executing);
2799 set_running (this, ptid, running);
2800
2801 return thread;
2802 }
2803
2804 /* Come here when we learn about a thread id from the remote target.
2805 It may be the first time we hear about such thread, so take the
2806 opportunity to add it to GDB's thread list. In case this is the
2807 first time we're noticing its corresponding inferior, add it to
2808 GDB's inferior list as well. EXECUTING indicates whether the
2809 thread is (internally) executing or stopped. */
2810
2811 void
2812 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2813 {
2814 /* In non-stop mode, we assume new found threads are (externally)
2815 running until proven otherwise with a stop reply. In all-stop,
2816 we can only get here if all threads are stopped. */
2817 bool running = target_is_non_stop_p ();
2818
2819 /* If this is a new thread, add it to GDB's thread list.
2820 If we leave it up to WFI to do this, bad things will happen. */
2821
2822 thread_info *tp = this->find_thread (currthread);
2823 if (tp != NULL && tp->state == THREAD_EXITED)
2824 {
2825 /* We're seeing an event on a thread id we knew had exited.
2826 This has to be a new thread reusing the old id. Add it. */
2827 remote_add_thread (currthread, running, executing, false);
2828 return;
2829 }
2830
2831 if (!in_thread_list (this, currthread))
2832 {
2833 struct inferior *inf = NULL;
2834 int pid = currthread.pid ();
2835
2836 if (inferior_ptid.is_pid ()
2837 && pid == inferior_ptid.pid ())
2838 {
2839 /* inferior_ptid has no thread member yet. This can happen
2840 with the vAttach -> remote_wait,"TAAthread:" path if the
2841 stub doesn't support qC. This is the first stop reported
2842 after an attach, so this is the main thread. Update the
2843 ptid in the thread list. */
2844 if (in_thread_list (this, ptid_t (pid)))
2845 thread_change_ptid (this, inferior_ptid, currthread);
2846 else
2847 {
2848 thread_info *thr
2849 = remote_add_thread (currthread, running, executing, false);
2850 switch_to_thread (thr);
2851 }
2852 return;
2853 }
2854
2855 if (magic_null_ptid == inferior_ptid)
2856 {
2857 /* inferior_ptid is not set yet. This can happen with the
2858 vRun -> remote_wait,"TAAthread:" path if the stub
2859 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 thread_change_ptid (this, inferior_ptid, currthread);
2863 return;
2864 }
2865
2866 /* When connecting to a target remote, or to a target
2867 extended-remote which already was debugging an inferior, we
2868 may not know about it yet. Add it before adding its child
2869 thread, so notifications are emitted in a sensible order. */
2870 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2871 {
2872 bool fake_pid_p = !m_features.remote_multi_process_p ();
2873
2874 inf = remote_add_inferior (fake_pid_p,
2875 currthread.pid (), -1, 1);
2876 }
2877
2878 /* This is really a new thread. Add it. */
2879 thread_info *new_thr
2880 = remote_add_thread (currthread, running, executing, false);
2881
2882 /* If we found a new inferior, let the common code do whatever
2883 it needs to with it (e.g., read shared libraries, insert
2884 breakpoints), unless we're just setting up an all-stop
2885 connection. */
2886 if (inf != NULL)
2887 {
2888 struct remote_state *rs = get_remote_state ();
2889
2890 if (!rs->starting_up)
2891 notice_new_inferior (new_thr, executing, 0);
2892 }
2893 }
2894 }
2895
2896 /* Return THREAD's private thread data, creating it if necessary. */
2897
2898 static remote_thread_info *
2899 get_remote_thread_info (thread_info *thread)
2900 {
2901 gdb_assert (thread != NULL);
2902
2903 if (thread->priv == NULL)
2904 thread->priv.reset (new remote_thread_info);
2905
2906 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2907 }
2908
2909 /* Return PTID's private thread data, creating it if necessary. */
2910
2911 static remote_thread_info *
2912 get_remote_thread_info (remote_target *target, ptid_t ptid)
2913 {
2914 thread_info *thr = target->find_thread (ptid);
2915 return get_remote_thread_info (thr);
2916 }
2917
2918 /* Call this function as a result of
2919 1) A halt indication (T packet) containing a thread id
2920 2) A direct query of currthread
2921 3) Successful execution of set thread */
2922
2923 static void
2924 record_currthread (struct remote_state *rs, ptid_t currthread)
2925 {
2926 rs->general_thread = currthread;
2927 }
2928
2929 /* If 'QPassSignals' is supported, tell the remote stub what signals
2930 it can simply pass through to the inferior without reporting. */
2931
2932 void
2933 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2934 {
2935 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2936 {
2937 char *pass_packet, *p;
2938 int count = 0;
2939 struct remote_state *rs = get_remote_state ();
2940
2941 gdb_assert (pass_signals.size () < 256);
2942 for (size_t i = 0; i < pass_signals.size (); i++)
2943 {
2944 if (pass_signals[i])
2945 count++;
2946 }
2947 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2948 strcpy (pass_packet, "QPassSignals:");
2949 p = pass_packet + strlen (pass_packet);
2950 for (size_t i = 0; i < pass_signals.size (); i++)
2951 {
2952 if (pass_signals[i])
2953 {
2954 if (i >= 16)
2955 *p++ = tohex (i >> 4);
2956 *p++ = tohex (i & 15);
2957 if (count)
2958 *p++ = ';';
2959 else
2960 break;
2961 count--;
2962 }
2963 }
2964 *p = 0;
2965 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2966 {
2967 putpkt (pass_packet);
2968 getpkt (&rs->buf);
2969 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2970 xfree (rs->last_pass_packet);
2971 rs->last_pass_packet = pass_packet;
2972 }
2973 else
2974 xfree (pass_packet);
2975 }
2976 }
2977
2978 /* If 'QCatchSyscalls' is supported, tell the remote stub
2979 to report syscalls to GDB. */
2980
2981 int
2982 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2983 gdb::array_view<const int> syscall_counts)
2984 {
2985 const char *catch_packet;
2986 enum packet_result result;
2987 int n_sysno = 0;
2988
2989 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2990 {
2991 /* Not supported. */
2992 return 1;
2993 }
2994
2995 if (needed && any_count == 0)
2996 {
2997 /* Count how many syscalls are to be caught. */
2998 for (size_t i = 0; i < syscall_counts.size (); i++)
2999 {
3000 if (syscall_counts[i] != 0)
3001 n_sysno++;
3002 }
3003 }
3004
3005 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3006 pid, needed, any_count, n_sysno);
3007
3008 std::string built_packet;
3009 if (needed)
3010 {
3011 /* Prepare a packet with the sysno list, assuming max 8+1
3012 characters for a sysno. If the resulting packet size is too
3013 big, fallback on the non-selective packet. */
3014 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3015 built_packet.reserve (maxpktsz);
3016 built_packet = "QCatchSyscalls:1";
3017 if (any_count == 0)
3018 {
3019 /* Add in each syscall to be caught. */
3020 for (size_t i = 0; i < syscall_counts.size (); i++)
3021 {
3022 if (syscall_counts[i] != 0)
3023 string_appendf (built_packet, ";%zx", i);
3024 }
3025 }
3026 if (built_packet.size () > get_remote_packet_size ())
3027 {
3028 /* catch_packet too big. Fallback to less efficient
3029 non selective mode, with GDB doing the filtering. */
3030 catch_packet = "QCatchSyscalls:1";
3031 }
3032 else
3033 catch_packet = built_packet.c_str ();
3034 }
3035 else
3036 catch_packet = "QCatchSyscalls:0";
3037
3038 struct remote_state *rs = get_remote_state ();
3039
3040 putpkt (catch_packet);
3041 getpkt (&rs->buf);
3042 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3043 if (result == PACKET_OK)
3044 return 0;
3045 else
3046 return -1;
3047 }
3048
3049 /* If 'QProgramSignals' is supported, tell the remote stub what
3050 signals it should pass through to the inferior when detaching. */
3051
3052 void
3053 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3054 {
3055 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3056 {
3057 char *packet, *p;
3058 int count = 0;
3059 struct remote_state *rs = get_remote_state ();
3060
3061 gdb_assert (signals.size () < 256);
3062 for (size_t i = 0; i < signals.size (); i++)
3063 {
3064 if (signals[i])
3065 count++;
3066 }
3067 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3068 strcpy (packet, "QProgramSignals:");
3069 p = packet + strlen (packet);
3070 for (size_t i = 0; i < signals.size (); i++)
3071 {
3072 if (signal_pass_state (i))
3073 {
3074 if (i >= 16)
3075 *p++ = tohex (i >> 4);
3076 *p++ = tohex (i & 15);
3077 if (count)
3078 *p++ = ';';
3079 else
3080 break;
3081 count--;
3082 }
3083 }
3084 *p = 0;
3085 if (!rs->last_program_signals_packet
3086 || strcmp (rs->last_program_signals_packet, packet) != 0)
3087 {
3088 putpkt (packet);
3089 getpkt (&rs->buf);
3090 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3091 xfree (rs->last_program_signals_packet);
3092 rs->last_program_signals_packet = packet;
3093 }
3094 else
3095 xfree (packet);
3096 }
3097 }
3098
3099 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3100 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3101 thread. If GEN is set, set the general thread, if not, then set
3102 the step/continue thread. */
3103 void
3104 remote_target::set_thread (ptid_t ptid, int gen)
3105 {
3106 struct remote_state *rs = get_remote_state ();
3107 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3108 char *buf = rs->buf.data ();
3109 char *endbuf = buf + get_remote_packet_size ();
3110
3111 if (state == ptid)
3112 return;
3113
3114 *buf++ = 'H';
3115 *buf++ = gen ? 'g' : 'c';
3116 if (ptid == magic_null_ptid)
3117 xsnprintf (buf, endbuf - buf, "0");
3118 else if (ptid == any_thread_ptid)
3119 xsnprintf (buf, endbuf - buf, "0");
3120 else if (ptid == minus_one_ptid)
3121 xsnprintf (buf, endbuf - buf, "-1");
3122 else
3123 write_ptid (buf, endbuf, ptid);
3124 putpkt (rs->buf);
3125 getpkt (&rs->buf);
3126 if (gen)
3127 rs->general_thread = ptid;
3128 else
3129 rs->continue_thread = ptid;
3130 }
3131
3132 void
3133 remote_target::set_general_thread (ptid_t ptid)
3134 {
3135 set_thread (ptid, 1);
3136 }
3137
3138 void
3139 remote_target::set_continue_thread (ptid_t ptid)
3140 {
3141 set_thread (ptid, 0);
3142 }
3143
3144 /* Change the remote current process. Which thread within the process
3145 ends up selected isn't important, as long as it is the same process
3146 as what INFERIOR_PTID points to.
3147
3148 This comes from that fact that there is no explicit notion of
3149 "selected process" in the protocol. The selected process for
3150 general operations is the process the selected general thread
3151 belongs to. */
3152
3153 void
3154 remote_target::set_general_process ()
3155 {
3156 /* If the remote can't handle multiple processes, don't bother. */
3157 if (!m_features.remote_multi_process_p ())
3158 return;
3159
3160 remote_state *rs = get_remote_state ();
3161
3162 /* We only need to change the remote current thread if it's pointing
3163 at some other process. */
3164 if (rs->general_thread.pid () != inferior_ptid.pid ())
3165 set_general_thread (inferior_ptid);
3166 }
3167
3168 \f
3169 /* Return nonzero if this is the main thread that we made up ourselves
3170 to model non-threaded targets as single-threaded. */
3171
3172 static int
3173 remote_thread_always_alive (ptid_t ptid)
3174 {
3175 if (ptid == magic_null_ptid)
3176 /* The main thread is always alive. */
3177 return 1;
3178
3179 if (ptid.pid () != 0 && ptid.lwp () == 0)
3180 /* The main thread is always alive. This can happen after a
3181 vAttach, if the remote side doesn't support
3182 multi-threading. */
3183 return 1;
3184
3185 return 0;
3186 }
3187
3188 /* Return nonzero if the thread PTID is still alive on the remote
3189 system. */
3190
3191 bool
3192 remote_target::thread_alive (ptid_t ptid)
3193 {
3194 struct remote_state *rs = get_remote_state ();
3195 char *p, *endp;
3196
3197 /* Check if this is a thread that we made up ourselves to model
3198 non-threaded targets as single-threaded. */
3199 if (remote_thread_always_alive (ptid))
3200 return 1;
3201
3202 p = rs->buf.data ();
3203 endp = p + get_remote_packet_size ();
3204
3205 *p++ = 'T';
3206 write_ptid (p, endp, ptid);
3207
3208 putpkt (rs->buf);
3209 getpkt (&rs->buf);
3210 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3211 }
3212
3213 /* Return a pointer to a thread name if we know it and NULL otherwise.
3214 The thread_info object owns the memory for the name. */
3215
3216 const char *
3217 remote_target::thread_name (struct thread_info *info)
3218 {
3219 if (info->priv != NULL)
3220 {
3221 const std::string &name = get_remote_thread_info (info)->name;
3222 return !name.empty () ? name.c_str () : NULL;
3223 }
3224
3225 return NULL;
3226 }
3227
3228 /* About these extended threadlist and threadinfo packets. They are
3229 variable length packets but, the fields within them are often fixed
3230 length. They are redundant enough to send over UDP as is the
3231 remote protocol in general. There is a matching unit test module
3232 in libstub. */
3233
3234 /* WARNING: This threadref data structure comes from the remote O.S.,
3235 libstub protocol encoding, and remote.c. It is not particularly
3236 changeable. */
3237
3238 /* Right now, the internal structure is int. We want it to be bigger.
3239 Plan to fix this. */
3240
3241 typedef int gdb_threadref; /* Internal GDB thread reference. */
3242
3243 /* gdb_ext_thread_info is an internal GDB data structure which is
3244 equivalent to the reply of the remote threadinfo packet. */
3245
3246 struct gdb_ext_thread_info
3247 {
3248 threadref threadid; /* External form of thread reference. */
3249 int active; /* Has state interesting to GDB?
3250 regs, stack. */
3251 char display[256]; /* Brief state display, name,
3252 blocked/suspended. */
3253 char shortname[32]; /* To be used to name threads. */
3254 char more_display[256]; /* Long info, statistics, queue depth,
3255 whatever. */
3256 };
3257
3258 /* The volume of remote transfers can be limited by submitting
3259 a mask containing bits specifying the desired information.
3260 Use a union of these values as the 'selection' parameter to
3261 get_thread_info. FIXME: Make these TAG names more thread specific. */
3262
3263 #define TAG_THREADID 1
3264 #define TAG_EXISTS 2
3265 #define TAG_DISPLAY 4
3266 #define TAG_THREADNAME 8
3267 #define TAG_MOREDISPLAY 16
3268
3269 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3270
3271 static const char *unpack_nibble (const char *buf, int *val);
3272
3273 static const char *unpack_byte (const char *buf, int *value);
3274
3275 static char *pack_int (char *buf, int value);
3276
3277 static const char *unpack_int (const char *buf, int *value);
3278
3279 static const char *unpack_string (const char *src, char *dest, int length);
3280
3281 static char *pack_threadid (char *pkt, threadref *id);
3282
3283 static const char *unpack_threadid (const char *inbuf, threadref *id);
3284
3285 void int_to_threadref (threadref *id, int value);
3286
3287 static int threadref_to_int (threadref *ref);
3288
3289 static void copy_threadref (threadref *dest, threadref *src);
3290
3291 static int threadmatch (threadref *dest, threadref *src);
3292
3293 static char *pack_threadinfo_request (char *pkt, int mode,
3294 threadref *id);
3295
3296 static char *pack_threadlist_request (char *pkt, int startflag,
3297 int threadcount,
3298 threadref *nextthread);
3299
3300 static int remote_newthread_step (threadref *ref, void *context);
3301
3302
3303 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3304 buffer we're allowed to write to. Returns
3305 BUF+CHARACTERS_WRITTEN. */
3306
3307 char *
3308 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3309 {
3310 int pid, tid;
3311
3312 if (m_features.remote_multi_process_p ())
3313 {
3314 pid = ptid.pid ();
3315 if (pid < 0)
3316 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3317 else
3318 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3319 }
3320 tid = ptid.lwp ();
3321 if (tid < 0)
3322 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3323 else
3324 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3325
3326 return buf;
3327 }
3328
3329 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3330 last parsed char. Returns null_ptid if no thread id is found, and
3331 throws an error if the thread id has an invalid format. */
3332
3333 static ptid_t
3334 read_ptid (const char *buf, const char **obuf)
3335 {
3336 const char *p = buf;
3337 const char *pp;
3338 ULONGEST pid = 0, tid = 0;
3339
3340 if (*p == 'p')
3341 {
3342 /* Multi-process ptid. */
3343 pp = unpack_varlen_hex (p + 1, &pid);
3344 if (*pp != '.')
3345 error (_("invalid remote ptid: %s"), p);
3346
3347 p = pp;
3348 pp = unpack_varlen_hex (p + 1, &tid);
3349 if (obuf)
3350 *obuf = pp;
3351 return ptid_t (pid, tid);
3352 }
3353
3354 /* No multi-process. Just a tid. */
3355 pp = unpack_varlen_hex (p, &tid);
3356
3357 /* Return null_ptid when no thread id is found. */
3358 if (p == pp)
3359 {
3360 if (obuf)
3361 *obuf = pp;
3362 return null_ptid;
3363 }
3364
3365 /* Since the stub is not sending a process id, default to what's
3366 current_inferior, unless it doesn't have a PID yet. If so,
3367 then since there's no way to know the pid of the reported
3368 threads, use the magic number. */
3369 inferior *inf = current_inferior ();
3370 if (inf->pid == 0)
3371 pid = magic_null_ptid.pid ();
3372 else
3373 pid = inf->pid;
3374
3375 if (obuf)
3376 *obuf = pp;
3377 return ptid_t (pid, tid);
3378 }
3379
3380 static int
3381 stubhex (int ch)
3382 {
3383 if (ch >= 'a' && ch <= 'f')
3384 return ch - 'a' + 10;
3385 if (ch >= '0' && ch <= '9')
3386 return ch - '0';
3387 if (ch >= 'A' && ch <= 'F')
3388 return ch - 'A' + 10;
3389 return -1;
3390 }
3391
3392 static int
3393 stub_unpack_int (const char *buff, int fieldlength)
3394 {
3395 int nibble;
3396 int retval = 0;
3397
3398 while (fieldlength)
3399 {
3400 nibble = stubhex (*buff++);
3401 retval |= nibble;
3402 fieldlength--;
3403 if (fieldlength)
3404 retval = retval << 4;
3405 }
3406 return retval;
3407 }
3408
3409 static const char *
3410 unpack_nibble (const char *buf, int *val)
3411 {
3412 *val = fromhex (*buf++);
3413 return buf;
3414 }
3415
3416 static const char *
3417 unpack_byte (const char *buf, int *value)
3418 {
3419 *value = stub_unpack_int (buf, 2);
3420 return buf + 2;
3421 }
3422
3423 static char *
3424 pack_int (char *buf, int value)
3425 {
3426 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3427 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3428 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3429 buf = pack_hex_byte (buf, (value & 0xff));
3430 return buf;
3431 }
3432
3433 static const char *
3434 unpack_int (const char *buf, int *value)
3435 {
3436 *value = stub_unpack_int (buf, 8);
3437 return buf + 8;
3438 }
3439
3440 #if 0 /* Currently unused, uncomment when needed. */
3441 static char *pack_string (char *pkt, char *string);
3442
3443 static char *
3444 pack_string (char *pkt, char *string)
3445 {
3446 char ch;
3447 int len;
3448
3449 len = strlen (string);
3450 if (len > 200)
3451 len = 200; /* Bigger than most GDB packets, junk??? */
3452 pkt = pack_hex_byte (pkt, len);
3453 while (len-- > 0)
3454 {
3455 ch = *string++;
3456 if ((ch == '\0') || (ch == '#'))
3457 ch = '*'; /* Protect encapsulation. */
3458 *pkt++ = ch;
3459 }
3460 return pkt;
3461 }
3462 #endif /* 0 (unused) */
3463
3464 static const char *
3465 unpack_string (const char *src, char *dest, int length)
3466 {
3467 while (length--)
3468 *dest++ = *src++;
3469 *dest = '\0';
3470 return src;
3471 }
3472
3473 static char *
3474 pack_threadid (char *pkt, threadref *id)
3475 {
3476 char *limit;
3477 unsigned char *altid;
3478
3479 altid = (unsigned char *) id;
3480 limit = pkt + BUF_THREAD_ID_SIZE;
3481 while (pkt < limit)
3482 pkt = pack_hex_byte (pkt, *altid++);
3483 return pkt;
3484 }
3485
3486
3487 static const char *
3488 unpack_threadid (const char *inbuf, threadref *id)
3489 {
3490 char *altref;
3491 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3492 int x, y;
3493
3494 altref = (char *) id;
3495
3496 while (inbuf < limit)
3497 {
3498 x = stubhex (*inbuf++);
3499 y = stubhex (*inbuf++);
3500 *altref++ = (x << 4) | y;
3501 }
3502 return inbuf;
3503 }
3504
3505 /* Externally, threadrefs are 64 bits but internally, they are still
3506 ints. This is due to a mismatch of specifications. We would like
3507 to use 64bit thread references internally. This is an adapter
3508 function. */
3509
3510 void
3511 int_to_threadref (threadref *id, int value)
3512 {
3513 unsigned char *scan;
3514
3515 scan = (unsigned char *) id;
3516 {
3517 int i = 4;
3518 while (i--)
3519 *scan++ = 0;
3520 }
3521 *scan++ = (value >> 24) & 0xff;
3522 *scan++ = (value >> 16) & 0xff;
3523 *scan++ = (value >> 8) & 0xff;
3524 *scan++ = (value & 0xff);
3525 }
3526
3527 static int
3528 threadref_to_int (threadref *ref)
3529 {
3530 int i, value = 0;
3531 unsigned char *scan;
3532
3533 scan = *ref;
3534 scan += 4;
3535 i = 4;
3536 while (i-- > 0)
3537 value = (value << 8) | ((*scan++) & 0xff);
3538 return value;
3539 }
3540
3541 static void
3542 copy_threadref (threadref *dest, threadref *src)
3543 {
3544 int i;
3545 unsigned char *csrc, *cdest;
3546
3547 csrc = (unsigned char *) src;
3548 cdest = (unsigned char *) dest;
3549 i = 8;
3550 while (i--)
3551 *cdest++ = *csrc++;
3552 }
3553
3554 static int
3555 threadmatch (threadref *dest, threadref *src)
3556 {
3557 /* Things are broken right now, so just assume we got a match. */
3558 #if 0
3559 unsigned char *srcp, *destp;
3560 int i, result;
3561 srcp = (char *) src;
3562 destp = (char *) dest;
3563
3564 result = 1;
3565 while (i-- > 0)
3566 result &= (*srcp++ == *destp++) ? 1 : 0;
3567 return result;
3568 #endif
3569 return 1;
3570 }
3571
3572 /*
3573 threadid:1, # always request threadid
3574 context_exists:2,
3575 display:4,
3576 unique_name:8,
3577 more_display:16
3578 */
3579
3580 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3581
3582 static char *
3583 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3584 {
3585 *pkt++ = 'q'; /* Info Query */
3586 *pkt++ = 'P'; /* process or thread info */
3587 pkt = pack_int (pkt, mode); /* mode */
3588 pkt = pack_threadid (pkt, id); /* threadid */
3589 *pkt = '\0'; /* terminate */
3590 return pkt;
3591 }
3592
3593 /* These values tag the fields in a thread info response packet. */
3594 /* Tagging the fields allows us to request specific fields and to
3595 add more fields as time goes by. */
3596
3597 #define TAG_THREADID 1 /* Echo the thread identifier. */
3598 #define TAG_EXISTS 2 /* Is this process defined enough to
3599 fetch registers and its stack? */
3600 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3601 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3602 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3603 the process. */
3604
3605 int
3606 remote_target::remote_unpack_thread_info_response (const char *pkt,
3607 threadref *expectedref,
3608 gdb_ext_thread_info *info)
3609 {
3610 struct remote_state *rs = get_remote_state ();
3611 int mask, length;
3612 int tag;
3613 threadref ref;
3614 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3615 int retval = 1;
3616
3617 /* info->threadid = 0; FIXME: implement zero_threadref. */
3618 info->active = 0;
3619 info->display[0] = '\0';
3620 info->shortname[0] = '\0';
3621 info->more_display[0] = '\0';
3622
3623 /* Assume the characters indicating the packet type have been
3624 stripped. */
3625 pkt = unpack_int (pkt, &mask); /* arg mask */
3626 pkt = unpack_threadid (pkt, &ref);
3627
3628 if (mask == 0)
3629 warning (_("Incomplete response to threadinfo request."));
3630 if (!threadmatch (&ref, expectedref))
3631 { /* This is an answer to a different request. */
3632 warning (_("ERROR RMT Thread info mismatch."));
3633 return 0;
3634 }
3635 copy_threadref (&info->threadid, &ref);
3636
3637 /* Loop on tagged fields , try to bail if something goes wrong. */
3638
3639 /* Packets are terminated with nulls. */
3640 while ((pkt < limit) && mask && *pkt)
3641 {
3642 pkt = unpack_int (pkt, &tag); /* tag */
3643 pkt = unpack_byte (pkt, &length); /* length */
3644 if (!(tag & mask)) /* Tags out of synch with mask. */
3645 {
3646 warning (_("ERROR RMT: threadinfo tag mismatch."));
3647 retval = 0;
3648 break;
3649 }
3650 if (tag == TAG_THREADID)
3651 {
3652 if (length != 16)
3653 {
3654 warning (_("ERROR RMT: length of threadid is not 16."));
3655 retval = 0;
3656 break;
3657 }
3658 pkt = unpack_threadid (pkt, &ref);
3659 mask = mask & ~TAG_THREADID;
3660 continue;
3661 }
3662 if (tag == TAG_EXISTS)
3663 {
3664 info->active = stub_unpack_int (pkt, length);
3665 pkt += length;
3666 mask = mask & ~(TAG_EXISTS);
3667 if (length > 8)
3668 {
3669 warning (_("ERROR RMT: 'exists' length too long."));
3670 retval = 0;
3671 break;
3672 }
3673 continue;
3674 }
3675 if (tag == TAG_THREADNAME)
3676 {
3677 pkt = unpack_string (pkt, &info->shortname[0], length);
3678 mask = mask & ~TAG_THREADNAME;
3679 continue;
3680 }
3681 if (tag == TAG_DISPLAY)
3682 {
3683 pkt = unpack_string (pkt, &info->display[0], length);
3684 mask = mask & ~TAG_DISPLAY;
3685 continue;
3686 }
3687 if (tag == TAG_MOREDISPLAY)
3688 {
3689 pkt = unpack_string (pkt, &info->more_display[0], length);
3690 mask = mask & ~TAG_MOREDISPLAY;
3691 continue;
3692 }
3693 warning (_("ERROR RMT: unknown thread info tag."));
3694 break; /* Not a tag we know about. */
3695 }
3696 return retval;
3697 }
3698
3699 int
3700 remote_target::remote_get_threadinfo (threadref *threadid,
3701 int fieldset,
3702 gdb_ext_thread_info *info)
3703 {
3704 struct remote_state *rs = get_remote_state ();
3705 int result;
3706
3707 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3708 putpkt (rs->buf);
3709 getpkt (&rs->buf);
3710
3711 if (rs->buf[0] == '\0')
3712 return 0;
3713
3714 result = remote_unpack_thread_info_response (&rs->buf[2],
3715 threadid, info);
3716 return result;
3717 }
3718
3719 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3720
3721 static char *
3722 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3723 threadref *nextthread)
3724 {
3725 *pkt++ = 'q'; /* info query packet */
3726 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3727 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3728 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3729 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3730 *pkt = '\0';
3731 return pkt;
3732 }
3733
3734 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3735
3736 int
3737 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3738 threadref *original_echo,
3739 threadref *resultlist,
3740 int *doneflag)
3741 {
3742 struct remote_state *rs = get_remote_state ();
3743 int count, resultcount, done;
3744
3745 resultcount = 0;
3746 /* Assume the 'q' and 'M chars have been stripped. */
3747 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3748 /* done parse past here */
3749 pkt = unpack_byte (pkt, &count); /* count field */
3750 pkt = unpack_nibble (pkt, &done);
3751 /* The first threadid is the argument threadid. */
3752 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3753 while ((count-- > 0) && (pkt < limit))
3754 {
3755 pkt = unpack_threadid (pkt, resultlist++);
3756 if (resultcount++ >= result_limit)
3757 break;
3758 }
3759 if (doneflag)
3760 *doneflag = done;
3761 return resultcount;
3762 }
3763
3764 /* Fetch the next batch of threads from the remote. Returns -1 if the
3765 qL packet is not supported, 0 on error and 1 on success. */
3766
3767 int
3768 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3769 int result_limit, int *done, int *result_count,
3770 threadref *threadlist)
3771 {
3772 struct remote_state *rs = get_remote_state ();
3773 int result = 1;
3774
3775 /* Truncate result limit to be smaller than the packet size. */
3776 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3777 >= get_remote_packet_size ())
3778 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3779
3780 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3781 nextthread);
3782 putpkt (rs->buf);
3783 getpkt (&rs->buf);
3784 if (rs->buf[0] == '\0')
3785 {
3786 /* Packet not supported. */
3787 return -1;
3788 }
3789
3790 *result_count =
3791 parse_threadlist_response (&rs->buf[2], result_limit,
3792 &rs->echo_nextthread, threadlist, done);
3793
3794 if (!threadmatch (&rs->echo_nextthread, nextthread))
3795 {
3796 /* FIXME: This is a good reason to drop the packet. */
3797 /* Possibly, there is a duplicate response. */
3798 /* Possibilities :
3799 retransmit immediatly - race conditions
3800 retransmit after timeout - yes
3801 exit
3802 wait for packet, then exit
3803 */
3804 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3805 return 0; /* I choose simply exiting. */
3806 }
3807 if (*result_count <= 0)
3808 {
3809 if (*done != 1)
3810 {
3811 warning (_("RMT ERROR : failed to get remote thread list."));
3812 result = 0;
3813 }
3814 return result; /* break; */
3815 }
3816 if (*result_count > result_limit)
3817 {
3818 *result_count = 0;
3819 warning (_("RMT ERROR: threadlist response longer than requested."));
3820 return 0;
3821 }
3822 return result;
3823 }
3824
3825 /* Fetch the list of remote threads, with the qL packet, and call
3826 STEPFUNCTION for each thread found. Stops iterating and returns 1
3827 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3828 STEPFUNCTION returns false. If the packet is not supported,
3829 returns -1. */
3830
3831 int
3832 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3833 void *context, int looplimit)
3834 {
3835 struct remote_state *rs = get_remote_state ();
3836 int done, i, result_count;
3837 int startflag = 1;
3838 int result = 1;
3839 int loopcount = 0;
3840
3841 done = 0;
3842 while (!done)
3843 {
3844 if (loopcount++ > looplimit)
3845 {
3846 result = 0;
3847 warning (_("Remote fetch threadlist -infinite loop-."));
3848 break;
3849 }
3850 result = remote_get_threadlist (startflag, &rs->nextthread,
3851 MAXTHREADLISTRESULTS,
3852 &done, &result_count,
3853 rs->resultthreadlist);
3854 if (result <= 0)
3855 break;
3856 /* Clear for later iterations. */
3857 startflag = 0;
3858 /* Setup to resume next batch of thread references, set nextthread. */
3859 if (result_count >= 1)
3860 copy_threadref (&rs->nextthread,
3861 &rs->resultthreadlist[result_count - 1]);
3862 i = 0;
3863 while (result_count--)
3864 {
3865 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3866 {
3867 result = 0;
3868 break;
3869 }
3870 }
3871 }
3872 return result;
3873 }
3874
3875 /* A thread found on the remote target. */
3876
3877 struct thread_item
3878 {
3879 explicit thread_item (ptid_t ptid_)
3880 : ptid (ptid_)
3881 {}
3882
3883 thread_item (thread_item &&other) = default;
3884 thread_item &operator= (thread_item &&other) = default;
3885
3886 DISABLE_COPY_AND_ASSIGN (thread_item);
3887
3888 /* The thread's PTID. */
3889 ptid_t ptid;
3890
3891 /* The thread's extra info. */
3892 std::string extra;
3893
3894 /* The thread's name. */
3895 std::string name;
3896
3897 /* The core the thread was running on. -1 if not known. */
3898 int core = -1;
3899
3900 /* The thread handle associated with the thread. */
3901 gdb::byte_vector thread_handle;
3902 };
3903
3904 /* Context passed around to the various methods listing remote
3905 threads. As new threads are found, they're added to the ITEMS
3906 vector. */
3907
3908 struct threads_listing_context
3909 {
3910 /* Return true if this object contains an entry for a thread with ptid
3911 PTID. */
3912
3913 bool contains_thread (ptid_t ptid) const
3914 {
3915 auto match_ptid = [&] (const thread_item &item)
3916 {
3917 return item.ptid == ptid;
3918 };
3919
3920 auto it = std::find_if (this->items.begin (),
3921 this->items.end (),
3922 match_ptid);
3923
3924 return it != this->items.end ();
3925 }
3926
3927 /* Remove the thread with ptid PTID. */
3928
3929 void remove_thread (ptid_t ptid)
3930 {
3931 auto match_ptid = [&] (const thread_item &item)
3932 {
3933 return item.ptid == ptid;
3934 };
3935
3936 auto it = std::remove_if (this->items.begin (),
3937 this->items.end (),
3938 match_ptid);
3939
3940 if (it != this->items.end ())
3941 this->items.erase (it);
3942 }
3943
3944 /* The threads found on the remote target. */
3945 std::vector<thread_item> items;
3946 };
3947
3948 static int
3949 remote_newthread_step (threadref *ref, void *data)
3950 {
3951 struct threads_listing_context *context
3952 = (struct threads_listing_context *) data;
3953 int pid = inferior_ptid.pid ();
3954 int lwp = threadref_to_int (ref);
3955 ptid_t ptid (pid, lwp);
3956
3957 context->items.emplace_back (ptid);
3958
3959 return 1; /* continue iterator */
3960 }
3961
3962 #define CRAZY_MAX_THREADS 1000
3963
3964 ptid_t
3965 remote_target::remote_current_thread (ptid_t oldpid)
3966 {
3967 struct remote_state *rs = get_remote_state ();
3968
3969 putpkt ("qC");
3970 getpkt (&rs->buf);
3971 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3972 {
3973 const char *obuf;
3974 ptid_t result;
3975
3976 result = read_ptid (&rs->buf[2], &obuf);
3977 if (*obuf != '\0')
3978 remote_debug_printf ("warning: garbage in qC reply");
3979
3980 return result;
3981 }
3982 else
3983 return oldpid;
3984 }
3985
3986 /* List remote threads using the deprecated qL packet. */
3987
3988 int
3989 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3990 {
3991 if (remote_threadlist_iterator (remote_newthread_step, context,
3992 CRAZY_MAX_THREADS) >= 0)
3993 return 1;
3994
3995 return 0;
3996 }
3997
3998 #if defined(HAVE_LIBEXPAT)
3999
4000 static void
4001 start_thread (struct gdb_xml_parser *parser,
4002 const struct gdb_xml_element *element,
4003 void *user_data,
4004 std::vector<gdb_xml_value> &attributes)
4005 {
4006 struct threads_listing_context *data
4007 = (struct threads_listing_context *) user_data;
4008 struct gdb_xml_value *attr;
4009
4010 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4011 ptid_t ptid = read_ptid (id, NULL);
4012
4013 data->items.emplace_back (ptid);
4014 thread_item &item = data->items.back ();
4015
4016 attr = xml_find_attribute (attributes, "core");
4017 if (attr != NULL)
4018 item.core = *(ULONGEST *) attr->value.get ();
4019
4020 attr = xml_find_attribute (attributes, "name");
4021 if (attr != NULL)
4022 item.name = (const char *) attr->value.get ();
4023
4024 attr = xml_find_attribute (attributes, "handle");
4025 if (attr != NULL)
4026 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4027 }
4028
4029 static void
4030 end_thread (struct gdb_xml_parser *parser,
4031 const struct gdb_xml_element *element,
4032 void *user_data, const char *body_text)
4033 {
4034 struct threads_listing_context *data
4035 = (struct threads_listing_context *) user_data;
4036
4037 if (body_text != NULL && *body_text != '\0')
4038 data->items.back ().extra = body_text;
4039 }
4040
4041 const struct gdb_xml_attribute thread_attributes[] = {
4042 { "id", GDB_XML_AF_NONE, NULL, NULL },
4043 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4044 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4045 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4046 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4047 };
4048
4049 const struct gdb_xml_element thread_children[] = {
4050 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4051 };
4052
4053 const struct gdb_xml_element threads_children[] = {
4054 { "thread", thread_attributes, thread_children,
4055 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4056 start_thread, end_thread },
4057 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4058 };
4059
4060 const struct gdb_xml_element threads_elements[] = {
4061 { "threads", NULL, threads_children,
4062 GDB_XML_EF_NONE, NULL, NULL },
4063 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4064 };
4065
4066 #endif
4067
4068 /* List remote threads using qXfer:threads:read. */
4069
4070 int
4071 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4072 {
4073 #if defined(HAVE_LIBEXPAT)
4074 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4075 {
4076 gdb::optional<gdb::char_vector> xml
4077 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4078
4079 if (xml && (*xml)[0] != '\0')
4080 {
4081 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4082 threads_elements, xml->data (), context);
4083 }
4084
4085 return 1;
4086 }
4087 #endif
4088
4089 return 0;
4090 }
4091
4092 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4093
4094 int
4095 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4096 {
4097 struct remote_state *rs = get_remote_state ();
4098
4099 if (rs->use_threadinfo_query)
4100 {
4101 const char *bufp;
4102
4103 putpkt ("qfThreadInfo");
4104 getpkt (&rs->buf);
4105 bufp = rs->buf.data ();
4106 if (bufp[0] != '\0') /* q packet recognized */
4107 {
4108 while (*bufp++ == 'm') /* reply contains one or more TID */
4109 {
4110 do
4111 {
4112 ptid_t ptid = read_ptid (bufp, &bufp);
4113 context->items.emplace_back (ptid);
4114 }
4115 while (*bufp++ == ','); /* comma-separated list */
4116 putpkt ("qsThreadInfo");
4117 getpkt (&rs->buf);
4118 bufp = rs->buf.data ();
4119 }
4120 return 1;
4121 }
4122 else
4123 {
4124 /* Packet not recognized. */
4125 rs->use_threadinfo_query = 0;
4126 }
4127 }
4128
4129 return 0;
4130 }
4131
4132 /* Return true if INF only has one non-exited thread. */
4133
4134 static bool
4135 has_single_non_exited_thread (inferior *inf)
4136 {
4137 int count = 0;
4138 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4139 if (++count > 1)
4140 break;
4141 return count == 1;
4142 }
4143
4144 /* Implement the to_update_thread_list function for the remote
4145 targets. */
4146
4147 void
4148 remote_target::update_thread_list ()
4149 {
4150 struct threads_listing_context context;
4151 int got_list = 0;
4152
4153 /* We have a few different mechanisms to fetch the thread list. Try
4154 them all, starting with the most preferred one first, falling
4155 back to older methods. */
4156 if (remote_get_threads_with_qxfer (&context)
4157 || remote_get_threads_with_qthreadinfo (&context)
4158 || remote_get_threads_with_ql (&context))
4159 {
4160 got_list = 1;
4161
4162 if (context.items.empty ()
4163 && remote_thread_always_alive (inferior_ptid))
4164 {
4165 /* Some targets don't really support threads, but still
4166 reply an (empty) thread list in response to the thread
4167 listing packets, instead of replying "packet not
4168 supported". Exit early so we don't delete the main
4169 thread. */
4170 return;
4171 }
4172
4173 /* CONTEXT now holds the current thread list on the remote
4174 target end. Delete GDB-side threads no longer found on the
4175 target. */
4176 for (thread_info *tp : all_threads_safe ())
4177 {
4178 if (tp->inf->process_target () != this)
4179 continue;
4180
4181 if (!context.contains_thread (tp->ptid))
4182 {
4183 /* Do not remove the thread if it is the last thread in
4184 the inferior. This situation happens when we have a
4185 pending exit process status to process. Otherwise we
4186 may end up with a seemingly live inferior (i.e. pid
4187 != 0) that has no threads. */
4188 if (has_single_non_exited_thread (tp->inf))
4189 continue;
4190
4191 /* Not found. */
4192 delete_thread (tp);
4193 }
4194 }
4195
4196 /* Remove any unreported fork/vfork/clone child threads from
4197 CONTEXT so that we don't interfere with follow
4198 fork/vfork/clone, which is where creation of such threads is
4199 handled. */
4200 remove_new_children (&context);
4201
4202 /* And now add threads we don't know about yet to our list. */
4203 for (thread_item &item : context.items)
4204 {
4205 if (item.ptid != null_ptid)
4206 {
4207 /* In non-stop mode, we assume new found threads are
4208 executing until proven otherwise with a stop reply.
4209 In all-stop, we can only get here if all threads are
4210 stopped. */
4211 bool executing = target_is_non_stop_p ();
4212
4213 remote_notice_new_inferior (item.ptid, executing);
4214
4215 thread_info *tp = this->find_thread (item.ptid);
4216 remote_thread_info *info = get_remote_thread_info (tp);
4217 info->core = item.core;
4218 info->extra = std::move (item.extra);
4219 info->name = std::move (item.name);
4220 info->thread_handle = std::move (item.thread_handle);
4221 }
4222 }
4223 }
4224
4225 if (!got_list)
4226 {
4227 /* If no thread listing method is supported, then query whether
4228 each known thread is alive, one by one, with the T packet.
4229 If the target doesn't support threads at all, then this is a
4230 no-op. See remote_thread_alive. */
4231 prune_threads ();
4232 }
4233 }
4234
4235 /*
4236 * Collect a descriptive string about the given thread.
4237 * The target may say anything it wants to about the thread
4238 * (typically info about its blocked / runnable state, name, etc.).
4239 * This string will appear in the info threads display.
4240 *
4241 * Optional: targets are not required to implement this function.
4242 */
4243
4244 const char *
4245 remote_target::extra_thread_info (thread_info *tp)
4246 {
4247 struct remote_state *rs = get_remote_state ();
4248 int set;
4249 threadref id;
4250 struct gdb_ext_thread_info threadinfo;
4251
4252 if (rs->remote_desc == 0) /* paranoia */
4253 internal_error (_("remote_threads_extra_info"));
4254
4255 if (tp->ptid == magic_null_ptid
4256 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4257 /* This is the main thread which was added by GDB. The remote
4258 server doesn't know about it. */
4259 return NULL;
4260
4261 std::string &extra = get_remote_thread_info (tp)->extra;
4262
4263 /* If already have cached info, use it. */
4264 if (!extra.empty ())
4265 return extra.c_str ();
4266
4267 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4268 {
4269 /* If we're using qXfer:threads:read, then the extra info is
4270 included in the XML. So if we didn't have anything cached,
4271 it's because there's really no extra info. */
4272 return NULL;
4273 }
4274
4275 if (rs->use_threadextra_query)
4276 {
4277 char *b = rs->buf.data ();
4278 char *endb = b + get_remote_packet_size ();
4279
4280 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4281 b += strlen (b);
4282 write_ptid (b, endb, tp->ptid);
4283
4284 putpkt (rs->buf);
4285 getpkt (&rs->buf);
4286 if (rs->buf[0] != 0)
4287 {
4288 extra.resize (strlen (rs->buf.data ()) / 2);
4289 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4290 return extra.c_str ();
4291 }
4292 }
4293
4294 /* If the above query fails, fall back to the old method. */
4295 rs->use_threadextra_query = 0;
4296 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4297 | TAG_MOREDISPLAY | TAG_DISPLAY;
4298 int_to_threadref (&id, tp->ptid.lwp ());
4299 if (remote_get_threadinfo (&id, set, &threadinfo))
4300 if (threadinfo.active)
4301 {
4302 if (*threadinfo.shortname)
4303 string_appendf (extra, " Name: %s", threadinfo.shortname);
4304 if (*threadinfo.display)
4305 {
4306 if (!extra.empty ())
4307 extra += ',';
4308 string_appendf (extra, " State: %s", threadinfo.display);
4309 }
4310 if (*threadinfo.more_display)
4311 {
4312 if (!extra.empty ())
4313 extra += ',';
4314 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4315 }
4316 return extra.c_str ();
4317 }
4318 return NULL;
4319 }
4320 \f
4321
4322 bool
4323 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4324 struct static_tracepoint_marker *marker)
4325 {
4326 struct remote_state *rs = get_remote_state ();
4327 char *p = rs->buf.data ();
4328
4329 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4330 p += strlen (p);
4331 p += hexnumstr (p, addr);
4332 putpkt (rs->buf);
4333 getpkt (&rs->buf);
4334 p = rs->buf.data ();
4335
4336 if (*p == 'E')
4337 error (_("Remote failure reply: %s"), p);
4338
4339 if (*p++ == 'm')
4340 {
4341 parse_static_tracepoint_marker_definition (p, NULL, marker);
4342 return true;
4343 }
4344
4345 return false;
4346 }
4347
4348 std::vector<static_tracepoint_marker>
4349 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4350 {
4351 struct remote_state *rs = get_remote_state ();
4352 std::vector<static_tracepoint_marker> markers;
4353 const char *p;
4354 static_tracepoint_marker marker;
4355
4356 /* Ask for a first packet of static tracepoint marker
4357 definition. */
4358 putpkt ("qTfSTM");
4359 getpkt (&rs->buf);
4360 p = rs->buf.data ();
4361 if (*p == 'E')
4362 error (_("Remote failure reply: %s"), p);
4363
4364 while (*p++ == 'm')
4365 {
4366 do
4367 {
4368 parse_static_tracepoint_marker_definition (p, &p, &marker);
4369
4370 if (strid == NULL || marker.str_id == strid)
4371 markers.push_back (std::move (marker));
4372 }
4373 while (*p++ == ','); /* comma-separated list */
4374 /* Ask for another packet of static tracepoint definition. */
4375 putpkt ("qTsSTM");
4376 getpkt (&rs->buf);
4377 p = rs->buf.data ();
4378 }
4379
4380 return markers;
4381 }
4382
4383 \f
4384 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4385
4386 ptid_t
4387 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4388 {
4389 return ptid_t (inferior_ptid.pid (), lwp);
4390 }
4391 \f
4392
4393 /* Restart the remote side; this is an extended protocol operation. */
4394
4395 void
4396 remote_target::extended_remote_restart ()
4397 {
4398 struct remote_state *rs = get_remote_state ();
4399
4400 /* Send the restart command; for reasons I don't understand the
4401 remote side really expects a number after the "R". */
4402 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4403 putpkt (rs->buf);
4404
4405 remote_fileio_reset ();
4406 }
4407 \f
4408 /* Clean up connection to a remote debugger. */
4409
4410 void
4411 remote_target::close ()
4412 {
4413 /* Make sure we leave stdin registered in the event loop. */
4414 terminal_ours ();
4415
4416 trace_reset_local_state ();
4417
4418 delete this;
4419 }
4420
4421 remote_target::~remote_target ()
4422 {
4423 struct remote_state *rs = get_remote_state ();
4424
4425 /* Check for NULL because we may get here with a partially
4426 constructed target/connection. */
4427 if (rs->remote_desc == nullptr)
4428 return;
4429
4430 serial_close (rs->remote_desc);
4431
4432 /* We are destroying the remote target, so we should discard
4433 everything of this target. */
4434 discard_pending_stop_replies_in_queue ();
4435
4436 rs->delete_async_event_handler ();
4437
4438 delete rs->notif_state;
4439 }
4440
4441 /* Query the remote side for the text, data and bss offsets. */
4442
4443 void
4444 remote_target::get_offsets ()
4445 {
4446 struct remote_state *rs = get_remote_state ();
4447 char *buf;
4448 char *ptr;
4449 int lose, num_segments = 0, do_sections, do_segments;
4450 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4451
4452 if (current_program_space->symfile_object_file == NULL)
4453 return;
4454
4455 putpkt ("qOffsets");
4456 getpkt (&rs->buf);
4457 buf = rs->buf.data ();
4458
4459 if (buf[0] == '\000')
4460 return; /* Return silently. Stub doesn't support
4461 this command. */
4462 if (buf[0] == 'E')
4463 {
4464 warning (_("Remote failure reply: %s"), buf);
4465 return;
4466 }
4467
4468 /* Pick up each field in turn. This used to be done with scanf, but
4469 scanf will make trouble if CORE_ADDR size doesn't match
4470 conversion directives correctly. The following code will work
4471 with any size of CORE_ADDR. */
4472 text_addr = data_addr = bss_addr = 0;
4473 ptr = buf;
4474 lose = 0;
4475
4476 if (startswith (ptr, "Text="))
4477 {
4478 ptr += 5;
4479 /* Don't use strtol, could lose on big values. */
4480 while (*ptr && *ptr != ';')
4481 text_addr = (text_addr << 4) + fromhex (*ptr++);
4482
4483 if (startswith (ptr, ";Data="))
4484 {
4485 ptr += 6;
4486 while (*ptr && *ptr != ';')
4487 data_addr = (data_addr << 4) + fromhex (*ptr++);
4488 }
4489 else
4490 lose = 1;
4491
4492 if (!lose && startswith (ptr, ";Bss="))
4493 {
4494 ptr += 5;
4495 while (*ptr && *ptr != ';')
4496 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4497
4498 if (bss_addr != data_addr)
4499 warning (_("Target reported unsupported offsets: %s"), buf);
4500 }
4501 else
4502 lose = 1;
4503 }
4504 else if (startswith (ptr, "TextSeg="))
4505 {
4506 ptr += 8;
4507 /* Don't use strtol, could lose on big values. */
4508 while (*ptr && *ptr != ';')
4509 text_addr = (text_addr << 4) + fromhex (*ptr++);
4510 num_segments = 1;
4511
4512 if (startswith (ptr, ";DataSeg="))
4513 {
4514 ptr += 9;
4515 while (*ptr && *ptr != ';')
4516 data_addr = (data_addr << 4) + fromhex (*ptr++);
4517 num_segments++;
4518 }
4519 }
4520 else
4521 lose = 1;
4522
4523 if (lose)
4524 error (_("Malformed response to offset query, %s"), buf);
4525 else if (*ptr != '\0')
4526 warning (_("Target reported unsupported offsets: %s"), buf);
4527
4528 objfile *objf = current_program_space->symfile_object_file;
4529 section_offsets offs = objf->section_offsets;
4530
4531 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4532 do_segments = (data != NULL);
4533 do_sections = num_segments == 0;
4534
4535 if (num_segments > 0)
4536 {
4537 segments[0] = text_addr;
4538 segments[1] = data_addr;
4539 }
4540 /* If we have two segments, we can still try to relocate everything
4541 by assuming that the .text and .data offsets apply to the whole
4542 text and data segments. Convert the offsets given in the packet
4543 to base addresses for symfile_map_offsets_to_segments. */
4544 else if (data != nullptr && data->segments.size () == 2)
4545 {
4546 segments[0] = data->segments[0].base + text_addr;
4547 segments[1] = data->segments[1].base + data_addr;
4548 num_segments = 2;
4549 }
4550 /* If the object file has only one segment, assume that it is text
4551 rather than data; main programs with no writable data are rare,
4552 but programs with no code are useless. Of course the code might
4553 have ended up in the data segment... to detect that we would need
4554 the permissions here. */
4555 else if (data && data->segments.size () == 1)
4556 {
4557 segments[0] = data->segments[0].base + text_addr;
4558 num_segments = 1;
4559 }
4560 /* There's no way to relocate by segment. */
4561 else
4562 do_segments = 0;
4563
4564 if (do_segments)
4565 {
4566 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4567 data.get (), offs,
4568 num_segments, segments);
4569
4570 if (ret == 0 && !do_sections)
4571 error (_("Can not handle qOffsets TextSeg "
4572 "response with this symbol file"));
4573
4574 if (ret > 0)
4575 do_sections = 0;
4576 }
4577
4578 if (do_sections)
4579 {
4580 offs[SECT_OFF_TEXT (objf)] = text_addr;
4581
4582 /* This is a temporary kludge to force data and bss to use the
4583 same offsets because that's what nlmconv does now. The real
4584 solution requires changes to the stub and remote.c that I
4585 don't have time to do right now. */
4586
4587 offs[SECT_OFF_DATA (objf)] = data_addr;
4588 offs[SECT_OFF_BSS (objf)] = data_addr;
4589 }
4590
4591 objfile_relocate (objf, offs);
4592 }
4593
4594 /* Send interrupt_sequence to remote target. */
4595
4596 void
4597 remote_target::send_interrupt_sequence ()
4598 {
4599 struct remote_state *rs = get_remote_state ();
4600
4601 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4602 remote_serial_write ("\x03", 1);
4603 else if (interrupt_sequence_mode == interrupt_sequence_break)
4604 serial_send_break (rs->remote_desc);
4605 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4606 {
4607 serial_send_break (rs->remote_desc);
4608 remote_serial_write ("g", 1);
4609 }
4610 else
4611 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4612 interrupt_sequence_mode);
4613 }
4614
4615
4616 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4617 and extract the PTID. Returns NULL_PTID if not found. */
4618
4619 static ptid_t
4620 stop_reply_extract_thread (const char *stop_reply)
4621 {
4622 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4623 {
4624 const char *p;
4625
4626 /* Txx r:val ; r:val (...) */
4627 p = &stop_reply[3];
4628
4629 /* Look for "register" named "thread". */
4630 while (*p != '\0')
4631 {
4632 const char *p1;
4633
4634 p1 = strchr (p, ':');
4635 if (p1 == NULL)
4636 return null_ptid;
4637
4638 if (strncmp (p, "thread", p1 - p) == 0)
4639 return read_ptid (++p1, &p);
4640
4641 p1 = strchr (p, ';');
4642 if (p1 == NULL)
4643 return null_ptid;
4644 p1++;
4645
4646 p = p1;
4647 }
4648 }
4649
4650 return null_ptid;
4651 }
4652
4653 /* Determine the remote side's current thread. If we have a stop
4654 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4655 "thread" register we can extract the current thread from. If not,
4656 ask the remote which is the current thread with qC. The former
4657 method avoids a roundtrip. */
4658
4659 ptid_t
4660 remote_target::get_current_thread (const char *wait_status)
4661 {
4662 ptid_t ptid = null_ptid;
4663
4664 /* Note we don't use remote_parse_stop_reply as that makes use of
4665 the target architecture, which we haven't yet fully determined at
4666 this point. */
4667 if (wait_status != NULL)
4668 ptid = stop_reply_extract_thread (wait_status);
4669 if (ptid == null_ptid)
4670 ptid = remote_current_thread (inferior_ptid);
4671
4672 return ptid;
4673 }
4674
4675 /* Query the remote target for which is the current thread/process,
4676 add it to our tables, and update INFERIOR_PTID. The caller is
4677 responsible for setting the state such that the remote end is ready
4678 to return the current thread.
4679
4680 This function is called after handling the '?' or 'vRun' packets,
4681 whose response is a stop reply from which we can also try
4682 extracting the thread. If the target doesn't support the explicit
4683 qC query, we infer the current thread from that stop reply, passed
4684 in in WAIT_STATUS, which may be NULL.
4685
4686 The function returns pointer to the main thread of the inferior. */
4687
4688 thread_info *
4689 remote_target::add_current_inferior_and_thread (const char *wait_status)
4690 {
4691 bool fake_pid_p = false;
4692
4693 switch_to_no_thread ();
4694
4695 /* Now, if we have thread information, update the current thread's
4696 ptid. */
4697 ptid_t curr_ptid = get_current_thread (wait_status);
4698
4699 if (curr_ptid != null_ptid)
4700 {
4701 if (!m_features.remote_multi_process_p ())
4702 fake_pid_p = true;
4703 }
4704 else
4705 {
4706 /* Without this, some commands which require an active target
4707 (such as kill) won't work. This variable serves (at least)
4708 double duty as both the pid of the target process (if it has
4709 such), and as a flag indicating that a target is active. */
4710 curr_ptid = magic_null_ptid;
4711 fake_pid_p = true;
4712 }
4713
4714 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4715
4716 /* Add the main thread and switch to it. Don't try reading
4717 registers yet, since we haven't fetched the target description
4718 yet. */
4719 thread_info *tp = add_thread_silent (this, curr_ptid);
4720 switch_to_thread_no_regs (tp);
4721
4722 return tp;
4723 }
4724
4725 /* Print info about a thread that was found already stopped on
4726 connection. */
4727
4728 void
4729 remote_target::print_one_stopped_thread (thread_info *thread)
4730 {
4731 target_waitstatus ws;
4732
4733 /* If there is a pending waitstatus, use it. If there isn't it's because
4734 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4735 and process_initial_stop_replies decided it wasn't interesting to save
4736 and report to the core. */
4737 if (thread->has_pending_waitstatus ())
4738 {
4739 ws = thread->pending_waitstatus ();
4740 thread->clear_pending_waitstatus ();
4741 }
4742 else
4743 {
4744 ws.set_stopped (GDB_SIGNAL_0);
4745 }
4746
4747 switch_to_thread (thread);
4748 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4749 set_current_sal_from_frame (get_current_frame ());
4750
4751 /* For "info program". */
4752 set_last_target_status (this, thread->ptid, ws);
4753
4754 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4755 {
4756 enum gdb_signal sig = ws.sig ();
4757
4758 if (signal_print_state (sig))
4759 notify_signal_received (sig);
4760 }
4761
4762 notify_normal_stop (nullptr, 1);
4763 }
4764
4765 /* Process all initial stop replies the remote side sent in response
4766 to the ? packet. These indicate threads that were already stopped
4767 on initial connection. We mark these threads as stopped and print
4768 their current frame before giving the user the prompt. */
4769
4770 void
4771 remote_target::process_initial_stop_replies (int from_tty)
4772 {
4773 int pending_stop_replies = stop_reply_queue_length ();
4774 struct thread_info *selected = NULL;
4775 struct thread_info *lowest_stopped = NULL;
4776 struct thread_info *first = NULL;
4777
4778 /* This is only used when the target is non-stop. */
4779 gdb_assert (target_is_non_stop_p ());
4780
4781 /* Consume the initial pending events. */
4782 while (pending_stop_replies-- > 0)
4783 {
4784 ptid_t waiton_ptid = minus_one_ptid;
4785 ptid_t event_ptid;
4786 struct target_waitstatus ws;
4787 int ignore_event = 0;
4788
4789 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4790 if (remote_debug)
4791 print_target_wait_results (waiton_ptid, event_ptid, ws);
4792
4793 switch (ws.kind ())
4794 {
4795 case TARGET_WAITKIND_IGNORE:
4796 case TARGET_WAITKIND_NO_RESUMED:
4797 case TARGET_WAITKIND_SIGNALLED:
4798 case TARGET_WAITKIND_EXITED:
4799 /* We shouldn't see these, but if we do, just ignore. */
4800 remote_debug_printf ("event ignored");
4801 ignore_event = 1;
4802 break;
4803
4804 default:
4805 break;
4806 }
4807
4808 if (ignore_event)
4809 continue;
4810
4811 thread_info *evthread = this->find_thread (event_ptid);
4812
4813 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4814 {
4815 enum gdb_signal sig = ws.sig ();
4816
4817 /* Stubs traditionally report SIGTRAP as initial signal,
4818 instead of signal 0. Suppress it. */
4819 if (sig == GDB_SIGNAL_TRAP)
4820 sig = GDB_SIGNAL_0;
4821 evthread->set_stop_signal (sig);
4822 ws.set_stopped (sig);
4823 }
4824
4825 if (ws.kind () != TARGET_WAITKIND_STOPPED
4826 || ws.sig () != GDB_SIGNAL_0)
4827 evthread->set_pending_waitstatus (ws);
4828
4829 set_executing (this, event_ptid, false);
4830 set_running (this, event_ptid, false);
4831 get_remote_thread_info (evthread)->set_not_resumed ();
4832 }
4833
4834 /* "Notice" the new inferiors before anything related to
4835 registers/memory. */
4836 for (inferior *inf : all_non_exited_inferiors (this))
4837 {
4838 inf->needs_setup = true;
4839
4840 if (non_stop)
4841 {
4842 thread_info *thread = any_live_thread_of_inferior (inf);
4843 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4844 from_tty);
4845 }
4846 }
4847
4848 /* If all-stop on top of non-stop, pause all threads. Note this
4849 records the threads' stop pc, so must be done after "noticing"
4850 the inferiors. */
4851 if (!non_stop)
4852 {
4853 {
4854 /* At this point, the remote target is not async. It needs to be for
4855 the poll in stop_all_threads to consider events from it, so enable
4856 it temporarily. */
4857 gdb_assert (!this->is_async_p ());
4858 SCOPE_EXIT { target_async (false); };
4859 target_async (true);
4860 stop_all_threads ("remote connect in all-stop");
4861 }
4862
4863 /* If all threads of an inferior were already stopped, we
4864 haven't setup the inferior yet. */
4865 for (inferior *inf : all_non_exited_inferiors (this))
4866 {
4867 if (inf->needs_setup)
4868 {
4869 thread_info *thread = any_live_thread_of_inferior (inf);
4870 switch_to_thread_no_regs (thread);
4871 setup_inferior (0);
4872 }
4873 }
4874 }
4875
4876 /* Now go over all threads that are stopped, and print their current
4877 frame. If all-stop, then if there's a signalled thread, pick
4878 that as current. */
4879 for (thread_info *thread : all_non_exited_threads (this))
4880 {
4881 if (first == NULL)
4882 first = thread;
4883
4884 if (!non_stop)
4885 thread->set_running (false);
4886 else if (thread->state != THREAD_STOPPED)
4887 continue;
4888
4889 if (selected == nullptr && thread->has_pending_waitstatus ())
4890 selected = thread;
4891
4892 if (lowest_stopped == NULL
4893 || thread->inf->num < lowest_stopped->inf->num
4894 || thread->per_inf_num < lowest_stopped->per_inf_num)
4895 lowest_stopped = thread;
4896
4897 if (non_stop)
4898 print_one_stopped_thread (thread);
4899 }
4900
4901 /* In all-stop, we only print the status of one thread, and leave
4902 others with their status pending. */
4903 if (!non_stop)
4904 {
4905 thread_info *thread = selected;
4906 if (thread == NULL)
4907 thread = lowest_stopped;
4908 if (thread == NULL)
4909 thread = first;
4910
4911 print_one_stopped_thread (thread);
4912 }
4913 }
4914
4915 /* Mark a remote_target as starting (by setting the starting_up flag within
4916 its remote_state) for the lifetime of this object. The reference count
4917 on the remote target is temporarily incremented, to prevent the target
4918 being deleted under our feet. */
4919
4920 struct scoped_mark_target_starting
4921 {
4922 /* Constructor, TARGET is the target to be marked as starting, its
4923 reference count will be incremented. */
4924 scoped_mark_target_starting (remote_target *target)
4925 : m_remote_target (remote_target_ref::new_reference (target)),
4926 m_restore_starting_up (set_starting_up_flag (target))
4927 { /* Nothing. */ }
4928
4929 private:
4930
4931 /* Helper function, set the starting_up flag on TARGET and return an
4932 object which, when it goes out of scope, will restore the previous
4933 value of the starting_up flag. */
4934 static scoped_restore_tmpl<bool>
4935 set_starting_up_flag (remote_target *target)
4936 {
4937 remote_state *rs = target->get_remote_state ();
4938 gdb_assert (!rs->starting_up);
4939 return make_scoped_restore (&rs->starting_up, true);
4940 }
4941
4942 /* A gdb::ref_ptr pointer to a remote_target. */
4943 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4944
4945 /* A reference to the target on which we are operating. */
4946 remote_target_ref m_remote_target;
4947
4948 /* An object which restores the previous value of the starting_up flag
4949 when it goes out of scope. */
4950 scoped_restore_tmpl<bool> m_restore_starting_up;
4951 };
4952
4953 /* Helper for remote_target::start_remote, start the remote connection and
4954 sync state. Return true if everything goes OK, otherwise, return false.
4955 This function exists so that the scoped_restore created within it will
4956 expire before we return to remote_target::start_remote. */
4957
4958 bool
4959 remote_target::start_remote_1 (int from_tty, int extended_p)
4960 {
4961 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4962
4963 struct remote_state *rs = get_remote_state ();
4964
4965 /* Signal other parts that we're going through the initial setup,
4966 and so things may not be stable yet. E.g., we don't try to
4967 install tracepoints until we've relocated symbols. Also, a
4968 Ctrl-C before we're connected and synced up can't interrupt the
4969 target. Instead, it offers to drop the (potentially wedged)
4970 connection. */
4971 scoped_mark_target_starting target_is_starting (this);
4972
4973 QUIT;
4974
4975 if (interrupt_on_connect)
4976 send_interrupt_sequence ();
4977
4978 /* Ack any packet which the remote side has already sent. */
4979 remote_serial_write ("+", 1);
4980
4981 /* The first packet we send to the target is the optional "supported
4982 packets" request. If the target can answer this, it will tell us
4983 which later probes to skip. */
4984 remote_query_supported ();
4985
4986 /* Check vCont support and set the remote state's vCont_action_support
4987 attribute. */
4988 remote_vcont_probe ();
4989
4990 /* If the stub wants to get a QAllow, compose one and send it. */
4991 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4992 set_permissions ();
4993
4994 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4995 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4996 as a reply to known packet. For packet "vFile:setfs:" it is an
4997 invalid reply and GDB would return error in
4998 remote_hostio_set_filesystem, making remote files access impossible.
4999 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5000 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5001 {
5002 const char v_mustreplyempty[] = "vMustReplyEmpty";
5003
5004 putpkt (v_mustreplyempty);
5005 getpkt (&rs->buf);
5006 if (strcmp (rs->buf.data (), "OK") == 0)
5007 {
5008 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5009 = PACKET_DISABLE;
5010 }
5011 else if (strcmp (rs->buf.data (), "") != 0)
5012 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5013 rs->buf.data ());
5014 }
5015
5016 /* Next, we possibly activate noack mode.
5017
5018 If the QStartNoAckMode packet configuration is set to AUTO,
5019 enable noack mode if the stub reported a wish for it with
5020 qSupported.
5021
5022 If set to TRUE, then enable noack mode even if the stub didn't
5023 report it in qSupported. If the stub doesn't reply OK, the
5024 session ends with an error.
5025
5026 If FALSE, then don't activate noack mode, regardless of what the
5027 stub claimed should be the default with qSupported. */
5028
5029 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5030 {
5031 putpkt ("QStartNoAckMode");
5032 getpkt (&rs->buf);
5033 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5034 rs->noack_mode = 1;
5035 }
5036
5037 if (extended_p)
5038 {
5039 /* Tell the remote that we are using the extended protocol. */
5040 putpkt ("!");
5041 getpkt (&rs->buf);
5042 }
5043
5044 /* Let the target know which signals it is allowed to pass down to
5045 the program. */
5046 update_signals_program_target ();
5047
5048 /* Next, if the target can specify a description, read it. We do
5049 this before anything involving memory or registers. */
5050 target_find_description ();
5051
5052 /* Next, now that we know something about the target, update the
5053 address spaces in the program spaces. */
5054 update_address_spaces ();
5055
5056 /* On OSs where the list of libraries is global to all
5057 processes, we fetch them early. */
5058 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5059 solib_add (NULL, from_tty, auto_solib_add);
5060
5061 if (target_is_non_stop_p ())
5062 {
5063 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5064 error (_("Non-stop mode requested, but remote "
5065 "does not support non-stop"));
5066
5067 putpkt ("QNonStop:1");
5068 getpkt (&rs->buf);
5069
5070 if (strcmp (rs->buf.data (), "OK") != 0)
5071 error (_("Remote refused setting non-stop mode with: %s"),
5072 rs->buf.data ());
5073
5074 /* Find about threads and processes the stub is already
5075 controlling. We default to adding them in the running state.
5076 The '?' query below will then tell us about which threads are
5077 stopped. */
5078 this->update_thread_list ();
5079 }
5080 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5081 {
5082 /* Don't assume that the stub can operate in all-stop mode.
5083 Request it explicitly. */
5084 putpkt ("QNonStop:0");
5085 getpkt (&rs->buf);
5086
5087 if (strcmp (rs->buf.data (), "OK") != 0)
5088 error (_("Remote refused setting all-stop mode with: %s"),
5089 rs->buf.data ());
5090 }
5091
5092 /* Upload TSVs regardless of whether the target is running or not. The
5093 remote stub, such as GDBserver, may have some predefined or builtin
5094 TSVs, even if the target is not running. */
5095 if (get_trace_status (current_trace_status ()) != -1)
5096 {
5097 struct uploaded_tsv *uploaded_tsvs = NULL;
5098
5099 upload_trace_state_variables (&uploaded_tsvs);
5100 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5101 }
5102
5103 /* Check whether the target is running now. */
5104 putpkt ("?");
5105 getpkt (&rs->buf);
5106
5107 if (!target_is_non_stop_p ())
5108 {
5109 char *wait_status = NULL;
5110
5111 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5112 {
5113 if (!extended_p)
5114 error (_("The target is not running (try extended-remote?)"));
5115 return false;
5116 }
5117 else
5118 {
5119 /* Save the reply for later. */
5120 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5121 strcpy (wait_status, rs->buf.data ());
5122 }
5123
5124 /* Fetch thread list. */
5125 target_update_thread_list ();
5126
5127 /* Let the stub know that we want it to return the thread. */
5128 set_continue_thread (minus_one_ptid);
5129
5130 if (thread_count (this) == 0)
5131 {
5132 /* Target has no concept of threads at all. GDB treats
5133 non-threaded target as single-threaded; add a main
5134 thread. */
5135 thread_info *tp = add_current_inferior_and_thread (wait_status);
5136 get_remote_thread_info (tp)->set_resumed ();
5137 }
5138 else
5139 {
5140 /* We have thread information; select the thread the target
5141 says should be current. If we're reconnecting to a
5142 multi-threaded program, this will ideally be the thread
5143 that last reported an event before GDB disconnected. */
5144 ptid_t curr_thread = get_current_thread (wait_status);
5145 if (curr_thread == null_ptid)
5146 {
5147 /* Odd... The target was able to list threads, but not
5148 tell us which thread was current (no "thread"
5149 register in T stop reply?). Just pick the first
5150 thread in the thread list then. */
5151
5152 remote_debug_printf ("warning: couldn't determine remote "
5153 "current thread; picking first in list.");
5154
5155 for (thread_info *tp : all_non_exited_threads (this,
5156 minus_one_ptid))
5157 {
5158 switch_to_thread (tp);
5159 break;
5160 }
5161 }
5162 else
5163 switch_to_thread (this->find_thread (curr_thread));
5164
5165 get_remote_thread_info (inferior_thread ())->set_resumed ();
5166 }
5167
5168 /* init_wait_for_inferior should be called before get_offsets in order
5169 to manage `inserted' flag in bp loc in a correct state.
5170 breakpoint_init_inferior, called from init_wait_for_inferior, set
5171 `inserted' flag to 0, while before breakpoint_re_set, called from
5172 start_remote, set `inserted' flag to 1. In the initialization of
5173 inferior, breakpoint_init_inferior should be called first, and then
5174 breakpoint_re_set can be called. If this order is broken, state of
5175 `inserted' flag is wrong, and cause some problems on breakpoint
5176 manipulation. */
5177 init_wait_for_inferior ();
5178
5179 get_offsets (); /* Get text, data & bss offsets. */
5180
5181 /* If we could not find a description using qXfer, and we know
5182 how to do it some other way, try again. This is not
5183 supported for non-stop; it could be, but it is tricky if
5184 there are no stopped threads when we connect. */
5185 if (remote_read_description_p (this)
5186 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5187 {
5188 target_clear_description ();
5189 target_find_description ();
5190 }
5191
5192 /* Use the previously fetched status. */
5193 gdb_assert (wait_status != NULL);
5194 struct notif_event *reply
5195 = remote_notif_parse (this, &notif_client_stop, wait_status);
5196 push_stop_reply ((struct stop_reply *) reply);
5197
5198 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5199 }
5200 else
5201 {
5202 /* Clear WFI global state. Do this before finding about new
5203 threads and inferiors, and setting the current inferior.
5204 Otherwise we would clear the proceed status of the current
5205 inferior when we want its stop_soon state to be preserved
5206 (see notice_new_inferior). */
5207 init_wait_for_inferior ();
5208
5209 /* In non-stop, we will either get an "OK", meaning that there
5210 are no stopped threads at this time; or, a regular stop
5211 reply. In the latter case, there may be more than one thread
5212 stopped --- we pull them all out using the vStopped
5213 mechanism. */
5214 if (strcmp (rs->buf.data (), "OK") != 0)
5215 {
5216 const notif_client *notif = &notif_client_stop;
5217
5218 /* remote_notif_get_pending_replies acks this one, and gets
5219 the rest out. */
5220 rs->notif_state->pending_event[notif_client_stop.id]
5221 = remote_notif_parse (this, notif, rs->buf.data ());
5222 remote_notif_get_pending_events (notif);
5223 }
5224
5225 if (thread_count (this) == 0)
5226 {
5227 if (!extended_p)
5228 error (_("The target is not running (try extended-remote?)"));
5229 return false;
5230 }
5231
5232 /* Report all signals during attach/startup. */
5233 pass_signals ({});
5234
5235 /* If there are already stopped threads, mark them stopped and
5236 report their stops before giving the prompt to the user. */
5237 process_initial_stop_replies (from_tty);
5238
5239 if (target_can_async_p ())
5240 target_async (true);
5241 }
5242
5243 /* Give the target a chance to look up symbols. */
5244 for (inferior *inf : all_inferiors (this))
5245 {
5246 /* The inferiors that exist at this point were created from what
5247 was found already running on the remote side, so we know they
5248 have execution. */
5249 gdb_assert (this->has_execution (inf));
5250
5251 /* No use without a symbol-file. */
5252 if (inf->pspace->symfile_object_file == nullptr)
5253 continue;
5254
5255 /* Need to switch to a specific thread, because remote_check_symbols
5256 uses INFERIOR_PTID to set the general thread. */
5257 scoped_restore_current_thread restore_thread;
5258 thread_info *thread = any_thread_of_inferior (inf);
5259 switch_to_thread (thread);
5260 this->remote_check_symbols ();
5261 }
5262
5263 /* Possibly the target has been engaged in a trace run started
5264 previously; find out where things are at. */
5265 if (get_trace_status (current_trace_status ()) != -1)
5266 {
5267 struct uploaded_tp *uploaded_tps = NULL;
5268
5269 if (current_trace_status ()->running)
5270 gdb_printf (_("Trace is already running on the target.\n"));
5271
5272 upload_tracepoints (&uploaded_tps);
5273
5274 merge_uploaded_tracepoints (&uploaded_tps);
5275 }
5276
5277 /* Possibly the target has been engaged in a btrace record started
5278 previously; find out where things are at. */
5279 remote_btrace_maybe_reopen ();
5280
5281 return true;
5282 }
5283
5284 /* Start the remote connection and sync state. */
5285
5286 void
5287 remote_target::start_remote (int from_tty, int extended_p)
5288 {
5289 if (start_remote_1 (from_tty, extended_p)
5290 && breakpoints_should_be_inserted_now ())
5291 insert_breakpoints ();
5292 }
5293
5294 const char *
5295 remote_target::connection_string ()
5296 {
5297 remote_state *rs = get_remote_state ();
5298
5299 if (rs->remote_desc->name != NULL)
5300 return rs->remote_desc->name;
5301 else
5302 return NULL;
5303 }
5304
5305 /* Open a connection to a remote debugger.
5306 NAME is the filename used for communication. */
5307
5308 void
5309 remote_target::open (const char *name, int from_tty)
5310 {
5311 open_1 (name, from_tty, 0);
5312 }
5313
5314 /* Open a connection to a remote debugger using the extended
5315 remote gdb protocol. NAME is the filename used for communication. */
5316
5317 void
5318 extended_remote_target::open (const char *name, int from_tty)
5319 {
5320 open_1 (name, from_tty, 1 /*extended_p */);
5321 }
5322
5323 void
5324 remote_features::reset_all_packet_configs_support ()
5325 {
5326 int i;
5327
5328 for (i = 0; i < PACKET_MAX; i++)
5329 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5330 }
5331
5332 /* Initialize all packet configs. */
5333
5334 static void
5335 init_all_packet_configs (void)
5336 {
5337 int i;
5338
5339 for (i = 0; i < PACKET_MAX; i++)
5340 {
5341 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5342 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5343 }
5344 }
5345
5346 /* Symbol look-up. */
5347
5348 void
5349 remote_target::remote_check_symbols ()
5350 {
5351 char *tmp;
5352 int end;
5353
5354 /* It doesn't make sense to send a qSymbol packet for an inferior that
5355 doesn't have execution, because the remote side doesn't know about
5356 inferiors without execution. */
5357 gdb_assert (target_has_execution ());
5358
5359 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5360 return;
5361
5362 /* Make sure the remote is pointing at the right process. Note
5363 there's no way to select "no process". */
5364 set_general_process ();
5365
5366 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5367 because we need both at the same time. */
5368 gdb::char_vector msg (get_remote_packet_size ());
5369 gdb::char_vector reply (get_remote_packet_size ());
5370
5371 /* Invite target to request symbol lookups. */
5372
5373 putpkt ("qSymbol::");
5374 getpkt (&reply);
5375 m_features.packet_ok (reply, PACKET_qSymbol);
5376
5377 while (startswith (reply.data (), "qSymbol:"))
5378 {
5379 struct bound_minimal_symbol sym;
5380
5381 tmp = &reply[8];
5382 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5383 strlen (tmp) / 2);
5384 msg[end] = '\0';
5385 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5386 if (sym.minsym == NULL)
5387 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5388 &reply[8]);
5389 else
5390 {
5391 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5392 CORE_ADDR sym_addr = sym.value_address ();
5393
5394 /* If this is a function address, return the start of code
5395 instead of any data function descriptor. */
5396 sym_addr = gdbarch_convert_from_func_ptr_addr
5397 (current_inferior ()->arch (), sym_addr,
5398 current_inferior ()->top_target ());
5399
5400 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5401 phex_nz (sym_addr, addr_size), &reply[8]);
5402 }
5403
5404 putpkt (msg.data ());
5405 getpkt (&reply);
5406 }
5407 }
5408
5409 static struct serial *
5410 remote_serial_open (const char *name)
5411 {
5412 static int udp_warning = 0;
5413
5414 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5415 of in ser-tcp.c, because it is the remote protocol assuming that the
5416 serial connection is reliable and not the serial connection promising
5417 to be. */
5418 if (!udp_warning && startswith (name, "udp:"))
5419 {
5420 warning (_("The remote protocol may be unreliable over UDP.\n"
5421 "Some events may be lost, rendering further debugging "
5422 "impossible."));
5423 udp_warning = 1;
5424 }
5425
5426 return serial_open (name);
5427 }
5428
5429 /* Inform the target of our permission settings. The permission flags
5430 work without this, but if the target knows the settings, it can do
5431 a couple things. First, it can add its own check, to catch cases
5432 that somehow manage to get by the permissions checks in target
5433 methods. Second, if the target is wired to disallow particular
5434 settings (for instance, a system in the field that is not set up to
5435 be able to stop at a breakpoint), it can object to any unavailable
5436 permissions. */
5437
5438 void
5439 remote_target::set_permissions ()
5440 {
5441 struct remote_state *rs = get_remote_state ();
5442
5443 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5444 "WriteReg:%x;WriteMem:%x;"
5445 "InsertBreak:%x;InsertTrace:%x;"
5446 "InsertFastTrace:%x;Stop:%x",
5447 may_write_registers, may_write_memory,
5448 may_insert_breakpoints, may_insert_tracepoints,
5449 may_insert_fast_tracepoints, may_stop);
5450 putpkt (rs->buf);
5451 getpkt (&rs->buf);
5452
5453 /* If the target didn't like the packet, warn the user. Do not try
5454 to undo the user's settings, that would just be maddening. */
5455 if (strcmp (rs->buf.data (), "OK") != 0)
5456 warning (_("Remote refused setting permissions with: %s"),
5457 rs->buf.data ());
5458 }
5459
5460 /* This type describes each known response to the qSupported
5461 packet. */
5462 struct protocol_feature
5463 {
5464 /* The name of this protocol feature. */
5465 const char *name;
5466
5467 /* The default for this protocol feature. */
5468 enum packet_support default_support;
5469
5470 /* The function to call when this feature is reported, or after
5471 qSupported processing if the feature is not supported.
5472 The first argument points to this structure. The second
5473 argument indicates whether the packet requested support be
5474 enabled, disabled, or probed (or the default, if this function
5475 is being called at the end of processing and this feature was
5476 not reported). The third argument may be NULL; if not NULL, it
5477 is a NUL-terminated string taken from the packet following
5478 this feature's name and an equals sign. */
5479 void (*func) (remote_target *remote, const struct protocol_feature *,
5480 enum packet_support, const char *);
5481
5482 /* The corresponding packet for this feature. Only used if
5483 FUNC is remote_supported_packet. */
5484 int packet;
5485 };
5486
5487 static void
5488 remote_supported_packet (remote_target *remote,
5489 const struct protocol_feature *feature,
5490 enum packet_support support,
5491 const char *argument)
5492 {
5493 if (argument)
5494 {
5495 warning (_("Remote qSupported response supplied an unexpected value for"
5496 " \"%s\"."), feature->name);
5497 return;
5498 }
5499
5500 remote->m_features.m_protocol_packets[feature->packet].support = support;
5501 }
5502
5503 void
5504 remote_target::remote_packet_size (const protocol_feature *feature,
5505 enum packet_support support, const char *value)
5506 {
5507 struct remote_state *rs = get_remote_state ();
5508
5509 int packet_size;
5510 char *value_end;
5511
5512 if (support != PACKET_ENABLE)
5513 return;
5514
5515 if (value == NULL || *value == '\0')
5516 {
5517 warning (_("Remote target reported \"%s\" without a size."),
5518 feature->name);
5519 return;
5520 }
5521
5522 errno = 0;
5523 packet_size = strtol (value, &value_end, 16);
5524 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5525 {
5526 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5527 feature->name, value);
5528 return;
5529 }
5530
5531 /* Record the new maximum packet size. */
5532 rs->explicit_packet_size = packet_size;
5533 }
5534
5535 static void
5536 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5537 enum packet_support support, const char *value)
5538 {
5539 remote->remote_packet_size (feature, support, value);
5540 }
5541
5542 static const struct protocol_feature remote_protocol_features[] = {
5543 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5544 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5545 PACKET_qXfer_auxv },
5546 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5547 PACKET_qXfer_exec_file },
5548 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5549 PACKET_qXfer_features },
5550 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5551 PACKET_qXfer_libraries },
5552 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5553 PACKET_qXfer_libraries_svr4 },
5554 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5555 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5556 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5557 PACKET_qXfer_memory_map },
5558 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5559 PACKET_qXfer_osdata },
5560 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5561 PACKET_qXfer_threads },
5562 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5563 PACKET_qXfer_traceframe_info },
5564 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5565 PACKET_QPassSignals },
5566 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_QCatchSyscalls },
5568 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_QProgramSignals },
5570 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_QSetWorkingDir },
5572 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_QStartupWithShell },
5574 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_QEnvironmentHexEncoded },
5576 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5577 PACKET_QEnvironmentReset },
5578 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5579 PACKET_QEnvironmentUnset },
5580 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5581 PACKET_QStartNoAckMode },
5582 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5583 PACKET_multiprocess_feature },
5584 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5585 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5586 PACKET_qXfer_siginfo_read },
5587 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5588 PACKET_qXfer_siginfo_write },
5589 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5590 PACKET_ConditionalTracepoints },
5591 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5592 PACKET_ConditionalBreakpoints },
5593 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5594 PACKET_BreakpointCommands },
5595 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5596 PACKET_FastTracepoints },
5597 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5598 PACKET_StaticTracepoints },
5599 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5600 PACKET_InstallInTrace},
5601 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5602 PACKET_DisconnectedTracing_feature },
5603 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5604 PACKET_bc },
5605 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5606 PACKET_bs },
5607 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5608 PACKET_TracepointSource },
5609 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5610 PACKET_QAllow },
5611 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5612 PACKET_EnableDisableTracepoints_feature },
5613 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5614 PACKET_qXfer_fdpic },
5615 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5616 PACKET_qXfer_uib },
5617 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5618 PACKET_QDisableRandomization },
5619 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5620 { "QTBuffer:size", PACKET_DISABLE,
5621 remote_supported_packet, PACKET_QTBuffer_size},
5622 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5623 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5624 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5625 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5626 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5627 PACKET_qXfer_btrace },
5628 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5629 PACKET_qXfer_btrace_conf },
5630 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5631 PACKET_Qbtrace_conf_bts_size },
5632 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5633 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5634 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5635 PACKET_fork_event_feature },
5636 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5637 PACKET_vfork_event_feature },
5638 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5639 PACKET_exec_event_feature },
5640 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5641 PACKET_Qbtrace_conf_pt_size },
5642 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5643 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5644 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5645 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5646 PACKET_memory_tagging_feature },
5647 };
5648
5649 static char *remote_support_xml;
5650
5651 /* Register string appended to "xmlRegisters=" in qSupported query. */
5652
5653 void
5654 register_remote_support_xml (const char *xml)
5655 {
5656 #if defined(HAVE_LIBEXPAT)
5657 if (remote_support_xml == NULL)
5658 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5659 else
5660 {
5661 char *copy = xstrdup (remote_support_xml + 13);
5662 char *saveptr;
5663 char *p = strtok_r (copy, ",", &saveptr);
5664
5665 do
5666 {
5667 if (strcmp (p, xml) == 0)
5668 {
5669 /* already there */
5670 xfree (copy);
5671 return;
5672 }
5673 }
5674 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5675 xfree (copy);
5676
5677 remote_support_xml = reconcat (remote_support_xml,
5678 remote_support_xml, ",", xml,
5679 (char *) NULL);
5680 }
5681 #endif
5682 }
5683
5684 static void
5685 remote_query_supported_append (std::string *msg, const char *append)
5686 {
5687 if (!msg->empty ())
5688 msg->append (";");
5689 msg->append (append);
5690 }
5691
5692 void
5693 remote_target::remote_query_supported ()
5694 {
5695 struct remote_state *rs = get_remote_state ();
5696 char *next;
5697 int i;
5698 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5699
5700 /* The packet support flags are handled differently for this packet
5701 than for most others. We treat an error, a disabled packet, and
5702 an empty response identically: any features which must be reported
5703 to be used will be automatically disabled. An empty buffer
5704 accomplishes this, since that is also the representation for a list
5705 containing no features. */
5706
5707 rs->buf[0] = 0;
5708 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5709 {
5710 std::string q;
5711
5712 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5713 != AUTO_BOOLEAN_FALSE)
5714 remote_query_supported_append (&q, "multiprocess+");
5715
5716 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5717 != AUTO_BOOLEAN_FALSE)
5718 remote_query_supported_append (&q, "swbreak+");
5719
5720 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5721 != AUTO_BOOLEAN_FALSE)
5722 remote_query_supported_append (&q, "hwbreak+");
5723
5724 remote_query_supported_append (&q, "qRelocInsn+");
5725
5726 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5727 != AUTO_BOOLEAN_FALSE)
5728 remote_query_supported_append (&q, "fork-events+");
5729
5730 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5731 != AUTO_BOOLEAN_FALSE)
5732 remote_query_supported_append (&q, "vfork-events+");
5733
5734 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5735 != AUTO_BOOLEAN_FALSE)
5736 remote_query_supported_append (&q, "exec-events+");
5737
5738 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5739 != AUTO_BOOLEAN_FALSE)
5740 remote_query_supported_append (&q, "vContSupported+");
5741
5742 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5743 != AUTO_BOOLEAN_FALSE)
5744 remote_query_supported_append (&q, "QThreadEvents+");
5745
5746 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5747 != AUTO_BOOLEAN_FALSE)
5748 remote_query_supported_append (&q, "no-resumed+");
5749
5750 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5751 != AUTO_BOOLEAN_FALSE)
5752 remote_query_supported_append (&q, "memory-tagging+");
5753
5754 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5755 the qSupported:xmlRegisters=i386 handling. */
5756 if (remote_support_xml != NULL
5757 && (m_features.packet_support (PACKET_qXfer_features)
5758 != PACKET_DISABLE))
5759 remote_query_supported_append (&q, remote_support_xml);
5760
5761 q = "qSupported:" + q;
5762 putpkt (q.c_str ());
5763
5764 getpkt (&rs->buf);
5765
5766 /* If an error occurred, warn, but do not return - just reset the
5767 buffer to empty and go on to disable features. */
5768 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5769 {
5770 warning (_("Remote failure reply: %s"), rs->buf.data ());
5771 rs->buf[0] = 0;
5772 }
5773 }
5774
5775 memset (seen, 0, sizeof (seen));
5776
5777 next = rs->buf.data ();
5778 while (*next)
5779 {
5780 enum packet_support is_supported;
5781 char *p, *end, *name_end, *value;
5782
5783 /* First separate out this item from the rest of the packet. If
5784 there's another item after this, we overwrite the separator
5785 (terminated strings are much easier to work with). */
5786 p = next;
5787 end = strchr (p, ';');
5788 if (end == NULL)
5789 {
5790 end = p + strlen (p);
5791 next = end;
5792 }
5793 else
5794 {
5795 *end = '\0';
5796 next = end + 1;
5797
5798 if (end == p)
5799 {
5800 warning (_("empty item in \"qSupported\" response"));
5801 continue;
5802 }
5803 }
5804
5805 name_end = strchr (p, '=');
5806 if (name_end)
5807 {
5808 /* This is a name=value entry. */
5809 is_supported = PACKET_ENABLE;
5810 value = name_end + 1;
5811 *name_end = '\0';
5812 }
5813 else
5814 {
5815 value = NULL;
5816 switch (end[-1])
5817 {
5818 case '+':
5819 is_supported = PACKET_ENABLE;
5820 break;
5821
5822 case '-':
5823 is_supported = PACKET_DISABLE;
5824 break;
5825
5826 case '?':
5827 is_supported = PACKET_SUPPORT_UNKNOWN;
5828 break;
5829
5830 default:
5831 warning (_("unrecognized item \"%s\" "
5832 "in \"qSupported\" response"), p);
5833 continue;
5834 }
5835 end[-1] = '\0';
5836 }
5837
5838 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5839 if (strcmp (remote_protocol_features[i].name, p) == 0)
5840 {
5841 const struct protocol_feature *feature;
5842
5843 seen[i] = 1;
5844 feature = &remote_protocol_features[i];
5845 feature->func (this, feature, is_supported, value);
5846 break;
5847 }
5848 }
5849
5850 /* If we increased the packet size, make sure to increase the global
5851 buffer size also. We delay this until after parsing the entire
5852 qSupported packet, because this is the same buffer we were
5853 parsing. */
5854 if (rs->buf.size () < rs->explicit_packet_size)
5855 rs->buf.resize (rs->explicit_packet_size);
5856
5857 /* Handle the defaults for unmentioned features. */
5858 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5859 if (!seen[i])
5860 {
5861 const struct protocol_feature *feature;
5862
5863 feature = &remote_protocol_features[i];
5864 feature->func (this, feature, feature->default_support, NULL);
5865 }
5866 }
5867
5868 /* Serial QUIT handler for the remote serial descriptor.
5869
5870 Defers handling a Ctrl-C until we're done with the current
5871 command/response packet sequence, unless:
5872
5873 - We're setting up the connection. Don't send a remote interrupt
5874 request, as we're not fully synced yet. Quit immediately
5875 instead.
5876
5877 - The target has been resumed in the foreground
5878 (target_terminal::is_ours is false) with a synchronous resume
5879 packet, and we're blocked waiting for the stop reply, thus a
5880 Ctrl-C should be immediately sent to the target.
5881
5882 - We get a second Ctrl-C while still within the same serial read or
5883 write. In that case the serial is seemingly wedged --- offer to
5884 quit/disconnect.
5885
5886 - We see a second Ctrl-C without target response, after having
5887 previously interrupted the target. In that case the target/stub
5888 is probably wedged --- offer to quit/disconnect.
5889 */
5890
5891 void
5892 remote_target::remote_serial_quit_handler ()
5893 {
5894 struct remote_state *rs = get_remote_state ();
5895
5896 if (check_quit_flag ())
5897 {
5898 /* If we're starting up, we're not fully synced yet. Quit
5899 immediately. */
5900 if (rs->starting_up)
5901 quit ();
5902 else if (rs->got_ctrlc_during_io)
5903 {
5904 if (query (_("The target is not responding to GDB commands.\n"
5905 "Stop debugging it? ")))
5906 remote_unpush_and_throw (this);
5907 }
5908 /* If ^C has already been sent once, offer to disconnect. */
5909 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5910 interrupt_query ();
5911 /* All-stop protocol, and blocked waiting for stop reply. Send
5912 an interrupt request. */
5913 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5914 target_interrupt ();
5915 else
5916 rs->got_ctrlc_during_io = 1;
5917 }
5918 }
5919
5920 /* The remote_target that is current while the quit handler is
5921 overridden with remote_serial_quit_handler. */
5922 static remote_target *curr_quit_handler_target;
5923
5924 static void
5925 remote_serial_quit_handler ()
5926 {
5927 curr_quit_handler_target->remote_serial_quit_handler ();
5928 }
5929
5930 /* Remove the remote target from the target stack of each inferior
5931 that is using it. Upper targets depend on it so remove them
5932 first. */
5933
5934 static void
5935 remote_unpush_target (remote_target *target)
5936 {
5937 /* We have to unpush the target from all inferiors, even those that
5938 aren't running. */
5939 scoped_restore_current_inferior restore_current_inferior;
5940
5941 for (inferior *inf : all_inferiors (target))
5942 {
5943 switch_to_inferior_no_thread (inf);
5944 inf->pop_all_targets_at_and_above (process_stratum);
5945 generic_mourn_inferior ();
5946 }
5947
5948 /* Don't rely on target_close doing this when the target is popped
5949 from the last remote inferior above, because something may be
5950 holding a reference to the target higher up on the stack, meaning
5951 target_close won't be called yet. We lost the connection to the
5952 target, so clear these now, otherwise we may later throw
5953 TARGET_CLOSE_ERROR while trying to tell the remote target to
5954 close the file. */
5955 fileio_handles_invalidate_target (target);
5956 }
5957
5958 static void
5959 remote_unpush_and_throw (remote_target *target)
5960 {
5961 remote_unpush_target (target);
5962 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5963 }
5964
5965 void
5966 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5967 {
5968 remote_target *curr_remote = get_current_remote_target ();
5969
5970 if (name == 0)
5971 error (_("To open a remote debug connection, you need to specify what\n"
5972 "serial device is attached to the remote system\n"
5973 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5974
5975 /* If we're connected to a running target, target_preopen will kill it.
5976 Ask this question first, before target_preopen has a chance to kill
5977 anything. */
5978 if (curr_remote != NULL && !target_has_execution ())
5979 {
5980 if (from_tty
5981 && !query (_("Already connected to a remote target. Disconnect? ")))
5982 error (_("Still connected."));
5983 }
5984
5985 /* Here the possibly existing remote target gets unpushed. */
5986 target_preopen (from_tty);
5987
5988 remote_fileio_reset ();
5989 reopen_exec_file ();
5990 reread_symbols (from_tty);
5991
5992 remote_target *remote
5993 = (extended_p ? new extended_remote_target () : new remote_target ());
5994 target_ops_up target_holder (remote);
5995
5996 remote_state *rs = remote->get_remote_state ();
5997
5998 /* See FIXME above. */
5999 if (!target_async_permitted)
6000 rs->wait_forever_enabled_p = true;
6001
6002 rs->remote_desc = remote_serial_open (name);
6003 if (!rs->remote_desc)
6004 perror_with_name (name);
6005
6006 if (baud_rate != -1)
6007 {
6008 if (serial_setbaudrate (rs->remote_desc, baud_rate))
6009 {
6010 /* The requested speed could not be set. Error out to
6011 top level after closing remote_desc. Take care to
6012 set remote_desc to NULL to avoid closing remote_desc
6013 more than once. */
6014 serial_close (rs->remote_desc);
6015 rs->remote_desc = NULL;
6016 perror_with_name (name);
6017 }
6018 }
6019
6020 serial_setparity (rs->remote_desc, serial_parity);
6021 serial_raw (rs->remote_desc);
6022
6023 /* If there is something sitting in the buffer we might take it as a
6024 response to a command, which would be bad. */
6025 serial_flush_input (rs->remote_desc);
6026
6027 if (from_tty)
6028 {
6029 gdb_puts ("Remote debugging using ");
6030 gdb_puts (name);
6031 gdb_puts ("\n");
6032 }
6033
6034 /* Switch to using the remote target now. */
6035 current_inferior ()->push_target (std::move (target_holder));
6036
6037 /* Register extra event sources in the event loop. */
6038 rs->create_async_event_handler ();
6039
6040 rs->notif_state = remote_notif_state_allocate (remote);
6041
6042 /* Reset the target state; these things will be queried either by
6043 remote_query_supported or as they are needed. */
6044 remote->m_features.reset_all_packet_configs_support ();
6045 rs->explicit_packet_size = 0;
6046 rs->noack_mode = 0;
6047 rs->extended = extended_p;
6048 rs->waiting_for_stop_reply = 0;
6049 rs->ctrlc_pending_p = 0;
6050 rs->got_ctrlc_during_io = 0;
6051
6052 rs->general_thread = not_sent_ptid;
6053 rs->continue_thread = not_sent_ptid;
6054 rs->remote_traceframe_number = -1;
6055
6056 rs->last_resume_exec_dir = EXEC_FORWARD;
6057
6058 /* Probe for ability to use "ThreadInfo" query, as required. */
6059 rs->use_threadinfo_query = 1;
6060 rs->use_threadextra_query = 1;
6061
6062 rs->readahead_cache.invalidate ();
6063
6064 if (target_async_permitted)
6065 {
6066 /* FIXME: cagney/1999-09-23: During the initial connection it is
6067 assumed that the target is already ready and able to respond to
6068 requests. Unfortunately remote_start_remote() eventually calls
6069 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6070 around this. Eventually a mechanism that allows
6071 wait_for_inferior() to expect/get timeouts will be
6072 implemented. */
6073 rs->wait_forever_enabled_p = false;
6074 }
6075
6076 /* First delete any symbols previously loaded from shared libraries. */
6077 no_shared_libraries (NULL, 0);
6078
6079 /* Start the remote connection. If error() or QUIT, discard this
6080 target (we'd otherwise be in an inconsistent state) and then
6081 propogate the error on up the exception chain. This ensures that
6082 the caller doesn't stumble along blindly assuming that the
6083 function succeeded. The CLI doesn't have this problem but other
6084 UI's, such as MI do.
6085
6086 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6087 this function should return an error indication letting the
6088 caller restore the previous state. Unfortunately the command
6089 ``target remote'' is directly wired to this function making that
6090 impossible. On a positive note, the CLI side of this problem has
6091 been fixed - the function set_cmd_context() makes it possible for
6092 all the ``target ....'' commands to share a common callback
6093 function. See cli-dump.c. */
6094 {
6095
6096 try
6097 {
6098 remote->start_remote (from_tty, extended_p);
6099 }
6100 catch (const gdb_exception &ex)
6101 {
6102 /* Pop the partially set up target - unless something else did
6103 already before throwing the exception. */
6104 if (ex.error != TARGET_CLOSE_ERROR)
6105 remote_unpush_target (remote);
6106 throw;
6107 }
6108 }
6109
6110 remote_btrace_reset (rs);
6111
6112 if (target_async_permitted)
6113 rs->wait_forever_enabled_p = true;
6114 }
6115
6116 /* Determine if WS represents a fork status. */
6117
6118 static bool
6119 is_fork_status (target_waitkind kind)
6120 {
6121 return (kind == TARGET_WAITKIND_FORKED
6122 || kind == TARGET_WAITKIND_VFORKED);
6123 }
6124
6125 /* Return a reference to the field where a pending child status, if
6126 there's one, is recorded. If there's no child event pending, the
6127 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6128
6129 static const target_waitstatus &
6130 thread_pending_status (struct thread_info *thread)
6131 {
6132 return (thread->has_pending_waitstatus ()
6133 ? thread->pending_waitstatus ()
6134 : thread->pending_follow);
6135 }
6136
6137 /* Return THREAD's pending status if it is a pending fork/vfork (but
6138 not clone) parent, else return nullptr. */
6139
6140 static const target_waitstatus *
6141 thread_pending_fork_status (struct thread_info *thread)
6142 {
6143 const target_waitstatus &ws = thread_pending_status (thread);
6144
6145 if (!is_fork_status (ws.kind ()))
6146 return nullptr;
6147
6148 return &ws;
6149 }
6150
6151 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6152 event, else return nullptr. */
6153
6154 static const target_waitstatus *
6155 thread_pending_child_status (thread_info *thread)
6156 {
6157 const target_waitstatus &ws = thread_pending_status (thread);
6158
6159 if (!is_new_child_status (ws.kind ()))
6160 return nullptr;
6161
6162 return &ws;
6163 }
6164
6165 /* Detach the specified process. */
6166
6167 void
6168 remote_target::remote_detach_pid (int pid)
6169 {
6170 struct remote_state *rs = get_remote_state ();
6171
6172 /* This should not be necessary, but the handling for D;PID in
6173 GDBserver versions prior to 8.2 incorrectly assumes that the
6174 selected process points to the same process we're detaching,
6175 leading to misbehavior (and possibly GDBserver crashing) when it
6176 does not. Since it's easy and cheap, work around it by forcing
6177 GDBserver to select GDB's current process. */
6178 set_general_process ();
6179
6180 if (m_features.remote_multi_process_p ())
6181 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6182 else
6183 strcpy (rs->buf.data (), "D");
6184
6185 putpkt (rs->buf);
6186 getpkt (&rs->buf);
6187
6188 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6189 ;
6190 else if (rs->buf[0] == '\0')
6191 error (_("Remote doesn't know how to detach"));
6192 else
6193 {
6194 /* It is possible that we have an unprocessed exit event for this
6195 pid. If this is the case then we can ignore the failure to detach
6196 and just pretend that the detach worked, as far as the user is
6197 concerned, the process exited immediately after the detach. */
6198 bool process_has_already_exited = false;
6199 remote_notif_get_pending_events (&notif_client_stop);
6200 for (stop_reply_up &reply : rs->stop_reply_queue)
6201 {
6202 if (reply->ptid.pid () != pid)
6203 continue;
6204
6205 enum target_waitkind kind = reply->ws.kind ();
6206 if (kind == TARGET_WAITKIND_EXITED
6207 || kind == TARGET_WAITKIND_SIGNALLED)
6208 {
6209 process_has_already_exited = true;
6210 remote_debug_printf
6211 ("detach failed, but process already exited");
6212 break;
6213 }
6214 }
6215
6216 if (!process_has_already_exited)
6217 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6218 }
6219 }
6220
6221 /* This detaches a program to which we previously attached, using
6222 inferior_ptid to identify the process. After this is done, GDB
6223 can be used to debug some other program. We better not have left
6224 any breakpoints in the target program or it'll die when it hits
6225 one. */
6226
6227 void
6228 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6229 {
6230 int pid = inferior_ptid.pid ();
6231 struct remote_state *rs = get_remote_state ();
6232 int is_fork_parent;
6233
6234 if (!target_has_execution ())
6235 error (_("No process to detach from."));
6236
6237 target_announce_detach (from_tty);
6238
6239 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6240 {
6241 /* If we're in breakpoints-always-inserted mode, or the inferior
6242 is running, we have to remove breakpoints before detaching.
6243 We don't do this in common code instead because not all
6244 targets support removing breakpoints while the target is
6245 running. The remote target / gdbserver does, though. */
6246 remove_breakpoints_inf (current_inferior ());
6247 }
6248
6249 /* Tell the remote target to detach. */
6250 remote_detach_pid (pid);
6251
6252 /* Exit only if this is the only active inferior. */
6253 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6254 gdb_puts (_("Ending remote debugging.\n"));
6255
6256 /* See if any thread of the inferior we are detaching has a pending fork
6257 status. In that case, we must detach from the child resulting from
6258 that fork. */
6259 for (thread_info *thread : inf->non_exited_threads ())
6260 {
6261 const target_waitstatus *ws = thread_pending_fork_status (thread);
6262
6263 if (ws == nullptr)
6264 continue;
6265
6266 remote_detach_pid (ws->child_ptid ().pid ());
6267 }
6268
6269 /* Check also for any pending fork events in the stop reply queue. */
6270 remote_notif_get_pending_events (&notif_client_stop);
6271 for (stop_reply_up &reply : rs->stop_reply_queue)
6272 {
6273 if (reply->ptid.pid () != pid)
6274 continue;
6275
6276 if (!is_fork_status (reply->ws.kind ()))
6277 continue;
6278
6279 remote_detach_pid (reply->ws.child_ptid ().pid ());
6280 }
6281
6282 thread_info *tp = this->find_thread (inferior_ptid);
6283
6284 /* Check to see if we are detaching a fork parent. Note that if we
6285 are detaching a fork child, tp == NULL. */
6286 is_fork_parent = (tp != NULL
6287 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6288
6289 /* If doing detach-on-fork, we don't mourn, because that will delete
6290 breakpoints that should be available for the followed inferior. */
6291 if (!is_fork_parent)
6292 {
6293 /* Save the pid as a string before mourning, since that will
6294 unpush the remote target, and we need the string after. */
6295 std::string infpid = target_pid_to_str (ptid_t (pid));
6296
6297 target_mourn_inferior (inferior_ptid);
6298 if (print_inferior_events)
6299 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6300 inf->num, infpid.c_str ());
6301 }
6302 else
6303 {
6304 switch_to_no_thread ();
6305 detach_inferior (current_inferior ());
6306 }
6307 }
6308
6309 void
6310 remote_target::detach (inferior *inf, int from_tty)
6311 {
6312 remote_detach_1 (inf, from_tty);
6313 }
6314
6315 void
6316 extended_remote_target::detach (inferior *inf, int from_tty)
6317 {
6318 remote_detach_1 (inf, from_tty);
6319 }
6320
6321 /* Target follow-fork function for remote targets. On entry, and
6322 at return, the current inferior is the fork parent.
6323
6324 Note that although this is currently only used for extended-remote,
6325 it is named remote_follow_fork in anticipation of using it for the
6326 remote target as well. */
6327
6328 void
6329 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6330 target_waitkind fork_kind, bool follow_child,
6331 bool detach_fork)
6332 {
6333 process_stratum_target::follow_fork (child_inf, child_ptid,
6334 fork_kind, follow_child, detach_fork);
6335
6336 if ((fork_kind == TARGET_WAITKIND_FORKED
6337 && m_features.remote_fork_event_p ())
6338 || (fork_kind == TARGET_WAITKIND_VFORKED
6339 && m_features.remote_vfork_event_p ()))
6340 {
6341 /* When following the parent and detaching the child, we detach
6342 the child here. For the case of following the child and
6343 detaching the parent, the detach is done in the target-
6344 independent follow fork code in infrun.c. We can't use
6345 target_detach when detaching an unfollowed child because
6346 the client side doesn't know anything about the child. */
6347 if (detach_fork && !follow_child)
6348 {
6349 /* Detach the fork child. */
6350 remote_detach_pid (child_ptid.pid ());
6351 }
6352 }
6353 }
6354
6355 void
6356 remote_target::follow_clone (ptid_t child_ptid)
6357 {
6358 remote_add_thread (child_ptid, false, false, false);
6359 }
6360
6361 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6362 in the program space of the new inferior. */
6363
6364 void
6365 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6366 const char *execd_pathname)
6367 {
6368 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6369
6370 /* We know that this is a target file name, so if it has the "target:"
6371 prefix we strip it off before saving it in the program space. */
6372 if (is_target_filename (execd_pathname))
6373 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6374
6375 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6376 }
6377
6378 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6379
6380 void
6381 remote_target::disconnect (const char *args, int from_tty)
6382 {
6383 if (args)
6384 error (_("Argument given to \"disconnect\" when remotely debugging."));
6385
6386 /* Make sure we unpush even the extended remote targets. Calling
6387 target_mourn_inferior won't unpush, and
6388 remote_target::mourn_inferior won't unpush if there is more than
6389 one inferior left. */
6390 remote_unpush_target (this);
6391
6392 if (from_tty)
6393 gdb_puts ("Ending remote debugging.\n");
6394 }
6395
6396 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6397 be chatty about it. */
6398
6399 void
6400 extended_remote_target::attach (const char *args, int from_tty)
6401 {
6402 struct remote_state *rs = get_remote_state ();
6403 int pid;
6404 char *wait_status = NULL;
6405
6406 pid = parse_pid_to_attach (args);
6407
6408 /* Remote PID can be freely equal to getpid, do not check it here the same
6409 way as in other targets. */
6410
6411 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6412 error (_("This target does not support attaching to a process"));
6413
6414 target_announce_attach (from_tty, pid);
6415
6416 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6417 putpkt (rs->buf);
6418 getpkt (&rs->buf);
6419
6420 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6421 {
6422 case PACKET_OK:
6423 if (!target_is_non_stop_p ())
6424 {
6425 /* Save the reply for later. */
6426 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6427 strcpy (wait_status, rs->buf.data ());
6428 }
6429 else if (strcmp (rs->buf.data (), "OK") != 0)
6430 error (_("Attaching to %s failed with: %s"),
6431 target_pid_to_str (ptid_t (pid)).c_str (),
6432 rs->buf.data ());
6433 break;
6434 case PACKET_UNKNOWN:
6435 error (_("This target does not support attaching to a process"));
6436 default:
6437 error (_("Attaching to %s failed"),
6438 target_pid_to_str (ptid_t (pid)).c_str ());
6439 }
6440
6441 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6442
6443 inferior_ptid = ptid_t (pid);
6444
6445 if (target_is_non_stop_p ())
6446 {
6447 /* Get list of threads. */
6448 update_thread_list ();
6449
6450 thread_info *thread = first_thread_of_inferior (current_inferior ());
6451 if (thread != nullptr)
6452 switch_to_thread (thread);
6453
6454 /* Invalidate our notion of the remote current thread. */
6455 record_currthread (rs, minus_one_ptid);
6456 }
6457 else
6458 {
6459 /* Now, if we have thread information, update the main thread's
6460 ptid. */
6461 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6462
6463 /* Add the main thread to the thread list. We add the thread
6464 silently in this case (the final true parameter). */
6465 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6466
6467 switch_to_thread (thr);
6468 }
6469
6470 /* Next, if the target can specify a description, read it. We do
6471 this before anything involving memory or registers. */
6472 target_find_description ();
6473
6474 if (!target_is_non_stop_p ())
6475 {
6476 /* Use the previously fetched status. */
6477 gdb_assert (wait_status != NULL);
6478
6479 struct notif_event *reply
6480 = remote_notif_parse (this, &notif_client_stop, wait_status);
6481
6482 push_stop_reply ((struct stop_reply *) reply);
6483 }
6484 else
6485 {
6486 gdb_assert (wait_status == NULL);
6487
6488 gdb_assert (target_can_async_p ());
6489 }
6490 }
6491
6492 /* Implementation of the to_post_attach method. */
6493
6494 void
6495 extended_remote_target::post_attach (int pid)
6496 {
6497 /* Get text, data & bss offsets. */
6498 get_offsets ();
6499
6500 /* In certain cases GDB might not have had the chance to start
6501 symbol lookup up until now. This could happen if the debugged
6502 binary is not using shared libraries, the vsyscall page is not
6503 present (on Linux) and the binary itself hadn't changed since the
6504 debugging process was started. */
6505 if (current_program_space->symfile_object_file != NULL)
6506 remote_check_symbols();
6507 }
6508
6509 \f
6510 /* Check for the availability of vCont. This function should also check
6511 the response. */
6512
6513 void
6514 remote_target::remote_vcont_probe ()
6515 {
6516 remote_state *rs = get_remote_state ();
6517 char *buf;
6518
6519 strcpy (rs->buf.data (), "vCont?");
6520 putpkt (rs->buf);
6521 getpkt (&rs->buf);
6522 buf = rs->buf.data ();
6523
6524 /* Make sure that the features we assume are supported. */
6525 if (startswith (buf, "vCont"))
6526 {
6527 char *p = &buf[5];
6528 int support_c, support_C;
6529
6530 rs->supports_vCont.s = 0;
6531 rs->supports_vCont.S = 0;
6532 support_c = 0;
6533 support_C = 0;
6534 rs->supports_vCont.t = 0;
6535 rs->supports_vCont.r = 0;
6536 while (p && *p == ';')
6537 {
6538 p++;
6539 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6540 rs->supports_vCont.s = 1;
6541 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6542 rs->supports_vCont.S = 1;
6543 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6544 support_c = 1;
6545 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6546 support_C = 1;
6547 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6548 rs->supports_vCont.t = 1;
6549 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6550 rs->supports_vCont.r = 1;
6551
6552 p = strchr (p, ';');
6553 }
6554
6555 /* If c, and C are not all supported, we can't use vCont. Clearing
6556 BUF will make packet_ok disable the packet. */
6557 if (!support_c || !support_C)
6558 buf[0] = 0;
6559 }
6560
6561 m_features.packet_ok (rs->buf, PACKET_vCont);
6562 }
6563
6564 /* Helper function for building "vCont" resumptions. Write a
6565 resumption to P. ENDP points to one-passed-the-end of the buffer
6566 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6567 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6568 resumed thread should be single-stepped and/or signalled. If PTID
6569 equals minus_one_ptid, then all threads are resumed; if PTID
6570 represents a process, then all threads of the process are
6571 resumed. */
6572
6573 char *
6574 remote_target::append_resumption (char *p, char *endp,
6575 ptid_t ptid, int step, gdb_signal siggnal)
6576 {
6577 struct remote_state *rs = get_remote_state ();
6578
6579 if (step && siggnal != GDB_SIGNAL_0)
6580 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6581 else if (step
6582 /* GDB is willing to range step. */
6583 && use_range_stepping
6584 /* Target supports range stepping. */
6585 && rs->supports_vCont.r
6586 /* We don't currently support range stepping multiple
6587 threads with a wildcard (though the protocol allows it,
6588 so stubs shouldn't make an active effort to forbid
6589 it). */
6590 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6591 {
6592 struct thread_info *tp;
6593
6594 if (ptid == minus_one_ptid)
6595 {
6596 /* If we don't know about the target thread's tid, then
6597 we're resuming magic_null_ptid (see caller). */
6598 tp = this->find_thread (magic_null_ptid);
6599 }
6600 else
6601 tp = this->find_thread (ptid);
6602 gdb_assert (tp != NULL);
6603
6604 if (tp->control.may_range_step)
6605 {
6606 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6607
6608 p += xsnprintf (p, endp - p, ";r%s,%s",
6609 phex_nz (tp->control.step_range_start,
6610 addr_size),
6611 phex_nz (tp->control.step_range_end,
6612 addr_size));
6613 }
6614 else
6615 p += xsnprintf (p, endp - p, ";s");
6616 }
6617 else if (step)
6618 p += xsnprintf (p, endp - p, ";s");
6619 else if (siggnal != GDB_SIGNAL_0)
6620 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6621 else
6622 p += xsnprintf (p, endp - p, ";c");
6623
6624 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6625 {
6626 ptid_t nptid;
6627
6628 /* All (-1) threads of process. */
6629 nptid = ptid_t (ptid.pid (), -1);
6630
6631 p += xsnprintf (p, endp - p, ":");
6632 p = write_ptid (p, endp, nptid);
6633 }
6634 else if (ptid != minus_one_ptid)
6635 {
6636 p += xsnprintf (p, endp - p, ":");
6637 p = write_ptid (p, endp, ptid);
6638 }
6639
6640 return p;
6641 }
6642
6643 /* Clear the thread's private info on resume. */
6644
6645 static void
6646 resume_clear_thread_private_info (struct thread_info *thread)
6647 {
6648 if (thread->priv != NULL)
6649 {
6650 remote_thread_info *priv = get_remote_thread_info (thread);
6651
6652 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6653 priv->watch_data_address = 0;
6654 }
6655 }
6656
6657 /* Append a vCont continue-with-signal action for threads that have a
6658 non-zero stop signal. */
6659
6660 char *
6661 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6662 ptid_t ptid)
6663 {
6664 for (thread_info *thread : all_non_exited_threads (this, ptid))
6665 if (inferior_ptid != thread->ptid
6666 && thread->stop_signal () != GDB_SIGNAL_0)
6667 {
6668 p = append_resumption (p, endp, thread->ptid,
6669 0, thread->stop_signal ());
6670 thread->set_stop_signal (GDB_SIGNAL_0);
6671 resume_clear_thread_private_info (thread);
6672 }
6673
6674 return p;
6675 }
6676
6677 /* Set the target running, using the packets that use Hc
6678 (c/s/C/S). */
6679
6680 void
6681 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6682 gdb_signal siggnal)
6683 {
6684 struct remote_state *rs = get_remote_state ();
6685 char *buf;
6686
6687 rs->last_sent_signal = siggnal;
6688 rs->last_sent_step = step;
6689
6690 /* The c/s/C/S resume packets use Hc, so set the continue
6691 thread. */
6692 if (ptid == minus_one_ptid)
6693 set_continue_thread (any_thread_ptid);
6694 else
6695 set_continue_thread (ptid);
6696
6697 for (thread_info *thread : all_non_exited_threads (this))
6698 resume_clear_thread_private_info (thread);
6699
6700 buf = rs->buf.data ();
6701 if (::execution_direction == EXEC_REVERSE)
6702 {
6703 /* We don't pass signals to the target in reverse exec mode. */
6704 if (info_verbose && siggnal != GDB_SIGNAL_0)
6705 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6706 siggnal);
6707
6708 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6709 error (_("Remote reverse-step not supported."));
6710 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6711 error (_("Remote reverse-continue not supported."));
6712
6713 strcpy (buf, step ? "bs" : "bc");
6714 }
6715 else if (siggnal != GDB_SIGNAL_0)
6716 {
6717 buf[0] = step ? 'S' : 'C';
6718 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6719 buf[2] = tohex (((int) siggnal) & 0xf);
6720 buf[3] = '\0';
6721 }
6722 else
6723 strcpy (buf, step ? "s" : "c");
6724
6725 putpkt (buf);
6726 }
6727
6728 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6729 STEP, and SIGGNAL have the same meaning as in target_resume. This
6730 function returns non-zero iff it resumes the inferior.
6731
6732 This function issues a strict subset of all possible vCont commands
6733 at the moment. */
6734
6735 int
6736 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6737 enum gdb_signal siggnal)
6738 {
6739 struct remote_state *rs = get_remote_state ();
6740 char *p;
6741 char *endp;
6742
6743 /* No reverse execution actions defined for vCont. */
6744 if (::execution_direction == EXEC_REVERSE)
6745 return 0;
6746
6747 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6748 return 0;
6749
6750 p = rs->buf.data ();
6751 endp = p + get_remote_packet_size ();
6752
6753 /* If we could generate a wider range of packets, we'd have to worry
6754 about overflowing BUF. Should there be a generic
6755 "multi-part-packet" packet? */
6756
6757 p += xsnprintf (p, endp - p, "vCont");
6758
6759 if (scope_ptid == magic_null_ptid)
6760 {
6761 /* MAGIC_NULL_PTID means that we don't have any active threads,
6762 so we don't have any TID numbers the inferior will
6763 understand. Make sure to only send forms that do not specify
6764 a TID. */
6765 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6766 }
6767 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6768 {
6769 /* Resume all threads (of all processes, or of a single
6770 process), with preference for INFERIOR_PTID. This assumes
6771 inferior_ptid belongs to the set of all threads we are about
6772 to resume. */
6773 if (step || siggnal != GDB_SIGNAL_0)
6774 {
6775 /* Step inferior_ptid, with or without signal. */
6776 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6777 }
6778
6779 /* Also pass down any pending signaled resumption for other
6780 threads not the current. */
6781 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6782
6783 /* And continue others without a signal. */
6784 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6785 }
6786 else
6787 {
6788 /* Scheduler locking; resume only SCOPE_PTID. */
6789 append_resumption (p, endp, scope_ptid, step, siggnal);
6790 }
6791
6792 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6793 putpkt (rs->buf);
6794
6795 if (target_is_non_stop_p ())
6796 {
6797 /* In non-stop, the stub replies to vCont with "OK". The stop
6798 reply will be reported asynchronously by means of a `%Stop'
6799 notification. */
6800 getpkt (&rs->buf);
6801 if (strcmp (rs->buf.data (), "OK") != 0)
6802 error (_("Unexpected vCont reply in non-stop mode: %s"),
6803 rs->buf.data ());
6804 }
6805
6806 return 1;
6807 }
6808
6809 /* Tell the remote machine to resume. */
6810
6811 void
6812 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6813 {
6814 struct remote_state *rs = get_remote_state ();
6815
6816 /* When connected in non-stop mode, the core resumes threads
6817 individually. Resuming remote threads directly in target_resume
6818 would thus result in sending one packet per thread. Instead, to
6819 minimize roundtrip latency, here we just store the resume
6820 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6821 resumption will be done in remote_target::commit_resume, where we'll be
6822 able to do vCont action coalescing. */
6823 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6824 {
6825 remote_thread_info *remote_thr
6826 = get_remote_thread_info (inferior_thread ());
6827
6828 /* We don't expect the core to ask to resume an already resumed (from
6829 its point of view) thread. */
6830 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6831
6832 remote_thr->set_resumed_pending_vcont (step, siggnal);
6833
6834 /* There's actually nothing that says that the core can't
6835 request a wildcard resume in non-stop mode, though. It's
6836 just that we know it doesn't currently, so we don't bother
6837 with it. */
6838 gdb_assert (scope_ptid == inferior_ptid);
6839 return;
6840 }
6841
6842 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6843 (explained in remote-notif.c:handle_notification) so
6844 remote_notif_process is not called. We need find a place where
6845 it is safe to start a 'vNotif' sequence. It is good to do it
6846 before resuming inferior, because inferior was stopped and no RSP
6847 traffic at that moment. */
6848 if (!target_is_non_stop_p ())
6849 remote_notif_process (rs->notif_state, &notif_client_stop);
6850
6851 rs->last_resume_exec_dir = ::execution_direction;
6852
6853 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6854 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6855 remote_resume_with_hc (scope_ptid, step, siggnal);
6856
6857 /* Update resumed state tracked by the remote target. */
6858 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6859 get_remote_thread_info (tp)->set_resumed ();
6860
6861 /* We've just told the target to resume. The remote server will
6862 wait for the inferior to stop, and then send a stop reply. In
6863 the mean time, we can't start another command/query ourselves
6864 because the stub wouldn't be ready to process it. This applies
6865 only to the base all-stop protocol, however. In non-stop (which
6866 only supports vCont), the stub replies with an "OK", and is
6867 immediate able to process further serial input. */
6868 if (!target_is_non_stop_p ())
6869 rs->waiting_for_stop_reply = 1;
6870 }
6871
6872 /* Private per-inferior info for target remote processes. */
6873
6874 struct remote_inferior : public private_inferior
6875 {
6876 /* Whether we can send a wildcard vCont for this process. */
6877 bool may_wildcard_vcont = true;
6878 };
6879
6880 /* Get the remote private inferior data associated to INF. */
6881
6882 static remote_inferior *
6883 get_remote_inferior (inferior *inf)
6884 {
6885 if (inf->priv == NULL)
6886 inf->priv.reset (new remote_inferior);
6887
6888 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6889 }
6890
6891 /* Class used to track the construction of a vCont packet in the
6892 outgoing packet buffer. This is used to send multiple vCont
6893 packets if we have more actions than would fit a single packet. */
6894
6895 class vcont_builder
6896 {
6897 public:
6898 explicit vcont_builder (remote_target *remote)
6899 : m_remote (remote)
6900 {
6901 restart ();
6902 }
6903
6904 void flush ();
6905 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6906
6907 private:
6908 void restart ();
6909
6910 /* The remote target. */
6911 remote_target *m_remote;
6912
6913 /* Pointer to the first action. P points here if no action has been
6914 appended yet. */
6915 char *m_first_action;
6916
6917 /* Where the next action will be appended. */
6918 char *m_p;
6919
6920 /* The end of the buffer. Must never write past this. */
6921 char *m_endp;
6922 };
6923
6924 /* Prepare the outgoing buffer for a new vCont packet. */
6925
6926 void
6927 vcont_builder::restart ()
6928 {
6929 struct remote_state *rs = m_remote->get_remote_state ();
6930
6931 m_p = rs->buf.data ();
6932 m_endp = m_p + m_remote->get_remote_packet_size ();
6933 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6934 m_first_action = m_p;
6935 }
6936
6937 /* If the vCont packet being built has any action, send it to the
6938 remote end. */
6939
6940 void
6941 vcont_builder::flush ()
6942 {
6943 struct remote_state *rs;
6944
6945 if (m_p == m_first_action)
6946 return;
6947
6948 rs = m_remote->get_remote_state ();
6949 m_remote->putpkt (rs->buf);
6950 m_remote->getpkt (&rs->buf);
6951 if (strcmp (rs->buf.data (), "OK") != 0)
6952 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6953 }
6954
6955 /* The largest action is range-stepping, with its two addresses. This
6956 is more than sufficient. If a new, bigger action is created, it'll
6957 quickly trigger a failed assertion in append_resumption (and we'll
6958 just bump this). */
6959 #define MAX_ACTION_SIZE 200
6960
6961 /* Append a new vCont action in the outgoing packet being built. If
6962 the action doesn't fit the packet along with previous actions, push
6963 what we've got so far to the remote end and start over a new vCont
6964 packet (with the new action). */
6965
6966 void
6967 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6968 {
6969 char buf[MAX_ACTION_SIZE + 1];
6970
6971 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6972 ptid, step, siggnal);
6973
6974 /* Check whether this new action would fit in the vCont packet along
6975 with previous actions. If not, send what we've got so far and
6976 start a new vCont packet. */
6977 size_t rsize = endp - buf;
6978 if (rsize > m_endp - m_p)
6979 {
6980 flush ();
6981 restart ();
6982
6983 /* Should now fit. */
6984 gdb_assert (rsize <= m_endp - m_p);
6985 }
6986
6987 memcpy (m_p, buf, rsize);
6988 m_p += rsize;
6989 *m_p = '\0';
6990 }
6991
6992 /* to_commit_resume implementation. */
6993
6994 void
6995 remote_target::commit_resumed ()
6996 {
6997 /* If connected in all-stop mode, we'd send the remote resume
6998 request directly from remote_resume. Likewise if
6999 reverse-debugging, as there are no defined vCont actions for
7000 reverse execution. */
7001 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7002 return;
7003
7004 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7005 instead of resuming all threads of each process individually.
7006 However, if any thread of a process must remain halted, we can't
7007 send wildcard resumes and must send one action per thread.
7008
7009 Care must be taken to not resume threads/processes the server
7010 side already told us are stopped, but the core doesn't know about
7011 yet, because the events are still in the vStopped notification
7012 queue. For example:
7013
7014 #1 => vCont s:p1.1;c
7015 #2 <= OK
7016 #3 <= %Stopped T05 p1.1
7017 #4 => vStopped
7018 #5 <= T05 p1.2
7019 #6 => vStopped
7020 #7 <= OK
7021 #8 (infrun handles the stop for p1.1 and continues stepping)
7022 #9 => vCont s:p1.1;c
7023
7024 The last vCont above would resume thread p1.2 by mistake, because
7025 the server has no idea that the event for p1.2 had not been
7026 handled yet.
7027
7028 The server side must similarly ignore resume actions for the
7029 thread that has a pending %Stopped notification (and any other
7030 threads with events pending), until GDB acks the notification
7031 with vStopped. Otherwise, e.g., the following case is
7032 mishandled:
7033
7034 #1 => g (or any other packet)
7035 #2 <= [registers]
7036 #3 <= %Stopped T05 p1.2
7037 #4 => vCont s:p1.1;c
7038 #5 <= OK
7039
7040 Above, the server must not resume thread p1.2. GDB can't know
7041 that p1.2 stopped until it acks the %Stopped notification, and
7042 since from GDB's perspective all threads should be running, it
7043 sends a "c" action.
7044
7045 Finally, special care must also be given to handling fork/vfork
7046 events. A (v)fork event actually tells us that two processes
7047 stopped -- the parent and the child. Until we follow the fork,
7048 we must not resume the child. Therefore, if we have a pending
7049 fork follow, we must not send a global wildcard resume action
7050 (vCont;c). We can still send process-wide wildcards though. */
7051
7052 /* Start by assuming a global wildcard (vCont;c) is possible. */
7053 bool may_global_wildcard_vcont = true;
7054
7055 /* And assume every process is individually wildcard-able too. */
7056 for (inferior *inf : all_non_exited_inferiors (this))
7057 {
7058 remote_inferior *priv = get_remote_inferior (inf);
7059
7060 priv->may_wildcard_vcont = true;
7061 }
7062
7063 /* Check for any pending events (not reported or processed yet) and
7064 disable process and global wildcard resumes appropriately. */
7065 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7066
7067 bool any_pending_vcont_resume = false;
7068
7069 for (thread_info *tp : all_non_exited_threads (this))
7070 {
7071 remote_thread_info *priv = get_remote_thread_info (tp);
7072
7073 /* If a thread of a process is not meant to be resumed, then we
7074 can't wildcard that process. */
7075 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7076 {
7077 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7078
7079 /* And if we can't wildcard a process, we can't wildcard
7080 everything either. */
7081 may_global_wildcard_vcont = false;
7082 continue;
7083 }
7084
7085 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7086 any_pending_vcont_resume = true;
7087
7088 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7089 then we can't do a global wildcard, as that would resume the
7090 pending child. */
7091 if (thread_pending_child_status (tp) != nullptr)
7092 may_global_wildcard_vcont = false;
7093 }
7094
7095 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7096 do. */
7097 if (!any_pending_vcont_resume)
7098 return;
7099
7100 /* Now let's build the vCont packet(s). Actions must be appended
7101 from narrower to wider scopes (thread -> process -> global). If
7102 we end up with too many actions for a single packet vcont_builder
7103 flushes the current vCont packet to the remote side and starts a
7104 new one. */
7105 struct vcont_builder vcont_builder (this);
7106
7107 /* Threads first. */
7108 for (thread_info *tp : all_non_exited_threads (this))
7109 {
7110 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7111
7112 /* If the thread was previously vCont-resumed, no need to send a specific
7113 action for it. If we didn't receive a resume request for it, don't
7114 send an action for it either. */
7115 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7116 continue;
7117
7118 gdb_assert (!thread_is_in_step_over_chain (tp));
7119
7120 /* We should never be commit-resuming a thread that has a stop reply.
7121 Otherwise, we would end up reporting a stop event for a thread while
7122 it is running on the remote target. */
7123 remote_state *rs = get_remote_state ();
7124 for (const auto &stop_reply : rs->stop_reply_queue)
7125 gdb_assert (stop_reply->ptid != tp->ptid);
7126
7127 const resumed_pending_vcont_info &info
7128 = remote_thr->resumed_pending_vcont_info ();
7129
7130 /* Check if we need to send a specific action for this thread. If not,
7131 it will be included in a wildcard resume instead. */
7132 if (info.step || info.sig != GDB_SIGNAL_0
7133 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7134 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7135
7136 remote_thr->set_resumed ();
7137 }
7138
7139 /* Now check whether we can send any process-wide wildcard. This is
7140 to avoid sending a global wildcard in the case nothing is
7141 supposed to be resumed. */
7142 bool any_process_wildcard = false;
7143
7144 for (inferior *inf : all_non_exited_inferiors (this))
7145 {
7146 if (get_remote_inferior (inf)->may_wildcard_vcont)
7147 {
7148 any_process_wildcard = true;
7149 break;
7150 }
7151 }
7152
7153 if (any_process_wildcard)
7154 {
7155 /* If all processes are wildcard-able, then send a single "c"
7156 action, otherwise, send an "all (-1) threads of process"
7157 continue action for each running process, if any. */
7158 if (may_global_wildcard_vcont)
7159 {
7160 vcont_builder.push_action (minus_one_ptid,
7161 false, GDB_SIGNAL_0);
7162 }
7163 else
7164 {
7165 for (inferior *inf : all_non_exited_inferiors (this))
7166 {
7167 if (get_remote_inferior (inf)->may_wildcard_vcont)
7168 {
7169 vcont_builder.push_action (ptid_t (inf->pid),
7170 false, GDB_SIGNAL_0);
7171 }
7172 }
7173 }
7174 }
7175
7176 vcont_builder.flush ();
7177 }
7178
7179 /* Implementation of target_has_pending_events. */
7180
7181 bool
7182 remote_target::has_pending_events ()
7183 {
7184 if (target_can_async_p ())
7185 {
7186 remote_state *rs = get_remote_state ();
7187
7188 if (rs->async_event_handler_marked ())
7189 return true;
7190
7191 /* Note that BUFCNT can be negative, indicating sticky
7192 error. */
7193 if (rs->remote_desc->bufcnt != 0)
7194 return true;
7195 }
7196 return false;
7197 }
7198
7199 \f
7200
7201 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7202 thread, all threads of a remote process, or all threads of all
7203 processes. */
7204
7205 void
7206 remote_target::remote_stop_ns (ptid_t ptid)
7207 {
7208 struct remote_state *rs = get_remote_state ();
7209 char *p = rs->buf.data ();
7210 char *endp = p + get_remote_packet_size ();
7211
7212 /* If any thread that needs to stop was resumed but pending a vCont
7213 resume, generate a phony stop_reply. However, first check
7214 whether the thread wasn't resumed with a signal. Generating a
7215 phony stop in that case would result in losing the signal. */
7216 bool needs_commit = false;
7217 for (thread_info *tp : all_non_exited_threads (this, ptid))
7218 {
7219 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7220
7221 if (remote_thr->get_resume_state ()
7222 == resume_state::RESUMED_PENDING_VCONT)
7223 {
7224 const resumed_pending_vcont_info &info
7225 = remote_thr->resumed_pending_vcont_info ();
7226 if (info.sig != GDB_SIGNAL_0)
7227 {
7228 /* This signal must be forwarded to the inferior. We
7229 could commit-resume just this thread, but its simpler
7230 to just commit-resume everything. */
7231 needs_commit = true;
7232 break;
7233 }
7234 }
7235 }
7236
7237 if (needs_commit)
7238 commit_resumed ();
7239 else
7240 for (thread_info *tp : all_non_exited_threads (this, ptid))
7241 {
7242 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7243
7244 if (remote_thr->get_resume_state ()
7245 == resume_state::RESUMED_PENDING_VCONT)
7246 {
7247 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7248 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7249 tp->ptid.lwp (),
7250 pulongest (tp->ptid.tid ()));
7251
7252 /* Check that the thread wasn't resumed with a signal.
7253 Generating a phony stop would result in losing the
7254 signal. */
7255 const resumed_pending_vcont_info &info
7256 = remote_thr->resumed_pending_vcont_info ();
7257 gdb_assert (info.sig == GDB_SIGNAL_0);
7258
7259 stop_reply *sr = new stop_reply ();
7260 sr->ptid = tp->ptid;
7261 sr->rs = rs;
7262 sr->ws.set_stopped (GDB_SIGNAL_0);
7263 sr->arch = tp->inf->arch ();
7264 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7265 sr->watch_data_address = 0;
7266 sr->core = 0;
7267 this->push_stop_reply (sr);
7268
7269 /* Pretend that this thread was actually resumed on the
7270 remote target, then stopped. If we leave it in the
7271 RESUMED_PENDING_VCONT state and the commit_resumed
7272 method is called while the stop reply is still in the
7273 queue, we'll end up reporting a stop event to the core
7274 for that thread while it is running on the remote
7275 target... that would be bad. */
7276 remote_thr->set_resumed ();
7277 }
7278 }
7279
7280 if (!rs->supports_vCont.t)
7281 error (_("Remote server does not support stopping threads"));
7282
7283 if (ptid == minus_one_ptid
7284 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7285 p += xsnprintf (p, endp - p, "vCont;t");
7286 else
7287 {
7288 ptid_t nptid;
7289
7290 p += xsnprintf (p, endp - p, "vCont;t:");
7291
7292 if (ptid.is_pid ())
7293 /* All (-1) threads of process. */
7294 nptid = ptid_t (ptid.pid (), -1);
7295 else
7296 {
7297 /* Small optimization: if we already have a stop reply for
7298 this thread, no use in telling the stub we want this
7299 stopped. */
7300 if (peek_stop_reply (ptid))
7301 return;
7302
7303 nptid = ptid;
7304 }
7305
7306 write_ptid (p, endp, nptid);
7307 }
7308
7309 /* In non-stop, we get an immediate OK reply. The stop reply will
7310 come in asynchronously by notification. */
7311 putpkt (rs->buf);
7312 getpkt (&rs->buf);
7313 if (strcmp (rs->buf.data (), "OK") != 0)
7314 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7315 rs->buf.data ());
7316 }
7317
7318 /* All-stop version of target_interrupt. Sends a break or a ^C to
7319 interrupt the remote target. It is undefined which thread of which
7320 process reports the interrupt. */
7321
7322 void
7323 remote_target::remote_interrupt_as ()
7324 {
7325 struct remote_state *rs = get_remote_state ();
7326
7327 rs->ctrlc_pending_p = 1;
7328
7329 /* If the inferior is stopped already, but the core didn't know
7330 about it yet, just ignore the request. The pending stop events
7331 will be collected in remote_wait. */
7332 if (stop_reply_queue_length () > 0)
7333 return;
7334
7335 /* Send interrupt_sequence to remote target. */
7336 send_interrupt_sequence ();
7337 }
7338
7339 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7340 the remote target. It is undefined which thread of which process
7341 reports the interrupt. Throws an error if the packet is not
7342 supported by the server. */
7343
7344 void
7345 remote_target::remote_interrupt_ns ()
7346 {
7347 struct remote_state *rs = get_remote_state ();
7348 char *p = rs->buf.data ();
7349 char *endp = p + get_remote_packet_size ();
7350
7351 xsnprintf (p, endp - p, "vCtrlC");
7352
7353 /* In non-stop, we get an immediate OK reply. The stop reply will
7354 come in asynchronously by notification. */
7355 putpkt (rs->buf);
7356 getpkt (&rs->buf);
7357
7358 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7359 {
7360 case PACKET_OK:
7361 break;
7362 case PACKET_UNKNOWN:
7363 error (_("No support for interrupting the remote target."));
7364 case PACKET_ERROR:
7365 error (_("Interrupting target failed: %s"), rs->buf.data ());
7366 }
7367 }
7368
7369 /* Implement the to_stop function for the remote targets. */
7370
7371 void
7372 remote_target::stop (ptid_t ptid)
7373 {
7374 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7375
7376 if (target_is_non_stop_p ())
7377 remote_stop_ns (ptid);
7378 else
7379 {
7380 /* We don't currently have a way to transparently pause the
7381 remote target in all-stop mode. Interrupt it instead. */
7382 remote_interrupt_as ();
7383 }
7384 }
7385
7386 /* Implement the to_interrupt function for the remote targets. */
7387
7388 void
7389 remote_target::interrupt ()
7390 {
7391 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7392
7393 if (target_is_non_stop_p ())
7394 remote_interrupt_ns ();
7395 else
7396 remote_interrupt_as ();
7397 }
7398
7399 /* Implement the to_pass_ctrlc function for the remote targets. */
7400
7401 void
7402 remote_target::pass_ctrlc ()
7403 {
7404 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7405
7406 struct remote_state *rs = get_remote_state ();
7407
7408 /* If we're starting up, we're not fully synced yet. Quit
7409 immediately. */
7410 if (rs->starting_up)
7411 quit ();
7412 /* If ^C has already been sent once, offer to disconnect. */
7413 else if (rs->ctrlc_pending_p)
7414 interrupt_query ();
7415 else
7416 target_interrupt ();
7417 }
7418
7419 /* Ask the user what to do when an interrupt is received. */
7420
7421 void
7422 remote_target::interrupt_query ()
7423 {
7424 struct remote_state *rs = get_remote_state ();
7425
7426 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7427 {
7428 if (query (_("The target is not responding to interrupt requests.\n"
7429 "Stop debugging it? ")))
7430 {
7431 remote_unpush_target (this);
7432 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7433 }
7434 }
7435 else
7436 {
7437 if (query (_("Interrupted while waiting for the program.\n"
7438 "Give up waiting? ")))
7439 quit ();
7440 }
7441 }
7442
7443 /* Enable/disable target terminal ownership. Most targets can use
7444 terminal groups to control terminal ownership. Remote targets are
7445 different in that explicit transfer of ownership to/from GDB/target
7446 is required. */
7447
7448 void
7449 remote_target::terminal_inferior ()
7450 {
7451 /* NOTE: At this point we could also register our selves as the
7452 recipient of all input. Any characters typed could then be
7453 passed on down to the target. */
7454 }
7455
7456 void
7457 remote_target::terminal_ours ()
7458 {
7459 }
7460
7461 static void
7462 remote_console_output (const char *msg)
7463 {
7464 const char *p;
7465
7466 for (p = msg; p[0] && p[1]; p += 2)
7467 {
7468 char tb[2];
7469 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7470
7471 tb[0] = c;
7472 tb[1] = 0;
7473 gdb_stdtarg->puts (tb);
7474 }
7475 gdb_stdtarg->flush ();
7476 }
7477
7478 /* Return the length of the stop reply queue. */
7479
7480 int
7481 remote_target::stop_reply_queue_length ()
7482 {
7483 remote_state *rs = get_remote_state ();
7484 return rs->stop_reply_queue.size ();
7485 }
7486
7487 static void
7488 remote_notif_stop_parse (remote_target *remote,
7489 const notif_client *self, const char *buf,
7490 struct notif_event *event)
7491 {
7492 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7493 }
7494
7495 static void
7496 remote_notif_stop_ack (remote_target *remote,
7497 const notif_client *self, const char *buf,
7498 struct notif_event *event)
7499 {
7500 struct stop_reply *stop_reply = (struct stop_reply *) event;
7501
7502 /* acknowledge */
7503 putpkt (remote, self->ack_command);
7504
7505 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7506 the notification. It was left in the queue because we need to
7507 acknowledge it and pull the rest of the notifications out. */
7508 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7509 remote->push_stop_reply (stop_reply);
7510 }
7511
7512 static int
7513 remote_notif_stop_can_get_pending_events (remote_target *remote,
7514 const notif_client *self)
7515 {
7516 /* We can't get pending events in remote_notif_process for
7517 notification stop, and we have to do this in remote_wait_ns
7518 instead. If we fetch all queued events from stub, remote stub
7519 may exit and we have no chance to process them back in
7520 remote_wait_ns. */
7521 remote_state *rs = remote->get_remote_state ();
7522 rs->mark_async_event_handler ();
7523 return 0;
7524 }
7525
7526 stop_reply::~stop_reply ()
7527 {
7528 for (cached_reg_t &reg : regcache)
7529 xfree (reg.data);
7530 }
7531
7532 static notif_event_up
7533 remote_notif_stop_alloc_reply ()
7534 {
7535 return notif_event_up (new struct stop_reply ());
7536 }
7537
7538 /* A client of notification Stop. */
7539
7540 const notif_client notif_client_stop =
7541 {
7542 "Stop",
7543 "vStopped",
7544 remote_notif_stop_parse,
7545 remote_notif_stop_ack,
7546 remote_notif_stop_can_get_pending_events,
7547 remote_notif_stop_alloc_reply,
7548 REMOTE_NOTIF_STOP,
7549 };
7550
7551 /* If CONTEXT contains any fork/vfork/clone child threads that have
7552 not been reported yet, remove them from the CONTEXT list. If such
7553 a thread exists it is because we are stopped at a fork/vfork/clone
7554 catchpoint and have not yet called follow_fork/follow_clone, which
7555 will set up the host-side data structures for the new child. */
7556
7557 void
7558 remote_target::remove_new_children (threads_listing_context *context)
7559 {
7560 const notif_client *notif = &notif_client_stop;
7561
7562 /* For any threads stopped at a (v)fork/clone event, remove the
7563 corresponding child threads from the CONTEXT list. */
7564 for (thread_info *thread : all_non_exited_threads (this))
7565 {
7566 const target_waitstatus *ws = thread_pending_child_status (thread);
7567
7568 if (ws == nullptr)
7569 continue;
7570
7571 context->remove_thread (ws->child_ptid ());
7572 }
7573
7574 /* Check for any pending (v)fork/clone events (not reported or
7575 processed yet) in process PID and remove those child threads from
7576 the CONTEXT list as well. */
7577 remote_notif_get_pending_events (notif);
7578 for (auto &event : get_remote_state ()->stop_reply_queue)
7579 if (is_new_child_status (event->ws.kind ()))
7580 context->remove_thread (event->ws.child_ptid ());
7581 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7582 context->remove_thread (event->ptid);
7583 }
7584
7585 /* Check whether any event pending in the vStopped queue would prevent a
7586 global or process wildcard vCont action. Set *may_global_wildcard to
7587 false if we can't do a global wildcard (vCont;c), and clear the event
7588 inferior's may_wildcard_vcont flag if we can't do a process-wide
7589 wildcard resume (vCont;c:pPID.-1). */
7590
7591 void
7592 remote_target::check_pending_events_prevent_wildcard_vcont
7593 (bool *may_global_wildcard)
7594 {
7595 const notif_client *notif = &notif_client_stop;
7596
7597 remote_notif_get_pending_events (notif);
7598 for (auto &event : get_remote_state ()->stop_reply_queue)
7599 {
7600 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7601 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7602 continue;
7603
7604 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7605 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7606 *may_global_wildcard = false;
7607
7608 /* This may be the first time we heard about this process.
7609 Regardless, we must not do a global wildcard resume, otherwise
7610 we'd resume this process too. */
7611 *may_global_wildcard = false;
7612 if (event->ptid != null_ptid)
7613 {
7614 inferior *inf = find_inferior_ptid (this, event->ptid);
7615 if (inf != NULL)
7616 get_remote_inferior (inf)->may_wildcard_vcont = false;
7617 }
7618 }
7619 }
7620
7621 /* Discard all pending stop replies of inferior INF. */
7622
7623 void
7624 remote_target::discard_pending_stop_replies (struct inferior *inf)
7625 {
7626 struct stop_reply *reply;
7627 struct remote_state *rs = get_remote_state ();
7628 struct remote_notif_state *rns = rs->notif_state;
7629
7630 /* This function can be notified when an inferior exists. When the
7631 target is not remote, the notification state is NULL. */
7632 if (rs->remote_desc == NULL)
7633 return;
7634
7635 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7636
7637 /* Discard the in-flight notification. */
7638 if (reply != NULL && reply->ptid.pid () == inf->pid)
7639 {
7640 /* Leave the notification pending, since the server expects that
7641 we acknowledge it with vStopped. But clear its contents, so
7642 that later on when we acknowledge it, we also discard it. */
7643 remote_debug_printf
7644 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7645 reply->ptid.to_string().c_str(),
7646 reply->ws.to_string ().c_str ());
7647 reply->ws.set_ignore ();
7648 }
7649
7650 /* Discard the stop replies we have already pulled with
7651 vStopped. */
7652 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7653 rs->stop_reply_queue.end (),
7654 [=] (const stop_reply_up &event)
7655 {
7656 return event->ptid.pid () == inf->pid;
7657 });
7658 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7659 remote_debug_printf
7660 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7661 (*it)->ptid.to_string().c_str(),
7662 (*it)->ws.to_string ().c_str ());
7663 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7664 }
7665
7666 /* Discard the stop replies for RS in stop_reply_queue. */
7667
7668 void
7669 remote_target::discard_pending_stop_replies_in_queue ()
7670 {
7671 remote_state *rs = get_remote_state ();
7672
7673 /* Discard the stop replies we have already pulled with
7674 vStopped. */
7675 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7676 rs->stop_reply_queue.end (),
7677 [=] (const stop_reply_up &event)
7678 {
7679 return event->rs == rs;
7680 });
7681 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7682 }
7683
7684 /* Remove the first reply in 'stop_reply_queue' which matches
7685 PTID. */
7686
7687 struct stop_reply *
7688 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7689 {
7690 remote_state *rs = get_remote_state ();
7691
7692 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7693 rs->stop_reply_queue.end (),
7694 [=] (const stop_reply_up &event)
7695 {
7696 return event->ptid.matches (ptid);
7697 });
7698 struct stop_reply *result;
7699 if (iter == rs->stop_reply_queue.end ())
7700 result = nullptr;
7701 else
7702 {
7703 result = iter->release ();
7704 rs->stop_reply_queue.erase (iter);
7705 }
7706
7707 if (notif_debug)
7708 gdb_printf (gdb_stdlog,
7709 "notif: discard queued event: 'Stop' in %s\n",
7710 ptid.to_string ().c_str ());
7711
7712 return result;
7713 }
7714
7715 /* Look for a queued stop reply belonging to PTID. If one is found,
7716 remove it from the queue, and return it. Returns NULL if none is
7717 found. If there are still queued events left to process, tell the
7718 event loop to get back to target_wait soon. */
7719
7720 struct stop_reply *
7721 remote_target::queued_stop_reply (ptid_t ptid)
7722 {
7723 remote_state *rs = get_remote_state ();
7724 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7725
7726 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7727 {
7728 /* There's still at least an event left. */
7729 rs->mark_async_event_handler ();
7730 }
7731
7732 return r;
7733 }
7734
7735 /* Push a fully parsed stop reply in the stop reply queue. Since we
7736 know that we now have at least one queued event left to pass to the
7737 core side, tell the event loop to get back to target_wait soon. */
7738
7739 void
7740 remote_target::push_stop_reply (struct stop_reply *new_event)
7741 {
7742 remote_state *rs = get_remote_state ();
7743 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7744
7745 if (notif_debug)
7746 gdb_printf (gdb_stdlog,
7747 "notif: push 'Stop' %s to queue %d\n",
7748 new_event->ptid.to_string ().c_str (),
7749 int (rs->stop_reply_queue.size ()));
7750
7751 /* Mark the pending event queue only if async mode is currently enabled.
7752 If async mode is not currently enabled, then, if it later becomes
7753 enabled, and there are events in this queue, we will mark the event
7754 token at that point, see remote_target::async. */
7755 if (target_is_async_p ())
7756 rs->mark_async_event_handler ();
7757 }
7758
7759 /* Returns true if we have a stop reply for PTID. */
7760
7761 int
7762 remote_target::peek_stop_reply (ptid_t ptid)
7763 {
7764 remote_state *rs = get_remote_state ();
7765 for (auto &event : rs->stop_reply_queue)
7766 if (ptid == event->ptid
7767 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7768 return 1;
7769 return 0;
7770 }
7771
7772 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7773 starting with P and ending with PEND matches PREFIX. */
7774
7775 static int
7776 strprefix (const char *p, const char *pend, const char *prefix)
7777 {
7778 for ( ; p < pend; p++, prefix++)
7779 if (*p != *prefix)
7780 return 0;
7781 return *prefix == '\0';
7782 }
7783
7784 /* Parse the stop reply in BUF. Either the function succeeds, and the
7785 result is stored in EVENT, or throws an error. */
7786
7787 void
7788 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7789 {
7790 remote_arch_state *rsa = NULL;
7791 ULONGEST addr;
7792 const char *p;
7793 int skipregs = 0;
7794
7795 event->ptid = null_ptid;
7796 event->rs = get_remote_state ();
7797 event->ws.set_ignore ();
7798 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7799 event->regcache.clear ();
7800 event->core = -1;
7801
7802 switch (buf[0])
7803 {
7804 case 'T': /* Status with PC, SP, FP, ... */
7805 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7806 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7807 ss = signal number
7808 n... = register number
7809 r... = register contents
7810 */
7811
7812 p = &buf[3]; /* after Txx */
7813 while (*p)
7814 {
7815 const char *p1;
7816 int fieldsize;
7817
7818 p1 = strchr (p, ':');
7819 if (p1 == NULL)
7820 error (_("Malformed packet(a) (missing colon): %s\n\
7821 Packet: '%s'\n"),
7822 p, buf);
7823 if (p == p1)
7824 error (_("Malformed packet(a) (missing register number): %s\n\
7825 Packet: '%s'\n"),
7826 p, buf);
7827
7828 /* Some "registers" are actually extended stop information.
7829 Note if you're adding a new entry here: GDB 7.9 and
7830 earlier assume that all register "numbers" that start
7831 with an hex digit are real register numbers. Make sure
7832 the server only sends such a packet if it knows the
7833 client understands it. */
7834
7835 if (strprefix (p, p1, "thread"))
7836 event->ptid = read_ptid (++p1, &p);
7837 else if (strprefix (p, p1, "syscall_entry"))
7838 {
7839 ULONGEST sysno;
7840
7841 p = unpack_varlen_hex (++p1, &sysno);
7842 event->ws.set_syscall_entry ((int) sysno);
7843 }
7844 else if (strprefix (p, p1, "syscall_return"))
7845 {
7846 ULONGEST sysno;
7847
7848 p = unpack_varlen_hex (++p1, &sysno);
7849 event->ws.set_syscall_return ((int) sysno);
7850 }
7851 else if (strprefix (p, p1, "watch")
7852 || strprefix (p, p1, "rwatch")
7853 || strprefix (p, p1, "awatch"))
7854 {
7855 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7856 p = unpack_varlen_hex (++p1, &addr);
7857 event->watch_data_address = (CORE_ADDR) addr;
7858 }
7859 else if (strprefix (p, p1, "swbreak"))
7860 {
7861 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7862
7863 /* Make sure the stub doesn't forget to indicate support
7864 with qSupported. */
7865 if (m_features.packet_support (PACKET_swbreak_feature)
7866 != PACKET_ENABLE)
7867 error (_("Unexpected swbreak stop reason"));
7868
7869 /* The value part is documented as "must be empty",
7870 though we ignore it, in case we ever decide to make
7871 use of it in a backward compatible way. */
7872 p = strchrnul (p1 + 1, ';');
7873 }
7874 else if (strprefix (p, p1, "hwbreak"))
7875 {
7876 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7877
7878 /* Make sure the stub doesn't forget to indicate support
7879 with qSupported. */
7880 if (m_features.packet_support (PACKET_hwbreak_feature)
7881 != PACKET_ENABLE)
7882 error (_("Unexpected hwbreak stop reason"));
7883
7884 /* See above. */
7885 p = strchrnul (p1 + 1, ';');
7886 }
7887 else if (strprefix (p, p1, "library"))
7888 {
7889 event->ws.set_loaded ();
7890 p = strchrnul (p1 + 1, ';');
7891 }
7892 else if (strprefix (p, p1, "replaylog"))
7893 {
7894 event->ws.set_no_history ();
7895 /* p1 will indicate "begin" or "end", but it makes
7896 no difference for now, so ignore it. */
7897 p = strchrnul (p1 + 1, ';');
7898 }
7899 else if (strprefix (p, p1, "core"))
7900 {
7901 ULONGEST c;
7902
7903 p = unpack_varlen_hex (++p1, &c);
7904 event->core = c;
7905 }
7906 else if (strprefix (p, p1, "fork"))
7907 event->ws.set_forked (read_ptid (++p1, &p));
7908 else if (strprefix (p, p1, "vfork"))
7909 event->ws.set_vforked (read_ptid (++p1, &p));
7910 else if (strprefix (p, p1, "clone"))
7911 event->ws.set_thread_cloned (read_ptid (++p1, &p));
7912 else if (strprefix (p, p1, "vforkdone"))
7913 {
7914 event->ws.set_vfork_done ();
7915 p = strchrnul (p1 + 1, ';');
7916 }
7917 else if (strprefix (p, p1, "exec"))
7918 {
7919 ULONGEST ignored;
7920 int pathlen;
7921
7922 /* Determine the length of the execd pathname. */
7923 p = unpack_varlen_hex (++p1, &ignored);
7924 pathlen = (p - p1) / 2;
7925
7926 /* Save the pathname for event reporting and for
7927 the next run command. */
7928 gdb::unique_xmalloc_ptr<char> pathname
7929 ((char *) xmalloc (pathlen + 1));
7930 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7931 pathname.get ()[pathlen] = '\0';
7932
7933 /* This is freed during event handling. */
7934 event->ws.set_execd (std::move (pathname));
7935
7936 /* Skip the registers included in this packet, since
7937 they may be for an architecture different from the
7938 one used by the original program. */
7939 skipregs = 1;
7940 }
7941 else if (strprefix (p, p1, "create"))
7942 {
7943 event->ws.set_thread_created ();
7944 p = strchrnul (p1 + 1, ';');
7945 }
7946 else
7947 {
7948 ULONGEST pnum;
7949 const char *p_temp;
7950
7951 if (skipregs)
7952 {
7953 p = strchrnul (p1 + 1, ';');
7954 p++;
7955 continue;
7956 }
7957
7958 /* Maybe a real ``P'' register number. */
7959 p_temp = unpack_varlen_hex (p, &pnum);
7960 /* If the first invalid character is the colon, we got a
7961 register number. Otherwise, it's an unknown stop
7962 reason. */
7963 if (p_temp == p1)
7964 {
7965 /* If we haven't parsed the event's thread yet, find
7966 it now, in order to find the architecture of the
7967 reported expedited registers. */
7968 if (event->ptid == null_ptid)
7969 {
7970 /* If there is no thread-id information then leave
7971 the event->ptid as null_ptid. Later in
7972 process_stop_reply we will pick a suitable
7973 thread. */
7974 const char *thr = strstr (p1 + 1, ";thread:");
7975 if (thr != NULL)
7976 event->ptid = read_ptid (thr + strlen (";thread:"),
7977 NULL);
7978 }
7979
7980 if (rsa == NULL)
7981 {
7982 inferior *inf
7983 = (event->ptid == null_ptid
7984 ? NULL
7985 : find_inferior_ptid (this, event->ptid));
7986 /* If this is the first time we learn anything
7987 about this process, skip the registers
7988 included in this packet, since we don't yet
7989 know which architecture to use to parse them.
7990 We'll determine the architecture later when
7991 we process the stop reply and retrieve the
7992 target description, via
7993 remote_notice_new_inferior ->
7994 post_create_inferior. */
7995 if (inf == NULL)
7996 {
7997 p = strchrnul (p1 + 1, ';');
7998 p++;
7999 continue;
8000 }
8001
8002 event->arch = inf->arch ();
8003 rsa = event->rs->get_remote_arch_state (event->arch);
8004 }
8005
8006 packet_reg *reg
8007 = packet_reg_from_pnum (event->arch, rsa, pnum);
8008 cached_reg_t cached_reg;
8009
8010 if (reg == NULL)
8011 error (_("Remote sent bad register number %s: %s\n\
8012 Packet: '%s'\n"),
8013 hex_string (pnum), p, buf);
8014
8015 cached_reg.num = reg->regnum;
8016 cached_reg.data = (gdb_byte *)
8017 xmalloc (register_size (event->arch, reg->regnum));
8018
8019 p = p1 + 1;
8020 fieldsize = hex2bin (p, cached_reg.data,
8021 register_size (event->arch, reg->regnum));
8022 p += 2 * fieldsize;
8023 if (fieldsize < register_size (event->arch, reg->regnum))
8024 warning (_("Remote reply is too short: %s"), buf);
8025
8026 event->regcache.push_back (cached_reg);
8027 }
8028 else
8029 {
8030 /* Not a number. Silently skip unknown optional
8031 info. */
8032 p = strchrnul (p1 + 1, ';');
8033 }
8034 }
8035
8036 if (*p != ';')
8037 error (_("Remote register badly formatted: %s\nhere: %s"),
8038 buf, p);
8039 ++p;
8040 }
8041
8042 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8043 break;
8044
8045 /* fall through */
8046 case 'S': /* Old style status, just signal only. */
8047 {
8048 int sig;
8049
8050 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8051 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8052 event->ws.set_stopped ((enum gdb_signal) sig);
8053 else
8054 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8055 }
8056 break;
8057 case 'w': /* Thread exited. */
8058 {
8059 ULONGEST value;
8060
8061 p = unpack_varlen_hex (&buf[1], &value);
8062 event->ws.set_thread_exited (value);
8063 if (*p != ';')
8064 error (_("stop reply packet badly formatted: %s"), buf);
8065 event->ptid = read_ptid (++p, NULL);
8066 break;
8067 }
8068 case 'W': /* Target exited. */
8069 case 'X':
8070 {
8071 ULONGEST value;
8072
8073 /* GDB used to accept only 2 hex chars here. Stubs should
8074 only send more if they detect GDB supports multi-process
8075 support. */
8076 p = unpack_varlen_hex (&buf[1], &value);
8077
8078 if (buf[0] == 'W')
8079 {
8080 /* The remote process exited. */
8081 event->ws.set_exited (value);
8082 }
8083 else
8084 {
8085 /* The remote process exited with a signal. */
8086 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8087 event->ws.set_signalled ((enum gdb_signal) value);
8088 else
8089 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8090 }
8091
8092 /* If no process is specified, return null_ptid, and let the
8093 caller figure out the right process to use. */
8094 int pid = 0;
8095 if (*p == '\0')
8096 ;
8097 else if (*p == ';')
8098 {
8099 p++;
8100
8101 if (*p == '\0')
8102 ;
8103 else if (startswith (p, "process:"))
8104 {
8105 ULONGEST upid;
8106
8107 p += sizeof ("process:") - 1;
8108 unpack_varlen_hex (p, &upid);
8109 pid = upid;
8110 }
8111 else
8112 error (_("unknown stop reply packet: %s"), buf);
8113 }
8114 else
8115 error (_("unknown stop reply packet: %s"), buf);
8116 event->ptid = ptid_t (pid);
8117 }
8118 break;
8119 case 'N':
8120 event->ws.set_no_resumed ();
8121 event->ptid = minus_one_ptid;
8122 break;
8123 }
8124 }
8125
8126 /* When the stub wants to tell GDB about a new notification reply, it
8127 sends a notification (%Stop, for example). Those can come it at
8128 any time, hence, we have to make sure that any pending
8129 putpkt/getpkt sequence we're making is finished, before querying
8130 the stub for more events with the corresponding ack command
8131 (vStopped, for example). E.g., if we started a vStopped sequence
8132 immediately upon receiving the notification, something like this
8133 could happen:
8134
8135 1.1) --> Hg 1
8136 1.2) <-- OK
8137 1.3) --> g
8138 1.4) <-- %Stop
8139 1.5) --> vStopped
8140 1.6) <-- (registers reply to step #1.3)
8141
8142 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8143 query.
8144
8145 To solve this, whenever we parse a %Stop notification successfully,
8146 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8147 doing whatever we were doing:
8148
8149 2.1) --> Hg 1
8150 2.2) <-- OK
8151 2.3) --> g
8152 2.4) <-- %Stop
8153 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8154 2.5) <-- (registers reply to step #2.3)
8155
8156 Eventually after step #2.5, we return to the event loop, which
8157 notices there's an event on the
8158 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8159 associated callback --- the function below. At this point, we're
8160 always safe to start a vStopped sequence. :
8161
8162 2.6) --> vStopped
8163 2.7) <-- T05 thread:2
8164 2.8) --> vStopped
8165 2.9) --> OK
8166 */
8167
8168 void
8169 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8170 {
8171 struct remote_state *rs = get_remote_state ();
8172
8173 if (rs->notif_state->pending_event[nc->id] != NULL)
8174 {
8175 if (notif_debug)
8176 gdb_printf (gdb_stdlog,
8177 "notif: process: '%s' ack pending event\n",
8178 nc->name);
8179
8180 /* acknowledge */
8181 nc->ack (this, nc, rs->buf.data (),
8182 rs->notif_state->pending_event[nc->id]);
8183 rs->notif_state->pending_event[nc->id] = NULL;
8184
8185 while (1)
8186 {
8187 getpkt (&rs->buf);
8188 if (strcmp (rs->buf.data (), "OK") == 0)
8189 break;
8190 else
8191 remote_notif_ack (this, nc, rs->buf.data ());
8192 }
8193 }
8194 else
8195 {
8196 if (notif_debug)
8197 gdb_printf (gdb_stdlog,
8198 "notif: process: '%s' no pending reply\n",
8199 nc->name);
8200 }
8201 }
8202
8203 /* Wrapper around remote_target::remote_notif_get_pending_events to
8204 avoid having to export the whole remote_target class. */
8205
8206 void
8207 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8208 {
8209 remote->remote_notif_get_pending_events (nc);
8210 }
8211
8212 /* Called from process_stop_reply when the stop packet we are responding
8213 to didn't include a process-id or thread-id. STATUS is the stop event
8214 we are responding to.
8215
8216 It is the task of this function to select a suitable thread (or process)
8217 and return its ptid, this is the thread (or process) we will assume the
8218 stop event came from.
8219
8220 In some cases there isn't really any choice about which thread (or
8221 process) is selected, a basic remote with a single process containing a
8222 single thread might choose not to send any process-id or thread-id in
8223 its stop packets, this function will select and return the one and only
8224 thread.
8225
8226 However, if a target supports multiple threads (or processes) and still
8227 doesn't include a thread-id (or process-id) in its stop packet then
8228 first, this is a badly behaving target, and second, we're going to have
8229 to select a thread (or process) at random and use that. This function
8230 will print a warning to the user if it detects that there is the
8231 possibility that GDB is guessing which thread (or process) to
8232 report.
8233
8234 Note that this is called before GDB fetches the updated thread list from the
8235 target. So it's possible for the stop reply to be ambiguous and for GDB to
8236 not realize it. For example, if there's initially one thread, the target
8237 spawns a second thread, and then sends a stop reply without an id that
8238 concerns the first thread. GDB will assume the stop reply is about the
8239 first thread - the only thread it knows about - without printing a warning.
8240 Anyway, if the remote meant for the stop reply to be about the second thread,
8241 then it would be really broken, because GDB doesn't know about that thread
8242 yet. */
8243
8244 ptid_t
8245 remote_target::select_thread_for_ambiguous_stop_reply
8246 (const target_waitstatus &status)
8247 {
8248 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8249
8250 /* Some stop events apply to all threads in an inferior, while others
8251 only apply to a single thread. */
8252 bool process_wide_stop
8253 = (status.kind () == TARGET_WAITKIND_EXITED
8254 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8255
8256 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8257
8258 thread_info *first_resumed_thread = nullptr;
8259 bool ambiguous = false;
8260
8261 /* Consider all non-exited threads of the target, find the first resumed
8262 one. */
8263 for (thread_info *thr : all_non_exited_threads (this))
8264 {
8265 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8266
8267 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8268 continue;
8269
8270 if (first_resumed_thread == nullptr)
8271 first_resumed_thread = thr;
8272 else if (!process_wide_stop
8273 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8274 ambiguous = true;
8275 }
8276
8277 gdb_assert (first_resumed_thread != nullptr);
8278
8279 remote_debug_printf ("first resumed thread is %s",
8280 pid_to_str (first_resumed_thread->ptid).c_str ());
8281 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8282
8283 /* Warn if the remote target is sending ambiguous stop replies. */
8284 if (ambiguous)
8285 {
8286 static bool warned = false;
8287
8288 if (!warned)
8289 {
8290 /* If you are seeing this warning then the remote target has
8291 stopped without specifying a thread-id, but the target
8292 does have multiple threads (or inferiors), and so GDB is
8293 having to guess which thread stopped.
8294
8295 Examples of what might cause this are the target sending
8296 and 'S' stop packet, or a 'T' stop packet and not
8297 including a thread-id.
8298
8299 Additionally, the target might send a 'W' or 'X packet
8300 without including a process-id, when the target has
8301 multiple running inferiors. */
8302 if (process_wide_stop)
8303 warning (_("multi-inferior target stopped without "
8304 "sending a process-id, using first "
8305 "non-exited inferior"));
8306 else
8307 warning (_("multi-threaded target stopped without "
8308 "sending a thread-id, using first "
8309 "non-exited thread"));
8310 warned = true;
8311 }
8312 }
8313
8314 /* If this is a stop for all threads then don't use a particular threads
8315 ptid, instead create a new ptid where only the pid field is set. */
8316 if (process_wide_stop)
8317 return ptid_t (first_resumed_thread->ptid.pid ());
8318 else
8319 return first_resumed_thread->ptid;
8320 }
8321
8322 /* Called when it is decided that STOP_REPLY holds the info of the
8323 event that is to be returned to the core. This function always
8324 destroys STOP_REPLY. */
8325
8326 ptid_t
8327 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8328 struct target_waitstatus *status)
8329 {
8330 *status = stop_reply->ws;
8331 ptid_t ptid = stop_reply->ptid;
8332
8333 /* If no thread/process was reported by the stub then select a suitable
8334 thread/process. */
8335 if (ptid == null_ptid)
8336 ptid = select_thread_for_ambiguous_stop_reply (*status);
8337 gdb_assert (ptid != null_ptid);
8338
8339 if (status->kind () != TARGET_WAITKIND_EXITED
8340 && status->kind () != TARGET_WAITKIND_SIGNALLED
8341 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8342 {
8343 /* Expedited registers. */
8344 if (!stop_reply->regcache.empty ())
8345 {
8346 struct regcache *regcache
8347 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8348
8349 for (cached_reg_t &reg : stop_reply->regcache)
8350 {
8351 regcache->raw_supply (reg.num, reg.data);
8352 xfree (reg.data);
8353 }
8354
8355 stop_reply->regcache.clear ();
8356 }
8357
8358 remote_notice_new_inferior (ptid, false);
8359 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8360 remote_thr->core = stop_reply->core;
8361 remote_thr->stop_reason = stop_reply->stop_reason;
8362 remote_thr->watch_data_address = stop_reply->watch_data_address;
8363
8364 if (target_is_non_stop_p ())
8365 {
8366 /* If the target works in non-stop mode, a stop-reply indicates that
8367 only this thread stopped. */
8368 remote_thr->set_not_resumed ();
8369 }
8370 else
8371 {
8372 /* If the target works in all-stop mode, a stop-reply indicates that
8373 all the target's threads stopped. */
8374 for (thread_info *tp : all_non_exited_threads (this))
8375 get_remote_thread_info (tp)->set_not_resumed ();
8376 }
8377 }
8378
8379 delete stop_reply;
8380 return ptid;
8381 }
8382
8383 /* The non-stop mode version of target_wait. */
8384
8385 ptid_t
8386 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8387 target_wait_flags options)
8388 {
8389 struct remote_state *rs = get_remote_state ();
8390 struct stop_reply *stop_reply;
8391 int ret;
8392 bool is_notif = false;
8393
8394 /* If in non-stop mode, get out of getpkt even if a
8395 notification is received. */
8396
8397 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8398 while (1)
8399 {
8400 if (ret != -1 && !is_notif)
8401 switch (rs->buf[0])
8402 {
8403 case 'E': /* Error of some sort. */
8404 /* We're out of sync with the target now. Did it continue
8405 or not? We can't tell which thread it was in non-stop,
8406 so just ignore this. */
8407 warning (_("Remote failure reply: %s"), rs->buf.data ());
8408 break;
8409 case 'O': /* Console output. */
8410 remote_console_output (&rs->buf[1]);
8411 break;
8412 default:
8413 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8414 break;
8415 }
8416
8417 /* Acknowledge a pending stop reply that may have arrived in the
8418 mean time. */
8419 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8420 remote_notif_get_pending_events (&notif_client_stop);
8421
8422 /* If indeed we noticed a stop reply, we're done. */
8423 stop_reply = queued_stop_reply (ptid);
8424 if (stop_reply != NULL)
8425 return process_stop_reply (stop_reply, status);
8426
8427 /* Still no event. If we're just polling for an event, then
8428 return to the event loop. */
8429 if (options & TARGET_WNOHANG)
8430 {
8431 status->set_ignore ();
8432 return minus_one_ptid;
8433 }
8434
8435 /* Otherwise do a blocking wait. */
8436 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8437 }
8438 }
8439
8440 /* Return the first resumed thread. */
8441
8442 static ptid_t
8443 first_remote_resumed_thread (remote_target *target)
8444 {
8445 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8446 if (tp->resumed ())
8447 return tp->ptid;
8448 return null_ptid;
8449 }
8450
8451 /* Wait until the remote machine stops, then return, storing status in
8452 STATUS just as `wait' would. */
8453
8454 ptid_t
8455 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8456 target_wait_flags options)
8457 {
8458 struct remote_state *rs = get_remote_state ();
8459 ptid_t event_ptid = null_ptid;
8460 char *buf;
8461 struct stop_reply *stop_reply;
8462
8463 again:
8464
8465 status->set_ignore ();
8466
8467 stop_reply = queued_stop_reply (ptid);
8468 if (stop_reply != NULL)
8469 {
8470 /* None of the paths that push a stop reply onto the queue should
8471 have set the waiting_for_stop_reply flag. */
8472 gdb_assert (!rs->waiting_for_stop_reply);
8473 event_ptid = process_stop_reply (stop_reply, status);
8474 }
8475 else
8476 {
8477 bool forever = ((options & TARGET_WNOHANG) == 0
8478 && rs->wait_forever_enabled_p);
8479
8480 if (!rs->waiting_for_stop_reply)
8481 {
8482 status->set_no_resumed ();
8483 return minus_one_ptid;
8484 }
8485
8486 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8487 _never_ wait for ever -> test on target_is_async_p().
8488 However, before we do that we need to ensure that the caller
8489 knows how to take the target into/out of async mode. */
8490 bool is_notif;
8491 int ret = getpkt (&rs->buf, forever, &is_notif);
8492
8493 /* GDB gets a notification. Return to core as this event is
8494 not interesting. */
8495 if (ret != -1 && is_notif)
8496 return minus_one_ptid;
8497
8498 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8499 return minus_one_ptid;
8500
8501 buf = rs->buf.data ();
8502
8503 /* Assume that the target has acknowledged Ctrl-C unless we receive
8504 an 'F' or 'O' packet. */
8505 if (buf[0] != 'F' && buf[0] != 'O')
8506 rs->ctrlc_pending_p = 0;
8507
8508 switch (buf[0])
8509 {
8510 case 'E': /* Error of some sort. */
8511 /* We're out of sync with the target now. Did it continue or
8512 not? Not is more likely, so report a stop. */
8513 rs->waiting_for_stop_reply = 0;
8514
8515 warning (_("Remote failure reply: %s"), buf);
8516 status->set_stopped (GDB_SIGNAL_0);
8517 break;
8518 case 'F': /* File-I/O request. */
8519 /* GDB may access the inferior memory while handling the File-I/O
8520 request, but we don't want GDB accessing memory while waiting
8521 for a stop reply. See the comments in putpkt_binary. Set
8522 waiting_for_stop_reply to 0 temporarily. */
8523 rs->waiting_for_stop_reply = 0;
8524 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8525 rs->ctrlc_pending_p = 0;
8526 /* GDB handled the File-I/O request, and the target is running
8527 again. Keep waiting for events. */
8528 rs->waiting_for_stop_reply = 1;
8529 break;
8530 case 'N': case 'T': case 'S': case 'X': case 'W':
8531 {
8532 /* There is a stop reply to handle. */
8533 rs->waiting_for_stop_reply = 0;
8534
8535 stop_reply
8536 = (struct stop_reply *) remote_notif_parse (this,
8537 &notif_client_stop,
8538 rs->buf.data ());
8539
8540 event_ptid = process_stop_reply (stop_reply, status);
8541 break;
8542 }
8543 case 'O': /* Console output. */
8544 remote_console_output (buf + 1);
8545 break;
8546 case '\0':
8547 if (rs->last_sent_signal != GDB_SIGNAL_0)
8548 {
8549 /* Zero length reply means that we tried 'S' or 'C' and the
8550 remote system doesn't support it. */
8551 target_terminal::ours_for_output ();
8552 gdb_printf
8553 ("Can't send signals to this remote system. %s not sent.\n",
8554 gdb_signal_to_name (rs->last_sent_signal));
8555 rs->last_sent_signal = GDB_SIGNAL_0;
8556 target_terminal::inferior ();
8557
8558 strcpy (buf, rs->last_sent_step ? "s" : "c");
8559 putpkt (buf);
8560 break;
8561 }
8562 /* fallthrough */
8563 default:
8564 warning (_("Invalid remote reply: %s"), buf);
8565 break;
8566 }
8567 }
8568
8569 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8570 return minus_one_ptid;
8571 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8572 {
8573 /* Nothing interesting happened. If we're doing a non-blocking
8574 poll, we're done. Otherwise, go back to waiting. */
8575 if (options & TARGET_WNOHANG)
8576 return minus_one_ptid;
8577 else
8578 goto again;
8579 }
8580 else if (status->kind () != TARGET_WAITKIND_EXITED
8581 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8582 {
8583 if (event_ptid != null_ptid)
8584 record_currthread (rs, event_ptid);
8585 else
8586 event_ptid = first_remote_resumed_thread (this);
8587 }
8588 else
8589 {
8590 /* A process exit. Invalidate our notion of current thread. */
8591 record_currthread (rs, minus_one_ptid);
8592 /* It's possible that the packet did not include a pid. */
8593 if (event_ptid == null_ptid)
8594 event_ptid = first_remote_resumed_thread (this);
8595 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8596 if (event_ptid == null_ptid)
8597 event_ptid = magic_null_ptid;
8598 }
8599
8600 return event_ptid;
8601 }
8602
8603 /* Wait until the remote machine stops, then return, storing status in
8604 STATUS just as `wait' would. */
8605
8606 ptid_t
8607 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8608 target_wait_flags options)
8609 {
8610 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8611
8612 remote_state *rs = get_remote_state ();
8613
8614 /* Start by clearing the flag that asks for our wait method to be called,
8615 we'll mark it again at the end if needed. If the target is not in
8616 async mode then the async token should not be marked. */
8617 if (target_is_async_p ())
8618 rs->clear_async_event_handler ();
8619 else
8620 gdb_assert (!rs->async_event_handler_marked ());
8621
8622 ptid_t event_ptid;
8623
8624 if (target_is_non_stop_p ())
8625 event_ptid = wait_ns (ptid, status, options);
8626 else
8627 event_ptid = wait_as (ptid, status, options);
8628
8629 if (target_is_async_p ())
8630 {
8631 /* If there are events left in the queue, or unacknowledged
8632 notifications, then tell the event loop to call us again. */
8633 if (!rs->stop_reply_queue.empty ()
8634 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8635 rs->mark_async_event_handler ();
8636 }
8637
8638 return event_ptid;
8639 }
8640
8641 /* Fetch a single register using a 'p' packet. */
8642
8643 int
8644 remote_target::fetch_register_using_p (struct regcache *regcache,
8645 packet_reg *reg)
8646 {
8647 struct gdbarch *gdbarch = regcache->arch ();
8648 struct remote_state *rs = get_remote_state ();
8649 char *buf, *p;
8650 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8651 int i;
8652
8653 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8654 return 0;
8655
8656 if (reg->pnum == -1)
8657 return 0;
8658
8659 p = rs->buf.data ();
8660 *p++ = 'p';
8661 p += hexnumstr (p, reg->pnum);
8662 *p++ = '\0';
8663 putpkt (rs->buf);
8664 getpkt (&rs->buf);
8665
8666 buf = rs->buf.data ();
8667
8668 switch (m_features.packet_ok (rs->buf, PACKET_p))
8669 {
8670 case PACKET_OK:
8671 break;
8672 case PACKET_UNKNOWN:
8673 return 0;
8674 case PACKET_ERROR:
8675 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8676 gdbarch_register_name (regcache->arch (), reg->regnum),
8677 buf);
8678 }
8679
8680 /* If this register is unfetchable, tell the regcache. */
8681 if (buf[0] == 'x')
8682 {
8683 regcache->raw_supply (reg->regnum, NULL);
8684 return 1;
8685 }
8686
8687 /* Otherwise, parse and supply the value. */
8688 p = buf;
8689 i = 0;
8690 while (p[0] != 0)
8691 {
8692 if (p[1] == 0)
8693 error (_("fetch_register_using_p: early buf termination"));
8694
8695 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8696 p += 2;
8697 }
8698 regcache->raw_supply (reg->regnum, regp);
8699 return 1;
8700 }
8701
8702 /* Fetch the registers included in the target's 'g' packet. */
8703
8704 int
8705 remote_target::send_g_packet ()
8706 {
8707 struct remote_state *rs = get_remote_state ();
8708 int buf_len;
8709
8710 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8711 putpkt (rs->buf);
8712 getpkt (&rs->buf);
8713 if (packet_check_result (rs->buf) == PACKET_ERROR)
8714 error (_("Could not read registers; remote failure reply '%s'"),
8715 rs->buf.data ());
8716
8717 /* We can get out of synch in various cases. If the first character
8718 in the buffer is not a hex character, assume that has happened
8719 and try to fetch another packet to read. */
8720 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8721 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8722 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8723 && rs->buf[0] != 'x') /* New: unavailable register value. */
8724 {
8725 remote_debug_printf ("Bad register packet; fetching a new packet");
8726 getpkt (&rs->buf);
8727 }
8728
8729 buf_len = strlen (rs->buf.data ());
8730
8731 /* Sanity check the received packet. */
8732 if (buf_len % 2 != 0)
8733 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8734
8735 return buf_len / 2;
8736 }
8737
8738 void
8739 remote_target::process_g_packet (struct regcache *regcache)
8740 {
8741 struct gdbarch *gdbarch = regcache->arch ();
8742 struct remote_state *rs = get_remote_state ();
8743 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8744 int i, buf_len;
8745 char *p;
8746 char *regs;
8747
8748 buf_len = strlen (rs->buf.data ());
8749
8750 /* Further sanity checks, with knowledge of the architecture. */
8751 if (buf_len > 2 * rsa->sizeof_g_packet)
8752 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8753 "bytes): %s"),
8754 rsa->sizeof_g_packet, buf_len / 2,
8755 rs->buf.data ());
8756
8757 /* Save the size of the packet sent to us by the target. It is used
8758 as a heuristic when determining the max size of packets that the
8759 target can safely receive. */
8760 if (rsa->actual_register_packet_size == 0)
8761 rsa->actual_register_packet_size = buf_len;
8762
8763 /* If this is smaller than we guessed the 'g' packet would be,
8764 update our records. A 'g' reply that doesn't include a register's
8765 value implies either that the register is not available, or that
8766 the 'p' packet must be used. */
8767 if (buf_len < 2 * rsa->sizeof_g_packet)
8768 {
8769 long sizeof_g_packet = buf_len / 2;
8770
8771 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8772 {
8773 long offset = rsa->regs[i].offset;
8774 long reg_size = register_size (gdbarch, i);
8775
8776 if (rsa->regs[i].pnum == -1)
8777 continue;
8778
8779 if (offset >= sizeof_g_packet)
8780 rsa->regs[i].in_g_packet = 0;
8781 else if (offset + reg_size > sizeof_g_packet)
8782 error (_("Truncated register %d in remote 'g' packet"), i);
8783 else
8784 rsa->regs[i].in_g_packet = 1;
8785 }
8786
8787 /* Looks valid enough, we can assume this is the correct length
8788 for a 'g' packet. It's important not to adjust
8789 rsa->sizeof_g_packet if we have truncated registers otherwise
8790 this "if" won't be run the next time the method is called
8791 with a packet of the same size and one of the internal errors
8792 below will trigger instead. */
8793 rsa->sizeof_g_packet = sizeof_g_packet;
8794 }
8795
8796 regs = (char *) alloca (rsa->sizeof_g_packet);
8797
8798 /* Unimplemented registers read as all bits zero. */
8799 memset (regs, 0, rsa->sizeof_g_packet);
8800
8801 /* Reply describes registers byte by byte, each byte encoded as two
8802 hex characters. Suck them all up, then supply them to the
8803 register cacheing/storage mechanism. */
8804
8805 p = rs->buf.data ();
8806 for (i = 0; i < rsa->sizeof_g_packet; i++)
8807 {
8808 if (p[0] == 0 || p[1] == 0)
8809 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8810 internal_error (_("unexpected end of 'g' packet reply"));
8811
8812 if (p[0] == 'x' && p[1] == 'x')
8813 regs[i] = 0; /* 'x' */
8814 else
8815 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8816 p += 2;
8817 }
8818
8819 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8820 {
8821 struct packet_reg *r = &rsa->regs[i];
8822 long reg_size = register_size (gdbarch, i);
8823
8824 if (r->in_g_packet)
8825 {
8826 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8827 /* This shouldn't happen - we adjusted in_g_packet above. */
8828 internal_error (_("unexpected end of 'g' packet reply"));
8829 else if (rs->buf[r->offset * 2] == 'x')
8830 {
8831 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8832 /* The register isn't available, mark it as such (at
8833 the same time setting the value to zero). */
8834 regcache->raw_supply (r->regnum, NULL);
8835 }
8836 else
8837 regcache->raw_supply (r->regnum, regs + r->offset);
8838 }
8839 }
8840 }
8841
8842 void
8843 remote_target::fetch_registers_using_g (struct regcache *regcache)
8844 {
8845 send_g_packet ();
8846 process_g_packet (regcache);
8847 }
8848
8849 /* Make the remote selected traceframe match GDB's selected
8850 traceframe. */
8851
8852 void
8853 remote_target::set_remote_traceframe ()
8854 {
8855 int newnum;
8856 struct remote_state *rs = get_remote_state ();
8857
8858 if (rs->remote_traceframe_number == get_traceframe_number ())
8859 return;
8860
8861 /* Avoid recursion, remote_trace_find calls us again. */
8862 rs->remote_traceframe_number = get_traceframe_number ();
8863
8864 newnum = target_trace_find (tfind_number,
8865 get_traceframe_number (), 0, 0, NULL);
8866
8867 /* Should not happen. If it does, all bets are off. */
8868 if (newnum != get_traceframe_number ())
8869 warning (_("could not set remote traceframe"));
8870 }
8871
8872 void
8873 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8874 {
8875 struct gdbarch *gdbarch = regcache->arch ();
8876 struct remote_state *rs = get_remote_state ();
8877 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8878 int i;
8879
8880 set_remote_traceframe ();
8881 set_general_thread (regcache->ptid ());
8882
8883 if (regnum >= 0)
8884 {
8885 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8886
8887 gdb_assert (reg != NULL);
8888
8889 /* If this register might be in the 'g' packet, try that first -
8890 we are likely to read more than one register. If this is the
8891 first 'g' packet, we might be overly optimistic about its
8892 contents, so fall back to 'p'. */
8893 if (reg->in_g_packet)
8894 {
8895 fetch_registers_using_g (regcache);
8896 if (reg->in_g_packet)
8897 return;
8898 }
8899
8900 if (fetch_register_using_p (regcache, reg))
8901 return;
8902
8903 /* This register is not available. */
8904 regcache->raw_supply (reg->regnum, NULL);
8905
8906 return;
8907 }
8908
8909 fetch_registers_using_g (regcache);
8910
8911 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8912 if (!rsa->regs[i].in_g_packet)
8913 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8914 {
8915 /* This register is not available. */
8916 regcache->raw_supply (i, NULL);
8917 }
8918 }
8919
8920 /* Prepare to store registers. Since we may send them all (using a
8921 'G' request), we have to read out the ones we don't want to change
8922 first. */
8923
8924 void
8925 remote_target::prepare_to_store (struct regcache *regcache)
8926 {
8927 struct remote_state *rs = get_remote_state ();
8928 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8929 int i;
8930
8931 /* Make sure the entire registers array is valid. */
8932 switch (m_features.packet_support (PACKET_P))
8933 {
8934 case PACKET_DISABLE:
8935 case PACKET_SUPPORT_UNKNOWN:
8936 /* Make sure all the necessary registers are cached. */
8937 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8938 if (rsa->regs[i].in_g_packet)
8939 regcache->raw_update (rsa->regs[i].regnum);
8940 break;
8941 case PACKET_ENABLE:
8942 break;
8943 }
8944 }
8945
8946 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8947 packet was not recognized. */
8948
8949 int
8950 remote_target::store_register_using_P (const struct regcache *regcache,
8951 packet_reg *reg)
8952 {
8953 struct gdbarch *gdbarch = regcache->arch ();
8954 struct remote_state *rs = get_remote_state ();
8955 /* Try storing a single register. */
8956 char *buf = rs->buf.data ();
8957 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8958 char *p;
8959
8960 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8961 return 0;
8962
8963 if (reg->pnum == -1)
8964 return 0;
8965
8966 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8967 p = buf + strlen (buf);
8968 regcache->raw_collect (reg->regnum, regp);
8969 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8970 putpkt (rs->buf);
8971 getpkt (&rs->buf);
8972
8973 switch (m_features.packet_ok (rs->buf, PACKET_P))
8974 {
8975 case PACKET_OK:
8976 return 1;
8977 case PACKET_ERROR:
8978 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8979 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8980 case PACKET_UNKNOWN:
8981 return 0;
8982 default:
8983 internal_error (_("Bad result from packet_ok"));
8984 }
8985 }
8986
8987 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8988 contents of the register cache buffer. FIXME: ignores errors. */
8989
8990 void
8991 remote_target::store_registers_using_G (const struct regcache *regcache)
8992 {
8993 struct remote_state *rs = get_remote_state ();
8994 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8995 gdb_byte *regs;
8996 char *p;
8997
8998 /* Extract all the registers in the regcache copying them into a
8999 local buffer. */
9000 {
9001 int i;
9002
9003 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9004 memset (regs, 0, rsa->sizeof_g_packet);
9005 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9006 {
9007 struct packet_reg *r = &rsa->regs[i];
9008
9009 if (r->in_g_packet)
9010 regcache->raw_collect (r->regnum, regs + r->offset);
9011 }
9012 }
9013
9014 /* Command describes registers byte by byte,
9015 each byte encoded as two hex characters. */
9016 p = rs->buf.data ();
9017 *p++ = 'G';
9018 bin2hex (regs, p, rsa->sizeof_g_packet);
9019 putpkt (rs->buf);
9020 getpkt (&rs->buf);
9021 if (packet_check_result (rs->buf) == PACKET_ERROR)
9022 error (_("Could not write registers; remote failure reply '%s'"),
9023 rs->buf.data ());
9024 }
9025
9026 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9027 of the register cache buffer. FIXME: ignores errors. */
9028
9029 void
9030 remote_target::store_registers (struct regcache *regcache, int regnum)
9031 {
9032 struct gdbarch *gdbarch = regcache->arch ();
9033 struct remote_state *rs = get_remote_state ();
9034 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9035 int i;
9036
9037 set_remote_traceframe ();
9038 set_general_thread (regcache->ptid ());
9039
9040 if (regnum >= 0)
9041 {
9042 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9043
9044 gdb_assert (reg != NULL);
9045
9046 /* Always prefer to store registers using the 'P' packet if
9047 possible; we often change only a small number of registers.
9048 Sometimes we change a larger number; we'd need help from a
9049 higher layer to know to use 'G'. */
9050 if (store_register_using_P (regcache, reg))
9051 return;
9052
9053 /* For now, don't complain if we have no way to write the
9054 register. GDB loses track of unavailable registers too
9055 easily. Some day, this may be an error. We don't have
9056 any way to read the register, either... */
9057 if (!reg->in_g_packet)
9058 return;
9059
9060 store_registers_using_G (regcache);
9061 return;
9062 }
9063
9064 store_registers_using_G (regcache);
9065
9066 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9067 if (!rsa->regs[i].in_g_packet)
9068 if (!store_register_using_P (regcache, &rsa->regs[i]))
9069 /* See above for why we do not issue an error here. */
9070 continue;
9071 }
9072 \f
9073
9074 /* Return the number of hex digits in num. */
9075
9076 static int
9077 hexnumlen (ULONGEST num)
9078 {
9079 int i;
9080
9081 for (i = 0; num != 0; i++)
9082 num >>= 4;
9083
9084 return std::max (i, 1);
9085 }
9086
9087 /* Set BUF to the minimum number of hex digits representing NUM. */
9088
9089 static int
9090 hexnumstr (char *buf, ULONGEST num)
9091 {
9092 int len = hexnumlen (num);
9093
9094 return hexnumnstr (buf, num, len);
9095 }
9096
9097
9098 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9099
9100 static int
9101 hexnumnstr (char *buf, ULONGEST num, int width)
9102 {
9103 int i;
9104
9105 buf[width] = '\0';
9106
9107 for (i = width - 1; i >= 0; i--)
9108 {
9109 buf[i] = "0123456789abcdef"[(num & 0xf)];
9110 num >>= 4;
9111 }
9112
9113 return width;
9114 }
9115
9116 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9117
9118 static CORE_ADDR
9119 remote_address_masked (CORE_ADDR addr)
9120 {
9121 unsigned int address_size = remote_address_size;
9122
9123 /* If "remoteaddresssize" was not set, default to target address size. */
9124 if (!address_size)
9125 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9126
9127 if (address_size > 0
9128 && address_size < (sizeof (ULONGEST) * 8))
9129 {
9130 /* Only create a mask when that mask can safely be constructed
9131 in a ULONGEST variable. */
9132 ULONGEST mask = 1;
9133
9134 mask = (mask << address_size) - 1;
9135 addr &= mask;
9136 }
9137 return addr;
9138 }
9139
9140 /* Determine whether the remote target supports binary downloading.
9141 This is accomplished by sending a no-op memory write of zero length
9142 to the target at the specified address. It does not suffice to send
9143 the whole packet, since many stubs strip the eighth bit and
9144 subsequently compute a wrong checksum, which causes real havoc with
9145 remote_write_bytes.
9146
9147 NOTE: This can still lose if the serial line is not eight-bit
9148 clean. In cases like this, the user should clear "remote
9149 X-packet". */
9150
9151 void
9152 remote_target::check_binary_download (CORE_ADDR addr)
9153 {
9154 struct remote_state *rs = get_remote_state ();
9155
9156 switch (m_features.packet_support (PACKET_X))
9157 {
9158 case PACKET_DISABLE:
9159 break;
9160 case PACKET_ENABLE:
9161 break;
9162 case PACKET_SUPPORT_UNKNOWN:
9163 {
9164 char *p;
9165
9166 p = rs->buf.data ();
9167 *p++ = 'X';
9168 p += hexnumstr (p, (ULONGEST) addr);
9169 *p++ = ',';
9170 p += hexnumstr (p, (ULONGEST) 0);
9171 *p++ = ':';
9172 *p = '\0';
9173
9174 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9175 getpkt (&rs->buf);
9176
9177 if (rs->buf[0] == '\0')
9178 {
9179 remote_debug_printf ("binary downloading NOT supported by target");
9180 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9181 }
9182 else
9183 {
9184 remote_debug_printf ("binary downloading supported by target");
9185 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9186 }
9187 break;
9188 }
9189 }
9190 }
9191
9192 /* Helper function to resize the payload in order to try to get a good
9193 alignment. We try to write an amount of data such that the next write will
9194 start on an address aligned on REMOTE_ALIGN_WRITES. */
9195
9196 static int
9197 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9198 {
9199 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9200 }
9201
9202 /* Write memory data directly to the remote machine.
9203 This does not inform the data cache; the data cache uses this.
9204 HEADER is the starting part of the packet.
9205 MEMADDR is the address in the remote memory space.
9206 MYADDR is the address of the buffer in our space.
9207 LEN_UNITS is the number of addressable units to write.
9208 UNIT_SIZE is the length in bytes of an addressable unit.
9209 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9210 should send data as binary ('X'), or hex-encoded ('M').
9211
9212 The function creates packet of the form
9213 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9214
9215 where encoding of <DATA> is terminated by PACKET_FORMAT.
9216
9217 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9218 are omitted.
9219
9220 Return the transferred status, error or OK (an
9221 'enum target_xfer_status' value). Save the number of addressable units
9222 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9223
9224 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9225 exchange between gdb and the stub could look like (?? in place of the
9226 checksum):
9227
9228 -> $m1000,4#??
9229 <- aaaabbbbccccdddd
9230
9231 -> $M1000,3:eeeeffffeeee#??
9232 <- OK
9233
9234 -> $m1000,4#??
9235 <- eeeeffffeeeedddd */
9236
9237 target_xfer_status
9238 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9239 const gdb_byte *myaddr,
9240 ULONGEST len_units,
9241 int unit_size,
9242 ULONGEST *xfered_len_units,
9243 char packet_format, int use_length)
9244 {
9245 struct remote_state *rs = get_remote_state ();
9246 char *p;
9247 char *plen = NULL;
9248 int plenlen = 0;
9249 int todo_units;
9250 int units_written;
9251 int payload_capacity_bytes;
9252 int payload_length_bytes;
9253
9254 if (packet_format != 'X' && packet_format != 'M')
9255 internal_error (_("remote_write_bytes_aux: bad packet format"));
9256
9257 if (len_units == 0)
9258 return TARGET_XFER_EOF;
9259
9260 payload_capacity_bytes = get_memory_write_packet_size ();
9261
9262 /* The packet buffer will be large enough for the payload;
9263 get_memory_packet_size ensures this. */
9264 rs->buf[0] = '\0';
9265
9266 /* Compute the size of the actual payload by subtracting out the
9267 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9268
9269 payload_capacity_bytes -= strlen ("$,:#NN");
9270 if (!use_length)
9271 /* The comma won't be used. */
9272 payload_capacity_bytes += 1;
9273 payload_capacity_bytes -= strlen (header);
9274 payload_capacity_bytes -= hexnumlen (memaddr);
9275
9276 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9277
9278 strcat (rs->buf.data (), header);
9279 p = rs->buf.data () + strlen (header);
9280
9281 /* Compute a best guess of the number of bytes actually transfered. */
9282 if (packet_format == 'X')
9283 {
9284 /* Best guess at number of bytes that will fit. */
9285 todo_units = std::min (len_units,
9286 (ULONGEST) payload_capacity_bytes / unit_size);
9287 if (use_length)
9288 payload_capacity_bytes -= hexnumlen (todo_units);
9289 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9290 }
9291 else
9292 {
9293 /* Number of bytes that will fit. */
9294 todo_units
9295 = std::min (len_units,
9296 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9297 if (use_length)
9298 payload_capacity_bytes -= hexnumlen (todo_units);
9299 todo_units = std::min (todo_units,
9300 (payload_capacity_bytes / unit_size) / 2);
9301 }
9302
9303 if (todo_units <= 0)
9304 internal_error (_("minimum packet size too small to write data"));
9305
9306 /* If we already need another packet, then try to align the end
9307 of this packet to a useful boundary. */
9308 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9309 todo_units = align_for_efficient_write (todo_units, memaddr);
9310
9311 /* Append "<memaddr>". */
9312 memaddr = remote_address_masked (memaddr);
9313 p += hexnumstr (p, (ULONGEST) memaddr);
9314
9315 if (use_length)
9316 {
9317 /* Append ",". */
9318 *p++ = ',';
9319
9320 /* Append the length and retain its location and size. It may need to be
9321 adjusted once the packet body has been created. */
9322 plen = p;
9323 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9324 p += plenlen;
9325 }
9326
9327 /* Append ":". */
9328 *p++ = ':';
9329 *p = '\0';
9330
9331 /* Append the packet body. */
9332 if (packet_format == 'X')
9333 {
9334 /* Binary mode. Send target system values byte by byte, in
9335 increasing byte addresses. Only escape certain critical
9336 characters. */
9337 payload_length_bytes =
9338 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9339 &units_written, payload_capacity_bytes);
9340
9341 /* If not all TODO units fit, then we'll need another packet. Make
9342 a second try to keep the end of the packet aligned. Don't do
9343 this if the packet is tiny. */
9344 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9345 {
9346 int new_todo_units;
9347
9348 new_todo_units = align_for_efficient_write (units_written, memaddr);
9349
9350 if (new_todo_units != units_written)
9351 payload_length_bytes =
9352 remote_escape_output (myaddr, new_todo_units, unit_size,
9353 (gdb_byte *) p, &units_written,
9354 payload_capacity_bytes);
9355 }
9356
9357 p += payload_length_bytes;
9358 if (use_length && units_written < todo_units)
9359 {
9360 /* Escape chars have filled up the buffer prematurely,
9361 and we have actually sent fewer units than planned.
9362 Fix-up the length field of the packet. Use the same
9363 number of characters as before. */
9364 plen += hexnumnstr (plen, (ULONGEST) units_written,
9365 plenlen);
9366 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9367 }
9368 }
9369 else
9370 {
9371 /* Normal mode: Send target system values byte by byte, in
9372 increasing byte addresses. Each byte is encoded as a two hex
9373 value. */
9374 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9375 units_written = todo_units;
9376 }
9377
9378 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9379 getpkt (&rs->buf);
9380
9381 if (rs->buf[0] == 'E')
9382 return TARGET_XFER_E_IO;
9383
9384 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9385 send fewer units than we'd planned. */
9386 *xfered_len_units = (ULONGEST) units_written;
9387 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9388 }
9389
9390 /* Write memory data directly to the remote machine.
9391 This does not inform the data cache; the data cache uses this.
9392 MEMADDR is the address in the remote memory space.
9393 MYADDR is the address of the buffer in our space.
9394 LEN is the number of bytes.
9395
9396 Return the transferred status, error or OK (an
9397 'enum target_xfer_status' value). Save the number of bytes
9398 transferred in *XFERED_LEN. Only transfer a single packet. */
9399
9400 target_xfer_status
9401 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9402 ULONGEST len, int unit_size,
9403 ULONGEST *xfered_len)
9404 {
9405 const char *packet_format = NULL;
9406
9407 /* Check whether the target supports binary download. */
9408 check_binary_download (memaddr);
9409
9410 switch (m_features.packet_support (PACKET_X))
9411 {
9412 case PACKET_ENABLE:
9413 packet_format = "X";
9414 break;
9415 case PACKET_DISABLE:
9416 packet_format = "M";
9417 break;
9418 case PACKET_SUPPORT_UNKNOWN:
9419 internal_error (_("remote_write_bytes: bad internal state"));
9420 default:
9421 internal_error (_("bad switch"));
9422 }
9423
9424 return remote_write_bytes_aux (packet_format,
9425 memaddr, myaddr, len, unit_size, xfered_len,
9426 packet_format[0], 1);
9427 }
9428
9429 /* Read memory data directly from the remote machine.
9430 This does not use the data cache; the data cache uses this.
9431 MEMADDR is the address in the remote memory space.
9432 MYADDR is the address of the buffer in our space.
9433 LEN_UNITS is the number of addressable memory units to read..
9434 UNIT_SIZE is the length in bytes of an addressable unit.
9435
9436 Return the transferred status, error or OK (an
9437 'enum target_xfer_status' value). Save the number of bytes
9438 transferred in *XFERED_LEN_UNITS.
9439
9440 See the comment of remote_write_bytes_aux for an example of
9441 memory read/write exchange between gdb and the stub. */
9442
9443 target_xfer_status
9444 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9445 ULONGEST len_units,
9446 int unit_size, ULONGEST *xfered_len_units)
9447 {
9448 struct remote_state *rs = get_remote_state ();
9449 int buf_size_bytes; /* Max size of packet output buffer. */
9450 char *p;
9451 int todo_units;
9452 int decoded_bytes;
9453
9454 buf_size_bytes = get_memory_read_packet_size ();
9455 /* The packet buffer will be large enough for the payload;
9456 get_memory_packet_size ensures this. */
9457
9458 /* Number of units that will fit. */
9459 todo_units = std::min (len_units,
9460 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9461
9462 /* Construct "m"<memaddr>","<len>". */
9463 memaddr = remote_address_masked (memaddr);
9464 p = rs->buf.data ();
9465 *p++ = 'm';
9466 p += hexnumstr (p, (ULONGEST) memaddr);
9467 *p++ = ',';
9468 p += hexnumstr (p, (ULONGEST) todo_units);
9469 *p = '\0';
9470 putpkt (rs->buf);
9471 getpkt (&rs->buf);
9472 if (rs->buf[0] == 'E'
9473 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9474 && rs->buf[3] == '\0')
9475 return TARGET_XFER_E_IO;
9476 /* Reply describes memory byte by byte, each byte encoded as two hex
9477 characters. */
9478 p = rs->buf.data ();
9479 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9480 /* Return what we have. Let higher layers handle partial reads. */
9481 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9482 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9483 }
9484
9485 /* Using the set of read-only target sections of remote, read live
9486 read-only memory.
9487
9488 For interface/parameters/return description see target.h,
9489 to_xfer_partial. */
9490
9491 target_xfer_status
9492 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9493 ULONGEST memaddr,
9494 ULONGEST len,
9495 int unit_size,
9496 ULONGEST *xfered_len)
9497 {
9498 const struct target_section *secp;
9499
9500 secp = target_section_by_addr (this, memaddr);
9501 if (secp != NULL
9502 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9503 {
9504 ULONGEST memend = memaddr + len;
9505
9506 const std::vector<target_section> *table
9507 = target_get_section_table (this);
9508 for (const target_section &p : *table)
9509 {
9510 if (memaddr >= p.addr)
9511 {
9512 if (memend <= p.endaddr)
9513 {
9514 /* Entire transfer is within this section. */
9515 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9516 xfered_len);
9517 }
9518 else if (memaddr >= p.endaddr)
9519 {
9520 /* This section ends before the transfer starts. */
9521 continue;
9522 }
9523 else
9524 {
9525 /* This section overlaps the transfer. Just do half. */
9526 len = p.endaddr - memaddr;
9527 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9528 xfered_len);
9529 }
9530 }
9531 }
9532 }
9533
9534 return TARGET_XFER_EOF;
9535 }
9536
9537 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9538 first if the requested memory is unavailable in traceframe.
9539 Otherwise, fall back to remote_read_bytes_1. */
9540
9541 target_xfer_status
9542 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9543 gdb_byte *myaddr, ULONGEST len, int unit_size,
9544 ULONGEST *xfered_len)
9545 {
9546 if (len == 0)
9547 return TARGET_XFER_EOF;
9548
9549 if (get_traceframe_number () != -1)
9550 {
9551 std::vector<mem_range> available;
9552
9553 /* If we fail to get the set of available memory, then the
9554 target does not support querying traceframe info, and so we
9555 attempt reading from the traceframe anyway (assuming the
9556 target implements the old QTro packet then). */
9557 if (traceframe_available_memory (&available, memaddr, len))
9558 {
9559 if (available.empty () || available[0].start != memaddr)
9560 {
9561 enum target_xfer_status res;
9562
9563 /* Don't read into the traceframe's available
9564 memory. */
9565 if (!available.empty ())
9566 {
9567 LONGEST oldlen = len;
9568
9569 len = available[0].start - memaddr;
9570 gdb_assert (len <= oldlen);
9571 }
9572
9573 /* This goes through the topmost target again. */
9574 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9575 len, unit_size, xfered_len);
9576 if (res == TARGET_XFER_OK)
9577 return TARGET_XFER_OK;
9578 else
9579 {
9580 /* No use trying further, we know some memory starting
9581 at MEMADDR isn't available. */
9582 *xfered_len = len;
9583 return (*xfered_len != 0) ?
9584 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9585 }
9586 }
9587
9588 /* Don't try to read more than how much is available, in
9589 case the target implements the deprecated QTro packet to
9590 cater for older GDBs (the target's knowledge of read-only
9591 sections may be outdated by now). */
9592 len = available[0].length;
9593 }
9594 }
9595
9596 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9597 }
9598
9599 \f
9600
9601 /* Sends a packet with content determined by the printf format string
9602 FORMAT and the remaining arguments, then gets the reply. Returns
9603 whether the packet was a success, a failure, or unknown. */
9604
9605 packet_result
9606 remote_target::remote_send_printf (const char *format, ...)
9607 {
9608 struct remote_state *rs = get_remote_state ();
9609 int max_size = get_remote_packet_size ();
9610 va_list ap;
9611
9612 va_start (ap, format);
9613
9614 rs->buf[0] = '\0';
9615 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9616
9617 va_end (ap);
9618
9619 if (size >= max_size)
9620 internal_error (_("Too long remote packet."));
9621
9622 if (putpkt (rs->buf) < 0)
9623 error (_("Communication problem with target."));
9624
9625 rs->buf[0] = '\0';
9626 getpkt (&rs->buf);
9627
9628 return packet_check_result (rs->buf);
9629 }
9630
9631 /* Flash writing can take quite some time. We'll set
9632 effectively infinite timeout for flash operations.
9633 In future, we'll need to decide on a better approach. */
9634 static const int remote_flash_timeout = 1000;
9635
9636 void
9637 remote_target::flash_erase (ULONGEST address, LONGEST length)
9638 {
9639 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9640 enum packet_result ret;
9641 scoped_restore restore_timeout
9642 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9643
9644 ret = remote_send_printf ("vFlashErase:%s,%s",
9645 phex (address, addr_size),
9646 phex (length, 4));
9647 switch (ret)
9648 {
9649 case PACKET_UNKNOWN:
9650 error (_("Remote target does not support flash erase"));
9651 case PACKET_ERROR:
9652 error (_("Error erasing flash with vFlashErase packet"));
9653 default:
9654 break;
9655 }
9656 }
9657
9658 target_xfer_status
9659 remote_target::remote_flash_write (ULONGEST address,
9660 ULONGEST length, ULONGEST *xfered_len,
9661 const gdb_byte *data)
9662 {
9663 scoped_restore restore_timeout
9664 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9665 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9666 xfered_len,'X', 0);
9667 }
9668
9669 void
9670 remote_target::flash_done ()
9671 {
9672 int ret;
9673
9674 scoped_restore restore_timeout
9675 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9676
9677 ret = remote_send_printf ("vFlashDone");
9678
9679 switch (ret)
9680 {
9681 case PACKET_UNKNOWN:
9682 error (_("Remote target does not support vFlashDone"));
9683 case PACKET_ERROR:
9684 error (_("Error finishing flash operation"));
9685 default:
9686 break;
9687 }
9688 }
9689
9690 \f
9691 /* Stuff for dealing with the packets which are part of this protocol.
9692 See comment at top of file for details. */
9693
9694 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9695 error to higher layers. Called when a serial error is detected.
9696 The exception message is STRING, followed by a colon and a blank,
9697 the system error message for errno at function entry and final dot
9698 for output compatibility with throw_perror_with_name. */
9699
9700 static void
9701 unpush_and_perror (remote_target *target, const char *string)
9702 {
9703 int saved_errno = errno;
9704
9705 remote_unpush_target (target);
9706 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9707 safe_strerror (saved_errno));
9708 }
9709
9710 /* Read a single character from the remote end. The current quit
9711 handler is overridden to avoid quitting in the middle of packet
9712 sequence, as that would break communication with the remote server.
9713 See remote_serial_quit_handler for more detail. */
9714
9715 int
9716 remote_target::readchar (int timeout)
9717 {
9718 int ch;
9719 struct remote_state *rs = get_remote_state ();
9720
9721 {
9722 scoped_restore restore_quit_target
9723 = make_scoped_restore (&curr_quit_handler_target, this);
9724 scoped_restore restore_quit
9725 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9726
9727 rs->got_ctrlc_during_io = 0;
9728
9729 ch = serial_readchar (rs->remote_desc, timeout);
9730
9731 if (rs->got_ctrlc_during_io)
9732 set_quit_flag ();
9733 }
9734
9735 if (ch >= 0)
9736 return ch;
9737
9738 switch ((enum serial_rc) ch)
9739 {
9740 case SERIAL_EOF:
9741 remote_unpush_target (this);
9742 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9743 /* no return */
9744 case SERIAL_ERROR:
9745 unpush_and_perror (this, _("Remote communication error. "
9746 "Target disconnected"));
9747 /* no return */
9748 case SERIAL_TIMEOUT:
9749 break;
9750 }
9751 return ch;
9752 }
9753
9754 /* Wrapper for serial_write that closes the target and throws if
9755 writing fails. The current quit handler is overridden to avoid
9756 quitting in the middle of packet sequence, as that would break
9757 communication with the remote server. See
9758 remote_serial_quit_handler for more detail. */
9759
9760 void
9761 remote_target::remote_serial_write (const char *str, int len)
9762 {
9763 struct remote_state *rs = get_remote_state ();
9764
9765 scoped_restore restore_quit_target
9766 = make_scoped_restore (&curr_quit_handler_target, this);
9767 scoped_restore restore_quit
9768 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9769
9770 rs->got_ctrlc_during_io = 0;
9771
9772 if (serial_write (rs->remote_desc, str, len))
9773 {
9774 unpush_and_perror (this, _("Remote communication error. "
9775 "Target disconnected"));
9776 }
9777
9778 if (rs->got_ctrlc_during_io)
9779 set_quit_flag ();
9780 }
9781
9782 /* Return a string representing an escaped version of BUF, of len N.
9783 E.g. \n is converted to \\n, \t to \\t, etc. */
9784
9785 static std::string
9786 escape_buffer (const char *buf, int n)
9787 {
9788 string_file stb;
9789
9790 stb.putstrn (buf, n, '\\');
9791 return stb.release ();
9792 }
9793
9794 int
9795 remote_target::putpkt (const char *buf)
9796 {
9797 return putpkt_binary (buf, strlen (buf));
9798 }
9799
9800 /* Wrapper around remote_target::putpkt to avoid exporting
9801 remote_target. */
9802
9803 int
9804 putpkt (remote_target *remote, const char *buf)
9805 {
9806 return remote->putpkt (buf);
9807 }
9808
9809 /* Send a packet to the remote machine, with error checking. The data
9810 of the packet is in BUF. The string in BUF can be at most
9811 get_remote_packet_size () - 5 to account for the $, # and checksum,
9812 and for a possible /0 if we are debugging (remote_debug) and want
9813 to print the sent packet as a string. */
9814
9815 int
9816 remote_target::putpkt_binary (const char *buf, int cnt)
9817 {
9818 struct remote_state *rs = get_remote_state ();
9819 int i;
9820 unsigned char csum = 0;
9821 gdb::def_vector<char> data (cnt + 6);
9822 char *buf2 = data.data ();
9823
9824 int ch;
9825 int tcount = 0;
9826 char *p;
9827
9828 /* Catch cases like trying to read memory or listing threads while
9829 we're waiting for a stop reply. The remote server wouldn't be
9830 ready to handle this request, so we'd hang and timeout. We don't
9831 have to worry about this in synchronous mode, because in that
9832 case it's not possible to issue a command while the target is
9833 running. This is not a problem in non-stop mode, because in that
9834 case, the stub is always ready to process serial input. */
9835 if (!target_is_non_stop_p ()
9836 && target_is_async_p ()
9837 && rs->waiting_for_stop_reply)
9838 {
9839 error (_("Cannot execute this command while the target is running.\n"
9840 "Use the \"interrupt\" command to stop the target\n"
9841 "and then try again."));
9842 }
9843
9844 /* Copy the packet into buffer BUF2, encapsulating it
9845 and giving it a checksum. */
9846
9847 p = buf2;
9848 *p++ = '$';
9849
9850 for (i = 0; i < cnt; i++)
9851 {
9852 csum += buf[i];
9853 *p++ = buf[i];
9854 }
9855 *p++ = '#';
9856 *p++ = tohex ((csum >> 4) & 0xf);
9857 *p++ = tohex (csum & 0xf);
9858
9859 /* Send it over and over until we get a positive ack. */
9860
9861 while (1)
9862 {
9863 if (remote_debug)
9864 {
9865 *p = '\0';
9866
9867 int len = (int) (p - buf2);
9868 int max_chars;
9869
9870 if (remote_packet_max_chars < 0)
9871 max_chars = len;
9872 else
9873 max_chars = remote_packet_max_chars;
9874
9875 std::string str
9876 = escape_buffer (buf2, std::min (len, max_chars));
9877
9878 if (len > max_chars)
9879 remote_debug_printf_nofunc
9880 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9881 len - max_chars);
9882 else
9883 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9884 }
9885 remote_serial_write (buf2, p - buf2);
9886
9887 /* If this is a no acks version of the remote protocol, send the
9888 packet and move on. */
9889 if (rs->noack_mode)
9890 break;
9891
9892 /* Read until either a timeout occurs (-2) or '+' is read.
9893 Handle any notification that arrives in the mean time. */
9894 while (1)
9895 {
9896 ch = readchar (remote_timeout);
9897
9898 switch (ch)
9899 {
9900 case '+':
9901 remote_debug_printf_nofunc ("Received Ack");
9902 return 1;
9903 case '-':
9904 remote_debug_printf_nofunc ("Received Nak");
9905 /* FALLTHROUGH */
9906 case SERIAL_TIMEOUT:
9907 tcount++;
9908 if (tcount > 3)
9909 return 0;
9910 break; /* Retransmit buffer. */
9911 case '$':
9912 {
9913 remote_debug_printf ("Packet instead of Ack, ignoring it");
9914 /* It's probably an old response sent because an ACK
9915 was lost. Gobble up the packet and ack it so it
9916 doesn't get retransmitted when we resend this
9917 packet. */
9918 skip_frame ();
9919 remote_serial_write ("+", 1);
9920 continue; /* Now, go look for +. */
9921 }
9922
9923 case '%':
9924 {
9925 int val;
9926
9927 /* If we got a notification, handle it, and go back to looking
9928 for an ack. */
9929 /* We've found the start of a notification. Now
9930 collect the data. */
9931 val = read_frame (&rs->buf);
9932 if (val >= 0)
9933 {
9934 remote_debug_printf_nofunc
9935 (" Notification received: %s",
9936 escape_buffer (rs->buf.data (), val).c_str ());
9937
9938 handle_notification (rs->notif_state, rs->buf.data ());
9939 /* We're in sync now, rewait for the ack. */
9940 tcount = 0;
9941 }
9942 else
9943 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9944 rs->buf.data ());
9945 continue;
9946 }
9947 /* fall-through */
9948 default:
9949 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9950 rs->buf.data ());
9951 continue;
9952 }
9953 break; /* Here to retransmit. */
9954 }
9955
9956 #if 0
9957 /* This is wrong. If doing a long backtrace, the user should be
9958 able to get out next time we call QUIT, without anything as
9959 violent as interrupt_query. If we want to provide a way out of
9960 here without getting to the next QUIT, it should be based on
9961 hitting ^C twice as in remote_wait. */
9962 if (quit_flag)
9963 {
9964 quit_flag = 0;
9965 interrupt_query ();
9966 }
9967 #endif
9968 }
9969
9970 return 0;
9971 }
9972
9973 /* Come here after finding the start of a frame when we expected an
9974 ack. Do our best to discard the rest of this packet. */
9975
9976 void
9977 remote_target::skip_frame ()
9978 {
9979 int c;
9980
9981 while (1)
9982 {
9983 c = readchar (remote_timeout);
9984 switch (c)
9985 {
9986 case SERIAL_TIMEOUT:
9987 /* Nothing we can do. */
9988 return;
9989 case '#':
9990 /* Discard the two bytes of checksum and stop. */
9991 c = readchar (remote_timeout);
9992 if (c >= 0)
9993 c = readchar (remote_timeout);
9994
9995 return;
9996 case '*': /* Run length encoding. */
9997 /* Discard the repeat count. */
9998 c = readchar (remote_timeout);
9999 if (c < 0)
10000 return;
10001 break;
10002 default:
10003 /* A regular character. */
10004 break;
10005 }
10006 }
10007 }
10008
10009 /* Come here after finding the start of the frame. Collect the rest
10010 into *BUF, verifying the checksum, length, and handling run-length
10011 compression. NUL terminate the buffer. If there is not enough room,
10012 expand *BUF.
10013
10014 Returns -1 on error, number of characters in buffer (ignoring the
10015 trailing NULL) on success. (could be extended to return one of the
10016 SERIAL status indications). */
10017
10018 long
10019 remote_target::read_frame (gdb::char_vector *buf_p)
10020 {
10021 unsigned char csum;
10022 long bc;
10023 int c;
10024 char *buf = buf_p->data ();
10025 struct remote_state *rs = get_remote_state ();
10026
10027 csum = 0;
10028 bc = 0;
10029
10030 while (1)
10031 {
10032 c = readchar (remote_timeout);
10033 switch (c)
10034 {
10035 case SERIAL_TIMEOUT:
10036 remote_debug_printf ("Timeout in mid-packet, retrying");
10037 return -1;
10038
10039 case '$':
10040 remote_debug_printf ("Saw new packet start in middle of old one");
10041 return -1; /* Start a new packet, count retries. */
10042
10043 case '#':
10044 {
10045 unsigned char pktcsum;
10046 int check_0 = 0;
10047 int check_1 = 0;
10048
10049 buf[bc] = '\0';
10050
10051 check_0 = readchar (remote_timeout);
10052 if (check_0 >= 0)
10053 check_1 = readchar (remote_timeout);
10054
10055 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10056 {
10057 remote_debug_printf ("Timeout in checksum, retrying");
10058 return -1;
10059 }
10060 else if (check_0 < 0 || check_1 < 0)
10061 {
10062 remote_debug_printf ("Communication error in checksum");
10063 return -1;
10064 }
10065
10066 /* Don't recompute the checksum; with no ack packets we
10067 don't have any way to indicate a packet retransmission
10068 is necessary. */
10069 if (rs->noack_mode)
10070 return bc;
10071
10072 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10073 if (csum == pktcsum)
10074 return bc;
10075
10076 remote_debug_printf
10077 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10078 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10079
10080 /* Number of characters in buffer ignoring trailing
10081 NULL. */
10082 return -1;
10083 }
10084 case '*': /* Run length encoding. */
10085 {
10086 int repeat;
10087
10088 csum += c;
10089 c = readchar (remote_timeout);
10090 csum += c;
10091 repeat = c - ' ' + 3; /* Compute repeat count. */
10092
10093 /* The character before ``*'' is repeated. */
10094
10095 if (repeat > 0 && repeat <= 255 && bc > 0)
10096 {
10097 if (bc + repeat - 1 >= buf_p->size () - 1)
10098 {
10099 /* Make some more room in the buffer. */
10100 buf_p->resize (buf_p->size () + repeat);
10101 buf = buf_p->data ();
10102 }
10103
10104 memset (&buf[bc], buf[bc - 1], repeat);
10105 bc += repeat;
10106 continue;
10107 }
10108
10109 buf[bc] = '\0';
10110 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10111 return -1;
10112 }
10113 default:
10114 if (bc >= buf_p->size () - 1)
10115 {
10116 /* Make some more room in the buffer. */
10117 buf_p->resize (buf_p->size () * 2);
10118 buf = buf_p->data ();
10119 }
10120
10121 buf[bc++] = c;
10122 csum += c;
10123 continue;
10124 }
10125 }
10126 }
10127
10128 /* Set this to the maximum number of seconds to wait instead of waiting forever
10129 in target_wait(). If this timer times out, then it generates an error and
10130 the command is aborted. This replaces most of the need for timeouts in the
10131 GDB test suite, and makes it possible to distinguish between a hung target
10132 and one with slow communications. */
10133
10134 static int watchdog = 0;
10135 static void
10136 show_watchdog (struct ui_file *file, int from_tty,
10137 struct cmd_list_element *c, const char *value)
10138 {
10139 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10140 }
10141
10142 /* Read a packet from the remote machine, with error checking, and
10143 store it in *BUF. Resize *BUF if necessary to hold the result. If
10144 FOREVER, wait forever rather than timing out; this is used (in
10145 synchronous mode) to wait for a target that is is executing user
10146 code to stop. If FOREVER == false, this function is allowed to time
10147 out gracefully and return an indication of this to the caller.
10148 Otherwise return the number of bytes read. If IS_NOTIF is not
10149 NULL, then consider receiving a notification enough reason to
10150 return to the caller. In this case, *IS_NOTIF is an output boolean
10151 that indicates whether *BUF holds a notification or not (a regular
10152 packet). */
10153
10154 int
10155 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10156 {
10157 struct remote_state *rs = get_remote_state ();
10158 int c;
10159 int tries;
10160 int timeout;
10161 int val = -1;
10162
10163 strcpy (buf->data (), "timeout");
10164
10165 if (forever)
10166 timeout = watchdog > 0 ? watchdog : -1;
10167 else if (is_notif != nullptr)
10168 timeout = 0; /* There should already be a char in the buffer. If
10169 not, bail out. */
10170 else
10171 timeout = remote_timeout;
10172
10173 #define MAX_TRIES 3
10174
10175 /* Process any number of notifications, and then return when
10176 we get a packet. */
10177 for (;;)
10178 {
10179 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10180 times. */
10181 for (tries = 1; tries <= MAX_TRIES; tries++)
10182 {
10183 /* This can loop forever if the remote side sends us
10184 characters continuously, but if it pauses, we'll get
10185 SERIAL_TIMEOUT from readchar because of timeout. Then
10186 we'll count that as a retry.
10187
10188 Note that even when forever is set, we will only wait
10189 forever prior to the start of a packet. After that, we
10190 expect characters to arrive at a brisk pace. They should
10191 show up within remote_timeout intervals. */
10192 do
10193 c = readchar (timeout);
10194 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10195
10196 if (c == SERIAL_TIMEOUT)
10197 {
10198 if (is_notif != nullptr)
10199 return -1; /* Don't complain, it's normal to not get
10200 anything in this case. */
10201
10202 if (forever) /* Watchdog went off? Kill the target. */
10203 {
10204 remote_unpush_target (this);
10205 throw_error (TARGET_CLOSE_ERROR,
10206 _("Watchdog timeout has expired. "
10207 "Target detached."));
10208 }
10209
10210 remote_debug_printf ("Timed out.");
10211 }
10212 else
10213 {
10214 /* We've found the start of a packet or notification.
10215 Now collect the data. */
10216 val = read_frame (buf);
10217 if (val >= 0)
10218 break;
10219 }
10220
10221 remote_serial_write ("-", 1);
10222 }
10223
10224 if (tries > MAX_TRIES)
10225 {
10226 /* We have tried hard enough, and just can't receive the
10227 packet/notification. Give up. */
10228 gdb_printf (_("Ignoring packet error, continuing...\n"));
10229
10230 /* Skip the ack char if we're in no-ack mode. */
10231 if (!rs->noack_mode)
10232 remote_serial_write ("+", 1);
10233 return -1;
10234 }
10235
10236 /* If we got an ordinary packet, return that to our caller. */
10237 if (c == '$')
10238 {
10239 if (remote_debug)
10240 {
10241 int max_chars;
10242
10243 if (remote_packet_max_chars < 0)
10244 max_chars = val;
10245 else
10246 max_chars = remote_packet_max_chars;
10247
10248 std::string str
10249 = escape_buffer (buf->data (),
10250 std::min (val, max_chars));
10251
10252 if (val > max_chars)
10253 remote_debug_printf_nofunc
10254 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10255 val - max_chars);
10256 else
10257 remote_debug_printf_nofunc ("Packet received: %s",
10258 str.c_str ());
10259 }
10260
10261 /* Skip the ack char if we're in no-ack mode. */
10262 if (!rs->noack_mode)
10263 remote_serial_write ("+", 1);
10264 if (is_notif != NULL)
10265 *is_notif = false;
10266 return val;
10267 }
10268
10269 /* If we got a notification, handle it, and go back to looking
10270 for a packet. */
10271 else
10272 {
10273 gdb_assert (c == '%');
10274
10275 remote_debug_printf_nofunc
10276 (" Notification received: %s",
10277 escape_buffer (buf->data (), val).c_str ());
10278
10279 if (is_notif != NULL)
10280 *is_notif = true;
10281
10282 handle_notification (rs->notif_state, buf->data ());
10283
10284 /* Notifications require no acknowledgement. */
10285
10286 if (is_notif != nullptr)
10287 return val;
10288 }
10289 }
10290 }
10291
10292 /* Kill any new fork children of inferior INF that haven't been
10293 processed by follow_fork. */
10294
10295 void
10296 remote_target::kill_new_fork_children (inferior *inf)
10297 {
10298 remote_state *rs = get_remote_state ();
10299 const notif_client *notif = &notif_client_stop;
10300
10301 /* Kill the fork child threads of any threads in inferior INF that are stopped
10302 at a fork event. */
10303 for (thread_info *thread : inf->non_exited_threads ())
10304 {
10305 const target_waitstatus *ws = thread_pending_fork_status (thread);
10306
10307 if (ws == nullptr)
10308 continue;
10309
10310 int child_pid = ws->child_ptid ().pid ();
10311 int res = remote_vkill (child_pid);
10312
10313 if (res != 0)
10314 error (_("Can't kill fork child process %d"), child_pid);
10315 }
10316
10317 /* Check for any pending fork events (not reported or processed yet)
10318 in inferior INF and kill those fork child threads as well. */
10319 remote_notif_get_pending_events (notif);
10320 for (auto &event : rs->stop_reply_queue)
10321 {
10322 if (event->ptid.pid () != inf->pid)
10323 continue;
10324
10325 if (!is_fork_status (event->ws.kind ()))
10326 continue;
10327
10328 int child_pid = event->ws.child_ptid ().pid ();
10329 int res = remote_vkill (child_pid);
10330
10331 if (res != 0)
10332 error (_("Can't kill fork child process %d"), child_pid);
10333 }
10334 }
10335
10336 \f
10337 /* Target hook to kill the current inferior. */
10338
10339 void
10340 remote_target::kill ()
10341 {
10342 int res = -1;
10343 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10344
10345 gdb_assert (inf != nullptr);
10346
10347 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10348 {
10349 /* If we're stopped while forking and we haven't followed yet,
10350 kill the child task. We need to do this before killing the
10351 parent task because if this is a vfork then the parent will
10352 be sleeping. */
10353 kill_new_fork_children (inf);
10354
10355 res = remote_vkill (inf->pid);
10356 if (res == 0)
10357 {
10358 target_mourn_inferior (inferior_ptid);
10359 return;
10360 }
10361 }
10362
10363 /* If we are in 'target remote' mode and we are killing the only
10364 inferior, then we will tell gdbserver to exit and unpush the
10365 target. */
10366 if (res == -1 && !m_features.remote_multi_process_p ()
10367 && number_of_live_inferiors (this) == 1)
10368 {
10369 remote_kill_k ();
10370
10371 /* We've killed the remote end, we get to mourn it. If we are
10372 not in extended mode, mourning the inferior also unpushes
10373 remote_ops from the target stack, which closes the remote
10374 connection. */
10375 target_mourn_inferior (inferior_ptid);
10376
10377 return;
10378 }
10379
10380 error (_("Can't kill process"));
10381 }
10382
10383 /* Send a kill request to the target using the 'vKill' packet. */
10384
10385 int
10386 remote_target::remote_vkill (int pid)
10387 {
10388 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10389 return -1;
10390
10391 remote_state *rs = get_remote_state ();
10392
10393 /* Tell the remote target to detach. */
10394 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10395 putpkt (rs->buf);
10396 getpkt (&rs->buf);
10397
10398 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10399 {
10400 case PACKET_OK:
10401 return 0;
10402 case PACKET_ERROR:
10403 return 1;
10404 case PACKET_UNKNOWN:
10405 return -1;
10406 default:
10407 internal_error (_("Bad result from packet_ok"));
10408 }
10409 }
10410
10411 /* Send a kill request to the target using the 'k' packet. */
10412
10413 void
10414 remote_target::remote_kill_k ()
10415 {
10416 /* Catch errors so the user can quit from gdb even when we
10417 aren't on speaking terms with the remote system. */
10418 try
10419 {
10420 putpkt ("k");
10421 }
10422 catch (const gdb_exception_error &ex)
10423 {
10424 if (ex.error == TARGET_CLOSE_ERROR)
10425 {
10426 /* If we got an (EOF) error that caused the target
10427 to go away, then we're done, that's what we wanted.
10428 "k" is susceptible to cause a premature EOF, given
10429 that the remote server isn't actually required to
10430 reply to "k", and it can happen that it doesn't
10431 even get to reply ACK to the "k". */
10432 return;
10433 }
10434
10435 /* Otherwise, something went wrong. We didn't actually kill
10436 the target. Just propagate the exception, and let the
10437 user or higher layers decide what to do. */
10438 throw;
10439 }
10440 }
10441
10442 void
10443 remote_target::mourn_inferior ()
10444 {
10445 struct remote_state *rs = get_remote_state ();
10446
10447 /* We're no longer interested in notification events of an inferior
10448 that exited or was killed/detached. */
10449 discard_pending_stop_replies (current_inferior ());
10450
10451 /* In 'target remote' mode with one inferior, we close the connection. */
10452 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10453 {
10454 remote_unpush_target (this);
10455 return;
10456 }
10457
10458 /* In case we got here due to an error, but we're going to stay
10459 connected. */
10460 rs->waiting_for_stop_reply = 0;
10461
10462 /* If the current general thread belonged to the process we just
10463 detached from or has exited, the remote side current general
10464 thread becomes undefined. Considering a case like this:
10465
10466 - We just got here due to a detach.
10467 - The process that we're detaching from happens to immediately
10468 report a global breakpoint being hit in non-stop mode, in the
10469 same thread we had selected before.
10470 - GDB attaches to this process again.
10471 - This event happens to be the next event we handle.
10472
10473 GDB would consider that the current general thread didn't need to
10474 be set on the stub side (with Hg), since for all it knew,
10475 GENERAL_THREAD hadn't changed.
10476
10477 Notice that although in all-stop mode, the remote server always
10478 sets the current thread to the thread reporting the stop event,
10479 that doesn't happen in non-stop mode; in non-stop, the stub *must
10480 not* change the current thread when reporting a breakpoint hit,
10481 due to the decoupling of event reporting and event handling.
10482
10483 To keep things simple, we always invalidate our notion of the
10484 current thread. */
10485 record_currthread (rs, minus_one_ptid);
10486
10487 /* Call common code to mark the inferior as not running. */
10488 generic_mourn_inferior ();
10489 }
10490
10491 bool
10492 extended_remote_target::supports_disable_randomization ()
10493 {
10494 return (m_features.packet_support (PACKET_QDisableRandomization)
10495 == PACKET_ENABLE);
10496 }
10497
10498 void
10499 remote_target::extended_remote_disable_randomization (int val)
10500 {
10501 struct remote_state *rs = get_remote_state ();
10502 char *reply;
10503
10504 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10505 "QDisableRandomization:%x", val);
10506 putpkt (rs->buf);
10507 reply = remote_get_noisy_reply ();
10508 if (*reply == '\0')
10509 error (_("Target does not support QDisableRandomization."));
10510 if (strcmp (reply, "OK") != 0)
10511 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10512 }
10513
10514 int
10515 remote_target::extended_remote_run (const std::string &args)
10516 {
10517 struct remote_state *rs = get_remote_state ();
10518 int len;
10519 const char *remote_exec_file = get_remote_exec_file ();
10520
10521 /* If the user has disabled vRun support, or we have detected that
10522 support is not available, do not try it. */
10523 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10524 return -1;
10525
10526 strcpy (rs->buf.data (), "vRun;");
10527 len = strlen (rs->buf.data ());
10528
10529 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10530 error (_("Remote file name too long for run packet"));
10531 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10532 strlen (remote_exec_file));
10533
10534 if (!args.empty ())
10535 {
10536 int i;
10537
10538 gdb_argv argv (args.c_str ());
10539 for (i = 0; argv[i] != NULL; i++)
10540 {
10541 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10542 error (_("Argument list too long for run packet"));
10543 rs->buf[len++] = ';';
10544 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10545 strlen (argv[i]));
10546 }
10547 }
10548
10549 rs->buf[len++] = '\0';
10550
10551 putpkt (rs->buf);
10552 getpkt (&rs->buf);
10553
10554 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10555 {
10556 case PACKET_OK:
10557 /* We have a wait response. All is well. */
10558 return 0;
10559 case PACKET_UNKNOWN:
10560 return -1;
10561 case PACKET_ERROR:
10562 if (remote_exec_file[0] == '\0')
10563 error (_("Running the default executable on the remote target failed; "
10564 "try \"set remote exec-file\"?"));
10565 else
10566 error (_("Running \"%s\" on the remote target failed"),
10567 remote_exec_file);
10568 default:
10569 gdb_assert_not_reached ("bad switch");
10570 }
10571 }
10572
10573 /* Helper function to send set/unset environment packets. ACTION is
10574 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10575 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10576 sent. */
10577
10578 void
10579 remote_target::send_environment_packet (const char *action,
10580 const char *packet,
10581 const char *value)
10582 {
10583 remote_state *rs = get_remote_state ();
10584
10585 /* Convert the environment variable to an hex string, which
10586 is the best format to be transmitted over the wire. */
10587 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10588 strlen (value));
10589
10590 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10591 "%s:%s", packet, encoded_value.c_str ());
10592
10593 putpkt (rs->buf);
10594 getpkt (&rs->buf);
10595 if (strcmp (rs->buf.data (), "OK") != 0)
10596 warning (_("Unable to %s environment variable '%s' on remote."),
10597 action, value);
10598 }
10599
10600 /* Helper function to handle the QEnvironment* packets. */
10601
10602 void
10603 remote_target::extended_remote_environment_support ()
10604 {
10605 remote_state *rs = get_remote_state ();
10606
10607 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10608 {
10609 putpkt ("QEnvironmentReset");
10610 getpkt (&rs->buf);
10611 if (strcmp (rs->buf.data (), "OK") != 0)
10612 warning (_("Unable to reset environment on remote."));
10613 }
10614
10615 gdb_environ *e = &current_inferior ()->environment;
10616
10617 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10618 != PACKET_DISABLE)
10619 {
10620 for (const std::string &el : e->user_set_env ())
10621 send_environment_packet ("set", "QEnvironmentHexEncoded",
10622 el.c_str ());
10623 }
10624
10625
10626 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10627 for (const std::string &el : e->user_unset_env ())
10628 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10629 }
10630
10631 /* Helper function to set the current working directory for the
10632 inferior in the remote target. */
10633
10634 void
10635 remote_target::extended_remote_set_inferior_cwd ()
10636 {
10637 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10638 {
10639 const std::string &inferior_cwd = current_inferior ()->cwd ();
10640 remote_state *rs = get_remote_state ();
10641
10642 if (!inferior_cwd.empty ())
10643 {
10644 std::string hexpath
10645 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10646 inferior_cwd.size ());
10647
10648 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10649 "QSetWorkingDir:%s", hexpath.c_str ());
10650 }
10651 else
10652 {
10653 /* An empty inferior_cwd means that the user wants us to
10654 reset the remote server's inferior's cwd. */
10655 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10656 "QSetWorkingDir:");
10657 }
10658
10659 putpkt (rs->buf);
10660 getpkt (&rs->buf);
10661 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10662 error (_("\
10663 Remote replied unexpectedly while setting the inferior's working\n\
10664 directory: %s"),
10665 rs->buf.data ());
10666
10667 }
10668 }
10669
10670 /* In the extended protocol we want to be able to do things like
10671 "run" and have them basically work as expected. So we need
10672 a special create_inferior function. We support changing the
10673 executable file and the command line arguments, but not the
10674 environment. */
10675
10676 void
10677 extended_remote_target::create_inferior (const char *exec_file,
10678 const std::string &args,
10679 char **env, int from_tty)
10680 {
10681 int run_worked;
10682 char *stop_reply;
10683 struct remote_state *rs = get_remote_state ();
10684 const char *remote_exec_file = get_remote_exec_file ();
10685
10686 /* If running asynchronously, register the target file descriptor
10687 with the event loop. */
10688 if (target_can_async_p ())
10689 target_async (true);
10690
10691 /* Disable address space randomization if requested (and supported). */
10692 if (supports_disable_randomization ())
10693 extended_remote_disable_randomization (disable_randomization);
10694
10695 /* If startup-with-shell is on, we inform gdbserver to start the
10696 remote inferior using a shell. */
10697 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10698 {
10699 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10700 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10701 putpkt (rs->buf);
10702 getpkt (&rs->buf);
10703 if (strcmp (rs->buf.data (), "OK") != 0)
10704 error (_("\
10705 Remote replied unexpectedly while setting startup-with-shell: %s"),
10706 rs->buf.data ());
10707 }
10708
10709 extended_remote_environment_support ();
10710
10711 extended_remote_set_inferior_cwd ();
10712
10713 /* Now restart the remote server. */
10714 run_worked = extended_remote_run (args) != -1;
10715 if (!run_worked)
10716 {
10717 /* vRun was not supported. Fail if we need it to do what the
10718 user requested. */
10719 if (remote_exec_file[0])
10720 error (_("Remote target does not support \"set remote exec-file\""));
10721 if (!args.empty ())
10722 error (_("Remote target does not support \"set args\" or run ARGS"));
10723
10724 /* Fall back to "R". */
10725 extended_remote_restart ();
10726 }
10727
10728 /* vRun's success return is a stop reply. */
10729 stop_reply = run_worked ? rs->buf.data () : NULL;
10730 add_current_inferior_and_thread (stop_reply);
10731
10732 /* Get updated offsets, if the stub uses qOffsets. */
10733 get_offsets ();
10734 }
10735 \f
10736
10737 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10738 the list of conditions (in agent expression bytecode format), if any, the
10739 target needs to evaluate. The output is placed into the packet buffer
10740 started from BUF and ended at BUF_END. */
10741
10742 static int
10743 remote_add_target_side_condition (struct gdbarch *gdbarch,
10744 struct bp_target_info *bp_tgt, char *buf,
10745 char *buf_end)
10746 {
10747 if (bp_tgt->conditions.empty ())
10748 return 0;
10749
10750 buf += strlen (buf);
10751 xsnprintf (buf, buf_end - buf, "%s", ";");
10752 buf++;
10753
10754 /* Send conditions to the target. */
10755 for (agent_expr *aexpr : bp_tgt->conditions)
10756 {
10757 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10758 buf += strlen (buf);
10759 for (int i = 0; i < aexpr->buf.size (); ++i)
10760 buf = pack_hex_byte (buf, aexpr->buf[i]);
10761 *buf = '\0';
10762 }
10763 return 0;
10764 }
10765
10766 static void
10767 remote_add_target_side_commands (struct gdbarch *gdbarch,
10768 struct bp_target_info *bp_tgt, char *buf)
10769 {
10770 if (bp_tgt->tcommands.empty ())
10771 return;
10772
10773 buf += strlen (buf);
10774
10775 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10776 buf += strlen (buf);
10777
10778 /* Concatenate all the agent expressions that are commands into the
10779 cmds parameter. */
10780 for (agent_expr *aexpr : bp_tgt->tcommands)
10781 {
10782 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10783 buf += strlen (buf);
10784 for (int i = 0; i < aexpr->buf.size (); ++i)
10785 buf = pack_hex_byte (buf, aexpr->buf[i]);
10786 *buf = '\0';
10787 }
10788 }
10789
10790 /* Insert a breakpoint. On targets that have software breakpoint
10791 support, we ask the remote target to do the work; on targets
10792 which don't, we insert a traditional memory breakpoint. */
10793
10794 int
10795 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10796 struct bp_target_info *bp_tgt)
10797 {
10798 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10799 If it succeeds, then set the support to PACKET_ENABLE. If it
10800 fails, and the user has explicitly requested the Z support then
10801 report an error, otherwise, mark it disabled and go on. */
10802
10803 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10804 {
10805 CORE_ADDR addr = bp_tgt->reqstd_address;
10806 struct remote_state *rs;
10807 char *p, *endbuf;
10808
10809 /* Make sure the remote is pointing at the right process, if
10810 necessary. */
10811 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10812 set_general_process ();
10813
10814 rs = get_remote_state ();
10815 p = rs->buf.data ();
10816 endbuf = p + get_remote_packet_size ();
10817
10818 *(p++) = 'Z';
10819 *(p++) = '0';
10820 *(p++) = ',';
10821 addr = (ULONGEST) remote_address_masked (addr);
10822 p += hexnumstr (p, addr);
10823 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10824
10825 if (supports_evaluation_of_breakpoint_conditions ())
10826 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10827
10828 if (can_run_breakpoint_commands ())
10829 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10830
10831 putpkt (rs->buf);
10832 getpkt (&rs->buf);
10833
10834 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10835 {
10836 case PACKET_ERROR:
10837 return -1;
10838 case PACKET_OK:
10839 return 0;
10840 case PACKET_UNKNOWN:
10841 break;
10842 }
10843 }
10844
10845 /* If this breakpoint has target-side commands but this stub doesn't
10846 support Z0 packets, throw error. */
10847 if (!bp_tgt->tcommands.empty ())
10848 throw_error (NOT_SUPPORTED_ERROR, _("\
10849 Target doesn't support breakpoints that have target side commands."));
10850
10851 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10852 }
10853
10854 int
10855 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10856 struct bp_target_info *bp_tgt,
10857 enum remove_bp_reason reason)
10858 {
10859 CORE_ADDR addr = bp_tgt->placed_address;
10860 struct remote_state *rs = get_remote_state ();
10861
10862 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10863 {
10864 char *p = rs->buf.data ();
10865 char *endbuf = p + get_remote_packet_size ();
10866
10867 /* Make sure the remote is pointing at the right process, if
10868 necessary. */
10869 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10870 set_general_process ();
10871
10872 *(p++) = 'z';
10873 *(p++) = '0';
10874 *(p++) = ',';
10875
10876 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10877 p += hexnumstr (p, addr);
10878 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10879
10880 putpkt (rs->buf);
10881 getpkt (&rs->buf);
10882
10883 return (rs->buf[0] == 'E');
10884 }
10885
10886 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10887 }
10888
10889 static enum Z_packet_type
10890 watchpoint_to_Z_packet (int type)
10891 {
10892 switch (type)
10893 {
10894 case hw_write:
10895 return Z_PACKET_WRITE_WP;
10896 break;
10897 case hw_read:
10898 return Z_PACKET_READ_WP;
10899 break;
10900 case hw_access:
10901 return Z_PACKET_ACCESS_WP;
10902 break;
10903 default:
10904 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10905 }
10906 }
10907
10908 int
10909 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10910 enum target_hw_bp_type type, struct expression *cond)
10911 {
10912 struct remote_state *rs = get_remote_state ();
10913 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10914 char *p;
10915 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10916
10917 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10918 + to_underlying (packet))) == PACKET_DISABLE)
10919 return 1;
10920
10921 /* Make sure the remote is pointing at the right process, if
10922 necessary. */
10923 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10924 set_general_process ();
10925
10926 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10927 p = strchr (rs->buf.data (), '\0');
10928 addr = remote_address_masked (addr);
10929 p += hexnumstr (p, (ULONGEST) addr);
10930 xsnprintf (p, endbuf - p, ",%x", len);
10931
10932 putpkt (rs->buf);
10933 getpkt (&rs->buf);
10934
10935 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10936 + to_underlying (packet))))
10937 {
10938 case PACKET_ERROR:
10939 return -1;
10940 case PACKET_UNKNOWN:
10941 return 1;
10942 case PACKET_OK:
10943 return 0;
10944 }
10945 internal_error (_("remote_insert_watchpoint: reached end of function"));
10946 }
10947
10948 bool
10949 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10950 CORE_ADDR start, int length)
10951 {
10952 CORE_ADDR diff = remote_address_masked (addr - start);
10953
10954 return diff < length;
10955 }
10956
10957
10958 int
10959 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10960 enum target_hw_bp_type type, struct expression *cond)
10961 {
10962 struct remote_state *rs = get_remote_state ();
10963 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10964 char *p;
10965 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10966
10967 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10968 + to_underlying (packet))) == PACKET_DISABLE)
10969 return -1;
10970
10971 /* Make sure the remote is pointing at the right process, if
10972 necessary. */
10973 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10974 set_general_process ();
10975
10976 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10977 p = strchr (rs->buf.data (), '\0');
10978 addr = remote_address_masked (addr);
10979 p += hexnumstr (p, (ULONGEST) addr);
10980 xsnprintf (p, endbuf - p, ",%x", len);
10981 putpkt (rs->buf);
10982 getpkt (&rs->buf);
10983
10984 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10985 + to_underlying (packet))))
10986 {
10987 case PACKET_ERROR:
10988 case PACKET_UNKNOWN:
10989 return -1;
10990 case PACKET_OK:
10991 return 0;
10992 }
10993 internal_error (_("remote_remove_watchpoint: reached end of function"));
10994 }
10995
10996
10997 static int remote_hw_watchpoint_limit = -1;
10998 static int remote_hw_watchpoint_length_limit = -1;
10999 static int remote_hw_breakpoint_limit = -1;
11000
11001 int
11002 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11003 {
11004 if (remote_hw_watchpoint_length_limit == 0)
11005 return 0;
11006 else if (remote_hw_watchpoint_length_limit < 0)
11007 return 1;
11008 else if (len <= remote_hw_watchpoint_length_limit)
11009 return 1;
11010 else
11011 return 0;
11012 }
11013
11014 int
11015 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11016 {
11017 if (type == bp_hardware_breakpoint)
11018 {
11019 if (remote_hw_breakpoint_limit == 0)
11020 return 0;
11021 else if (remote_hw_breakpoint_limit < 0)
11022 return 1;
11023 else if (cnt <= remote_hw_breakpoint_limit)
11024 return 1;
11025 }
11026 else
11027 {
11028 if (remote_hw_watchpoint_limit == 0)
11029 return 0;
11030 else if (remote_hw_watchpoint_limit < 0)
11031 return 1;
11032 else if (ot)
11033 return -1;
11034 else if (cnt <= remote_hw_watchpoint_limit)
11035 return 1;
11036 }
11037 return -1;
11038 }
11039
11040 /* The to_stopped_by_sw_breakpoint method of target remote. */
11041
11042 bool
11043 remote_target::stopped_by_sw_breakpoint ()
11044 {
11045 struct thread_info *thread = inferior_thread ();
11046
11047 return (thread->priv != NULL
11048 && (get_remote_thread_info (thread)->stop_reason
11049 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11050 }
11051
11052 /* The to_supports_stopped_by_sw_breakpoint method of target
11053 remote. */
11054
11055 bool
11056 remote_target::supports_stopped_by_sw_breakpoint ()
11057 {
11058 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11059 }
11060
11061 /* The to_stopped_by_hw_breakpoint method of target remote. */
11062
11063 bool
11064 remote_target::stopped_by_hw_breakpoint ()
11065 {
11066 struct thread_info *thread = inferior_thread ();
11067
11068 return (thread->priv != NULL
11069 && (get_remote_thread_info (thread)->stop_reason
11070 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11071 }
11072
11073 /* The to_supports_stopped_by_hw_breakpoint method of target
11074 remote. */
11075
11076 bool
11077 remote_target::supports_stopped_by_hw_breakpoint ()
11078 {
11079 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11080 }
11081
11082 bool
11083 remote_target::stopped_by_watchpoint ()
11084 {
11085 struct thread_info *thread = inferior_thread ();
11086
11087 return (thread->priv != NULL
11088 && (get_remote_thread_info (thread)->stop_reason
11089 == TARGET_STOPPED_BY_WATCHPOINT));
11090 }
11091
11092 bool
11093 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11094 {
11095 struct thread_info *thread = inferior_thread ();
11096
11097 if (thread->priv != NULL
11098 && (get_remote_thread_info (thread)->stop_reason
11099 == TARGET_STOPPED_BY_WATCHPOINT))
11100 {
11101 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11102 return true;
11103 }
11104
11105 return false;
11106 }
11107
11108
11109 int
11110 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11111 struct bp_target_info *bp_tgt)
11112 {
11113 CORE_ADDR addr = bp_tgt->reqstd_address;
11114 struct remote_state *rs;
11115 char *p, *endbuf;
11116 char *message;
11117
11118 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11119 return -1;
11120
11121 /* Make sure the remote is pointing at the right process, if
11122 necessary. */
11123 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11124 set_general_process ();
11125
11126 rs = get_remote_state ();
11127 p = rs->buf.data ();
11128 endbuf = p + get_remote_packet_size ();
11129
11130 *(p++) = 'Z';
11131 *(p++) = '1';
11132 *(p++) = ',';
11133
11134 addr = remote_address_masked (addr);
11135 p += hexnumstr (p, (ULONGEST) addr);
11136 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11137
11138 if (supports_evaluation_of_breakpoint_conditions ())
11139 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11140
11141 if (can_run_breakpoint_commands ())
11142 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11143
11144 putpkt (rs->buf);
11145 getpkt (&rs->buf);
11146
11147 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11148 {
11149 case PACKET_ERROR:
11150 if (rs->buf[1] == '.')
11151 {
11152 message = strchr (&rs->buf[2], '.');
11153 if (message)
11154 error (_("Remote failure reply: %s"), message + 1);
11155 }
11156 return -1;
11157 case PACKET_UNKNOWN:
11158 return -1;
11159 case PACKET_OK:
11160 return 0;
11161 }
11162 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11163 }
11164
11165
11166 int
11167 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11168 struct bp_target_info *bp_tgt)
11169 {
11170 CORE_ADDR addr;
11171 struct remote_state *rs = get_remote_state ();
11172 char *p = rs->buf.data ();
11173 char *endbuf = p + get_remote_packet_size ();
11174
11175 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11176 return -1;
11177
11178 /* Make sure the remote is pointing at the right process, if
11179 necessary. */
11180 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11181 set_general_process ();
11182
11183 *(p++) = 'z';
11184 *(p++) = '1';
11185 *(p++) = ',';
11186
11187 addr = remote_address_masked (bp_tgt->placed_address);
11188 p += hexnumstr (p, (ULONGEST) addr);
11189 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11190
11191 putpkt (rs->buf);
11192 getpkt (&rs->buf);
11193
11194 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11195 {
11196 case PACKET_ERROR:
11197 case PACKET_UNKNOWN:
11198 return -1;
11199 case PACKET_OK:
11200 return 0;
11201 }
11202 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11203 }
11204
11205 /* Verify memory using the "qCRC:" request. */
11206
11207 int
11208 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11209 {
11210 struct remote_state *rs = get_remote_state ();
11211 unsigned long host_crc, target_crc;
11212 char *tmp;
11213
11214 /* It doesn't make sense to use qCRC if the remote target is
11215 connected but not running. */
11216 if (target_has_execution ()
11217 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11218 {
11219 enum packet_result result;
11220
11221 /* Make sure the remote is pointing at the right process. */
11222 set_general_process ();
11223
11224 /* FIXME: assumes lma can fit into long. */
11225 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11226 (long) lma, (long) size);
11227 putpkt (rs->buf);
11228
11229 /* Be clever; compute the host_crc before waiting for target
11230 reply. */
11231 host_crc = xcrc32 (data, size, 0xffffffff);
11232
11233 getpkt (&rs->buf);
11234
11235 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11236 if (result == PACKET_ERROR)
11237 return -1;
11238 else if (result == PACKET_OK)
11239 {
11240 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11241 target_crc = target_crc * 16 + fromhex (*tmp);
11242
11243 return (host_crc == target_crc);
11244 }
11245 }
11246
11247 return simple_verify_memory (this, data, lma, size);
11248 }
11249
11250 /* compare-sections command
11251
11252 With no arguments, compares each loadable section in the exec bfd
11253 with the same memory range on the target, and reports mismatches.
11254 Useful for verifying the image on the target against the exec file. */
11255
11256 static void
11257 compare_sections_command (const char *args, int from_tty)
11258 {
11259 asection *s;
11260 const char *sectname;
11261 bfd_size_type size;
11262 bfd_vma lma;
11263 int matched = 0;
11264 int mismatched = 0;
11265 int res;
11266 int read_only = 0;
11267
11268 if (!current_program_space->exec_bfd ())
11269 error (_("command cannot be used without an exec file"));
11270
11271 if (args != NULL && strcmp (args, "-r") == 0)
11272 {
11273 read_only = 1;
11274 args = NULL;
11275 }
11276
11277 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11278 {
11279 if (!(s->flags & SEC_LOAD))
11280 continue; /* Skip non-loadable section. */
11281
11282 if (read_only && (s->flags & SEC_READONLY) == 0)
11283 continue; /* Skip writeable sections */
11284
11285 size = bfd_section_size (s);
11286 if (size == 0)
11287 continue; /* Skip zero-length section. */
11288
11289 sectname = bfd_section_name (s);
11290 if (args && strcmp (args, sectname) != 0)
11291 continue; /* Not the section selected by user. */
11292
11293 matched = 1; /* Do this section. */
11294 lma = s->lma;
11295
11296 gdb::byte_vector sectdata (size);
11297 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11298 sectdata.data (), 0, size);
11299
11300 res = target_verify_memory (sectdata.data (), lma, size);
11301
11302 if (res == -1)
11303 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11304 paddress (current_inferior ()->arch (), lma),
11305 paddress (current_inferior ()->arch (), lma + size));
11306
11307 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11308 paddress (current_inferior ()->arch (), lma),
11309 paddress (current_inferior ()->arch (), lma + size));
11310 if (res)
11311 gdb_printf ("matched.\n");
11312 else
11313 {
11314 gdb_printf ("MIS-MATCHED!\n");
11315 mismatched++;
11316 }
11317 }
11318 if (mismatched > 0)
11319 warning (_("One or more sections of the target image does "
11320 "not match the loaded file"));
11321 if (args && !matched)
11322 gdb_printf (_("No loaded section named '%s'.\n"), args);
11323 }
11324
11325 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11326 into remote target. The number of bytes written to the remote
11327 target is returned, or -1 for error. */
11328
11329 target_xfer_status
11330 remote_target::remote_write_qxfer (const char *object_name,
11331 const char *annex, const gdb_byte *writebuf,
11332 ULONGEST offset, LONGEST len,
11333 ULONGEST *xfered_len,
11334 const unsigned int which_packet)
11335 {
11336 int i, buf_len;
11337 ULONGEST n;
11338 struct remote_state *rs = get_remote_state ();
11339 int max_size = get_memory_write_packet_size ();
11340
11341 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11342 return TARGET_XFER_E_IO;
11343
11344 /* Insert header. */
11345 i = snprintf (rs->buf.data (), max_size,
11346 "qXfer:%s:write:%s:%s:",
11347 object_name, annex ? annex : "",
11348 phex_nz (offset, sizeof offset));
11349 max_size -= (i + 1);
11350
11351 /* Escape as much data as fits into rs->buf. */
11352 buf_len = remote_escape_output
11353 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11354
11355 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11356 || getpkt (&rs->buf) < 0
11357 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11358 return TARGET_XFER_E_IO;
11359
11360 unpack_varlen_hex (rs->buf.data (), &n);
11361
11362 *xfered_len = n;
11363 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11364 }
11365
11366 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11367 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11368 number of bytes read is returned, or 0 for EOF, or -1 for error.
11369 The number of bytes read may be less than LEN without indicating an
11370 EOF. PACKET is checked and updated to indicate whether the remote
11371 target supports this object. */
11372
11373 target_xfer_status
11374 remote_target::remote_read_qxfer (const char *object_name,
11375 const char *annex,
11376 gdb_byte *readbuf, ULONGEST offset,
11377 LONGEST len,
11378 ULONGEST *xfered_len,
11379 const unsigned int which_packet)
11380 {
11381 struct remote_state *rs = get_remote_state ();
11382 LONGEST i, n, packet_len;
11383
11384 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11385 return TARGET_XFER_E_IO;
11386
11387 /* Check whether we've cached an end-of-object packet that matches
11388 this request. */
11389 if (rs->finished_object)
11390 {
11391 if (strcmp (object_name, rs->finished_object) == 0
11392 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11393 && offset == rs->finished_offset)
11394 return TARGET_XFER_EOF;
11395
11396
11397 /* Otherwise, we're now reading something different. Discard
11398 the cache. */
11399 xfree (rs->finished_object);
11400 xfree (rs->finished_annex);
11401 rs->finished_object = NULL;
11402 rs->finished_annex = NULL;
11403 }
11404
11405 /* Request only enough to fit in a single packet. The actual data
11406 may not, since we don't know how much of it will need to be escaped;
11407 the target is free to respond with slightly less data. We subtract
11408 five to account for the response type and the protocol frame. */
11409 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11410 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11411 "qXfer:%s:read:%s:%s,%s",
11412 object_name, annex ? annex : "",
11413 phex_nz (offset, sizeof offset),
11414 phex_nz (n, sizeof n));
11415 i = putpkt (rs->buf);
11416 if (i < 0)
11417 return TARGET_XFER_E_IO;
11418
11419 rs->buf[0] = '\0';
11420 packet_len = getpkt (&rs->buf);
11421 if (packet_len < 0
11422 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11423 return TARGET_XFER_E_IO;
11424
11425 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11426 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11427
11428 /* 'm' means there is (or at least might be) more data after this
11429 batch. That does not make sense unless there's at least one byte
11430 of data in this reply. */
11431 if (rs->buf[0] == 'm' && packet_len == 1)
11432 error (_("Remote qXfer reply contained no data."));
11433
11434 /* Got some data. */
11435 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11436 packet_len - 1, readbuf, n);
11437
11438 /* 'l' is an EOF marker, possibly including a final block of data,
11439 or possibly empty. If we have the final block of a non-empty
11440 object, record this fact to bypass a subsequent partial read. */
11441 if (rs->buf[0] == 'l' && offset + i > 0)
11442 {
11443 rs->finished_object = xstrdup (object_name);
11444 rs->finished_annex = xstrdup (annex ? annex : "");
11445 rs->finished_offset = offset + i;
11446 }
11447
11448 if (i == 0)
11449 return TARGET_XFER_EOF;
11450 else
11451 {
11452 *xfered_len = i;
11453 return TARGET_XFER_OK;
11454 }
11455 }
11456
11457 enum target_xfer_status
11458 remote_target::xfer_partial (enum target_object object,
11459 const char *annex, gdb_byte *readbuf,
11460 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11461 ULONGEST *xfered_len)
11462 {
11463 struct remote_state *rs;
11464 int i;
11465 char *p2;
11466 char query_type;
11467 int unit_size
11468 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11469
11470 set_remote_traceframe ();
11471 set_general_thread (inferior_ptid);
11472
11473 rs = get_remote_state ();
11474
11475 /* Handle memory using the standard memory routines. */
11476 if (object == TARGET_OBJECT_MEMORY)
11477 {
11478 /* If the remote target is connected but not running, we should
11479 pass this request down to a lower stratum (e.g. the executable
11480 file). */
11481 if (!target_has_execution ())
11482 return TARGET_XFER_EOF;
11483
11484 if (writebuf != NULL)
11485 return remote_write_bytes (offset, writebuf, len, unit_size,
11486 xfered_len);
11487 else
11488 return remote_read_bytes (offset, readbuf, len, unit_size,
11489 xfered_len);
11490 }
11491
11492 /* Handle extra signal info using qxfer packets. */
11493 if (object == TARGET_OBJECT_SIGNAL_INFO)
11494 {
11495 if (readbuf)
11496 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11497 xfered_len, PACKET_qXfer_siginfo_read);
11498 else
11499 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11500 xfered_len, PACKET_qXfer_siginfo_write);
11501 }
11502
11503 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11504 {
11505 if (readbuf)
11506 return remote_read_qxfer ("statictrace", annex,
11507 readbuf, offset, len, xfered_len,
11508 PACKET_qXfer_statictrace_read);
11509 else
11510 return TARGET_XFER_E_IO;
11511 }
11512
11513 /* Only handle flash writes. */
11514 if (writebuf != NULL)
11515 {
11516 switch (object)
11517 {
11518 case TARGET_OBJECT_FLASH:
11519 return remote_flash_write (offset, len, xfered_len,
11520 writebuf);
11521
11522 default:
11523 return TARGET_XFER_E_IO;
11524 }
11525 }
11526
11527 /* Map pre-existing objects onto letters. DO NOT do this for new
11528 objects!!! Instead specify new query packets. */
11529 switch (object)
11530 {
11531 case TARGET_OBJECT_AVR:
11532 query_type = 'R';
11533 break;
11534
11535 case TARGET_OBJECT_AUXV:
11536 gdb_assert (annex == NULL);
11537 return remote_read_qxfer
11538 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11539
11540 case TARGET_OBJECT_AVAILABLE_FEATURES:
11541 return remote_read_qxfer
11542 ("features", annex, readbuf, offset, len, xfered_len,
11543 PACKET_qXfer_features);
11544
11545 case TARGET_OBJECT_LIBRARIES:
11546 return remote_read_qxfer
11547 ("libraries", annex, readbuf, offset, len, xfered_len,
11548 PACKET_qXfer_libraries);
11549
11550 case TARGET_OBJECT_LIBRARIES_SVR4:
11551 return remote_read_qxfer
11552 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11553 PACKET_qXfer_libraries_svr4);
11554
11555 case TARGET_OBJECT_MEMORY_MAP:
11556 gdb_assert (annex == NULL);
11557 return remote_read_qxfer
11558 ("memory-map", annex, readbuf, offset, len, xfered_len,
11559 PACKET_qXfer_memory_map);
11560
11561 case TARGET_OBJECT_OSDATA:
11562 /* Should only get here if we're connected. */
11563 gdb_assert (rs->remote_desc);
11564 return remote_read_qxfer
11565 ("osdata", annex, readbuf, offset, len, xfered_len,
11566 PACKET_qXfer_osdata);
11567
11568 case TARGET_OBJECT_THREADS:
11569 gdb_assert (annex == NULL);
11570 return remote_read_qxfer
11571 ("threads", annex, readbuf, offset, len, xfered_len,
11572 PACKET_qXfer_threads);
11573
11574 case TARGET_OBJECT_TRACEFRAME_INFO:
11575 gdb_assert (annex == NULL);
11576 return remote_read_qxfer
11577 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11578 PACKET_qXfer_traceframe_info);
11579
11580 case TARGET_OBJECT_FDPIC:
11581 return remote_read_qxfer
11582 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11583
11584 case TARGET_OBJECT_OPENVMS_UIB:
11585 return remote_read_qxfer
11586 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11587
11588 case TARGET_OBJECT_BTRACE:
11589 return remote_read_qxfer
11590 ("btrace", annex, readbuf, offset, len, xfered_len,
11591 PACKET_qXfer_btrace);
11592
11593 case TARGET_OBJECT_BTRACE_CONF:
11594 return remote_read_qxfer
11595 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11596 PACKET_qXfer_btrace_conf);
11597
11598 case TARGET_OBJECT_EXEC_FILE:
11599 return remote_read_qxfer
11600 ("exec-file", annex, readbuf, offset, len, xfered_len,
11601 PACKET_qXfer_exec_file);
11602
11603 default:
11604 return TARGET_XFER_E_IO;
11605 }
11606
11607 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11608 large enough let the caller deal with it. */
11609 if (len < get_remote_packet_size ())
11610 return TARGET_XFER_E_IO;
11611 len = get_remote_packet_size ();
11612
11613 /* Except for querying the minimum buffer size, target must be open. */
11614 if (!rs->remote_desc)
11615 error (_("remote query is only available after target open"));
11616
11617 gdb_assert (annex != NULL);
11618 gdb_assert (readbuf != NULL);
11619
11620 p2 = rs->buf.data ();
11621 *p2++ = 'q';
11622 *p2++ = query_type;
11623
11624 /* We used one buffer char for the remote protocol q command and
11625 another for the query type. As the remote protocol encapsulation
11626 uses 4 chars plus one extra in case we are debugging
11627 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11628 string. */
11629 i = 0;
11630 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11631 {
11632 /* Bad caller may have sent forbidden characters. */
11633 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11634 *p2++ = annex[i];
11635 i++;
11636 }
11637 *p2 = '\0';
11638 gdb_assert (annex[i] == '\0');
11639
11640 i = putpkt (rs->buf);
11641 if (i < 0)
11642 return TARGET_XFER_E_IO;
11643
11644 getpkt (&rs->buf);
11645 strcpy ((char *) readbuf, rs->buf.data ());
11646
11647 *xfered_len = strlen ((char *) readbuf);
11648 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11649 }
11650
11651 /* Implementation of to_get_memory_xfer_limit. */
11652
11653 ULONGEST
11654 remote_target::get_memory_xfer_limit ()
11655 {
11656 return get_memory_write_packet_size ();
11657 }
11658
11659 int
11660 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11661 const gdb_byte *pattern, ULONGEST pattern_len,
11662 CORE_ADDR *found_addrp)
11663 {
11664 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11665 struct remote_state *rs = get_remote_state ();
11666 int max_size = get_memory_write_packet_size ();
11667
11668 /* Number of packet bytes used to encode the pattern;
11669 this could be more than PATTERN_LEN due to escape characters. */
11670 int escaped_pattern_len;
11671 /* Amount of pattern that was encodable in the packet. */
11672 int used_pattern_len;
11673 int i;
11674 int found;
11675 ULONGEST found_addr;
11676
11677 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11678 {
11679 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11680 == len);
11681 };
11682
11683 /* Don't go to the target if we don't have to. This is done before
11684 checking packet_support to avoid the possibility that a success for this
11685 edge case means the facility works in general. */
11686 if (pattern_len > search_space_len)
11687 return 0;
11688 if (pattern_len == 0)
11689 {
11690 *found_addrp = start_addr;
11691 return 1;
11692 }
11693
11694 /* If we already know the packet isn't supported, fall back to the simple
11695 way of searching memory. */
11696
11697 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11698 {
11699 /* Target doesn't provided special support, fall back and use the
11700 standard support (copy memory and do the search here). */
11701 return simple_search_memory (read_memory, start_addr, search_space_len,
11702 pattern, pattern_len, found_addrp);
11703 }
11704
11705 /* Make sure the remote is pointing at the right process. */
11706 set_general_process ();
11707
11708 /* Insert header. */
11709 i = snprintf (rs->buf.data (), max_size,
11710 "qSearch:memory:%s;%s;",
11711 phex_nz (start_addr, addr_size),
11712 phex_nz (search_space_len, sizeof (search_space_len)));
11713 max_size -= (i + 1);
11714
11715 /* Escape as much data as fits into rs->buf. */
11716 escaped_pattern_len =
11717 remote_escape_output (pattern, pattern_len, 1,
11718 (gdb_byte *) rs->buf.data () + i,
11719 &used_pattern_len, max_size);
11720
11721 /* Bail if the pattern is too large. */
11722 if (used_pattern_len != pattern_len)
11723 error (_("Pattern is too large to transmit to remote target."));
11724
11725 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11726 || getpkt (&rs->buf) < 0
11727 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11728 {
11729 /* The request may not have worked because the command is not
11730 supported. If so, fall back to the simple way. */
11731 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11732 {
11733 return simple_search_memory (read_memory, start_addr, search_space_len,
11734 pattern, pattern_len, found_addrp);
11735 }
11736 return -1;
11737 }
11738
11739 if (rs->buf[0] == '0')
11740 found = 0;
11741 else if (rs->buf[0] == '1')
11742 {
11743 found = 1;
11744 if (rs->buf[1] != ',')
11745 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11746 unpack_varlen_hex (&rs->buf[2], &found_addr);
11747 *found_addrp = found_addr;
11748 }
11749 else
11750 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11751
11752 return found;
11753 }
11754
11755 void
11756 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11757 {
11758 struct remote_state *rs = get_remote_state ();
11759 char *p = rs->buf.data ();
11760
11761 if (!rs->remote_desc)
11762 error (_("remote rcmd is only available after target open"));
11763
11764 /* Send a NULL command across as an empty command. */
11765 if (command == NULL)
11766 command = "";
11767
11768 /* The query prefix. */
11769 strcpy (rs->buf.data (), "qRcmd,");
11770 p = strchr (rs->buf.data (), '\0');
11771
11772 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11773 > get_remote_packet_size ())
11774 error (_("\"monitor\" command ``%s'' is too long."), command);
11775
11776 /* Encode the actual command. */
11777 bin2hex ((const gdb_byte *) command, p, strlen (command));
11778
11779 if (putpkt (rs->buf) < 0)
11780 error (_("Communication problem with target."));
11781
11782 /* get/display the response */
11783 while (1)
11784 {
11785 char *buf;
11786
11787 /* XXX - see also remote_get_noisy_reply(). */
11788 QUIT; /* Allow user to bail out with ^C. */
11789 rs->buf[0] = '\0';
11790 if (getpkt (&rs->buf) == -1)
11791 {
11792 /* Timeout. Continue to (try to) read responses.
11793 This is better than stopping with an error, assuming the stub
11794 is still executing the (long) monitor command.
11795 If needed, the user can interrupt gdb using C-c, obtaining
11796 an effect similar to stop on timeout. */
11797 continue;
11798 }
11799 buf = rs->buf.data ();
11800 if (buf[0] == '\0')
11801 error (_("Target does not support this command."));
11802 if (buf[0] == 'O' && buf[1] != 'K')
11803 {
11804 remote_console_output (buf + 1); /* 'O' message from stub. */
11805 continue;
11806 }
11807 if (strcmp (buf, "OK") == 0)
11808 break;
11809 if (strlen (buf) == 3 && buf[0] == 'E'
11810 && isxdigit (buf[1]) && isxdigit (buf[2]))
11811 {
11812 error (_("Protocol error with Rcmd"));
11813 }
11814 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11815 {
11816 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11817
11818 gdb_putc (c, outbuf);
11819 }
11820 break;
11821 }
11822 }
11823
11824 std::vector<mem_region>
11825 remote_target::memory_map ()
11826 {
11827 std::vector<mem_region> result;
11828 gdb::optional<gdb::char_vector> text
11829 = target_read_stralloc (current_inferior ()->top_target (),
11830 TARGET_OBJECT_MEMORY_MAP, NULL);
11831
11832 if (text)
11833 result = parse_memory_map (text->data ());
11834
11835 return result;
11836 }
11837
11838 /* Set of callbacks used to implement the 'maint packet' command. */
11839
11840 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11841 {
11842 /* Called before the packet is sent. BUF is the packet content before
11843 the protocol specific prefix, suffix, and escaping is added. */
11844
11845 void sending (gdb::array_view<const char> &buf) override
11846 {
11847 gdb_puts ("sending: ");
11848 print_packet (buf);
11849 gdb_puts ("\n");
11850 }
11851
11852 /* Called with BUF, the reply from the remote target. */
11853
11854 void received (gdb::array_view<const char> &buf) override
11855 {
11856 gdb_puts ("received: \"");
11857 print_packet (buf);
11858 gdb_puts ("\"\n");
11859 }
11860
11861 private:
11862
11863 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11864 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11865
11866 static void
11867 print_packet (gdb::array_view<const char> &buf)
11868 {
11869 string_file stb;
11870
11871 for (int i = 0; i < buf.size (); ++i)
11872 {
11873 gdb_byte c = buf[i];
11874 if (isprint (c))
11875 gdb_putc (c, &stb);
11876 else
11877 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11878 }
11879
11880 gdb_puts (stb.string ().c_str ());
11881 }
11882 };
11883
11884 /* See remote.h. */
11885
11886 void
11887 send_remote_packet (gdb::array_view<const char> &buf,
11888 send_remote_packet_callbacks *callbacks)
11889 {
11890 if (buf.size () == 0 || buf.data ()[0] == '\0')
11891 error (_("a remote packet must not be empty"));
11892
11893 remote_target *remote = get_current_remote_target ();
11894 if (remote == nullptr)
11895 error (_("packets can only be sent to a remote target"));
11896
11897 callbacks->sending (buf);
11898
11899 remote->putpkt_binary (buf.data (), buf.size ());
11900 remote_state *rs = remote->get_remote_state ();
11901 int bytes = remote->getpkt (&rs->buf);
11902
11903 if (bytes < 0)
11904 error (_("error while fetching packet from remote target"));
11905
11906 gdb::array_view<const char> view (&rs->buf[0], bytes);
11907 callbacks->received (view);
11908 }
11909
11910 /* Entry point for the 'maint packet' command. */
11911
11912 static void
11913 cli_packet_command (const char *args, int from_tty)
11914 {
11915 cli_packet_command_callbacks cb;
11916 gdb::array_view<const char> view
11917 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11918 send_remote_packet (view, &cb);
11919 }
11920
11921 #if 0
11922 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11923
11924 static void display_thread_info (struct gdb_ext_thread_info *info);
11925
11926 static void threadset_test_cmd (char *cmd, int tty);
11927
11928 static void threadalive_test (char *cmd, int tty);
11929
11930 static void threadlist_test_cmd (char *cmd, int tty);
11931
11932 int get_and_display_threadinfo (threadref *ref);
11933
11934 static void threadinfo_test_cmd (char *cmd, int tty);
11935
11936 static int thread_display_step (threadref *ref, void *context);
11937
11938 static void threadlist_update_test_cmd (char *cmd, int tty);
11939
11940 static void init_remote_threadtests (void);
11941
11942 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11943
11944 static void
11945 threadset_test_cmd (const char *cmd, int tty)
11946 {
11947 int sample_thread = SAMPLE_THREAD;
11948
11949 gdb_printf (_("Remote threadset test\n"));
11950 set_general_thread (sample_thread);
11951 }
11952
11953
11954 static void
11955 threadalive_test (const char *cmd, int tty)
11956 {
11957 int sample_thread = SAMPLE_THREAD;
11958 int pid = inferior_ptid.pid ();
11959 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11960
11961 if (remote_thread_alive (ptid))
11962 gdb_printf ("PASS: Thread alive test\n");
11963 else
11964 gdb_printf ("FAIL: Thread alive test\n");
11965 }
11966
11967 void output_threadid (char *title, threadref *ref);
11968
11969 void
11970 output_threadid (char *title, threadref *ref)
11971 {
11972 char hexid[20];
11973
11974 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11975 hexid[16] = 0;
11976 gdb_printf ("%s %s\n", title, (&hexid[0]));
11977 }
11978
11979 static void
11980 threadlist_test_cmd (const char *cmd, int tty)
11981 {
11982 int startflag = 1;
11983 threadref nextthread;
11984 int done, result_count;
11985 threadref threadlist[3];
11986
11987 gdb_printf ("Remote Threadlist test\n");
11988 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11989 &result_count, &threadlist[0]))
11990 gdb_printf ("FAIL: threadlist test\n");
11991 else
11992 {
11993 threadref *scan = threadlist;
11994 threadref *limit = scan + result_count;
11995
11996 while (scan < limit)
11997 output_threadid (" thread ", scan++);
11998 }
11999 }
12000
12001 void
12002 display_thread_info (struct gdb_ext_thread_info *info)
12003 {
12004 output_threadid ("Threadid: ", &info->threadid);
12005 gdb_printf ("Name: %s\n ", info->shortname);
12006 gdb_printf ("State: %s\n", info->display);
12007 gdb_printf ("other: %s\n\n", info->more_display);
12008 }
12009
12010 int
12011 get_and_display_threadinfo (threadref *ref)
12012 {
12013 int result;
12014 int set;
12015 struct gdb_ext_thread_info threadinfo;
12016
12017 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12018 | TAG_MOREDISPLAY | TAG_DISPLAY;
12019 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12020 display_thread_info (&threadinfo);
12021 return result;
12022 }
12023
12024 static void
12025 threadinfo_test_cmd (const char *cmd, int tty)
12026 {
12027 int athread = SAMPLE_THREAD;
12028 threadref thread;
12029 int set;
12030
12031 int_to_threadref (&thread, athread);
12032 gdb_printf ("Remote Threadinfo test\n");
12033 if (!get_and_display_threadinfo (&thread))
12034 gdb_printf ("FAIL cannot get thread info\n");
12035 }
12036
12037 static int
12038 thread_display_step (threadref *ref, void *context)
12039 {
12040 /* output_threadid(" threadstep ",ref); *//* simple test */
12041 return get_and_display_threadinfo (ref);
12042 }
12043
12044 static void
12045 threadlist_update_test_cmd (const char *cmd, int tty)
12046 {
12047 gdb_printf ("Remote Threadlist update test\n");
12048 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12049 }
12050
12051 static void
12052 init_remote_threadtests (void)
12053 {
12054 add_com ("tlist", class_obscure, threadlist_test_cmd,
12055 _("Fetch and print the remote list of "
12056 "thread identifiers, one pkt only."));
12057 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12058 _("Fetch and display info about one thread."));
12059 add_com ("tset", class_obscure, threadset_test_cmd,
12060 _("Test setting to a different thread."));
12061 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12062 _("Iterate through updating all remote thread info."));
12063 add_com ("talive", class_obscure, threadalive_test,
12064 _("Remote thread alive test."));
12065 }
12066
12067 #endif /* 0 */
12068
12069 /* Convert a thread ID to a string. */
12070
12071 std::string
12072 remote_target::pid_to_str (ptid_t ptid)
12073 {
12074 if (ptid == null_ptid)
12075 return normal_pid_to_str (ptid);
12076 else if (ptid.is_pid ())
12077 {
12078 /* Printing an inferior target id. */
12079
12080 /* When multi-process extensions are off, there's no way in the
12081 remote protocol to know the remote process id, if there's any
12082 at all. There's one exception --- when we're connected with
12083 target extended-remote, and we manually attached to a process
12084 with "attach PID". We don't record anywhere a flag that
12085 allows us to distinguish that case from the case of
12086 connecting with extended-remote and the stub already being
12087 attached to a process, and reporting yes to qAttached, hence
12088 no smart special casing here. */
12089 if (!m_features.remote_multi_process_p ())
12090 return "Remote target";
12091
12092 return normal_pid_to_str (ptid);
12093 }
12094 else
12095 {
12096 if (magic_null_ptid == ptid)
12097 return "Thread <main>";
12098 else if (m_features.remote_multi_process_p ())
12099 if (ptid.lwp () == 0)
12100 return normal_pid_to_str (ptid);
12101 else
12102 return string_printf ("Thread %d.%ld",
12103 ptid.pid (), ptid.lwp ());
12104 else
12105 return string_printf ("Thread %ld", ptid.lwp ());
12106 }
12107 }
12108
12109 /* Get the address of the thread local variable in OBJFILE which is
12110 stored at OFFSET within the thread local storage for thread PTID. */
12111
12112 CORE_ADDR
12113 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12114 CORE_ADDR offset)
12115 {
12116 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12117 {
12118 struct remote_state *rs = get_remote_state ();
12119 char *p = rs->buf.data ();
12120 char *endp = p + get_remote_packet_size ();
12121 enum packet_result result;
12122
12123 strcpy (p, "qGetTLSAddr:");
12124 p += strlen (p);
12125 p = write_ptid (p, endp, ptid);
12126 *p++ = ',';
12127 p += hexnumstr (p, offset);
12128 *p++ = ',';
12129 p += hexnumstr (p, lm);
12130 *p++ = '\0';
12131
12132 putpkt (rs->buf);
12133 getpkt (&rs->buf);
12134 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12135 if (result == PACKET_OK)
12136 {
12137 ULONGEST addr;
12138
12139 unpack_varlen_hex (rs->buf.data (), &addr);
12140 return addr;
12141 }
12142 else if (result == PACKET_UNKNOWN)
12143 throw_error (TLS_GENERIC_ERROR,
12144 _("Remote target doesn't support qGetTLSAddr packet"));
12145 else
12146 throw_error (TLS_GENERIC_ERROR,
12147 _("Remote target failed to process qGetTLSAddr request"));
12148 }
12149 else
12150 throw_error (TLS_GENERIC_ERROR,
12151 _("TLS not supported or disabled on this target"));
12152 /* Not reached. */
12153 return 0;
12154 }
12155
12156 /* Provide thread local base, i.e. Thread Information Block address.
12157 Returns 1 if ptid is found and thread_local_base is non zero. */
12158
12159 bool
12160 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12161 {
12162 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12163 {
12164 struct remote_state *rs = get_remote_state ();
12165 char *p = rs->buf.data ();
12166 char *endp = p + get_remote_packet_size ();
12167 enum packet_result result;
12168
12169 strcpy (p, "qGetTIBAddr:");
12170 p += strlen (p);
12171 p = write_ptid (p, endp, ptid);
12172 *p++ = '\0';
12173
12174 putpkt (rs->buf);
12175 getpkt (&rs->buf);
12176 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12177 if (result == PACKET_OK)
12178 {
12179 ULONGEST val;
12180 unpack_varlen_hex (rs->buf.data (), &val);
12181 if (addr)
12182 *addr = (CORE_ADDR) val;
12183 return true;
12184 }
12185 else if (result == PACKET_UNKNOWN)
12186 error (_("Remote target doesn't support qGetTIBAddr packet"));
12187 else
12188 error (_("Remote target failed to process qGetTIBAddr request"));
12189 }
12190 else
12191 error (_("qGetTIBAddr not supported or disabled on this target"));
12192 /* Not reached. */
12193 return false;
12194 }
12195
12196 /* Support for inferring a target description based on the current
12197 architecture and the size of a 'g' packet. While the 'g' packet
12198 can have any size (since optional registers can be left off the
12199 end), some sizes are easily recognizable given knowledge of the
12200 approximate architecture. */
12201
12202 struct remote_g_packet_guess
12203 {
12204 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12205 : bytes (bytes_),
12206 tdesc (tdesc_)
12207 {
12208 }
12209
12210 int bytes;
12211 const struct target_desc *tdesc;
12212 };
12213
12214 struct remote_g_packet_data
12215 {
12216 std::vector<remote_g_packet_guess> guesses;
12217 };
12218
12219 static const registry<gdbarch>::key<struct remote_g_packet_data>
12220 remote_g_packet_data_handle;
12221
12222 static struct remote_g_packet_data *
12223 get_g_packet_data (struct gdbarch *gdbarch)
12224 {
12225 struct remote_g_packet_data *data
12226 = remote_g_packet_data_handle.get (gdbarch);
12227 if (data == nullptr)
12228 data = remote_g_packet_data_handle.emplace (gdbarch);
12229 return data;
12230 }
12231
12232 void
12233 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12234 const struct target_desc *tdesc)
12235 {
12236 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12237
12238 gdb_assert (tdesc != NULL);
12239
12240 for (const remote_g_packet_guess &guess : data->guesses)
12241 if (guess.bytes == bytes)
12242 internal_error (_("Duplicate g packet description added for size %d"),
12243 bytes);
12244
12245 data->guesses.emplace_back (bytes, tdesc);
12246 }
12247
12248 /* Return true if remote_read_description would do anything on this target
12249 and architecture, false otherwise. */
12250
12251 static bool
12252 remote_read_description_p (struct target_ops *target)
12253 {
12254 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12255
12256 return !data->guesses.empty ();
12257 }
12258
12259 const struct target_desc *
12260 remote_target::read_description ()
12261 {
12262 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12263
12264 /* Do not try this during initial connection, when we do not know
12265 whether there is a running but stopped thread. */
12266 if (!target_has_execution () || inferior_ptid == null_ptid)
12267 return beneath ()->read_description ();
12268
12269 if (!data->guesses.empty ())
12270 {
12271 int bytes = send_g_packet ();
12272
12273 for (const remote_g_packet_guess &guess : data->guesses)
12274 if (guess.bytes == bytes)
12275 return guess.tdesc;
12276
12277 /* We discard the g packet. A minor optimization would be to
12278 hold on to it, and fill the register cache once we have selected
12279 an architecture, but it's too tricky to do safely. */
12280 }
12281
12282 return beneath ()->read_description ();
12283 }
12284
12285 /* Remote file transfer support. This is host-initiated I/O, not
12286 target-initiated; for target-initiated, see remote-fileio.c. */
12287
12288 /* If *LEFT is at least the length of STRING, copy STRING to
12289 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12290 decrease *LEFT. Otherwise raise an error. */
12291
12292 static void
12293 remote_buffer_add_string (char **buffer, int *left, const char *string)
12294 {
12295 int len = strlen (string);
12296
12297 if (len > *left)
12298 error (_("Packet too long for target."));
12299
12300 memcpy (*buffer, string, len);
12301 *buffer += len;
12302 *left -= len;
12303
12304 /* NUL-terminate the buffer as a convenience, if there is
12305 room. */
12306 if (*left)
12307 **buffer = '\0';
12308 }
12309
12310 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12311 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12312 decrease *LEFT. Otherwise raise an error. */
12313
12314 static void
12315 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12316 int len)
12317 {
12318 if (2 * len > *left)
12319 error (_("Packet too long for target."));
12320
12321 bin2hex (bytes, *buffer, len);
12322 *buffer += 2 * len;
12323 *left -= 2 * len;
12324
12325 /* NUL-terminate the buffer as a convenience, if there is
12326 room. */
12327 if (*left)
12328 **buffer = '\0';
12329 }
12330
12331 /* If *LEFT is large enough, convert VALUE to hex and add it to
12332 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12333 decrease *LEFT. Otherwise raise an error. */
12334
12335 static void
12336 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12337 {
12338 int len = hexnumlen (value);
12339
12340 if (len > *left)
12341 error (_("Packet too long for target."));
12342
12343 hexnumstr (*buffer, value);
12344 *buffer += len;
12345 *left -= len;
12346
12347 /* NUL-terminate the buffer as a convenience, if there is
12348 room. */
12349 if (*left)
12350 **buffer = '\0';
12351 }
12352
12353 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12354 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12355 was included, and *ATTACHMENT to point to the start of the annex
12356 if any. The length of the packet isn't needed here; there may
12357 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12358
12359 Return 0 if the packet could be parsed, -1 if it could not. If
12360 -1 is returned, the other variables may not be initialized. */
12361
12362 static int
12363 remote_hostio_parse_result (const char *buffer, int *retcode,
12364 fileio_error *remote_errno, const char **attachment)
12365 {
12366 char *p, *p2;
12367
12368 *remote_errno = FILEIO_SUCCESS;
12369 *attachment = NULL;
12370
12371 if (buffer[0] != 'F')
12372 return -1;
12373
12374 errno = 0;
12375 *retcode = strtol (&buffer[1], &p, 16);
12376 if (errno != 0 || p == &buffer[1])
12377 return -1;
12378
12379 /* Check for ",errno". */
12380 if (*p == ',')
12381 {
12382 errno = 0;
12383 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12384 if (errno != 0 || p + 1 == p2)
12385 return -1;
12386 p = p2;
12387 }
12388
12389 /* Check for ";attachment". If there is no attachment, the
12390 packet should end here. */
12391 if (*p == ';')
12392 {
12393 *attachment = p + 1;
12394 return 0;
12395 }
12396 else if (*p == '\0')
12397 return 0;
12398 else
12399 return -1;
12400 }
12401
12402 /* Send a prepared I/O packet to the target and read its response.
12403 The prepared packet is in the global RS->BUF before this function
12404 is called, and the answer is there when we return.
12405
12406 COMMAND_BYTES is the length of the request to send, which may include
12407 binary data. WHICH_PACKET is the packet configuration to check
12408 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12409 is set to the error number and -1 is returned. Otherwise the value
12410 returned by the function is returned.
12411
12412 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12413 attachment is expected; an error will be reported if there's a
12414 mismatch. If one is found, *ATTACHMENT will be set to point into
12415 the packet buffer and *ATTACHMENT_LEN will be set to the
12416 attachment's length. */
12417
12418 int
12419 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12420 fileio_error *remote_errno, const char **attachment,
12421 int *attachment_len)
12422 {
12423 struct remote_state *rs = get_remote_state ();
12424 int ret, bytes_read;
12425 const char *attachment_tmp;
12426
12427 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12428 {
12429 *remote_errno = FILEIO_ENOSYS;
12430 return -1;
12431 }
12432
12433 putpkt_binary (rs->buf.data (), command_bytes);
12434 bytes_read = getpkt (&rs->buf);
12435
12436 /* If it timed out, something is wrong. Don't try to parse the
12437 buffer. */
12438 if (bytes_read < 0)
12439 {
12440 *remote_errno = FILEIO_EINVAL;
12441 return -1;
12442 }
12443
12444 switch (m_features.packet_ok (rs->buf, which_packet))
12445 {
12446 case PACKET_ERROR:
12447 *remote_errno = FILEIO_EINVAL;
12448 return -1;
12449 case PACKET_UNKNOWN:
12450 *remote_errno = FILEIO_ENOSYS;
12451 return -1;
12452 case PACKET_OK:
12453 break;
12454 }
12455
12456 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12457 &attachment_tmp))
12458 {
12459 *remote_errno = FILEIO_EINVAL;
12460 return -1;
12461 }
12462
12463 /* Make sure we saw an attachment if and only if we expected one. */
12464 if ((attachment_tmp == NULL && attachment != NULL)
12465 || (attachment_tmp != NULL && attachment == NULL))
12466 {
12467 *remote_errno = FILEIO_EINVAL;
12468 return -1;
12469 }
12470
12471 /* If an attachment was found, it must point into the packet buffer;
12472 work out how many bytes there were. */
12473 if (attachment_tmp != NULL)
12474 {
12475 *attachment = attachment_tmp;
12476 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12477 }
12478
12479 return ret;
12480 }
12481
12482 /* See declaration.h. */
12483
12484 void
12485 readahead_cache::invalidate ()
12486 {
12487 this->fd = -1;
12488 }
12489
12490 /* See declaration.h. */
12491
12492 void
12493 readahead_cache::invalidate_fd (int fd)
12494 {
12495 if (this->fd == fd)
12496 this->fd = -1;
12497 }
12498
12499 /* Set the filesystem remote_hostio functions that take FILENAME
12500 arguments will use. Return 0 on success, or -1 if an error
12501 occurs (and set *REMOTE_ERRNO). */
12502
12503 int
12504 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12505 fileio_error *remote_errno)
12506 {
12507 struct remote_state *rs = get_remote_state ();
12508 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12509 char *p = rs->buf.data ();
12510 int left = get_remote_packet_size () - 1;
12511 char arg[9];
12512 int ret;
12513
12514 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12515 return 0;
12516
12517 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12518 return 0;
12519
12520 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12521
12522 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12523 remote_buffer_add_string (&p, &left, arg);
12524
12525 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12526 remote_errno, NULL, NULL);
12527
12528 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12529 return 0;
12530
12531 if (ret == 0)
12532 rs->fs_pid = required_pid;
12533
12534 return ret;
12535 }
12536
12537 /* Implementation of to_fileio_open. */
12538
12539 int
12540 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12541 int flags, int mode, int warn_if_slow,
12542 fileio_error *remote_errno)
12543 {
12544 struct remote_state *rs = get_remote_state ();
12545 char *p = rs->buf.data ();
12546 int left = get_remote_packet_size () - 1;
12547
12548 if (warn_if_slow)
12549 {
12550 static int warning_issued = 0;
12551
12552 gdb_printf (_("Reading %s from remote target...\n"),
12553 filename);
12554
12555 if (!warning_issued)
12556 {
12557 warning (_("File transfers from remote targets can be slow."
12558 " Use \"set sysroot\" to access files locally"
12559 " instead."));
12560 warning_issued = 1;
12561 }
12562 }
12563
12564 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12565 return -1;
12566
12567 remote_buffer_add_string (&p, &left, "vFile:open:");
12568
12569 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12570 strlen (filename));
12571 remote_buffer_add_string (&p, &left, ",");
12572
12573 remote_buffer_add_int (&p, &left, flags);
12574 remote_buffer_add_string (&p, &left, ",");
12575
12576 remote_buffer_add_int (&p, &left, mode);
12577
12578 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12579 remote_errno, NULL, NULL);
12580 }
12581
12582 int
12583 remote_target::fileio_open (struct inferior *inf, const char *filename,
12584 int flags, int mode, int warn_if_slow,
12585 fileio_error *remote_errno)
12586 {
12587 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12588 remote_errno);
12589 }
12590
12591 /* Implementation of to_fileio_pwrite. */
12592
12593 int
12594 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12595 ULONGEST offset, fileio_error *remote_errno)
12596 {
12597 struct remote_state *rs = get_remote_state ();
12598 char *p = rs->buf.data ();
12599 int left = get_remote_packet_size ();
12600 int out_len;
12601
12602 rs->readahead_cache.invalidate_fd (fd);
12603
12604 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12605
12606 remote_buffer_add_int (&p, &left, fd);
12607 remote_buffer_add_string (&p, &left, ",");
12608
12609 remote_buffer_add_int (&p, &left, offset);
12610 remote_buffer_add_string (&p, &left, ",");
12611
12612 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12613 (get_remote_packet_size ()
12614 - (p - rs->buf.data ())));
12615
12616 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12617 remote_errno, NULL, NULL);
12618 }
12619
12620 int
12621 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12622 ULONGEST offset, fileio_error *remote_errno)
12623 {
12624 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12625 }
12626
12627 /* Helper for the implementation of to_fileio_pread. Read the file
12628 from the remote side with vFile:pread. */
12629
12630 int
12631 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12632 ULONGEST offset, fileio_error *remote_errno)
12633 {
12634 struct remote_state *rs = get_remote_state ();
12635 char *p = rs->buf.data ();
12636 const char *attachment;
12637 int left = get_remote_packet_size ();
12638 int ret, attachment_len;
12639 int read_len;
12640
12641 remote_buffer_add_string (&p, &left, "vFile:pread:");
12642
12643 remote_buffer_add_int (&p, &left, fd);
12644 remote_buffer_add_string (&p, &left, ",");
12645
12646 remote_buffer_add_int (&p, &left, len);
12647 remote_buffer_add_string (&p, &left, ",");
12648
12649 remote_buffer_add_int (&p, &left, offset);
12650
12651 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12652 remote_errno, &attachment,
12653 &attachment_len);
12654
12655 if (ret < 0)
12656 return ret;
12657
12658 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12659 read_buf, len);
12660 if (read_len != ret)
12661 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12662
12663 return ret;
12664 }
12665
12666 /* See declaration.h. */
12667
12668 int
12669 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12670 ULONGEST offset)
12671 {
12672 if (this->fd == fd
12673 && this->offset <= offset
12674 && offset < this->offset + this->buf.size ())
12675 {
12676 ULONGEST max = this->offset + this->buf.size ();
12677
12678 if (offset + len > max)
12679 len = max - offset;
12680
12681 memcpy (read_buf, &this->buf[offset - this->offset], len);
12682 return len;
12683 }
12684
12685 return 0;
12686 }
12687
12688 /* Implementation of to_fileio_pread. */
12689
12690 int
12691 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12692 ULONGEST offset, fileio_error *remote_errno)
12693 {
12694 int ret;
12695 struct remote_state *rs = get_remote_state ();
12696 readahead_cache *cache = &rs->readahead_cache;
12697
12698 ret = cache->pread (fd, read_buf, len, offset);
12699 if (ret > 0)
12700 {
12701 cache->hit_count++;
12702
12703 remote_debug_printf ("readahead cache hit %s",
12704 pulongest (cache->hit_count));
12705 return ret;
12706 }
12707
12708 cache->miss_count++;
12709
12710 remote_debug_printf ("readahead cache miss %s",
12711 pulongest (cache->miss_count));
12712
12713 cache->fd = fd;
12714 cache->offset = offset;
12715 cache->buf.resize (get_remote_packet_size ());
12716
12717 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12718 cache->buf.size (),
12719 cache->offset, remote_errno);
12720 if (ret <= 0)
12721 {
12722 cache->invalidate_fd (fd);
12723 return ret;
12724 }
12725
12726 cache->buf.resize (ret);
12727 return cache->pread (fd, read_buf, len, offset);
12728 }
12729
12730 int
12731 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12732 ULONGEST offset, fileio_error *remote_errno)
12733 {
12734 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12735 }
12736
12737 /* Implementation of to_fileio_close. */
12738
12739 int
12740 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12741 {
12742 struct remote_state *rs = get_remote_state ();
12743 char *p = rs->buf.data ();
12744 int left = get_remote_packet_size () - 1;
12745
12746 rs->readahead_cache.invalidate_fd (fd);
12747
12748 remote_buffer_add_string (&p, &left, "vFile:close:");
12749
12750 remote_buffer_add_int (&p, &left, fd);
12751
12752 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12753 remote_errno, NULL, NULL);
12754 }
12755
12756 int
12757 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12758 {
12759 return remote_hostio_close (fd, remote_errno);
12760 }
12761
12762 /* Implementation of to_fileio_unlink. */
12763
12764 int
12765 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12766 fileio_error *remote_errno)
12767 {
12768 struct remote_state *rs = get_remote_state ();
12769 char *p = rs->buf.data ();
12770 int left = get_remote_packet_size () - 1;
12771
12772 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12773 return -1;
12774
12775 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12776
12777 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12778 strlen (filename));
12779
12780 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12781 remote_errno, NULL, NULL);
12782 }
12783
12784 int
12785 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12786 fileio_error *remote_errno)
12787 {
12788 return remote_hostio_unlink (inf, filename, remote_errno);
12789 }
12790
12791 /* Implementation of to_fileio_readlink. */
12792
12793 gdb::optional<std::string>
12794 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12795 fileio_error *remote_errno)
12796 {
12797 struct remote_state *rs = get_remote_state ();
12798 char *p = rs->buf.data ();
12799 const char *attachment;
12800 int left = get_remote_packet_size ();
12801 int len, attachment_len;
12802 int read_len;
12803
12804 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12805 return {};
12806
12807 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12808
12809 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12810 strlen (filename));
12811
12812 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12813 remote_errno, &attachment,
12814 &attachment_len);
12815
12816 if (len < 0)
12817 return {};
12818
12819 std::string ret (len, '\0');
12820
12821 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12822 (gdb_byte *) &ret[0], len);
12823 if (read_len != len)
12824 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12825
12826 return ret;
12827 }
12828
12829 /* Implementation of to_fileio_fstat. */
12830
12831 int
12832 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12833 {
12834 struct remote_state *rs = get_remote_state ();
12835 char *p = rs->buf.data ();
12836 int left = get_remote_packet_size ();
12837 int attachment_len, ret;
12838 const char *attachment;
12839 struct fio_stat fst;
12840 int read_len;
12841
12842 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12843
12844 remote_buffer_add_int (&p, &left, fd);
12845
12846 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12847 remote_errno, &attachment,
12848 &attachment_len);
12849 if (ret < 0)
12850 {
12851 if (*remote_errno != FILEIO_ENOSYS)
12852 return ret;
12853
12854 /* Strictly we should return -1, ENOSYS here, but when
12855 "set sysroot remote:" was implemented in August 2008
12856 BFD's need for a stat function was sidestepped with
12857 this hack. This was not remedied until March 2015
12858 so we retain the previous behavior to avoid breaking
12859 compatibility.
12860
12861 Note that the memset is a March 2015 addition; older
12862 GDBs set st_size *and nothing else* so the structure
12863 would have garbage in all other fields. This might
12864 break something but retaining the previous behavior
12865 here would be just too wrong. */
12866
12867 memset (st, 0, sizeof (struct stat));
12868 st->st_size = INT_MAX;
12869 return 0;
12870 }
12871
12872 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12873 (gdb_byte *) &fst, sizeof (fst));
12874
12875 if (read_len != ret)
12876 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12877
12878 if (read_len != sizeof (fst))
12879 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12880 read_len, (int) sizeof (fst));
12881
12882 remote_fileio_to_host_stat (&fst, st);
12883
12884 return 0;
12885 }
12886
12887 /* Implementation of to_filesystem_is_local. */
12888
12889 bool
12890 remote_target::filesystem_is_local ()
12891 {
12892 /* Valgrind GDB presents itself as a remote target but works
12893 on the local filesystem: it does not implement remote get
12894 and users are not expected to set a sysroot. To handle
12895 this case we treat the remote filesystem as local if the
12896 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12897 does not support vFile:open. */
12898 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12899 {
12900 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12901
12902 if (ps == PACKET_SUPPORT_UNKNOWN)
12903 {
12904 int fd;
12905 fileio_error remote_errno;
12906
12907 /* Try opening a file to probe support. The supplied
12908 filename is irrelevant, we only care about whether
12909 the stub recognizes the packet or not. */
12910 fd = remote_hostio_open (NULL, "just probing",
12911 FILEIO_O_RDONLY, 0700, 0,
12912 &remote_errno);
12913
12914 if (fd >= 0)
12915 remote_hostio_close (fd, &remote_errno);
12916
12917 ps = m_features.packet_support (PACKET_vFile_open);
12918 }
12919
12920 if (ps == PACKET_DISABLE)
12921 {
12922 static int warning_issued = 0;
12923
12924 if (!warning_issued)
12925 {
12926 warning (_("remote target does not support file"
12927 " transfer, attempting to access files"
12928 " from local filesystem."));
12929 warning_issued = 1;
12930 }
12931
12932 return true;
12933 }
12934 }
12935
12936 return false;
12937 }
12938
12939 static char *
12940 remote_hostio_error (fileio_error errnum)
12941 {
12942 int host_error = fileio_error_to_host (errnum);
12943
12944 if (host_error == -1)
12945 error (_("Unknown remote I/O error %d"), errnum);
12946 else
12947 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12948 }
12949
12950 /* A RAII wrapper around a remote file descriptor. */
12951
12952 class scoped_remote_fd
12953 {
12954 public:
12955 scoped_remote_fd (remote_target *remote, int fd)
12956 : m_remote (remote), m_fd (fd)
12957 {
12958 }
12959
12960 ~scoped_remote_fd ()
12961 {
12962 if (m_fd != -1)
12963 {
12964 try
12965 {
12966 fileio_error remote_errno;
12967 m_remote->remote_hostio_close (m_fd, &remote_errno);
12968 }
12969 catch (...)
12970 {
12971 /* Swallow exception before it escapes the dtor. If
12972 something goes wrong, likely the connection is gone,
12973 and there's nothing else that can be done. */
12974 }
12975 }
12976 }
12977
12978 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12979
12980 /* Release ownership of the file descriptor, and return it. */
12981 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12982 {
12983 int fd = m_fd;
12984 m_fd = -1;
12985 return fd;
12986 }
12987
12988 /* Return the owned file descriptor. */
12989 int get () const noexcept
12990 {
12991 return m_fd;
12992 }
12993
12994 private:
12995 /* The remote target. */
12996 remote_target *m_remote;
12997
12998 /* The owned remote I/O file descriptor. */
12999 int m_fd;
13000 };
13001
13002 void
13003 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13004 {
13005 remote_target *remote = get_current_remote_target ();
13006
13007 if (remote == nullptr)
13008 error (_("command can only be used with remote target"));
13009
13010 remote->remote_file_put (local_file, remote_file, from_tty);
13011 }
13012
13013 void
13014 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13015 int from_tty)
13016 {
13017 int retcode, bytes, io_size;
13018 fileio_error remote_errno;
13019 int bytes_in_buffer;
13020 int saw_eof;
13021 ULONGEST offset;
13022
13023 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13024 if (file == NULL)
13025 perror_with_name (local_file);
13026
13027 scoped_remote_fd fd
13028 (this, remote_hostio_open (NULL,
13029 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13030 | FILEIO_O_TRUNC),
13031 0700, 0, &remote_errno));
13032 if (fd.get () == -1)
13033 remote_hostio_error (remote_errno);
13034
13035 /* Send up to this many bytes at once. They won't all fit in the
13036 remote packet limit, so we'll transfer slightly fewer. */
13037 io_size = get_remote_packet_size ();
13038 gdb::byte_vector buffer (io_size);
13039
13040 bytes_in_buffer = 0;
13041 saw_eof = 0;
13042 offset = 0;
13043 while (bytes_in_buffer || !saw_eof)
13044 {
13045 if (!saw_eof)
13046 {
13047 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13048 io_size - bytes_in_buffer,
13049 file.get ());
13050 if (bytes == 0)
13051 {
13052 if (ferror (file.get ()))
13053 error (_("Error reading %s."), local_file);
13054 else
13055 {
13056 /* EOF. Unless there is something still in the
13057 buffer from the last iteration, we are done. */
13058 saw_eof = 1;
13059 if (bytes_in_buffer == 0)
13060 break;
13061 }
13062 }
13063 }
13064 else
13065 bytes = 0;
13066
13067 bytes += bytes_in_buffer;
13068 bytes_in_buffer = 0;
13069
13070 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13071 offset, &remote_errno);
13072
13073 if (retcode < 0)
13074 remote_hostio_error (remote_errno);
13075 else if (retcode == 0)
13076 error (_("Remote write of %d bytes returned 0!"), bytes);
13077 else if (retcode < bytes)
13078 {
13079 /* Short write. Save the rest of the read data for the next
13080 write. */
13081 bytes_in_buffer = bytes - retcode;
13082 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13083 }
13084
13085 offset += retcode;
13086 }
13087
13088 if (remote_hostio_close (fd.release (), &remote_errno))
13089 remote_hostio_error (remote_errno);
13090
13091 if (from_tty)
13092 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13093 }
13094
13095 void
13096 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13097 {
13098 remote_target *remote = get_current_remote_target ();
13099
13100 if (remote == nullptr)
13101 error (_("command can only be used with remote target"));
13102
13103 remote->remote_file_get (remote_file, local_file, from_tty);
13104 }
13105
13106 void
13107 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13108 int from_tty)
13109 {
13110 fileio_error remote_errno;
13111 int bytes, io_size;
13112 ULONGEST offset;
13113
13114 scoped_remote_fd fd
13115 (this, remote_hostio_open (NULL,
13116 remote_file, FILEIO_O_RDONLY, 0, 0,
13117 &remote_errno));
13118 if (fd.get () == -1)
13119 remote_hostio_error (remote_errno);
13120
13121 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13122 if (file == NULL)
13123 perror_with_name (local_file);
13124
13125 /* Send up to this many bytes at once. They won't all fit in the
13126 remote packet limit, so we'll transfer slightly fewer. */
13127 io_size = get_remote_packet_size ();
13128 gdb::byte_vector buffer (io_size);
13129
13130 offset = 0;
13131 while (1)
13132 {
13133 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13134 &remote_errno);
13135 if (bytes == 0)
13136 /* Success, but no bytes, means end-of-file. */
13137 break;
13138 if (bytes == -1)
13139 remote_hostio_error (remote_errno);
13140
13141 offset += bytes;
13142
13143 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13144 if (bytes == 0)
13145 perror_with_name (local_file);
13146 }
13147
13148 if (remote_hostio_close (fd.release (), &remote_errno))
13149 remote_hostio_error (remote_errno);
13150
13151 if (from_tty)
13152 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13153 }
13154
13155 void
13156 remote_file_delete (const char *remote_file, int from_tty)
13157 {
13158 remote_target *remote = get_current_remote_target ();
13159
13160 if (remote == nullptr)
13161 error (_("command can only be used with remote target"));
13162
13163 remote->remote_file_delete (remote_file, from_tty);
13164 }
13165
13166 void
13167 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13168 {
13169 int retcode;
13170 fileio_error remote_errno;
13171
13172 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13173 if (retcode == -1)
13174 remote_hostio_error (remote_errno);
13175
13176 if (from_tty)
13177 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13178 }
13179
13180 static void
13181 remote_put_command (const char *args, int from_tty)
13182 {
13183 if (args == NULL)
13184 error_no_arg (_("file to put"));
13185
13186 gdb_argv argv (args);
13187 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13188 error (_("Invalid parameters to remote put"));
13189
13190 remote_file_put (argv[0], argv[1], from_tty);
13191 }
13192
13193 static void
13194 remote_get_command (const char *args, int from_tty)
13195 {
13196 if (args == NULL)
13197 error_no_arg (_("file to get"));
13198
13199 gdb_argv argv (args);
13200 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13201 error (_("Invalid parameters to remote get"));
13202
13203 remote_file_get (argv[0], argv[1], from_tty);
13204 }
13205
13206 static void
13207 remote_delete_command (const char *args, int from_tty)
13208 {
13209 if (args == NULL)
13210 error_no_arg (_("file to delete"));
13211
13212 gdb_argv argv (args);
13213 if (argv[0] == NULL || argv[1] != NULL)
13214 error (_("Invalid parameters to remote delete"));
13215
13216 remote_file_delete (argv[0], from_tty);
13217 }
13218
13219 bool
13220 remote_target::can_execute_reverse ()
13221 {
13222 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13223 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13224 return true;
13225 else
13226 return false;
13227 }
13228
13229 bool
13230 remote_target::supports_non_stop ()
13231 {
13232 return true;
13233 }
13234
13235 bool
13236 remote_target::supports_disable_randomization ()
13237 {
13238 /* Only supported in extended mode. */
13239 return false;
13240 }
13241
13242 bool
13243 remote_target::supports_multi_process ()
13244 {
13245 return m_features.remote_multi_process_p ();
13246 }
13247
13248 int
13249 remote_target::remote_supports_cond_tracepoints ()
13250 {
13251 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13252 == PACKET_ENABLE);
13253 }
13254
13255 bool
13256 remote_target::supports_evaluation_of_breakpoint_conditions ()
13257 {
13258 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13259 == PACKET_ENABLE);
13260 }
13261
13262 int
13263 remote_target::remote_supports_fast_tracepoints ()
13264 {
13265 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13266 }
13267
13268 int
13269 remote_target::remote_supports_static_tracepoints ()
13270 {
13271 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13272 }
13273
13274 int
13275 remote_target::remote_supports_install_in_trace ()
13276 {
13277 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13278 }
13279
13280 bool
13281 remote_target::supports_enable_disable_tracepoint ()
13282 {
13283 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13284 == PACKET_ENABLE);
13285 }
13286
13287 bool
13288 remote_target::supports_string_tracing ()
13289 {
13290 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13291 }
13292
13293 bool
13294 remote_target::can_run_breakpoint_commands ()
13295 {
13296 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13297 }
13298
13299 void
13300 remote_target::trace_init ()
13301 {
13302 struct remote_state *rs = get_remote_state ();
13303
13304 putpkt ("QTinit");
13305 remote_get_noisy_reply ();
13306 if (strcmp (rs->buf.data (), "OK") != 0)
13307 error (_("Target does not support this command."));
13308 }
13309
13310 /* Recursive routine to walk through command list including loops, and
13311 download packets for each command. */
13312
13313 void
13314 remote_target::remote_download_command_source (int num, ULONGEST addr,
13315 struct command_line *cmds)
13316 {
13317 struct remote_state *rs = get_remote_state ();
13318 struct command_line *cmd;
13319
13320 for (cmd = cmds; cmd; cmd = cmd->next)
13321 {
13322 QUIT; /* Allow user to bail out with ^C. */
13323 strcpy (rs->buf.data (), "QTDPsrc:");
13324 encode_source_string (num, addr, "cmd", cmd->line,
13325 rs->buf.data () + strlen (rs->buf.data ()),
13326 rs->buf.size () - strlen (rs->buf.data ()));
13327 putpkt (rs->buf);
13328 remote_get_noisy_reply ();
13329 if (strcmp (rs->buf.data (), "OK"))
13330 warning (_("Target does not support source download."));
13331
13332 if (cmd->control_type == while_control
13333 || cmd->control_type == while_stepping_control)
13334 {
13335 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13336
13337 QUIT; /* Allow user to bail out with ^C. */
13338 strcpy (rs->buf.data (), "QTDPsrc:");
13339 encode_source_string (num, addr, "cmd", "end",
13340 rs->buf.data () + strlen (rs->buf.data ()),
13341 rs->buf.size () - strlen (rs->buf.data ()));
13342 putpkt (rs->buf);
13343 remote_get_noisy_reply ();
13344 if (strcmp (rs->buf.data (), "OK"))
13345 warning (_("Target does not support source download."));
13346 }
13347 }
13348 }
13349
13350 void
13351 remote_target::download_tracepoint (struct bp_location *loc)
13352 {
13353 CORE_ADDR tpaddr;
13354 char addrbuf[40];
13355 std::vector<std::string> tdp_actions;
13356 std::vector<std::string> stepping_actions;
13357 char *pkt;
13358 struct breakpoint *b = loc->owner;
13359 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13360 struct remote_state *rs = get_remote_state ();
13361 int ret;
13362 const char *err_msg = _("Tracepoint packet too large for target.");
13363 size_t size_left;
13364
13365 /* We use a buffer other than rs->buf because we'll build strings
13366 across multiple statements, and other statements in between could
13367 modify rs->buf. */
13368 gdb::char_vector buf (get_remote_packet_size ());
13369
13370 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13371
13372 tpaddr = loc->address;
13373 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13374 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13375 b->number, addrbuf, /* address */
13376 (b->enable_state == bp_enabled ? 'E' : 'D'),
13377 t->step_count, t->pass_count);
13378
13379 if (ret < 0 || ret >= buf.size ())
13380 error ("%s", err_msg);
13381
13382 /* Fast tracepoints are mostly handled by the target, but we can
13383 tell the target how big of an instruction block should be moved
13384 around. */
13385 if (b->type == bp_fast_tracepoint)
13386 {
13387 /* Only test for support at download time; we may not know
13388 target capabilities at definition time. */
13389 if (remote_supports_fast_tracepoints ())
13390 {
13391 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13392 NULL))
13393 {
13394 size_left = buf.size () - strlen (buf.data ());
13395 ret = snprintf (buf.data () + strlen (buf.data ()),
13396 size_left, ":F%x",
13397 gdb_insn_length (loc->gdbarch, tpaddr));
13398
13399 if (ret < 0 || ret >= size_left)
13400 error ("%s", err_msg);
13401 }
13402 else
13403 /* If it passed validation at definition but fails now,
13404 something is very wrong. */
13405 internal_error (_("Fast tracepoint not valid during download"));
13406 }
13407 else
13408 /* Fast tracepoints are functionally identical to regular
13409 tracepoints, so don't take lack of support as a reason to
13410 give up on the trace run. */
13411 warning (_("Target does not support fast tracepoints, "
13412 "downloading %d as regular tracepoint"), b->number);
13413 }
13414 else if (b->type == bp_static_tracepoint
13415 || b->type == bp_static_marker_tracepoint)
13416 {
13417 /* Only test for support at download time; we may not know
13418 target capabilities at definition time. */
13419 if (remote_supports_static_tracepoints ())
13420 {
13421 struct static_tracepoint_marker marker;
13422
13423 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13424 {
13425 size_left = buf.size () - strlen (buf.data ());
13426 ret = snprintf (buf.data () + strlen (buf.data ()),
13427 size_left, ":S");
13428
13429 if (ret < 0 || ret >= size_left)
13430 error ("%s", err_msg);
13431 }
13432 else
13433 error (_("Static tracepoint not valid during download"));
13434 }
13435 else
13436 /* Fast tracepoints are functionally identical to regular
13437 tracepoints, so don't take lack of support as a reason
13438 to give up on the trace run. */
13439 error (_("Target does not support static tracepoints"));
13440 }
13441 /* If the tracepoint has a conditional, make it into an agent
13442 expression and append to the definition. */
13443 if (loc->cond)
13444 {
13445 /* Only test support at download time, we may not know target
13446 capabilities at definition time. */
13447 if (remote_supports_cond_tracepoints ())
13448 {
13449 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13450 loc->cond.get ());
13451
13452 size_left = buf.size () - strlen (buf.data ());
13453
13454 ret = snprintf (buf.data () + strlen (buf.data ()),
13455 size_left, ":X%x,", (int) aexpr->buf.size ());
13456
13457 if (ret < 0 || ret >= size_left)
13458 error ("%s", err_msg);
13459
13460 size_left = buf.size () - strlen (buf.data ());
13461
13462 /* Two bytes to encode each aexpr byte, plus the terminating
13463 null byte. */
13464 if (aexpr->buf.size () * 2 + 1 > size_left)
13465 error ("%s", err_msg);
13466
13467 pkt = buf.data () + strlen (buf.data ());
13468
13469 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13470 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13471 *pkt = '\0';
13472 }
13473 else
13474 warning (_("Target does not support conditional tracepoints, "
13475 "ignoring tp %d cond"), b->number);
13476 }
13477
13478 if (b->commands || !default_collect.empty ())
13479 {
13480 size_left = buf.size () - strlen (buf.data ());
13481
13482 ret = snprintf (buf.data () + strlen (buf.data ()),
13483 size_left, "-");
13484
13485 if (ret < 0 || ret >= size_left)
13486 error ("%s", err_msg);
13487 }
13488
13489 putpkt (buf.data ());
13490 remote_get_noisy_reply ();
13491 if (strcmp (rs->buf.data (), "OK"))
13492 error (_("Target does not support tracepoints."));
13493
13494 /* do_single_steps (t); */
13495 for (auto action_it = tdp_actions.begin ();
13496 action_it != tdp_actions.end (); action_it++)
13497 {
13498 QUIT; /* Allow user to bail out with ^C. */
13499
13500 bool has_more = ((action_it + 1) != tdp_actions.end ()
13501 || !stepping_actions.empty ());
13502
13503 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13504 b->number, addrbuf, /* address */
13505 action_it->c_str (),
13506 has_more ? '-' : 0);
13507
13508 if (ret < 0 || ret >= buf.size ())
13509 error ("%s", err_msg);
13510
13511 putpkt (buf.data ());
13512 remote_get_noisy_reply ();
13513 if (strcmp (rs->buf.data (), "OK"))
13514 error (_("Error on target while setting tracepoints."));
13515 }
13516
13517 for (auto action_it = stepping_actions.begin ();
13518 action_it != stepping_actions.end (); action_it++)
13519 {
13520 QUIT; /* Allow user to bail out with ^C. */
13521
13522 bool is_first = action_it == stepping_actions.begin ();
13523 bool has_more = (action_it + 1) != stepping_actions.end ();
13524
13525 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13526 b->number, addrbuf, /* address */
13527 is_first ? "S" : "",
13528 action_it->c_str (),
13529 has_more ? "-" : "");
13530
13531 if (ret < 0 || ret >= buf.size ())
13532 error ("%s", err_msg);
13533
13534 putpkt (buf.data ());
13535 remote_get_noisy_reply ();
13536 if (strcmp (rs->buf.data (), "OK"))
13537 error (_("Error on target while setting tracepoints."));
13538 }
13539
13540 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13541 {
13542 if (b->locspec != nullptr)
13543 {
13544 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13545
13546 if (ret < 0 || ret >= buf.size ())
13547 error ("%s", err_msg);
13548
13549 const char *str = b->locspec->to_string ();
13550 encode_source_string (b->number, loc->address, "at", str,
13551 buf.data () + strlen (buf.data ()),
13552 buf.size () - strlen (buf.data ()));
13553 putpkt (buf.data ());
13554 remote_get_noisy_reply ();
13555 if (strcmp (rs->buf.data (), "OK"))
13556 warning (_("Target does not support source download."));
13557 }
13558 if (b->cond_string)
13559 {
13560 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13561
13562 if (ret < 0 || ret >= buf.size ())
13563 error ("%s", err_msg);
13564
13565 encode_source_string (b->number, loc->address,
13566 "cond", b->cond_string.get (),
13567 buf.data () + strlen (buf.data ()),
13568 buf.size () - strlen (buf.data ()));
13569 putpkt (buf.data ());
13570 remote_get_noisy_reply ();
13571 if (strcmp (rs->buf.data (), "OK"))
13572 warning (_("Target does not support source download."));
13573 }
13574 remote_download_command_source (b->number, loc->address,
13575 breakpoint_commands (b));
13576 }
13577 }
13578
13579 bool
13580 remote_target::can_download_tracepoint ()
13581 {
13582 struct remote_state *rs = get_remote_state ();
13583 struct trace_status *ts;
13584 int status;
13585
13586 /* Don't try to install tracepoints until we've relocated our
13587 symbols, and fetched and merged the target's tracepoint list with
13588 ours. */
13589 if (rs->starting_up)
13590 return false;
13591
13592 ts = current_trace_status ();
13593 status = get_trace_status (ts);
13594
13595 if (status == -1 || !ts->running_known || !ts->running)
13596 return false;
13597
13598 /* If we are in a tracing experiment, but remote stub doesn't support
13599 installing tracepoint in trace, we have to return. */
13600 if (!remote_supports_install_in_trace ())
13601 return false;
13602
13603 return true;
13604 }
13605
13606
13607 void
13608 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13609 {
13610 struct remote_state *rs = get_remote_state ();
13611 char *p;
13612
13613 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13614 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13615 tsv.builtin);
13616 p = rs->buf.data () + strlen (rs->buf.data ());
13617 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13618 >= get_remote_packet_size ())
13619 error (_("Trace state variable name too long for tsv definition packet"));
13620 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13621 *p++ = '\0';
13622 putpkt (rs->buf);
13623 remote_get_noisy_reply ();
13624 if (rs->buf[0] == '\0')
13625 error (_("Target does not support this command."));
13626 if (strcmp (rs->buf.data (), "OK") != 0)
13627 error (_("Error on target while downloading trace state variable."));
13628 }
13629
13630 void
13631 remote_target::enable_tracepoint (struct bp_location *location)
13632 {
13633 struct remote_state *rs = get_remote_state ();
13634
13635 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13636 location->owner->number,
13637 phex (location->address, sizeof (CORE_ADDR)));
13638 putpkt (rs->buf);
13639 remote_get_noisy_reply ();
13640 if (rs->buf[0] == '\0')
13641 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13642 if (strcmp (rs->buf.data (), "OK") != 0)
13643 error (_("Error on target while enabling tracepoint."));
13644 }
13645
13646 void
13647 remote_target::disable_tracepoint (struct bp_location *location)
13648 {
13649 struct remote_state *rs = get_remote_state ();
13650
13651 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13652 location->owner->number,
13653 phex (location->address, sizeof (CORE_ADDR)));
13654 putpkt (rs->buf);
13655 remote_get_noisy_reply ();
13656 if (rs->buf[0] == '\0')
13657 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13658 if (strcmp (rs->buf.data (), "OK") != 0)
13659 error (_("Error on target while disabling tracepoint."));
13660 }
13661
13662 void
13663 remote_target::trace_set_readonly_regions ()
13664 {
13665 asection *s;
13666 bfd_size_type size;
13667 bfd_vma vma;
13668 int anysecs = 0;
13669 int offset = 0;
13670 bfd *abfd = current_program_space->exec_bfd ();
13671
13672 if (!abfd)
13673 return; /* No information to give. */
13674
13675 struct remote_state *rs = get_remote_state ();
13676
13677 strcpy (rs->buf.data (), "QTro");
13678 offset = strlen (rs->buf.data ());
13679 for (s = abfd->sections; s; s = s->next)
13680 {
13681 char tmp1[40], tmp2[40];
13682 int sec_length;
13683
13684 if ((s->flags & SEC_LOAD) == 0
13685 /* || (s->flags & SEC_CODE) == 0 */
13686 || (s->flags & SEC_READONLY) == 0)
13687 continue;
13688
13689 anysecs = 1;
13690 vma = bfd_section_vma (s);
13691 size = bfd_section_size (s);
13692 bfd_sprintf_vma (abfd, tmp1, vma);
13693 bfd_sprintf_vma (abfd, tmp2, vma + size);
13694 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13695 if (offset + sec_length + 1 > rs->buf.size ())
13696 {
13697 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13698 != PACKET_ENABLE)
13699 warning (_("\
13700 Too many sections for read-only sections definition packet."));
13701 break;
13702 }
13703 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13704 tmp1, tmp2);
13705 offset += sec_length;
13706 }
13707 if (anysecs)
13708 {
13709 putpkt (rs->buf);
13710 getpkt (&rs->buf);
13711 }
13712 }
13713
13714 void
13715 remote_target::trace_start ()
13716 {
13717 struct remote_state *rs = get_remote_state ();
13718
13719 putpkt ("QTStart");
13720 remote_get_noisy_reply ();
13721 if (rs->buf[0] == '\0')
13722 error (_("Target does not support this command."));
13723 if (strcmp (rs->buf.data (), "OK") != 0)
13724 error (_("Bogus reply from target: %s"), rs->buf.data ());
13725 }
13726
13727 int
13728 remote_target::get_trace_status (struct trace_status *ts)
13729 {
13730 /* Initialize it just to avoid a GCC false warning. */
13731 char *p = NULL;
13732 enum packet_result result;
13733 struct remote_state *rs = get_remote_state ();
13734
13735 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13736 return -1;
13737
13738 /* FIXME we need to get register block size some other way. */
13739 trace_regblock_size
13740 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13741
13742 putpkt ("qTStatus");
13743
13744 try
13745 {
13746 p = remote_get_noisy_reply ();
13747 }
13748 catch (const gdb_exception_error &ex)
13749 {
13750 if (ex.error != TARGET_CLOSE_ERROR)
13751 {
13752 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13753 return -1;
13754 }
13755 throw;
13756 }
13757
13758 result = m_features.packet_ok (p, PACKET_qTStatus);
13759
13760 /* If the remote target doesn't do tracing, flag it. */
13761 if (result == PACKET_UNKNOWN)
13762 return -1;
13763
13764 /* We're working with a live target. */
13765 ts->filename = NULL;
13766
13767 if (*p++ != 'T')
13768 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13769
13770 /* Function 'parse_trace_status' sets default value of each field of
13771 'ts' at first, so we don't have to do it here. */
13772 parse_trace_status (p, ts);
13773
13774 return ts->running;
13775 }
13776
13777 void
13778 remote_target::get_tracepoint_status (tracepoint *tp,
13779 struct uploaded_tp *utp)
13780 {
13781 struct remote_state *rs = get_remote_state ();
13782 char *reply;
13783 size_t size = get_remote_packet_size ();
13784
13785 if (tp)
13786 {
13787 tp->hit_count = 0;
13788 tp->traceframe_usage = 0;
13789 for (bp_location &loc : tp->locations ())
13790 {
13791 /* If the tracepoint was never downloaded, don't go asking for
13792 any status. */
13793 if (tp->number_on_target == 0)
13794 continue;
13795 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13796 phex_nz (loc.address, 0));
13797 putpkt (rs->buf);
13798 reply = remote_get_noisy_reply ();
13799 if (reply && *reply)
13800 {
13801 if (*reply == 'V')
13802 parse_tracepoint_status (reply + 1, tp, utp);
13803 }
13804 }
13805 }
13806 else if (utp)
13807 {
13808 utp->hit_count = 0;
13809 utp->traceframe_usage = 0;
13810 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13811 phex_nz (utp->addr, 0));
13812 putpkt (rs->buf);
13813 reply = remote_get_noisy_reply ();
13814 if (reply && *reply)
13815 {
13816 if (*reply == 'V')
13817 parse_tracepoint_status (reply + 1, tp, utp);
13818 }
13819 }
13820 }
13821
13822 void
13823 remote_target::trace_stop ()
13824 {
13825 struct remote_state *rs = get_remote_state ();
13826
13827 putpkt ("QTStop");
13828 remote_get_noisy_reply ();
13829 if (rs->buf[0] == '\0')
13830 error (_("Target does not support this command."));
13831 if (strcmp (rs->buf.data (), "OK") != 0)
13832 error (_("Bogus reply from target: %s"), rs->buf.data ());
13833 }
13834
13835 int
13836 remote_target::trace_find (enum trace_find_type type, int num,
13837 CORE_ADDR addr1, CORE_ADDR addr2,
13838 int *tpp)
13839 {
13840 struct remote_state *rs = get_remote_state ();
13841 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13842 char *p, *reply;
13843 int target_frameno = -1, target_tracept = -1;
13844
13845 /* Lookups other than by absolute frame number depend on the current
13846 trace selected, so make sure it is correct on the remote end
13847 first. */
13848 if (type != tfind_number)
13849 set_remote_traceframe ();
13850
13851 p = rs->buf.data ();
13852 strcpy (p, "QTFrame:");
13853 p = strchr (p, '\0');
13854 switch (type)
13855 {
13856 case tfind_number:
13857 xsnprintf (p, endbuf - p, "%x", num);
13858 break;
13859 case tfind_pc:
13860 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13861 break;
13862 case tfind_tp:
13863 xsnprintf (p, endbuf - p, "tdp:%x", num);
13864 break;
13865 case tfind_range:
13866 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13867 phex_nz (addr2, 0));
13868 break;
13869 case tfind_outside:
13870 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13871 phex_nz (addr2, 0));
13872 break;
13873 default:
13874 error (_("Unknown trace find type %d"), type);
13875 }
13876
13877 putpkt (rs->buf);
13878 reply = remote_get_noisy_reply ();
13879 if (*reply == '\0')
13880 error (_("Target does not support this command."));
13881
13882 while (reply && *reply)
13883 switch (*reply)
13884 {
13885 case 'F':
13886 p = ++reply;
13887 target_frameno = (int) strtol (p, &reply, 16);
13888 if (reply == p)
13889 error (_("Unable to parse trace frame number"));
13890 /* Don't update our remote traceframe number cache on failure
13891 to select a remote traceframe. */
13892 if (target_frameno == -1)
13893 return -1;
13894 break;
13895 case 'T':
13896 p = ++reply;
13897 target_tracept = (int) strtol (p, &reply, 16);
13898 if (reply == p)
13899 error (_("Unable to parse tracepoint number"));
13900 break;
13901 case 'O': /* "OK"? */
13902 if (reply[1] == 'K' && reply[2] == '\0')
13903 reply += 2;
13904 else
13905 error (_("Bogus reply from target: %s"), reply);
13906 break;
13907 default:
13908 error (_("Bogus reply from target: %s"), reply);
13909 }
13910 if (tpp)
13911 *tpp = target_tracept;
13912
13913 rs->remote_traceframe_number = target_frameno;
13914 return target_frameno;
13915 }
13916
13917 bool
13918 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13919 {
13920 struct remote_state *rs = get_remote_state ();
13921 char *reply;
13922 ULONGEST uval;
13923
13924 set_remote_traceframe ();
13925
13926 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13927 putpkt (rs->buf);
13928 reply = remote_get_noisy_reply ();
13929 if (reply && *reply)
13930 {
13931 if (*reply == 'V')
13932 {
13933 unpack_varlen_hex (reply + 1, &uval);
13934 *val = (LONGEST) uval;
13935 return true;
13936 }
13937 }
13938 return false;
13939 }
13940
13941 int
13942 remote_target::save_trace_data (const char *filename)
13943 {
13944 struct remote_state *rs = get_remote_state ();
13945 char *p, *reply;
13946
13947 p = rs->buf.data ();
13948 strcpy (p, "QTSave:");
13949 p += strlen (p);
13950 if ((p - rs->buf.data ()) + strlen (filename) * 2
13951 >= get_remote_packet_size ())
13952 error (_("Remote file name too long for trace save packet"));
13953 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13954 *p++ = '\0';
13955 putpkt (rs->buf);
13956 reply = remote_get_noisy_reply ();
13957 if (*reply == '\0')
13958 error (_("Target does not support this command."));
13959 if (strcmp (reply, "OK") != 0)
13960 error (_("Bogus reply from target: %s"), reply);
13961 return 0;
13962 }
13963
13964 /* This is basically a memory transfer, but needs to be its own packet
13965 because we don't know how the target actually organizes its trace
13966 memory, plus we want to be able to ask for as much as possible, but
13967 not be unhappy if we don't get as much as we ask for. */
13968
13969 LONGEST
13970 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13971 {
13972 struct remote_state *rs = get_remote_state ();
13973 char *reply;
13974 char *p;
13975 int rslt;
13976
13977 p = rs->buf.data ();
13978 strcpy (p, "qTBuffer:");
13979 p += strlen (p);
13980 p += hexnumstr (p, offset);
13981 *p++ = ',';
13982 p += hexnumstr (p, len);
13983 *p++ = '\0';
13984
13985 putpkt (rs->buf);
13986 reply = remote_get_noisy_reply ();
13987 if (reply && *reply)
13988 {
13989 /* 'l' by itself means we're at the end of the buffer and
13990 there is nothing more to get. */
13991 if (*reply == 'l')
13992 return 0;
13993
13994 /* Convert the reply into binary. Limit the number of bytes to
13995 convert according to our passed-in buffer size, rather than
13996 what was returned in the packet; if the target is
13997 unexpectedly generous and gives us a bigger reply than we
13998 asked for, we don't want to crash. */
13999 rslt = hex2bin (reply, buf, len);
14000 return rslt;
14001 }
14002
14003 /* Something went wrong, flag as an error. */
14004 return -1;
14005 }
14006
14007 void
14008 remote_target::set_disconnected_tracing (int val)
14009 {
14010 struct remote_state *rs = get_remote_state ();
14011
14012 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14013 == PACKET_ENABLE)
14014 {
14015 char *reply;
14016
14017 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14018 "QTDisconnected:%x", val);
14019 putpkt (rs->buf);
14020 reply = remote_get_noisy_reply ();
14021 if (*reply == '\0')
14022 error (_("Target does not support this command."));
14023 if (strcmp (reply, "OK") != 0)
14024 error (_("Bogus reply from target: %s"), reply);
14025 }
14026 else if (val)
14027 warning (_("Target does not support disconnected tracing."));
14028 }
14029
14030 int
14031 remote_target::core_of_thread (ptid_t ptid)
14032 {
14033 thread_info *info = this->find_thread (ptid);
14034
14035 if (info != NULL && info->priv != NULL)
14036 return get_remote_thread_info (info)->core;
14037
14038 return -1;
14039 }
14040
14041 void
14042 remote_target::set_circular_trace_buffer (int val)
14043 {
14044 struct remote_state *rs = get_remote_state ();
14045 char *reply;
14046
14047 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14048 "QTBuffer:circular:%x", val);
14049 putpkt (rs->buf);
14050 reply = remote_get_noisy_reply ();
14051 if (*reply == '\0')
14052 error (_("Target does not support this command."));
14053 if (strcmp (reply, "OK") != 0)
14054 error (_("Bogus reply from target: %s"), reply);
14055 }
14056
14057 traceframe_info_up
14058 remote_target::traceframe_info ()
14059 {
14060 gdb::optional<gdb::char_vector> text
14061 = target_read_stralloc (current_inferior ()->top_target (),
14062 TARGET_OBJECT_TRACEFRAME_INFO,
14063 NULL);
14064 if (text)
14065 return parse_traceframe_info (text->data ());
14066
14067 return NULL;
14068 }
14069
14070 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14071 instruction on which a fast tracepoint may be placed. Returns -1
14072 if the packet is not supported, and 0 if the minimum instruction
14073 length is unknown. */
14074
14075 int
14076 remote_target::get_min_fast_tracepoint_insn_len ()
14077 {
14078 struct remote_state *rs = get_remote_state ();
14079 char *reply;
14080
14081 /* If we're not debugging a process yet, the IPA can't be
14082 loaded. */
14083 if (!target_has_execution ())
14084 return 0;
14085
14086 /* Make sure the remote is pointing at the right process. */
14087 set_general_process ();
14088
14089 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14090 putpkt (rs->buf);
14091 reply = remote_get_noisy_reply ();
14092 if (*reply == '\0')
14093 return -1;
14094 else
14095 {
14096 ULONGEST min_insn_len;
14097
14098 unpack_varlen_hex (reply, &min_insn_len);
14099
14100 return (int) min_insn_len;
14101 }
14102 }
14103
14104 void
14105 remote_target::set_trace_buffer_size (LONGEST val)
14106 {
14107 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14108 {
14109 struct remote_state *rs = get_remote_state ();
14110 char *buf = rs->buf.data ();
14111 char *endbuf = buf + get_remote_packet_size ();
14112 enum packet_result result;
14113
14114 gdb_assert (val >= 0 || val == -1);
14115 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14116 /* Send -1 as literal "-1" to avoid host size dependency. */
14117 if (val < 0)
14118 {
14119 *buf++ = '-';
14120 buf += hexnumstr (buf, (ULONGEST) -val);
14121 }
14122 else
14123 buf += hexnumstr (buf, (ULONGEST) val);
14124
14125 putpkt (rs->buf);
14126 remote_get_noisy_reply ();
14127 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14128
14129 if (result != PACKET_OK)
14130 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14131 }
14132 }
14133
14134 bool
14135 remote_target::set_trace_notes (const char *user, const char *notes,
14136 const char *stop_notes)
14137 {
14138 struct remote_state *rs = get_remote_state ();
14139 char *reply;
14140 char *buf = rs->buf.data ();
14141 char *endbuf = buf + get_remote_packet_size ();
14142 int nbytes;
14143
14144 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14145 if (user)
14146 {
14147 buf += xsnprintf (buf, endbuf - buf, "user:");
14148 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14149 buf += 2 * nbytes;
14150 *buf++ = ';';
14151 }
14152 if (notes)
14153 {
14154 buf += xsnprintf (buf, endbuf - buf, "notes:");
14155 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14156 buf += 2 * nbytes;
14157 *buf++ = ';';
14158 }
14159 if (stop_notes)
14160 {
14161 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14162 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14163 buf += 2 * nbytes;
14164 *buf++ = ';';
14165 }
14166 /* Ensure the buffer is terminated. */
14167 *buf = '\0';
14168
14169 putpkt (rs->buf);
14170 reply = remote_get_noisy_reply ();
14171 if (*reply == '\0')
14172 return false;
14173
14174 if (strcmp (reply, "OK") != 0)
14175 error (_("Bogus reply from target: %s"), reply);
14176
14177 return true;
14178 }
14179
14180 bool
14181 remote_target::use_agent (bool use)
14182 {
14183 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14184 {
14185 struct remote_state *rs = get_remote_state ();
14186
14187 /* If the stub supports QAgent. */
14188 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14189 putpkt (rs->buf);
14190 getpkt (&rs->buf);
14191
14192 if (strcmp (rs->buf.data (), "OK") == 0)
14193 {
14194 ::use_agent = use;
14195 return true;
14196 }
14197 }
14198
14199 return false;
14200 }
14201
14202 bool
14203 remote_target::can_use_agent ()
14204 {
14205 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14206 }
14207
14208 #if defined (HAVE_LIBEXPAT)
14209
14210 /* Check the btrace document version. */
14211
14212 static void
14213 check_xml_btrace_version (struct gdb_xml_parser *parser,
14214 const struct gdb_xml_element *element,
14215 void *user_data,
14216 std::vector<gdb_xml_value> &attributes)
14217 {
14218 const char *version
14219 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14220
14221 if (strcmp (version, "1.0") != 0)
14222 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14223 }
14224
14225 /* Parse a btrace "block" xml record. */
14226
14227 static void
14228 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14229 const struct gdb_xml_element *element,
14230 void *user_data,
14231 std::vector<gdb_xml_value> &attributes)
14232 {
14233 struct btrace_data *btrace;
14234 ULONGEST *begin, *end;
14235
14236 btrace = (struct btrace_data *) user_data;
14237
14238 switch (btrace->format)
14239 {
14240 case BTRACE_FORMAT_BTS:
14241 break;
14242
14243 case BTRACE_FORMAT_NONE:
14244 btrace->format = BTRACE_FORMAT_BTS;
14245 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14246 break;
14247
14248 default:
14249 gdb_xml_error (parser, _("Btrace format error."));
14250 }
14251
14252 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14253 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14254 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14255 }
14256
14257 /* Parse a "raw" xml record. */
14258
14259 static void
14260 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14261 gdb_byte **pdata, size_t *psize)
14262 {
14263 gdb_byte *bin;
14264 size_t len, size;
14265
14266 len = strlen (body_text);
14267 if (len % 2 != 0)
14268 gdb_xml_error (parser, _("Bad raw data size."));
14269
14270 size = len / 2;
14271
14272 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14273 bin = data.get ();
14274
14275 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14276 while (len > 0)
14277 {
14278 char hi, lo;
14279
14280 hi = *body_text++;
14281 lo = *body_text++;
14282
14283 if (hi == 0 || lo == 0)
14284 gdb_xml_error (parser, _("Bad hex encoding."));
14285
14286 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14287 len -= 2;
14288 }
14289
14290 *pdata = data.release ();
14291 *psize = size;
14292 }
14293
14294 /* Parse a btrace pt-config "cpu" xml record. */
14295
14296 static void
14297 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14298 const struct gdb_xml_element *element,
14299 void *user_data,
14300 std::vector<gdb_xml_value> &attributes)
14301 {
14302 struct btrace_data *btrace;
14303 const char *vendor;
14304 ULONGEST *family, *model, *stepping;
14305
14306 vendor
14307 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14308 family
14309 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14310 model
14311 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14312 stepping
14313 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14314
14315 btrace = (struct btrace_data *) user_data;
14316
14317 if (strcmp (vendor, "GenuineIntel") == 0)
14318 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14319
14320 btrace->variant.pt.config.cpu.family = *family;
14321 btrace->variant.pt.config.cpu.model = *model;
14322 btrace->variant.pt.config.cpu.stepping = *stepping;
14323 }
14324
14325 /* Parse a btrace pt "raw" xml record. */
14326
14327 static void
14328 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14329 const struct gdb_xml_element *element,
14330 void *user_data, const char *body_text)
14331 {
14332 struct btrace_data *btrace;
14333
14334 btrace = (struct btrace_data *) user_data;
14335 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14336 &btrace->variant.pt.size);
14337 }
14338
14339 /* Parse a btrace "pt" xml record. */
14340
14341 static void
14342 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14343 const struct gdb_xml_element *element,
14344 void *user_data,
14345 std::vector<gdb_xml_value> &attributes)
14346 {
14347 struct btrace_data *btrace;
14348
14349 btrace = (struct btrace_data *) user_data;
14350 btrace->format = BTRACE_FORMAT_PT;
14351 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14352 btrace->variant.pt.data = NULL;
14353 btrace->variant.pt.size = 0;
14354 }
14355
14356 static const struct gdb_xml_attribute block_attributes[] = {
14357 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14358 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14359 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14360 };
14361
14362 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14363 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14364 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14365 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14366 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14367 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14368 };
14369
14370 static const struct gdb_xml_element btrace_pt_config_children[] = {
14371 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14372 parse_xml_btrace_pt_config_cpu, NULL },
14373 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14374 };
14375
14376 static const struct gdb_xml_element btrace_pt_children[] = {
14377 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14378 NULL },
14379 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14380 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14381 };
14382
14383 static const struct gdb_xml_attribute btrace_attributes[] = {
14384 { "version", GDB_XML_AF_NONE, NULL, NULL },
14385 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14386 };
14387
14388 static const struct gdb_xml_element btrace_children[] = {
14389 { "block", block_attributes, NULL,
14390 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14391 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14392 NULL },
14393 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14394 };
14395
14396 static const struct gdb_xml_element btrace_elements[] = {
14397 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14398 check_xml_btrace_version, NULL },
14399 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14400 };
14401
14402 #endif /* defined (HAVE_LIBEXPAT) */
14403
14404 /* Parse a branch trace xml document XML into DATA. */
14405
14406 static void
14407 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14408 {
14409 #if defined (HAVE_LIBEXPAT)
14410
14411 int errcode;
14412 btrace_data result;
14413 result.format = BTRACE_FORMAT_NONE;
14414
14415 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14416 buffer, &result);
14417 if (errcode != 0)
14418 error (_("Error parsing branch trace."));
14419
14420 /* Keep parse results. */
14421 *btrace = std::move (result);
14422
14423 #else /* !defined (HAVE_LIBEXPAT) */
14424
14425 error (_("Cannot process branch trace. XML support was disabled at "
14426 "compile time."));
14427
14428 #endif /* !defined (HAVE_LIBEXPAT) */
14429 }
14430
14431 #if defined (HAVE_LIBEXPAT)
14432
14433 /* Parse a btrace-conf "bts" xml record. */
14434
14435 static void
14436 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14437 const struct gdb_xml_element *element,
14438 void *user_data,
14439 std::vector<gdb_xml_value> &attributes)
14440 {
14441 struct btrace_config *conf;
14442 struct gdb_xml_value *size;
14443
14444 conf = (struct btrace_config *) user_data;
14445 conf->format = BTRACE_FORMAT_BTS;
14446 conf->bts.size = 0;
14447
14448 size = xml_find_attribute (attributes, "size");
14449 if (size != NULL)
14450 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14451 }
14452
14453 /* Parse a btrace-conf "pt" xml record. */
14454
14455 static void
14456 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14457 const struct gdb_xml_element *element,
14458 void *user_data,
14459 std::vector<gdb_xml_value> &attributes)
14460 {
14461 struct btrace_config *conf;
14462 struct gdb_xml_value *size;
14463
14464 conf = (struct btrace_config *) user_data;
14465 conf->format = BTRACE_FORMAT_PT;
14466 conf->pt.size = 0;
14467
14468 size = xml_find_attribute (attributes, "size");
14469 if (size != NULL)
14470 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14471 }
14472
14473 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14474 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14475 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14476 };
14477
14478 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14479 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14480 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14481 };
14482
14483 static const struct gdb_xml_element btrace_conf_children[] = {
14484 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14485 parse_xml_btrace_conf_bts, NULL },
14486 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14487 parse_xml_btrace_conf_pt, NULL },
14488 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14489 };
14490
14491 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14492 { "version", GDB_XML_AF_NONE, NULL, NULL },
14493 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14494 };
14495
14496 static const struct gdb_xml_element btrace_conf_elements[] = {
14497 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14498 GDB_XML_EF_NONE, NULL, NULL },
14499 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14500 };
14501
14502 #endif /* defined (HAVE_LIBEXPAT) */
14503
14504 /* Parse a branch trace configuration xml document XML into CONF. */
14505
14506 static void
14507 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14508 {
14509 #if defined (HAVE_LIBEXPAT)
14510
14511 int errcode;
14512 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14513 btrace_conf_elements, xml, conf);
14514 if (errcode != 0)
14515 error (_("Error parsing branch trace configuration."));
14516
14517 #else /* !defined (HAVE_LIBEXPAT) */
14518
14519 error (_("Cannot process the branch trace configuration. XML support "
14520 "was disabled at compile time."));
14521
14522 #endif /* !defined (HAVE_LIBEXPAT) */
14523 }
14524
14525 /* Reset our idea of our target's btrace configuration. */
14526
14527 static void
14528 remote_btrace_reset (remote_state *rs)
14529 {
14530 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14531 }
14532
14533 /* Synchronize the configuration with the target. */
14534
14535 void
14536 remote_target::btrace_sync_conf (const btrace_config *conf)
14537 {
14538 struct remote_state *rs;
14539 char *buf, *pos, *endbuf;
14540
14541 rs = get_remote_state ();
14542 buf = rs->buf.data ();
14543 endbuf = buf + get_remote_packet_size ();
14544
14545 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14546 && conf->bts.size != rs->btrace_config.bts.size)
14547 {
14548 pos = buf;
14549 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14550 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14551 conf->bts.size);
14552
14553 putpkt (buf);
14554 getpkt (&rs->buf);
14555
14556 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14557 == PACKET_ERROR)
14558 {
14559 if (buf[0] == 'E' && buf[1] == '.')
14560 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14561 else
14562 error (_("Failed to configure the BTS buffer size."));
14563 }
14564
14565 rs->btrace_config.bts.size = conf->bts.size;
14566 }
14567
14568 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14569 && conf->pt.size != rs->btrace_config.pt.size)
14570 {
14571 pos = buf;
14572 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14573 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14574 conf->pt.size);
14575
14576 putpkt (buf);
14577 getpkt (&rs->buf);
14578
14579 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14580 == PACKET_ERROR)
14581 {
14582 if (buf[0] == 'E' && buf[1] == '.')
14583 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14584 else
14585 error (_("Failed to configure the trace buffer size."));
14586 }
14587
14588 rs->btrace_config.pt.size = conf->pt.size;
14589 }
14590 }
14591
14592 /* Read TP's btrace configuration from the target and store it into CONF. */
14593
14594 static void
14595 btrace_read_config (thread_info *tp, btrace_config *conf)
14596 {
14597 /* target_read_stralloc relies on INFERIOR_PTID. */
14598 scoped_restore_current_thread restore_thread;
14599 switch_to_thread (tp);
14600
14601 gdb::optional<gdb::char_vector> xml
14602 = target_read_stralloc (current_inferior ()->top_target (),
14603 TARGET_OBJECT_BTRACE_CONF, "");
14604 if (xml)
14605 parse_xml_btrace_conf (conf, xml->data ());
14606 }
14607
14608 /* Maybe reopen target btrace. */
14609
14610 void
14611 remote_target::remote_btrace_maybe_reopen ()
14612 {
14613 struct remote_state *rs = get_remote_state ();
14614 int btrace_target_pushed = 0;
14615 #if !defined (HAVE_LIBIPT)
14616 int warned = 0;
14617 #endif
14618
14619 /* Don't bother walking the entirety of the remote thread list when
14620 we know the feature isn't supported by the remote. */
14621 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14622 return;
14623
14624 for (thread_info *tp : all_non_exited_threads (this))
14625 {
14626 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14627 btrace_read_config (tp, &rs->btrace_config);
14628
14629 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14630 continue;
14631
14632 #if !defined (HAVE_LIBIPT)
14633 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14634 {
14635 if (!warned)
14636 {
14637 warned = 1;
14638 warning (_("Target is recording using Intel Processor Trace "
14639 "but support was disabled at compile time."));
14640 }
14641
14642 continue;
14643 }
14644 #endif /* !defined (HAVE_LIBIPT) */
14645
14646 /* Push target, once, but before anything else happens. This way our
14647 changes to the threads will be cleaned up by unpushing the target
14648 in case btrace_read_config () throws. */
14649 if (!btrace_target_pushed)
14650 {
14651 btrace_target_pushed = 1;
14652 record_btrace_push_target ();
14653 gdb_printf (_("Target is recording using %s.\n"),
14654 btrace_format_string (rs->btrace_config.format));
14655 }
14656
14657 tp->btrace.target
14658 = new btrace_target_info { tp->ptid, rs->btrace_config };
14659 }
14660 }
14661
14662 /* Enable branch tracing. */
14663
14664 struct btrace_target_info *
14665 remote_target::enable_btrace (thread_info *tp,
14666 const struct btrace_config *conf)
14667 {
14668 struct packet_config *packet = NULL;
14669 struct remote_state *rs = get_remote_state ();
14670 char *buf = rs->buf.data ();
14671 char *endbuf = buf + get_remote_packet_size ();
14672
14673 unsigned int which_packet;
14674 switch (conf->format)
14675 {
14676 case BTRACE_FORMAT_BTS:
14677 which_packet = PACKET_Qbtrace_bts;
14678 break;
14679 case BTRACE_FORMAT_PT:
14680 which_packet = PACKET_Qbtrace_pt;
14681 break;
14682 default:
14683 internal_error (_("Bad branch btrace format: %u."),
14684 (unsigned int) conf->format);
14685 }
14686
14687 packet = &m_features.m_protocol_packets[which_packet];
14688 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14689 error (_("Target does not support branch tracing."));
14690
14691 btrace_sync_conf (conf);
14692
14693 ptid_t ptid = tp->ptid;
14694 set_general_thread (ptid);
14695
14696 buf += xsnprintf (buf, endbuf - buf, "%s",
14697 packets_descriptions[which_packet].name);
14698 putpkt (rs->buf);
14699 getpkt (&rs->buf);
14700
14701 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14702 {
14703 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14704 error (_("Could not enable branch tracing for %s: %s"),
14705 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14706 else
14707 error (_("Could not enable branch tracing for %s."),
14708 target_pid_to_str (ptid).c_str ());
14709 }
14710
14711 btrace_target_info *tinfo = new btrace_target_info { ptid };
14712
14713 /* If we fail to read the configuration, we lose some information, but the
14714 tracing itself is not impacted. */
14715 try
14716 {
14717 btrace_read_config (tp, &tinfo->conf);
14718 }
14719 catch (const gdb_exception_error &err)
14720 {
14721 if (err.message != NULL)
14722 warning ("%s", err.what ());
14723 }
14724
14725 return tinfo;
14726 }
14727
14728 /* Disable branch tracing. */
14729
14730 void
14731 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14732 {
14733 struct remote_state *rs = get_remote_state ();
14734 char *buf = rs->buf.data ();
14735 char *endbuf = buf + get_remote_packet_size ();
14736
14737 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14738 error (_("Target does not support branch tracing."));
14739
14740 set_general_thread (tinfo->ptid);
14741
14742 buf += xsnprintf (buf, endbuf - buf, "%s",
14743 packets_descriptions[PACKET_Qbtrace_off].name);
14744 putpkt (rs->buf);
14745 getpkt (&rs->buf);
14746
14747 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14748 {
14749 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14750 error (_("Could not disable branch tracing for %s: %s"),
14751 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14752 else
14753 error (_("Could not disable branch tracing for %s."),
14754 target_pid_to_str (tinfo->ptid).c_str ());
14755 }
14756
14757 delete tinfo;
14758 }
14759
14760 /* Teardown branch tracing. */
14761
14762 void
14763 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14764 {
14765 /* We must not talk to the target during teardown. */
14766 delete tinfo;
14767 }
14768
14769 /* Read the branch trace. */
14770
14771 enum btrace_error
14772 remote_target::read_btrace (struct btrace_data *btrace,
14773 struct btrace_target_info *tinfo,
14774 enum btrace_read_type type)
14775 {
14776 const char *annex;
14777
14778 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14779 error (_("Target does not support branch tracing."));
14780
14781 #if !defined(HAVE_LIBEXPAT)
14782 error (_("Cannot process branch tracing result. XML parsing not supported."));
14783 #endif
14784
14785 switch (type)
14786 {
14787 case BTRACE_READ_ALL:
14788 annex = "all";
14789 break;
14790 case BTRACE_READ_NEW:
14791 annex = "new";
14792 break;
14793 case BTRACE_READ_DELTA:
14794 annex = "delta";
14795 break;
14796 default:
14797 internal_error (_("Bad branch tracing read type: %u."),
14798 (unsigned int) type);
14799 }
14800
14801 gdb::optional<gdb::char_vector> xml
14802 = target_read_stralloc (current_inferior ()->top_target (),
14803 TARGET_OBJECT_BTRACE, annex);
14804 if (!xml)
14805 return BTRACE_ERR_UNKNOWN;
14806
14807 parse_xml_btrace (btrace, xml->data ());
14808
14809 return BTRACE_ERR_NONE;
14810 }
14811
14812 const struct btrace_config *
14813 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14814 {
14815 return &tinfo->conf;
14816 }
14817
14818 bool
14819 remote_target::augmented_libraries_svr4_read ()
14820 {
14821 return
14822 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14823 == PACKET_ENABLE);
14824 }
14825
14826 /* Implementation of to_load. */
14827
14828 void
14829 remote_target::load (const char *name, int from_tty)
14830 {
14831 generic_load (name, from_tty);
14832 }
14833
14834 /* Accepts an integer PID; returns a string representing a file that
14835 can be opened on the remote side to get the symbols for the child
14836 process. Returns NULL if the operation is not supported. */
14837
14838 const char *
14839 remote_target::pid_to_exec_file (int pid)
14840 {
14841 static gdb::optional<gdb::char_vector> filename;
14842 char *annex = NULL;
14843
14844 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14845 return NULL;
14846
14847 inferior *inf = find_inferior_pid (this, pid);
14848 if (inf == NULL)
14849 internal_error (_("not currently attached to process %d"), pid);
14850
14851 if (!inf->fake_pid_p)
14852 {
14853 const int annex_size = 9;
14854
14855 annex = (char *) alloca (annex_size);
14856 xsnprintf (annex, annex_size, "%x", pid);
14857 }
14858
14859 filename = target_read_stralloc (current_inferior ()->top_target (),
14860 TARGET_OBJECT_EXEC_FILE, annex);
14861
14862 return filename ? filename->data () : nullptr;
14863 }
14864
14865 /* Implement the to_can_do_single_step target_ops method. */
14866
14867 int
14868 remote_target::can_do_single_step ()
14869 {
14870 /* We can only tell whether target supports single step or not by
14871 supported s and S vCont actions if the stub supports vContSupported
14872 feature. If the stub doesn't support vContSupported feature,
14873 we have conservatively to think target doesn't supports single
14874 step. */
14875 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14876 {
14877 struct remote_state *rs = get_remote_state ();
14878
14879 return rs->supports_vCont.s && rs->supports_vCont.S;
14880 }
14881 else
14882 return 0;
14883 }
14884
14885 /* Implementation of the to_execution_direction method for the remote
14886 target. */
14887
14888 enum exec_direction_kind
14889 remote_target::execution_direction ()
14890 {
14891 struct remote_state *rs = get_remote_state ();
14892
14893 return rs->last_resume_exec_dir;
14894 }
14895
14896 /* Return pointer to the thread_info struct which corresponds to
14897 THREAD_HANDLE (having length HANDLE_LEN). */
14898
14899 thread_info *
14900 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14901 int handle_len,
14902 inferior *inf)
14903 {
14904 for (thread_info *tp : all_non_exited_threads (this))
14905 {
14906 remote_thread_info *priv = get_remote_thread_info (tp);
14907
14908 if (tp->inf == inf && priv != NULL)
14909 {
14910 if (handle_len != priv->thread_handle.size ())
14911 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14912 handle_len, priv->thread_handle.size ());
14913 if (memcmp (thread_handle, priv->thread_handle.data (),
14914 handle_len) == 0)
14915 return tp;
14916 }
14917 }
14918
14919 return NULL;
14920 }
14921
14922 gdb::array_view<const gdb_byte>
14923 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14924 {
14925 remote_thread_info *priv = get_remote_thread_info (tp);
14926 return priv->thread_handle;
14927 }
14928
14929 bool
14930 remote_target::can_async_p ()
14931 {
14932 /* This flag should be checked in the common target.c code. */
14933 gdb_assert (target_async_permitted);
14934
14935 /* We're async whenever the serial device can. */
14936 return get_remote_state ()->can_async_p ();
14937 }
14938
14939 bool
14940 remote_target::is_async_p ()
14941 {
14942 /* We're async whenever the serial device is. */
14943 return get_remote_state ()->is_async_p ();
14944 }
14945
14946 /* Pass the SERIAL event on and up to the client. One day this code
14947 will be able to delay notifying the client of an event until the
14948 point where an entire packet has been received. */
14949
14950 static serial_event_ftype remote_async_serial_handler;
14951
14952 static void
14953 remote_async_serial_handler (struct serial *scb, void *context)
14954 {
14955 /* Don't propogate error information up to the client. Instead let
14956 the client find out about the error by querying the target. */
14957 inferior_event_handler (INF_REG_EVENT);
14958 }
14959
14960 int
14961 remote_target::async_wait_fd ()
14962 {
14963 struct remote_state *rs = get_remote_state ();
14964 return rs->remote_desc->fd;
14965 }
14966
14967 void
14968 remote_target::async (bool enable)
14969 {
14970 struct remote_state *rs = get_remote_state ();
14971
14972 if (enable)
14973 {
14974 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14975
14976 /* If there are pending events in the stop reply queue tell the
14977 event loop to process them. */
14978 if (!rs->stop_reply_queue.empty ())
14979 rs->mark_async_event_handler ();
14980
14981 /* For simplicity, below we clear the pending events token
14982 without remembering whether it is marked, so here we always
14983 mark it. If there's actually no pending notification to
14984 process, this ends up being a no-op (other than a spurious
14985 event-loop wakeup). */
14986 if (target_is_non_stop_p ())
14987 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14988 }
14989 else
14990 {
14991 serial_async (rs->remote_desc, NULL, NULL);
14992 /* If the core is disabling async, it doesn't want to be
14993 disturbed with target events. Clear all async event sources
14994 too. */
14995 rs->clear_async_event_handler ();
14996
14997 if (target_is_non_stop_p ())
14998 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14999 }
15000 }
15001
15002 /* Implementation of the to_thread_events method. */
15003
15004 void
15005 remote_target::thread_events (int enable)
15006 {
15007 struct remote_state *rs = get_remote_state ();
15008 size_t size = get_remote_packet_size ();
15009
15010 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15011 return;
15012
15013 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15014 putpkt (rs->buf);
15015 getpkt (&rs->buf);
15016
15017 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
15018 {
15019 case PACKET_OK:
15020 if (strcmp (rs->buf.data (), "OK") != 0)
15021 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15022 break;
15023 case PACKET_ERROR:
15024 warning (_("Remote failure reply: %s"), rs->buf.data ());
15025 break;
15026 case PACKET_UNKNOWN:
15027 break;
15028 }
15029 }
15030
15031 static void
15032 show_remote_cmd (const char *args, int from_tty)
15033 {
15034 /* We can't just use cmd_show_list here, because we want to skip
15035 the redundant "show remote Z-packet" and the legacy aliases. */
15036 struct cmd_list_element *list = remote_show_cmdlist;
15037 struct ui_out *uiout = current_uiout;
15038
15039 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15040 for (; list != NULL; list = list->next)
15041 if (strcmp (list->name, "Z-packet") == 0)
15042 continue;
15043 else if (list->type == not_set_cmd)
15044 /* Alias commands are exactly like the original, except they
15045 don't have the normal type. */
15046 continue;
15047 else
15048 {
15049 ui_out_emit_tuple option_emitter (uiout, "option");
15050
15051 uiout->field_string ("name", list->name);
15052 uiout->text (": ");
15053 if (list->type == show_cmd)
15054 do_show_command (NULL, from_tty, list);
15055 else
15056 cmd_func (list, NULL, from_tty);
15057 }
15058 }
15059
15060 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15061 offer all inferiors using that program space a change to look up symbols. */
15062
15063 static void
15064 remote_objfile_changed_check_symbols (program_space *pspace)
15065 {
15066 /* The affected program space is possibly shared by multiple inferiors.
15067 Consider sending a qSymbol packet for each of the inferiors using that
15068 program space. */
15069 for (inferior *inf : all_inferiors ())
15070 {
15071 if (inf->pspace != pspace)
15072 continue;
15073
15074 /* Check whether the inferior's process target is a remote target. */
15075 remote_target *remote = as_remote_target (inf->process_target ());
15076 if (remote == nullptr)
15077 continue;
15078
15079 /* When we are attaching or handling a fork child and the shared library
15080 subsystem reads the list of loaded libraries, we receive new objfile
15081 events in between each found library. The libraries are read in an
15082 undefined order, so if we gave the remote side a chance to look up
15083 symbols between each objfile, we might give it an inconsistent picture
15084 of the inferior. It could appear that a library A appears loaded but
15085 a library B does not, even though library A requires library B. That
15086 would present a state that couldn't normally exist in the inferior.
15087
15088 So, skip these events, we'll give the remote a chance to look up
15089 symbols once all the loaded libraries and their symbols are known to
15090 GDB. */
15091 if (inf->in_initial_library_scan)
15092 continue;
15093
15094 if (!remote->has_execution (inf))
15095 continue;
15096
15097 /* Need to switch to a specific thread, because remote_check_symbols will
15098 set the general thread using INFERIOR_PTID.
15099
15100 It's possible to have inferiors with no thread here, because we are
15101 called very early in the connection process, while the inferior is
15102 being set up, before threads are added. Just skip it, start_remote_1
15103 also calls remote_check_symbols when it's done setting things up. */
15104 thread_info *thread = any_thread_of_inferior (inf);
15105 if (thread != nullptr)
15106 {
15107 scoped_restore_current_thread restore_thread;
15108 switch_to_thread (thread);
15109 remote->remote_check_symbols ();
15110 }
15111 }
15112 }
15113
15114 /* Function to be called whenever a new objfile (shlib) is detected. */
15115
15116 static void
15117 remote_new_objfile (struct objfile *objfile)
15118 {
15119 remote_objfile_changed_check_symbols (objfile->pspace);
15120 }
15121
15122 /* Pull all the tracepoints defined on the target and create local
15123 data structures representing them. We don't want to create real
15124 tracepoints yet, we don't want to mess up the user's existing
15125 collection. */
15126
15127 int
15128 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15129 {
15130 struct remote_state *rs = get_remote_state ();
15131 char *p;
15132
15133 /* Ask for a first packet of tracepoint definition. */
15134 putpkt ("qTfP");
15135 getpkt (&rs->buf);
15136 p = rs->buf.data ();
15137 while (*p && *p != 'l')
15138 {
15139 parse_tracepoint_definition (p, utpp);
15140 /* Ask for another packet of tracepoint definition. */
15141 putpkt ("qTsP");
15142 getpkt (&rs->buf);
15143 p = rs->buf.data ();
15144 }
15145 return 0;
15146 }
15147
15148 int
15149 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15150 {
15151 struct remote_state *rs = get_remote_state ();
15152 char *p;
15153
15154 /* Ask for a first packet of variable definition. */
15155 putpkt ("qTfV");
15156 getpkt (&rs->buf);
15157 p = rs->buf.data ();
15158 while (*p && *p != 'l')
15159 {
15160 parse_tsv_definition (p, utsvp);
15161 /* Ask for another packet of variable definition. */
15162 putpkt ("qTsV");
15163 getpkt (&rs->buf);
15164 p = rs->buf.data ();
15165 }
15166 return 0;
15167 }
15168
15169 /* The "set/show range-stepping" show hook. */
15170
15171 static void
15172 show_range_stepping (struct ui_file *file, int from_tty,
15173 struct cmd_list_element *c,
15174 const char *value)
15175 {
15176 gdb_printf (file,
15177 _("Debugger's willingness to use range stepping "
15178 "is %s.\n"), value);
15179 }
15180
15181 /* Return true if the vCont;r action is supported by the remote
15182 stub. */
15183
15184 bool
15185 remote_target::vcont_r_supported ()
15186 {
15187 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15188 && get_remote_state ()->supports_vCont.r);
15189 }
15190
15191 /* The "set/show range-stepping" set hook. */
15192
15193 static void
15194 set_range_stepping (const char *ignore_args, int from_tty,
15195 struct cmd_list_element *c)
15196 {
15197 /* When enabling, check whether range stepping is actually supported
15198 by the target, and warn if not. */
15199 if (use_range_stepping)
15200 {
15201 remote_target *remote = get_current_remote_target ();
15202 if (remote == NULL
15203 || !remote->vcont_r_supported ())
15204 warning (_("Range stepping is not supported by the current target"));
15205 }
15206 }
15207
15208 static void
15209 show_remote_debug (struct ui_file *file, int from_tty,
15210 struct cmd_list_element *c, const char *value)
15211 {
15212 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15213 value);
15214 }
15215
15216 static void
15217 show_remote_timeout (struct ui_file *file, int from_tty,
15218 struct cmd_list_element *c, const char *value)
15219 {
15220 gdb_printf (file,
15221 _("Timeout limit to wait for target to respond is %s.\n"),
15222 value);
15223 }
15224
15225 /* Implement the "supports_memory_tagging" target_ops method. */
15226
15227 bool
15228 remote_target::supports_memory_tagging ()
15229 {
15230 return m_features.remote_memory_tagging_p ();
15231 }
15232
15233 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15234
15235 static void
15236 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15237 size_t len, int type)
15238 {
15239 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15240
15241 std::string request = string_printf ("qMemTags:%s,%s:%s",
15242 phex_nz (address, addr_size),
15243 phex_nz (len, sizeof (len)),
15244 phex_nz (type, sizeof (type)));
15245
15246 strcpy (packet.data (), request.c_str ());
15247 }
15248
15249 /* Parse the qMemTags packet reply into TAGS.
15250
15251 Return true if successful, false otherwise. */
15252
15253 static bool
15254 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15255 gdb::byte_vector &tags)
15256 {
15257 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15258 return false;
15259
15260 /* Copy the tag data. */
15261 tags = hex2bin (reply.data () + 1);
15262
15263 return true;
15264 }
15265
15266 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15267
15268 static void
15269 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15270 size_t len, int type,
15271 const gdb::byte_vector &tags)
15272 {
15273 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15274
15275 /* Put together the main packet, address and length. */
15276 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15277 phex_nz (address, addr_size),
15278 phex_nz (len, sizeof (len)),
15279 phex_nz (type, sizeof (type)));
15280 request += bin2hex (tags.data (), tags.size ());
15281
15282 /* Check if we have exceeded the maximum packet size. */
15283 if (packet.size () < request.length ())
15284 error (_("Contents too big for packet QMemTags."));
15285
15286 strcpy (packet.data (), request.c_str ());
15287 }
15288
15289 /* Implement the "fetch_memtags" target_ops method. */
15290
15291 bool
15292 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15293 gdb::byte_vector &tags, int type)
15294 {
15295 /* Make sure the qMemTags packet is supported. */
15296 if (!m_features.remote_memory_tagging_p ())
15297 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15298
15299 struct remote_state *rs = get_remote_state ();
15300
15301 create_fetch_memtags_request (rs->buf, address, len, type);
15302
15303 putpkt (rs->buf);
15304 getpkt (&rs->buf);
15305
15306 return parse_fetch_memtags_reply (rs->buf, tags);
15307 }
15308
15309 /* Implement the "store_memtags" target_ops method. */
15310
15311 bool
15312 remote_target::store_memtags (CORE_ADDR address, size_t len,
15313 const gdb::byte_vector &tags, int type)
15314 {
15315 /* Make sure the QMemTags packet is supported. */
15316 if (!m_features.remote_memory_tagging_p ())
15317 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15318
15319 struct remote_state *rs = get_remote_state ();
15320
15321 create_store_memtags_request (rs->buf, address, len, type, tags);
15322
15323 putpkt (rs->buf);
15324 getpkt (&rs->buf);
15325
15326 /* Verify if the request was successful. */
15327 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15328 }
15329
15330 /* Return true if remote target T is non-stop. */
15331
15332 bool
15333 remote_target_is_non_stop_p (remote_target *t)
15334 {
15335 scoped_restore_current_thread restore_thread;
15336 switch_to_target_no_thread (t);
15337
15338 return target_is_non_stop_p ();
15339 }
15340
15341 #if GDB_SELF_TEST
15342
15343 namespace selftests {
15344
15345 static void
15346 test_memory_tagging_functions ()
15347 {
15348 remote_target remote;
15349
15350 struct packet_config *config
15351 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15352
15353 scoped_restore restore_memtag_support_
15354 = make_scoped_restore (&config->support);
15355
15356 /* Test memory tagging packet support. */
15357 config->support = PACKET_SUPPORT_UNKNOWN;
15358 SELF_CHECK (remote.supports_memory_tagging () == false);
15359 config->support = PACKET_DISABLE;
15360 SELF_CHECK (remote.supports_memory_tagging () == false);
15361 config->support = PACKET_ENABLE;
15362 SELF_CHECK (remote.supports_memory_tagging () == true);
15363
15364 /* Setup testing. */
15365 gdb::char_vector packet;
15366 gdb::byte_vector tags, bv;
15367 std::string expected, reply;
15368 packet.resize (32000);
15369
15370 /* Test creating a qMemTags request. */
15371
15372 expected = "qMemTags:0,0:0";
15373 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15374 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15375
15376 expected = "qMemTags:deadbeef,10:1";
15377 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15378 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15379
15380 /* Test parsing a qMemTags reply. */
15381
15382 /* Error reply, tags vector unmodified. */
15383 reply = "E00";
15384 strcpy (packet.data (), reply.c_str ());
15385 tags.resize (0);
15386 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15387 SELF_CHECK (tags.size () == 0);
15388
15389 /* Valid reply, tags vector updated. */
15390 tags.resize (0);
15391 bv.resize (0);
15392
15393 for (int i = 0; i < 5; i++)
15394 bv.push_back (i);
15395
15396 reply = "m" + bin2hex (bv.data (), bv.size ());
15397 strcpy (packet.data (), reply.c_str ());
15398
15399 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15400 SELF_CHECK (tags.size () == 5);
15401
15402 for (int i = 0; i < 5; i++)
15403 SELF_CHECK (tags[i] == i);
15404
15405 /* Test creating a QMemTags request. */
15406
15407 /* Empty tag data. */
15408 tags.resize (0);
15409 expected = "QMemTags:0,0:0:";
15410 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15411 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15412 expected.length ()) == 0);
15413
15414 /* Non-empty tag data. */
15415 tags.resize (0);
15416 for (int i = 0; i < 5; i++)
15417 tags.push_back (i);
15418 expected = "QMemTags:deadbeef,ff:1:0001020304";
15419 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15420 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15421 expected.length ()) == 0);
15422 }
15423
15424 } // namespace selftests
15425 #endif /* GDB_SELF_TEST */
15426
15427 void _initialize_remote ();
15428 void
15429 _initialize_remote ()
15430 {
15431 add_target (remote_target_info, remote_target::open);
15432 add_target (extended_remote_target_info, extended_remote_target::open);
15433
15434 /* Hook into new objfile notification. */
15435 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15436 gdb::observers::all_objfiles_removed.attach
15437 (remote_objfile_changed_check_symbols, "remote");
15438
15439 #if 0
15440 init_remote_threadtests ();
15441 #endif
15442
15443 /* set/show remote ... */
15444
15445 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15446 Remote protocol specific variables.\n\
15447 Configure various remote-protocol specific variables such as\n\
15448 the packets being used."),
15449 &remote_set_cmdlist,
15450 0 /* allow-unknown */, &setlist);
15451 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15452 Remote protocol specific variables.\n\
15453 Configure various remote-protocol specific variables such as\n\
15454 the packets being used."),
15455 &remote_show_cmdlist,
15456 0 /* allow-unknown */, &showlist);
15457
15458 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15459 Compare section data on target to the exec file.\n\
15460 Argument is a single section name (default: all loaded sections).\n\
15461 To compare only read-only loaded sections, specify the -r option."),
15462 &cmdlist);
15463
15464 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15465 Send an arbitrary packet to a remote target.\n\
15466 maintenance packet TEXT\n\
15467 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15468 this command sends the string TEXT to the inferior, and displays the\n\
15469 response packet. GDB supplies the initial `$' character, and the\n\
15470 terminating `#' character and checksum."),
15471 &maintenancelist);
15472
15473 set_show_commands remotebreak_cmds
15474 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15475 Set whether to send break if interrupted."), _("\
15476 Show whether to send break if interrupted."), _("\
15477 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15478 set_remotebreak, show_remotebreak,
15479 &setlist, &showlist);
15480 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15481 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15482
15483 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15484 interrupt_sequence_modes, &interrupt_sequence_mode,
15485 _("\
15486 Set interrupt sequence to remote target."), _("\
15487 Show interrupt sequence to remote target."), _("\
15488 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15489 NULL, show_interrupt_sequence,
15490 &remote_set_cmdlist,
15491 &remote_show_cmdlist);
15492
15493 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15494 &interrupt_on_connect, _("\
15495 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15496 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15497 If set, interrupt sequence is sent to remote target."),
15498 NULL, NULL,
15499 &remote_set_cmdlist, &remote_show_cmdlist);
15500
15501 /* Install commands for configuring memory read/write packets. */
15502
15503 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15504 Set the maximum number of bytes per memory write packet (deprecated)."),
15505 &setlist);
15506 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15507 Show the maximum number of bytes per memory write packet (deprecated)."),
15508 &showlist);
15509 add_cmd ("memory-write-packet-size", no_class,
15510 set_memory_write_packet_size, _("\
15511 Set the maximum number of bytes per memory-write packet.\n\
15512 Specify the number of bytes in a packet or 0 (zero) for the\n\
15513 default packet size. The actual limit is further reduced\n\
15514 dependent on the target. Specify \"fixed\" to disable the\n\
15515 further restriction and \"limit\" to enable that restriction."),
15516 &remote_set_cmdlist);
15517 add_cmd ("memory-read-packet-size", no_class,
15518 set_memory_read_packet_size, _("\
15519 Set the maximum number of bytes per memory-read packet.\n\
15520 Specify the number of bytes in a packet or 0 (zero) for the\n\
15521 default packet size. The actual limit is further reduced\n\
15522 dependent on the target. Specify \"fixed\" to disable the\n\
15523 further restriction and \"limit\" to enable that restriction."),
15524 &remote_set_cmdlist);
15525 add_cmd ("memory-write-packet-size", no_class,
15526 show_memory_write_packet_size,
15527 _("Show the maximum number of bytes per memory-write packet."),
15528 &remote_show_cmdlist);
15529 add_cmd ("memory-read-packet-size", no_class,
15530 show_memory_read_packet_size,
15531 _("Show the maximum number of bytes per memory-read packet."),
15532 &remote_show_cmdlist);
15533
15534 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15535 &remote_hw_watchpoint_limit, _("\
15536 Set the maximum number of target hardware watchpoints."), _("\
15537 Show the maximum number of target hardware watchpoints."), _("\
15538 Specify \"unlimited\" for unlimited hardware watchpoints."),
15539 NULL, show_hardware_watchpoint_limit,
15540 &remote_set_cmdlist,
15541 &remote_show_cmdlist);
15542 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15543 no_class,
15544 &remote_hw_watchpoint_length_limit, _("\
15545 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15546 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15547 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15548 NULL, show_hardware_watchpoint_length_limit,
15549 &remote_set_cmdlist, &remote_show_cmdlist);
15550 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15551 &remote_hw_breakpoint_limit, _("\
15552 Set the maximum number of target hardware breakpoints."), _("\
15553 Show the maximum number of target hardware breakpoints."), _("\
15554 Specify \"unlimited\" for unlimited hardware breakpoints."),
15555 NULL, show_hardware_breakpoint_limit,
15556 &remote_set_cmdlist, &remote_show_cmdlist);
15557
15558 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15559 &remote_address_size, _("\
15560 Set the maximum size of the address (in bits) in a memory packet."), _("\
15561 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15562 NULL,
15563 NULL, /* FIXME: i18n: */
15564 &setlist, &showlist);
15565
15566 init_all_packet_configs ();
15567
15568 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15569
15570 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15571
15572 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15573 0);
15574
15575 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15576 "catch-syscalls", 0);
15577
15578 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15579 "program-signals", 0);
15580
15581 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15582 "set-working-dir", 0);
15583
15584 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15585 "startup-with-shell", 0);
15586
15587 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15588 "environment-hex-encoded", 0);
15589
15590 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15591 "environment-reset", 0);
15592
15593 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15594 "environment-unset", 0);
15595
15596 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15597
15598 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15599
15600 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15601
15602 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15603
15604 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15605
15606 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15607
15608 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15609
15610 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15611
15612 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15613 "read-aux-vector", 0);
15614
15615 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15616 "pid-to-exec-file", 0);
15617
15618 add_packet_config_cmd (PACKET_qXfer_features,
15619 "qXfer:features:read", "target-features", 0);
15620
15621 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15622 "library-info", 0);
15623
15624 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15625 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15626
15627 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15628 "memory-map", 0);
15629
15630 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15631
15632 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15633 0);
15634
15635 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15636 "read-siginfo-object", 0);
15637
15638 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15639 "write-siginfo-object", 0);
15640
15641 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15642 "qXfer:traceframe-info:read", "traceframe-info", 0);
15643
15644 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15645 "unwind-info-block", 0);
15646
15647 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15648 "get-thread-local-storage-address", 0);
15649
15650 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15651 "get-thread-information-block-address", 0);
15652
15653 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15654
15655 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15656
15657 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15658 0);
15659
15660 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15661 "search-memory", 0);
15662
15663 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15664
15665 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15666
15667 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15668
15669 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15670
15671 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15672 0);
15673
15674 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15675
15676 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15677 0);
15678
15679 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15680 "hostio-readlink", 0);
15681
15682 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15683
15684 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15685
15686 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15687
15688 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15689
15690 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15691
15692 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15693
15694 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15695 "ConditionalTracepoints", "conditional-tracepoints",
15696 0);
15697
15698 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15699 "ConditionalBreakpoints", "conditional-breakpoints",
15700 0);
15701
15702 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15703 "breakpoint-commands", 0);
15704
15705 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15706 "fast-tracepoints", 0);
15707
15708 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15709 "TracepointSource", 0);
15710
15711 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15712
15713 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15714 "static-tracepoints", 0);
15715
15716 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15717 "install-in-trace", 0);
15718
15719 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15720 "qXfer:statictrace:read", "read-sdata-object", 0);
15721
15722 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15723 "read-fdpic-loadmap", 0);
15724
15725 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15726 "disable-randomization", 0);
15727
15728 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15729
15730 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15731 "trace-buffer-size", 0);
15732
15733 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15734 0);
15735
15736 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15737 0);
15738
15739 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15740 0);
15741
15742 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15743
15744 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15745 "read-btrace-conf", 0);
15746
15747 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15748 "btrace-conf-bts-size", 0);
15749
15750 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15751 "multiprocess-feature", 0);
15752
15753 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15754 "swbreak-feature", 0);
15755
15756 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15757 "hwbreak-feature", 0);
15758
15759 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15760 "fork-event-feature", 0);
15761
15762 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15763 "vfork-event-feature", 0);
15764
15765 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15766 "btrace-conf-pt-size", 0);
15767
15768 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15769 "verbose-resume-supported", 0);
15770
15771 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15772 "exec-event-feature", 0);
15773
15774 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15775
15776 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15777 0);
15778
15779 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15780 "no-resumed-stop-reply", 0);
15781
15782 add_packet_config_cmd (PACKET_memory_tagging_feature,
15783 "memory-tagging-feature", "memory-tagging-feature", 0);
15784
15785 /* Assert that we've registered "set remote foo-packet" commands
15786 for all packet configs. */
15787 {
15788 int i;
15789
15790 for (i = 0; i < PACKET_MAX; i++)
15791 {
15792 /* Ideally all configs would have a command associated. Some
15793 still don't though. */
15794 int excepted;
15795
15796 switch (i)
15797 {
15798 case PACKET_QNonStop:
15799 case PACKET_EnableDisableTracepoints_feature:
15800 case PACKET_tracenz_feature:
15801 case PACKET_DisconnectedTracing_feature:
15802 case PACKET_augmented_libraries_svr4_read_feature:
15803 case PACKET_qCRC:
15804 /* Additions to this list need to be well justified:
15805 pre-existing packets are OK; new packets are not. */
15806 excepted = 1;
15807 break;
15808 default:
15809 excepted = 0;
15810 break;
15811 }
15812
15813 /* This catches both forgetting to add a config command, and
15814 forgetting to remove a packet from the exception list. */
15815 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15816 }
15817 }
15818
15819 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15820 Z sub-packet has its own set and show commands, but users may
15821 have sets to this variable in their .gdbinit files (or in their
15822 documentation). */
15823 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15824 &remote_Z_packet_detect, _("\
15825 Set use of remote protocol `Z' packets."), _("\
15826 Show use of remote protocol `Z' packets."), _("\
15827 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15828 packets."),
15829 set_remote_protocol_Z_packet_cmd,
15830 show_remote_protocol_Z_packet_cmd,
15831 /* FIXME: i18n: Use of remote protocol
15832 `Z' packets is %s. */
15833 &remote_set_cmdlist, &remote_show_cmdlist);
15834
15835 add_basic_prefix_cmd ("remote", class_files, _("\
15836 Manipulate files on the remote system.\n\
15837 Transfer files to and from the remote target system."),
15838 &remote_cmdlist,
15839 0 /* allow-unknown */, &cmdlist);
15840
15841 add_cmd ("put", class_files, remote_put_command,
15842 _("Copy a local file to the remote system."),
15843 &remote_cmdlist);
15844
15845 add_cmd ("get", class_files, remote_get_command,
15846 _("Copy a remote file to the local system."),
15847 &remote_cmdlist);
15848
15849 add_cmd ("delete", class_files, remote_delete_command,
15850 _("Delete a remote file."),
15851 &remote_cmdlist);
15852
15853 add_setshow_string_noescape_cmd ("exec-file", class_files,
15854 &remote_exec_file_var, _("\
15855 Set the remote pathname for \"run\"."), _("\
15856 Show the remote pathname for \"run\"."), NULL,
15857 set_remote_exec_file,
15858 show_remote_exec_file,
15859 &remote_set_cmdlist,
15860 &remote_show_cmdlist);
15861
15862 add_setshow_boolean_cmd ("range-stepping", class_run,
15863 &use_range_stepping, _("\
15864 Enable or disable range stepping."), _("\
15865 Show whether target-assisted range stepping is enabled."), _("\
15866 If on, and the target supports it, when stepping a source line, GDB\n\
15867 tells the target to step the corresponding range of addresses itself instead\n\
15868 of issuing multiple single-steps. This speeds up source level\n\
15869 stepping. If off, GDB always issues single-steps, even if range\n\
15870 stepping is supported by the target. The default is on."),
15871 set_range_stepping,
15872 show_range_stepping,
15873 &setlist,
15874 &showlist);
15875
15876 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15877 Set watchdog timer."), _("\
15878 Show watchdog timer."), _("\
15879 When non-zero, this timeout is used instead of waiting forever for a target\n\
15880 to finish a low-level step or continue operation. If the specified amount\n\
15881 of time passes without a response from the target, an error occurs."),
15882 NULL,
15883 show_watchdog,
15884 &setlist, &showlist);
15885
15886 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15887 &remote_packet_max_chars, _("\
15888 Set the maximum number of characters to display for each remote packet."), _("\
15889 Show the maximum number of characters to display for each remote packet."), _("\
15890 Specify \"unlimited\" to display all the characters."),
15891 NULL, show_remote_packet_max_chars,
15892 &setdebuglist, &showdebuglist);
15893
15894 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15895 _("Set debugging of remote protocol."),
15896 _("Show debugging of remote protocol."),
15897 _("\
15898 When enabled, each packet sent or received with the remote target\n\
15899 is displayed."),
15900 NULL,
15901 show_remote_debug,
15902 &setdebuglist, &showdebuglist);
15903
15904 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15905 &remote_timeout, _("\
15906 Set timeout limit to wait for target to respond."), _("\
15907 Show timeout limit to wait for target to respond."), _("\
15908 This value is used to set the time limit for gdb to wait for a response\n\
15909 from the target."),
15910 NULL,
15911 show_remote_timeout,
15912 &setlist, &showlist);
15913
15914 /* Eventually initialize fileio. See fileio.c */
15915 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15916
15917 #if GDB_SELF_TEST
15918 selftests::register_test ("remote_memory_tagging",
15919 selftests::test_memory_tagging_functions);
15920 #endif
15921 }