Avoid duplicate QThreadEvents packets
[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 /* Similarly, the last QThreadEvents state we sent to the
533 target. */
534 bool last_thread_events = false;
535
536 gdb_signal last_sent_signal = GDB_SIGNAL_0;
537
538 bool last_sent_step = false;
539
540 /* The execution direction of the last resume we got. */
541 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
542
543 char *finished_object = nullptr;
544 char *finished_annex = nullptr;
545 ULONGEST finished_offset = 0;
546
547 /* Should we try the 'ThreadInfo' query packet?
548
549 This variable (NOT available to the user: auto-detect only!)
550 determines whether GDB will use the new, simpler "ThreadInfo"
551 query or the older, more complex syntax for thread queries.
552 This is an auto-detect variable (set to true at each connect,
553 and set to false when the target fails to recognize it). */
554 bool use_threadinfo_query = false;
555 bool use_threadextra_query = false;
556
557 threadref echo_nextthread {};
558 threadref nextthread {};
559 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
560
561 /* The state of remote notification. */
562 struct remote_notif_state *notif_state = nullptr;
563
564 /* The branch trace configuration. */
565 struct btrace_config btrace_config {};
566
567 /* The argument to the last "vFile:setfs:" packet we sent, used
568 to avoid sending repeated unnecessary "vFile:setfs:" packets.
569 Initialized to -1 to indicate that no "vFile:setfs:" packet
570 has yet been sent. */
571 int fs_pid = -1;
572
573 /* A readahead cache for vFile:pread. Often, reading a binary
574 involves a sequence of small reads. E.g., when parsing an ELF
575 file. A readahead cache helps mostly the case of remote
576 debugging on a connection with higher latency, due to the
577 request/reply nature of the RSP. We only cache data for a single
578 file descriptor at a time. */
579 struct readahead_cache readahead_cache;
580
581 /* The list of already fetched and acknowledged stop events. This
582 queue is used for notification Stop, and other notifications
583 don't need queue for their events, because the notification
584 events of Stop can't be consumed immediately, so that events
585 should be queued first, and be consumed by remote_wait_{ns,as}
586 one per time. Other notifications can consume their events
587 immediately, so queue is not needed for them. */
588 std::vector<stop_reply_up> stop_reply_queue;
589
590 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
591 ``forever'' still use the normal timeout mechanism. This is
592 currently used by the ASYNC code to guarentee that target reads
593 during the initial connect always time-out. Once getpkt has been
594 modified to return a timeout indication and, in turn
595 remote_wait()/wait_for_inferior() have gained a timeout parameter
596 this can go away. */
597 bool wait_forever_enabled_p = true;
598
599 private:
600 /* Asynchronous signal handle registered as event loop source for
601 when we have pending events ready to be passed to the core. */
602 async_event_handler *m_async_event_handler_token = nullptr;
603
604 /* Mapping of remote protocol data for each gdbarch. Usually there
605 is only one entry here, though we may see more with stubs that
606 support multi-process. */
607 std::unordered_map<struct gdbarch *, remote_arch_state>
608 m_arch_states;
609 };
610
611 static const target_info remote_target_info = {
612 "remote",
613 N_("Remote target using gdb-specific protocol"),
614 remote_doc
615 };
616
617 /* Description of a remote packet. */
618
619 struct packet_description
620 {
621 /* Name of the packet used for gdb output. */
622 const char *name;
623
624 /* Title of the packet, used by the set/show remote name-packet
625 commands to identify the individual packages and gdb output. */
626 const char *title;
627 };
628
629 /* Configuration of a remote packet. */
630
631 struct packet_config
632 {
633 /* If auto, GDB auto-detects support for this packet or feature,
634 either through qSupported, or by trying the packet and looking
635 at the response. If true, GDB assumes the target supports this
636 packet. If false, the packet is disabled. Configs that don't
637 have an associated command always have this set to auto. */
638 enum auto_boolean detect;
639
640 /* Does the target support this packet? */
641 enum packet_support support;
642 };
643
644 /* User configurable variables for the number of characters in a
645 memory read/write packet. MIN (rsa->remote_packet_size,
646 rsa->sizeof_g_packet) is the default. Some targets need smaller
647 values (fifo overruns, et.al.) and some users need larger values
648 (speed up transfers). The variables ``preferred_*'' (the user
649 request), ``current_*'' (what was actually set) and ``forced_*''
650 (Positive - a soft limit, negative - a hard limit). */
651
652 struct memory_packet_config
653 {
654 const char *name;
655 long size;
656 int fixed_p;
657 };
658
659 /* These global variables contain the default configuration for every new
660 remote_feature object. */
661 static memory_packet_config memory_read_packet_config =
662 {
663 "memory-read-packet-size",
664 };
665 static memory_packet_config memory_write_packet_config =
666 {
667 "memory-write-packet-size",
668 };
669
670 /* This global array contains packet descriptions (name and title). */
671 static packet_description packets_descriptions[PACKET_MAX];
672 /* This global array contains the default configuration for every new
673 per-remote target array. */
674 static packet_config remote_protocol_packets[PACKET_MAX];
675
676 /* Description of a remote target's features. It stores the configuration
677 and provides functions to determine supported features of the target. */
678
679 struct remote_features
680 {
681 remote_features ()
682 {
683 m_memory_read_packet_config = memory_read_packet_config;
684 m_memory_write_packet_config = memory_write_packet_config;
685
686 std::copy (std::begin (remote_protocol_packets),
687 std::end (remote_protocol_packets),
688 std::begin (m_protocol_packets));
689 }
690 ~remote_features () = default;
691
692 DISABLE_COPY_AND_ASSIGN (remote_features);
693
694 /* Returns whether a given packet defined by its enum value is supported. */
695 enum packet_support packet_support (int) const;
696
697 /* Returns the packet's corresponding "set remote foo-packet" command
698 state. See struct packet_config for more details. */
699 enum auto_boolean packet_set_cmd_state (int packet) const
700 { return m_protocol_packets[packet].detect; }
701
702 /* Returns true if the multi-process extensions are in effect. */
703 int remote_multi_process_p () const
704 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
705
706 /* Returns true if fork events are supported. */
707 int remote_fork_event_p () const
708 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
709
710 /* Returns true if vfork events are supported. */
711 int remote_vfork_event_p () const
712 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
713
714 /* Returns true if exec events are supported. */
715 int remote_exec_event_p () const
716 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
717
718 /* Returns true if memory tagging is supported, false otherwise. */
719 bool remote_memory_tagging_p () const
720 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
721
722 /* Reset all packets back to "unknown support". Called when opening a
723 new connection to a remote target. */
724 void reset_all_packet_configs_support ();
725
726 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
727 support configuration accordingly. */
728 packet_result packet_ok (const char *buf, const int which_packet);
729 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
730
731 /* Configuration of a remote target's memory read packet. */
732 memory_packet_config m_memory_read_packet_config;
733 /* Configuration of a remote target's memory write packet. */
734 memory_packet_config m_memory_write_packet_config;
735
736 /* The per-remote target array which stores a remote's packet
737 configurations. */
738 packet_config m_protocol_packets[PACKET_MAX];
739 };
740
741 class remote_target : public process_stratum_target
742 {
743 public:
744 remote_target () = default;
745 ~remote_target () override;
746
747 const target_info &info () const override
748 { return remote_target_info; }
749
750 const char *connection_string () override;
751
752 thread_control_capabilities get_thread_control_capabilities () override
753 { return tc_schedlock; }
754
755 /* Open a remote connection. */
756 static void open (const char *, int);
757
758 void close () override;
759
760 void detach (inferior *, int) override;
761 void disconnect (const char *, int) override;
762
763 void commit_resumed () override;
764 void resume (ptid_t, int, enum gdb_signal) override;
765 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
766 bool has_pending_events () override;
767
768 void fetch_registers (struct regcache *, int) override;
769 void store_registers (struct regcache *, int) override;
770 void prepare_to_store (struct regcache *) override;
771
772 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
773
774 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
775 enum remove_bp_reason) override;
776
777
778 bool stopped_by_sw_breakpoint () override;
779 bool supports_stopped_by_sw_breakpoint () override;
780
781 bool stopped_by_hw_breakpoint () override;
782
783 bool supports_stopped_by_hw_breakpoint () override;
784
785 bool stopped_by_watchpoint () override;
786
787 bool stopped_data_address (CORE_ADDR *) override;
788
789 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
790
791 int can_use_hw_breakpoint (enum bptype, int, int) override;
792
793 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
794
795 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
796
797 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
798
799 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
800 struct expression *) override;
801
802 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
803 struct expression *) override;
804
805 void kill () override;
806
807 void load (const char *, int) override;
808
809 void mourn_inferior () override;
810
811 void pass_signals (gdb::array_view<const unsigned char>) override;
812
813 int set_syscall_catchpoint (int, bool, int,
814 gdb::array_view<const int>) override;
815
816 void program_signals (gdb::array_view<const unsigned char>) override;
817
818 bool thread_alive (ptid_t ptid) override;
819
820 const char *thread_name (struct thread_info *) override;
821
822 void update_thread_list () override;
823
824 std::string pid_to_str (ptid_t) override;
825
826 const char *extra_thread_info (struct thread_info *) override;
827
828 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
829
830 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
831 int handle_len,
832 inferior *inf) override;
833
834 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
835 override;
836
837 void stop (ptid_t) override;
838
839 void interrupt () override;
840
841 void pass_ctrlc () override;
842
843 enum target_xfer_status xfer_partial (enum target_object object,
844 const char *annex,
845 gdb_byte *readbuf,
846 const gdb_byte *writebuf,
847 ULONGEST offset, ULONGEST len,
848 ULONGEST *xfered_len) override;
849
850 ULONGEST get_memory_xfer_limit () override;
851
852 void rcmd (const char *command, struct ui_file *output) override;
853
854 const char *pid_to_exec_file (int pid) override;
855
856 void log_command (const char *cmd) override
857 {
858 serial_log_command (this, cmd);
859 }
860
861 CORE_ADDR get_thread_local_address (ptid_t ptid,
862 CORE_ADDR load_module_addr,
863 CORE_ADDR offset) override;
864
865 bool can_execute_reverse () override;
866
867 std::vector<mem_region> memory_map () override;
868
869 void flash_erase (ULONGEST address, LONGEST length) override;
870
871 void flash_done () override;
872
873 const struct target_desc *read_description () override;
874
875 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
876 const gdb_byte *pattern, ULONGEST pattern_len,
877 CORE_ADDR *found_addrp) override;
878
879 bool can_async_p () override;
880
881 bool is_async_p () override;
882
883 void async (bool) override;
884
885 int async_wait_fd () override;
886
887 void thread_events (int) override;
888
889 int can_do_single_step () override;
890
891 void terminal_inferior () override;
892
893 void terminal_ours () override;
894
895 bool supports_non_stop () override;
896
897 bool supports_multi_process () override;
898
899 bool supports_disable_randomization () override;
900
901 bool filesystem_is_local () override;
902
903
904 int fileio_open (struct inferior *inf, const char *filename,
905 int flags, int mode, int warn_if_slow,
906 fileio_error *target_errno) override;
907
908 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
909 ULONGEST offset, fileio_error *target_errno) override;
910
911 int fileio_pread (int fd, gdb_byte *read_buf, int len,
912 ULONGEST offset, fileio_error *target_errno) override;
913
914 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
915
916 int fileio_close (int fd, fileio_error *target_errno) override;
917
918 int fileio_unlink (struct inferior *inf,
919 const char *filename,
920 fileio_error *target_errno) override;
921
922 gdb::optional<std::string>
923 fileio_readlink (struct inferior *inf,
924 const char *filename,
925 fileio_error *target_errno) override;
926
927 bool supports_enable_disable_tracepoint () override;
928
929 bool supports_string_tracing () override;
930
931 int remote_supports_cond_tracepoints ();
932
933 bool supports_evaluation_of_breakpoint_conditions () override;
934
935 int remote_supports_fast_tracepoints ();
936
937 int remote_supports_static_tracepoints ();
938
939 int remote_supports_install_in_trace ();
940
941 bool can_run_breakpoint_commands () override;
942
943 void trace_init () override;
944
945 void download_tracepoint (struct bp_location *location) override;
946
947 bool can_download_tracepoint () override;
948
949 void download_trace_state_variable (const trace_state_variable &tsv) override;
950
951 void enable_tracepoint (struct bp_location *location) override;
952
953 void disable_tracepoint (struct bp_location *location) override;
954
955 void trace_set_readonly_regions () override;
956
957 void trace_start () override;
958
959 int get_trace_status (struct trace_status *ts) override;
960
961 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
962 override;
963
964 void trace_stop () override;
965
966 int trace_find (enum trace_find_type type, int num,
967 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
968
969 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
970
971 int save_trace_data (const char *filename) override;
972
973 int upload_tracepoints (struct uploaded_tp **utpp) override;
974
975 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
976
977 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
978
979 int get_min_fast_tracepoint_insn_len () override;
980
981 void set_disconnected_tracing (int val) override;
982
983 void set_circular_trace_buffer (int val) override;
984
985 void set_trace_buffer_size (LONGEST val) override;
986
987 bool set_trace_notes (const char *user, const char *notes,
988 const char *stopnotes) override;
989
990 int core_of_thread (ptid_t ptid) override;
991
992 int verify_memory (const gdb_byte *data,
993 CORE_ADDR memaddr, ULONGEST size) override;
994
995
996 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
997
998 void set_permissions () override;
999
1000 bool static_tracepoint_marker_at (CORE_ADDR,
1001 struct static_tracepoint_marker *marker)
1002 override;
1003
1004 std::vector<static_tracepoint_marker>
1005 static_tracepoint_markers_by_strid (const char *id) override;
1006
1007 traceframe_info_up traceframe_info () override;
1008
1009 bool use_agent (bool use) override;
1010 bool can_use_agent () override;
1011
1012 struct btrace_target_info *
1013 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1014
1015 void disable_btrace (struct btrace_target_info *tinfo) override;
1016
1017 void teardown_btrace (struct btrace_target_info *tinfo) override;
1018
1019 enum btrace_error read_btrace (struct btrace_data *data,
1020 struct btrace_target_info *btinfo,
1021 enum btrace_read_type type) override;
1022
1023 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1024 bool augmented_libraries_svr4_read () override;
1025 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1026 void follow_clone (ptid_t child_ptid) override;
1027 void follow_exec (inferior *, ptid_t, const char *) override;
1028 int insert_fork_catchpoint (int) override;
1029 int remove_fork_catchpoint (int) override;
1030 int insert_vfork_catchpoint (int) override;
1031 int remove_vfork_catchpoint (int) override;
1032 int insert_exec_catchpoint (int) override;
1033 int remove_exec_catchpoint (int) override;
1034 enum exec_direction_kind execution_direction () override;
1035
1036 bool supports_memory_tagging () override;
1037
1038 bool fetch_memtags (CORE_ADDR address, size_t len,
1039 gdb::byte_vector &tags, int type) override;
1040
1041 bool store_memtags (CORE_ADDR address, size_t len,
1042 const gdb::byte_vector &tags, int type) override;
1043
1044 public: /* Remote specific methods. */
1045
1046 void remote_download_command_source (int num, ULONGEST addr,
1047 struct command_line *cmds);
1048
1049 void remote_file_put (const char *local_file, const char *remote_file,
1050 int from_tty);
1051 void remote_file_get (const char *remote_file, const char *local_file,
1052 int from_tty);
1053 void remote_file_delete (const char *remote_file, int from_tty);
1054
1055 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1056 ULONGEST offset, fileio_error *remote_errno);
1057 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1058 ULONGEST offset, fileio_error *remote_errno);
1059 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1060 ULONGEST offset, fileio_error *remote_errno);
1061
1062 int remote_hostio_send_command (int command_bytes, int which_packet,
1063 fileio_error *remote_errno, const char **attachment,
1064 int *attachment_len);
1065 int remote_hostio_set_filesystem (struct inferior *inf,
1066 fileio_error *remote_errno);
1067 /* We should get rid of this and use fileio_open directly. */
1068 int remote_hostio_open (struct inferior *inf, const char *filename,
1069 int flags, int mode, int warn_if_slow,
1070 fileio_error *remote_errno);
1071 int remote_hostio_close (int fd, fileio_error *remote_errno);
1072
1073 int remote_hostio_unlink (inferior *inf, const char *filename,
1074 fileio_error *remote_errno);
1075
1076 struct remote_state *get_remote_state ();
1077
1078 long get_remote_packet_size (void);
1079 long get_memory_packet_size (struct memory_packet_config *config);
1080
1081 long get_memory_write_packet_size ();
1082 long get_memory_read_packet_size ();
1083
1084 char *append_pending_thread_resumptions (char *p, char *endp,
1085 ptid_t ptid);
1086 static void open_1 (const char *name, int from_tty, int extended_p);
1087 void start_remote (int from_tty, int extended_p);
1088 void remote_detach_1 (struct inferior *inf, int from_tty);
1089
1090 char *append_resumption (char *p, char *endp,
1091 ptid_t ptid, int step, gdb_signal siggnal);
1092 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1093 gdb_signal siggnal);
1094
1095 thread_info *add_current_inferior_and_thread (const char *wait_status);
1096
1097 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1098 target_wait_flags options);
1099 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1100 target_wait_flags options);
1101
1102 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1103 target_waitstatus *status);
1104
1105 ptid_t select_thread_for_ambiguous_stop_reply
1106 (const struct target_waitstatus &status);
1107
1108 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1109
1110 void print_one_stopped_thread (thread_info *thread);
1111 void process_initial_stop_replies (int from_tty);
1112
1113 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1114 bool silent_p);
1115
1116 void btrace_sync_conf (const btrace_config *conf);
1117
1118 void remote_btrace_maybe_reopen ();
1119
1120 void remove_new_children (threads_listing_context *context);
1121 void kill_new_fork_children (inferior *inf);
1122 void discard_pending_stop_replies (struct inferior *inf);
1123 int stop_reply_queue_length ();
1124
1125 void check_pending_events_prevent_wildcard_vcont
1126 (bool *may_global_wildcard_vcont);
1127
1128 void discard_pending_stop_replies_in_queue ();
1129 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1130 struct stop_reply *queued_stop_reply (ptid_t ptid);
1131 int peek_stop_reply (ptid_t ptid);
1132 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1133
1134 void remote_stop_ns (ptid_t ptid);
1135 void remote_interrupt_as ();
1136 void remote_interrupt_ns ();
1137
1138 char *remote_get_noisy_reply ();
1139 int remote_query_attached (int pid);
1140 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1141 int try_open_exec);
1142
1143 ptid_t remote_current_thread (ptid_t oldpid);
1144 ptid_t get_current_thread (const char *wait_status);
1145
1146 void set_thread (ptid_t ptid, int gen);
1147 void set_general_thread (ptid_t ptid);
1148 void set_continue_thread (ptid_t ptid);
1149 void set_general_process ();
1150
1151 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1152
1153 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1154 gdb_ext_thread_info *info);
1155 int remote_get_threadinfo (threadref *threadid, int fieldset,
1156 gdb_ext_thread_info *info);
1157
1158 int parse_threadlist_response (const char *pkt, int result_limit,
1159 threadref *original_echo,
1160 threadref *resultlist,
1161 int *doneflag);
1162 int remote_get_threadlist (int startflag, threadref *nextthread,
1163 int result_limit, int *done, int *result_count,
1164 threadref *threadlist);
1165
1166 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1167 void *context, int looplimit);
1168
1169 int remote_get_threads_with_ql (threads_listing_context *context);
1170 int remote_get_threads_with_qxfer (threads_listing_context *context);
1171 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1172
1173 void extended_remote_restart ();
1174
1175 void get_offsets ();
1176
1177 void remote_check_symbols ();
1178
1179 void remote_supported_packet (const struct protocol_feature *feature,
1180 enum packet_support support,
1181 const char *argument);
1182
1183 void remote_query_supported ();
1184
1185 void remote_packet_size (const protocol_feature *feature,
1186 packet_support support, const char *value);
1187
1188 void remote_serial_quit_handler ();
1189
1190 void remote_detach_pid (int pid);
1191
1192 void remote_vcont_probe ();
1193
1194 void remote_resume_with_hc (ptid_t ptid, int step,
1195 gdb_signal siggnal);
1196
1197 void send_interrupt_sequence ();
1198 void interrupt_query ();
1199
1200 void remote_notif_get_pending_events (const notif_client *nc);
1201
1202 int fetch_register_using_p (struct regcache *regcache,
1203 packet_reg *reg);
1204 int send_g_packet ();
1205 void process_g_packet (struct regcache *regcache);
1206 void fetch_registers_using_g (struct regcache *regcache);
1207 int store_register_using_P (const struct regcache *regcache,
1208 packet_reg *reg);
1209 void store_registers_using_G (const struct regcache *regcache);
1210
1211 void set_remote_traceframe ();
1212
1213 void check_binary_download (CORE_ADDR addr);
1214
1215 target_xfer_status remote_write_bytes_aux (const char *header,
1216 CORE_ADDR memaddr,
1217 const gdb_byte *myaddr,
1218 ULONGEST len_units,
1219 int unit_size,
1220 ULONGEST *xfered_len_units,
1221 char packet_format,
1222 int use_length);
1223
1224 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1225 const gdb_byte *myaddr, ULONGEST len,
1226 int unit_size, ULONGEST *xfered_len);
1227
1228 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1229 ULONGEST len_units,
1230 int unit_size, ULONGEST *xfered_len_units);
1231
1232 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1233 ULONGEST memaddr,
1234 ULONGEST len,
1235 int unit_size,
1236 ULONGEST *xfered_len);
1237
1238 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1239 gdb_byte *myaddr, ULONGEST len,
1240 int unit_size,
1241 ULONGEST *xfered_len);
1242
1243 packet_result remote_send_printf (const char *format, ...)
1244 ATTRIBUTE_PRINTF (2, 3);
1245
1246 target_xfer_status remote_flash_write (ULONGEST address,
1247 ULONGEST length, ULONGEST *xfered_len,
1248 const gdb_byte *data);
1249
1250 int readchar (int timeout);
1251
1252 void remote_serial_write (const char *str, int len);
1253
1254 int putpkt (const char *buf);
1255 int putpkt_binary (const char *buf, int cnt);
1256
1257 int putpkt (const gdb::char_vector &buf)
1258 {
1259 return putpkt (buf.data ());
1260 }
1261
1262 void skip_frame ();
1263 long read_frame (gdb::char_vector *buf_p);
1264 int getpkt (gdb::char_vector *buf, bool forever = false,
1265 bool *is_notif = nullptr);
1266 int remote_vkill (int pid);
1267 void remote_kill_k ();
1268
1269 void extended_remote_disable_randomization (int val);
1270 int extended_remote_run (const std::string &args);
1271
1272 void send_environment_packet (const char *action,
1273 const char *packet,
1274 const char *value);
1275
1276 void extended_remote_environment_support ();
1277 void extended_remote_set_inferior_cwd ();
1278
1279 target_xfer_status remote_write_qxfer (const char *object_name,
1280 const char *annex,
1281 const gdb_byte *writebuf,
1282 ULONGEST offset, LONGEST len,
1283 ULONGEST *xfered_len,
1284 const unsigned int which_packet);
1285
1286 target_xfer_status remote_read_qxfer (const char *object_name,
1287 const char *annex,
1288 gdb_byte *readbuf, ULONGEST offset,
1289 LONGEST len,
1290 ULONGEST *xfered_len,
1291 const unsigned int which_packet);
1292
1293 void push_stop_reply (struct stop_reply *new_event);
1294
1295 bool vcont_r_supported ();
1296
1297 remote_features m_features;
1298
1299 private:
1300
1301 bool start_remote_1 (int from_tty, int extended_p);
1302
1303 /* The remote state. Don't reference this directly. Use the
1304 get_remote_state method instead. */
1305 remote_state m_remote_state;
1306 };
1307
1308 static const target_info extended_remote_target_info = {
1309 "extended-remote",
1310 N_("Extended remote target using gdb-specific protocol"),
1311 remote_doc
1312 };
1313
1314 /* Set up the extended remote target by extending the standard remote
1315 target and adding to it. */
1316
1317 class extended_remote_target final : public remote_target
1318 {
1319 public:
1320 const target_info &info () const override
1321 { return extended_remote_target_info; }
1322
1323 /* Open an extended-remote connection. */
1324 static void open (const char *, int);
1325
1326 bool can_create_inferior () override { return true; }
1327 void create_inferior (const char *, const std::string &,
1328 char **, int) override;
1329
1330 void detach (inferior *, int) override;
1331
1332 bool can_attach () override { return true; }
1333 void attach (const char *, int) override;
1334
1335 void post_attach (int) override;
1336 bool supports_disable_randomization () override;
1337 };
1338
1339 struct stop_reply : public notif_event
1340 {
1341 ~stop_reply ();
1342
1343 /* The identifier of the thread about this event */
1344 ptid_t ptid;
1345
1346 /* The remote state this event is associated with. When the remote
1347 connection, represented by a remote_state object, is closed,
1348 all the associated stop_reply events should be released. */
1349 struct remote_state *rs;
1350
1351 struct target_waitstatus ws;
1352
1353 /* The architecture associated with the expedited registers. */
1354 gdbarch *arch;
1355
1356 /* Expedited registers. This makes remote debugging a bit more
1357 efficient for those targets that provide critical registers as
1358 part of their normal status mechanism (as another roundtrip to
1359 fetch them is avoided). */
1360 std::vector<cached_reg_t> regcache;
1361
1362 enum target_stop_reason stop_reason;
1363
1364 CORE_ADDR watch_data_address;
1365
1366 int core;
1367 };
1368
1369 /* Return TARGET as a remote_target if it is one, else nullptr. */
1370
1371 static remote_target *
1372 as_remote_target (process_stratum_target *target)
1373 {
1374 return dynamic_cast<remote_target *> (target);
1375 }
1376
1377 /* See remote.h. */
1378
1379 bool
1380 is_remote_target (process_stratum_target *target)
1381 {
1382 return as_remote_target (target) != nullptr;
1383 }
1384
1385 /* Per-program-space data key. */
1386 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1387 remote_pspace_data;
1388
1389 /* The variable registered as the control variable used by the
1390 remote exec-file commands. While the remote exec-file setting is
1391 per-program-space, the set/show machinery uses this as the
1392 location of the remote exec-file value. */
1393 static std::string remote_exec_file_var;
1394
1395 /* The size to align memory write packets, when practical. The protocol
1396 does not guarantee any alignment, and gdb will generate short
1397 writes and unaligned writes, but even as a best-effort attempt this
1398 can improve bulk transfers. For instance, if a write is misaligned
1399 relative to the target's data bus, the stub may need to make an extra
1400 round trip fetching data from the target. This doesn't make a
1401 huge difference, but it's easy to do, so we try to be helpful.
1402
1403 The alignment chosen is arbitrary; usually data bus width is
1404 important here, not the possibly larger cache line size. */
1405 enum { REMOTE_ALIGN_WRITES = 16 };
1406
1407 /* Prototypes for local functions. */
1408
1409 static int hexnumlen (ULONGEST num);
1410
1411 static int stubhex (int ch);
1412
1413 static int hexnumstr (char *, ULONGEST);
1414
1415 static int hexnumnstr (char *, ULONGEST, int);
1416
1417 static CORE_ADDR remote_address_masked (CORE_ADDR);
1418
1419 static int stub_unpack_int (const char *buff, int fieldlength);
1420
1421 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1422 cmd_list_element *c);
1423
1424 static void show_packet_config_cmd (ui_file *file,
1425 const unsigned int which_packet,
1426 remote_target *remote);
1427
1428 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1429 int from_tty,
1430 struct cmd_list_element *c,
1431 const char *value);
1432
1433 static ptid_t read_ptid (const char *buf, const char **obuf);
1434
1435 static bool remote_read_description_p (struct target_ops *target);
1436
1437 static void remote_console_output (const char *msg);
1438
1439 static void remote_btrace_reset (remote_state *rs);
1440
1441 static void remote_unpush_and_throw (remote_target *target);
1442
1443 /* For "remote". */
1444
1445 static struct cmd_list_element *remote_cmdlist;
1446
1447 /* For "set remote" and "show remote". */
1448
1449 static struct cmd_list_element *remote_set_cmdlist;
1450 static struct cmd_list_element *remote_show_cmdlist;
1451
1452 /* Controls whether GDB is willing to use range stepping. */
1453
1454 static bool use_range_stepping = true;
1455
1456 /* From the remote target's point of view, each thread is in one of these three
1457 states. */
1458 enum class resume_state
1459 {
1460 /* Not resumed - we haven't been asked to resume this thread. */
1461 NOT_RESUMED,
1462
1463 /* We have been asked to resume this thread, but haven't sent a vCont action
1464 for it yet. We'll need to consider it next time commit_resume is
1465 called. */
1466 RESUMED_PENDING_VCONT,
1467
1468 /* We have been asked to resume this thread, and we have sent a vCont action
1469 for it. */
1470 RESUMED,
1471 };
1472
1473 /* Information about a thread's pending vCont-resume. Used when a thread is in
1474 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1475 stores this information which is then picked up by
1476 remote_target::commit_resume to know which is the proper action for this
1477 thread to include in the vCont packet. */
1478 struct resumed_pending_vcont_info
1479 {
1480 /* True if the last resume call for this thread was a step request, false
1481 if a continue request. */
1482 bool step;
1483
1484 /* The signal specified in the last resume call for this thread. */
1485 gdb_signal sig;
1486 };
1487
1488 /* Private data that we'll store in (struct thread_info)->priv. */
1489 struct remote_thread_info : public private_thread_info
1490 {
1491 std::string extra;
1492 std::string name;
1493 int core = -1;
1494
1495 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1496 sequence of bytes. */
1497 gdb::byte_vector thread_handle;
1498
1499 /* Whether the target stopped for a breakpoint/watchpoint. */
1500 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1501
1502 /* This is set to the data address of the access causing the target
1503 to stop for a watchpoint. */
1504 CORE_ADDR watch_data_address = 0;
1505
1506 /* Get the thread's resume state. */
1507 enum resume_state get_resume_state () const
1508 {
1509 return m_resume_state;
1510 }
1511
1512 /* Put the thread in the NOT_RESUMED state. */
1513 void set_not_resumed ()
1514 {
1515 m_resume_state = resume_state::NOT_RESUMED;
1516 }
1517
1518 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1519 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1520 {
1521 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1522 m_resumed_pending_vcont_info.step = step;
1523 m_resumed_pending_vcont_info.sig = sig;
1524 }
1525
1526 /* Get the information this thread's pending vCont-resumption.
1527
1528 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1529 state. */
1530 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1531 {
1532 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1533
1534 return m_resumed_pending_vcont_info;
1535 }
1536
1537 /* Put the thread in the VCONT_RESUMED state. */
1538 void set_resumed ()
1539 {
1540 m_resume_state = resume_state::RESUMED;
1541 }
1542
1543 private:
1544 /* Resume state for this thread. This is used to implement vCont action
1545 coalescing (only when the target operates in non-stop mode).
1546
1547 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1548 which notes that this thread must be considered in the next commit_resume
1549 call.
1550
1551 remote_target::commit_resume sends a vCont packet with actions for the
1552 threads in the RESUMED_PENDING_VCONT state and moves them to the
1553 VCONT_RESUMED state.
1554
1555 When reporting a stop to the core for a thread, that thread is moved back
1556 to the NOT_RESUMED state. */
1557 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1558
1559 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1560 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1561 };
1562
1563 remote_state::remote_state ()
1564 : buf (400)
1565 {
1566 }
1567
1568 remote_state::~remote_state ()
1569 {
1570 xfree (this->last_pass_packet);
1571 xfree (this->last_program_signals_packet);
1572 xfree (this->finished_object);
1573 xfree (this->finished_annex);
1574 }
1575
1576 /* Utility: generate error from an incoming stub packet. */
1577 static void
1578 trace_error (char *buf)
1579 {
1580 if (*buf++ != 'E')
1581 return; /* not an error msg */
1582 switch (*buf)
1583 {
1584 case '1': /* malformed packet error */
1585 if (*++buf == '0') /* general case: */
1586 error (_("remote.c: error in outgoing packet."));
1587 else
1588 error (_("remote.c: error in outgoing packet at field #%ld."),
1589 strtol (buf, NULL, 16));
1590 default:
1591 error (_("Target returns error code '%s'."), buf);
1592 }
1593 }
1594
1595 /* Utility: wait for reply from stub, while accepting "O" packets. */
1596
1597 char *
1598 remote_target::remote_get_noisy_reply ()
1599 {
1600 struct remote_state *rs = get_remote_state ();
1601
1602 do /* Loop on reply from remote stub. */
1603 {
1604 char *buf;
1605
1606 QUIT; /* Allow user to bail out with ^C. */
1607 getpkt (&rs->buf);
1608 buf = rs->buf.data ();
1609 if (buf[0] == 'E')
1610 trace_error (buf);
1611 else if (startswith (buf, "qRelocInsn:"))
1612 {
1613 ULONGEST ul;
1614 CORE_ADDR from, to, org_to;
1615 const char *p, *pp;
1616 int adjusted_size = 0;
1617 int relocated = 0;
1618
1619 p = buf + strlen ("qRelocInsn:");
1620 pp = unpack_varlen_hex (p, &ul);
1621 if (*pp != ';')
1622 error (_("invalid qRelocInsn packet: %s"), buf);
1623 from = ul;
1624
1625 p = pp + 1;
1626 unpack_varlen_hex (p, &ul);
1627 to = ul;
1628
1629 org_to = to;
1630
1631 try
1632 {
1633 gdbarch_relocate_instruction (current_inferior ()->arch (),
1634 &to, from);
1635 relocated = 1;
1636 }
1637 catch (const gdb_exception &ex)
1638 {
1639 if (ex.error == MEMORY_ERROR)
1640 {
1641 /* Propagate memory errors silently back to the
1642 target. The stub may have limited the range of
1643 addresses we can write to, for example. */
1644 }
1645 else
1646 {
1647 /* Something unexpectedly bad happened. Be verbose
1648 so we can tell what, and propagate the error back
1649 to the stub, so it doesn't get stuck waiting for
1650 a response. */
1651 exception_fprintf (gdb_stderr, ex,
1652 _("warning: relocating instruction: "));
1653 }
1654 putpkt ("E01");
1655 }
1656
1657 if (relocated)
1658 {
1659 adjusted_size = to - org_to;
1660
1661 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1662 putpkt (buf);
1663 }
1664 }
1665 else if (buf[0] == 'O' && buf[1] != 'K')
1666 remote_console_output (buf + 1); /* 'O' message from stub */
1667 else
1668 return buf; /* Here's the actual reply. */
1669 }
1670 while (1);
1671 }
1672
1673 struct remote_arch_state *
1674 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1675 {
1676 remote_arch_state *rsa;
1677
1678 auto it = this->m_arch_states.find (gdbarch);
1679 if (it == this->m_arch_states.end ())
1680 {
1681 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1682 std::forward_as_tuple (gdbarch),
1683 std::forward_as_tuple (gdbarch));
1684 rsa = &p.first->second;
1685
1686 /* Make sure that the packet buffer is plenty big enough for
1687 this architecture. */
1688 if (this->buf.size () < rsa->remote_packet_size)
1689 this->buf.resize (2 * rsa->remote_packet_size);
1690 }
1691 else
1692 rsa = &it->second;
1693
1694 return rsa;
1695 }
1696
1697 /* Fetch the global remote target state. */
1698
1699 remote_state *
1700 remote_target::get_remote_state ()
1701 {
1702 /* Make sure that the remote architecture state has been
1703 initialized, because doing so might reallocate rs->buf. Any
1704 function which calls getpkt also needs to be mindful of changes
1705 to rs->buf, but this call limits the number of places which run
1706 into trouble. */
1707 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1708
1709 return &m_remote_state;
1710 }
1711
1712 /* Fetch the remote exec-file from the current program space. */
1713
1714 static const char *
1715 get_remote_exec_file (void)
1716 {
1717 char *remote_exec_file;
1718
1719 remote_exec_file = remote_pspace_data.get (current_program_space);
1720 if (remote_exec_file == NULL)
1721 return "";
1722
1723 return remote_exec_file;
1724 }
1725
1726 /* Set the remote exec file for PSPACE. */
1727
1728 static void
1729 set_pspace_remote_exec_file (struct program_space *pspace,
1730 const char *remote_exec_file)
1731 {
1732 char *old_file = remote_pspace_data.get (pspace);
1733
1734 xfree (old_file);
1735 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1736 }
1737
1738 /* The "set/show remote exec-file" set command hook. */
1739
1740 static void
1741 set_remote_exec_file (const char *ignored, int from_tty,
1742 struct cmd_list_element *c)
1743 {
1744 set_pspace_remote_exec_file (current_program_space,
1745 remote_exec_file_var.c_str ());
1746 }
1747
1748 /* The "set/show remote exec-file" show command hook. */
1749
1750 static void
1751 show_remote_exec_file (struct ui_file *file, int from_tty,
1752 struct cmd_list_element *cmd, const char *value)
1753 {
1754 gdb_printf (file, "%s\n", get_remote_exec_file ());
1755 }
1756
1757 static int
1758 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1759 {
1760 int regnum, num_remote_regs, offset;
1761 struct packet_reg **remote_regs;
1762
1763 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1764 {
1765 struct packet_reg *r = &regs[regnum];
1766
1767 if (register_size (gdbarch, regnum) == 0)
1768 /* Do not try to fetch zero-sized (placeholder) registers. */
1769 r->pnum = -1;
1770 else
1771 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1772
1773 r->regnum = regnum;
1774 }
1775
1776 /* Define the g/G packet format as the contents of each register
1777 with a remote protocol number, in order of ascending protocol
1778 number. */
1779
1780 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1781 for (num_remote_regs = 0, regnum = 0;
1782 regnum < gdbarch_num_regs (gdbarch);
1783 regnum++)
1784 if (regs[regnum].pnum != -1)
1785 remote_regs[num_remote_regs++] = &regs[regnum];
1786
1787 std::sort (remote_regs, remote_regs + num_remote_regs,
1788 [] (const packet_reg *a, const packet_reg *b)
1789 { return a->pnum < b->pnum; });
1790
1791 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1792 {
1793 remote_regs[regnum]->in_g_packet = 1;
1794 remote_regs[regnum]->offset = offset;
1795 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1796 }
1797
1798 return offset;
1799 }
1800
1801 /* Given the architecture described by GDBARCH, return the remote
1802 protocol register's number and the register's offset in the g/G
1803 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1804 If the target does not have a mapping for REGNUM, return false,
1805 otherwise, return true. */
1806
1807 int
1808 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1809 int *pnum, int *poffset)
1810 {
1811 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1812
1813 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1814
1815 map_regcache_remote_table (gdbarch, regs.data ());
1816
1817 *pnum = regs[regnum].pnum;
1818 *poffset = regs[regnum].offset;
1819
1820 return *pnum != -1;
1821 }
1822
1823 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1824 {
1825 /* Use the architecture to build a regnum<->pnum table, which will be
1826 1:1 unless a feature set specifies otherwise. */
1827 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1828
1829 /* Record the maximum possible size of the g packet - it may turn out
1830 to be smaller. */
1831 this->sizeof_g_packet
1832 = map_regcache_remote_table (gdbarch, this->regs.get ());
1833
1834 /* Default maximum number of characters in a packet body. Many
1835 remote stubs have a hardwired buffer size of 400 bytes
1836 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1837 as the maximum packet-size to ensure that the packet and an extra
1838 NUL character can always fit in the buffer. This stops GDB
1839 trashing stubs that try to squeeze an extra NUL into what is
1840 already a full buffer (As of 1999-12-04 that was most stubs). */
1841 this->remote_packet_size = 400 - 1;
1842
1843 /* This one is filled in when a ``g'' packet is received. */
1844 this->actual_register_packet_size = 0;
1845
1846 /* Should rsa->sizeof_g_packet needs more space than the
1847 default, adjust the size accordingly. Remember that each byte is
1848 encoded as two characters. 32 is the overhead for the packet
1849 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1850 (``$NN:G...#NN'') is a better guess, the below has been padded a
1851 little. */
1852 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1853 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1854 }
1855
1856 /* Get a pointer to the current remote target. If not connected to a
1857 remote target, return NULL. */
1858
1859 static remote_target *
1860 get_current_remote_target ()
1861 {
1862 target_ops *proc_target = current_inferior ()->process_target ();
1863 return dynamic_cast<remote_target *> (proc_target);
1864 }
1865
1866 /* Return the current allowed size of a remote packet. This is
1867 inferred from the current architecture, and should be used to
1868 limit the length of outgoing packets. */
1869 long
1870 remote_target::get_remote_packet_size ()
1871 {
1872 struct remote_state *rs = get_remote_state ();
1873 remote_arch_state *rsa
1874 = rs->get_remote_arch_state (current_inferior ()->arch ());
1875
1876 if (rs->explicit_packet_size)
1877 return rs->explicit_packet_size;
1878
1879 return rsa->remote_packet_size;
1880 }
1881
1882 static struct packet_reg *
1883 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1884 long regnum)
1885 {
1886 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1887 return NULL;
1888 else
1889 {
1890 struct packet_reg *r = &rsa->regs[regnum];
1891
1892 gdb_assert (r->regnum == regnum);
1893 return r;
1894 }
1895 }
1896
1897 static struct packet_reg *
1898 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1899 LONGEST pnum)
1900 {
1901 int i;
1902
1903 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1904 {
1905 struct packet_reg *r = &rsa->regs[i];
1906
1907 if (r->pnum == pnum)
1908 return r;
1909 }
1910 return NULL;
1911 }
1912
1913 /* Allow the user to specify what sequence to send to the remote
1914 when he requests a program interruption: Although ^C is usually
1915 what remote systems expect (this is the default, here), it is
1916 sometimes preferable to send a break. On other systems such
1917 as the Linux kernel, a break followed by g, which is Magic SysRq g
1918 is required in order to interrupt the execution. */
1919 const char interrupt_sequence_control_c[] = "Ctrl-C";
1920 const char interrupt_sequence_break[] = "BREAK";
1921 const char interrupt_sequence_break_g[] = "BREAK-g";
1922 static const char *const interrupt_sequence_modes[] =
1923 {
1924 interrupt_sequence_control_c,
1925 interrupt_sequence_break,
1926 interrupt_sequence_break_g,
1927 NULL
1928 };
1929 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1930
1931 static void
1932 show_interrupt_sequence (struct ui_file *file, int from_tty,
1933 struct cmd_list_element *c,
1934 const char *value)
1935 {
1936 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1937 gdb_printf (file,
1938 _("Send the ASCII ETX character (Ctrl-c) "
1939 "to the remote target to interrupt the "
1940 "execution of the program.\n"));
1941 else if (interrupt_sequence_mode == interrupt_sequence_break)
1942 gdb_printf (file,
1943 _("send a break signal to the remote target "
1944 "to interrupt the execution of the program.\n"));
1945 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1946 gdb_printf (file,
1947 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1948 "the remote target to interrupt the execution "
1949 "of Linux kernel.\n"));
1950 else
1951 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1952 interrupt_sequence_mode);
1953 }
1954
1955 /* This boolean variable specifies whether interrupt_sequence is sent
1956 to the remote target when gdb connects to it.
1957 This is mostly needed when you debug the Linux kernel: The Linux kernel
1958 expects BREAK g which is Magic SysRq g for connecting gdb. */
1959 static bool interrupt_on_connect = false;
1960
1961 /* This variable is used to implement the "set/show remotebreak" commands.
1962 Since these commands are now deprecated in favor of "set/show remote
1963 interrupt-sequence", it no longer has any effect on the code. */
1964 static bool remote_break;
1965
1966 static void
1967 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1968 {
1969 if (remote_break)
1970 interrupt_sequence_mode = interrupt_sequence_break;
1971 else
1972 interrupt_sequence_mode = interrupt_sequence_control_c;
1973 }
1974
1975 static void
1976 show_remotebreak (struct ui_file *file, int from_tty,
1977 struct cmd_list_element *c,
1978 const char *value)
1979 {
1980 }
1981
1982 /* This variable sets the number of bits in an address that are to be
1983 sent in a memory ("M" or "m") packet. Normally, after stripping
1984 leading zeros, the entire address would be sent. This variable
1985 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1986 initial implementation of remote.c restricted the address sent in
1987 memory packets to ``host::sizeof long'' bytes - (typically 32
1988 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1989 address was never sent. Since fixing this bug may cause a break in
1990 some remote targets this variable is principally provided to
1991 facilitate backward compatibility. */
1992
1993 static unsigned int remote_address_size;
1994
1995 \f
1996 /* The default max memory-write-packet-size, when the setting is
1997 "fixed". The 16k is historical. (It came from older GDB's using
1998 alloca for buffers and the knowledge (folklore?) that some hosts
1999 don't cope very well with large alloca calls.) */
2000 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2001
2002 /* The minimum remote packet size for memory transfers. Ensures we
2003 can write at least one byte. */
2004 #define MIN_MEMORY_PACKET_SIZE 20
2005
2006 /* Get the memory packet size, assuming it is fixed. */
2007
2008 static long
2009 get_fixed_memory_packet_size (struct memory_packet_config *config)
2010 {
2011 gdb_assert (config->fixed_p);
2012
2013 if (config->size <= 0)
2014 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2015 else
2016 return config->size;
2017 }
2018
2019 /* Compute the current size of a read/write packet. Since this makes
2020 use of ``actual_register_packet_size'' the computation is dynamic. */
2021
2022 long
2023 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2024 {
2025 struct remote_state *rs = get_remote_state ();
2026 remote_arch_state *rsa
2027 = rs->get_remote_arch_state (current_inferior ()->arch ());
2028
2029 long what_they_get;
2030 if (config->fixed_p)
2031 what_they_get = get_fixed_memory_packet_size (config);
2032 else
2033 {
2034 what_they_get = get_remote_packet_size ();
2035 /* Limit the packet to the size specified by the user. */
2036 if (config->size > 0
2037 && what_they_get > config->size)
2038 what_they_get = config->size;
2039
2040 /* Limit it to the size of the targets ``g'' response unless we have
2041 permission from the stub to use a larger packet size. */
2042 if (rs->explicit_packet_size == 0
2043 && rsa->actual_register_packet_size > 0
2044 && what_they_get > rsa->actual_register_packet_size)
2045 what_they_get = rsa->actual_register_packet_size;
2046 }
2047 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2048 what_they_get = MIN_MEMORY_PACKET_SIZE;
2049
2050 /* Make sure there is room in the global buffer for this packet
2051 (including its trailing NUL byte). */
2052 if (rs->buf.size () < what_they_get + 1)
2053 rs->buf.resize (2 * what_they_get);
2054
2055 return what_they_get;
2056 }
2057
2058 /* Update the size of a read/write packet. If they user wants
2059 something really big then do a sanity check. */
2060
2061 static void
2062 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2063 bool target_connected)
2064 {
2065 int fixed_p = config->fixed_p;
2066 long size = config->size;
2067
2068 if (args == NULL)
2069 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2070 else if (strcmp (args, "hard") == 0
2071 || strcmp (args, "fixed") == 0)
2072 fixed_p = 1;
2073 else if (strcmp (args, "soft") == 0
2074 || strcmp (args, "limit") == 0)
2075 fixed_p = 0;
2076 else
2077 {
2078 char *end;
2079
2080 size = strtoul (args, &end, 0);
2081 if (args == end)
2082 error (_("Invalid %s (bad syntax)."), config->name);
2083
2084 /* Instead of explicitly capping the size of a packet to or
2085 disallowing it, the user is allowed to set the size to
2086 something arbitrarily large. */
2087 }
2088
2089 /* Extra checks? */
2090 if (fixed_p && !config->fixed_p)
2091 {
2092 /* So that the query shows the correct value. */
2093 long query_size = (size <= 0
2094 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2095 : size);
2096
2097 if (target_connected
2098 && !query (_("The target may not be able to correctly handle a %s\n"
2099 "of %ld bytes. Change the packet size? "),
2100 config->name, query_size))
2101 error (_("Packet size not changed."));
2102 else if (!target_connected
2103 && !query (_("Future remote targets may not be able to "
2104 "correctly handle a %s\nof %ld bytes. Change the "
2105 "packet size for future remote targets? "),
2106 config->name, query_size))
2107 error (_("Packet size not changed."));
2108 }
2109 /* Update the config. */
2110 config->fixed_p = fixed_p;
2111 config->size = size;
2112
2113 const char *target_type = get_target_type_name (target_connected);
2114 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2115 args);
2116
2117 }
2118
2119 /* Show the memory-read or write-packet size configuration CONFIG of the
2120 target REMOTE. If REMOTE is nullptr, the default configuration for future
2121 remote targets should be passed in CONFIG. */
2122
2123 static void
2124 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2125 {
2126 const char *target_type = get_target_type_name (remote != nullptr);
2127
2128 if (config->size == 0)
2129 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2130 else
2131 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2132 config->size);
2133
2134 if (config->fixed_p)
2135 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2136 get_fixed_memory_packet_size (config));
2137 else
2138 {
2139 if (remote != nullptr)
2140 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2141 remote->get_memory_packet_size (config));
2142 else
2143 gdb_puts ("The actual limit will be further reduced "
2144 "dependent on the target.\n");
2145 }
2146 }
2147
2148 /* Configure the memory-write-packet size of the currently selected target. If
2149 no target is available, the default configuration for future remote targets
2150 is configured. */
2151
2152 static void
2153 set_memory_write_packet_size (const char *args, int from_tty)
2154 {
2155 remote_target *remote = get_current_remote_target ();
2156 if (remote != nullptr)
2157 {
2158 set_memory_packet_size
2159 (args, &remote->m_features.m_memory_write_packet_config, true);
2160 }
2161 else
2162 {
2163 memory_packet_config* config = &memory_write_packet_config;
2164 set_memory_packet_size (args, config, false);
2165 }
2166 }
2167
2168 /* Display the memory-write-packet size of the currently selected target. If
2169 no target is available, the default configuration for future remote targets
2170 is shown. */
2171
2172 static void
2173 show_memory_write_packet_size (const char *args, int from_tty)
2174 {
2175 remote_target *remote = get_current_remote_target ();
2176 if (remote != nullptr)
2177 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2178 remote);
2179 else
2180 show_memory_packet_size (&memory_write_packet_config, nullptr);
2181 }
2182
2183 /* Show the number of hardware watchpoints that can be used. */
2184
2185 static void
2186 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2187 struct cmd_list_element *c,
2188 const char *value)
2189 {
2190 gdb_printf (file, _("The maximum number of target hardware "
2191 "watchpoints is %s.\n"), value);
2192 }
2193
2194 /* Show the length limit (in bytes) for hardware watchpoints. */
2195
2196 static void
2197 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2198 struct cmd_list_element *c,
2199 const char *value)
2200 {
2201 gdb_printf (file, _("The maximum length (in bytes) of a target "
2202 "hardware watchpoint is %s.\n"), value);
2203 }
2204
2205 /* Show the number of hardware breakpoints that can be used. */
2206
2207 static void
2208 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2209 struct cmd_list_element *c,
2210 const char *value)
2211 {
2212 gdb_printf (file, _("The maximum number of target hardware "
2213 "breakpoints is %s.\n"), value);
2214 }
2215
2216 /* Controls the maximum number of characters to display in the debug output
2217 for each remote packet. The remaining characters are omitted. */
2218
2219 static int remote_packet_max_chars = 512;
2220
2221 /* Show the maximum number of characters to display for each remote packet
2222 when remote debugging is enabled. */
2223
2224 static void
2225 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2226 struct cmd_list_element *c,
2227 const char *value)
2228 {
2229 gdb_printf (file, _("Number of remote packet characters to "
2230 "display is %s.\n"), value);
2231 }
2232
2233 long
2234 remote_target::get_memory_write_packet_size ()
2235 {
2236 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2237 }
2238
2239 /* Configure the memory-read-packet size of the currently selected target. If
2240 no target is available, the default configuration for future remote targets
2241 is adapted. */
2242
2243 static void
2244 set_memory_read_packet_size (const char *args, int from_tty)
2245 {
2246 remote_target *remote = get_current_remote_target ();
2247 if (remote != nullptr)
2248 set_memory_packet_size
2249 (args, &remote->m_features.m_memory_read_packet_config, true);
2250 else
2251 {
2252 memory_packet_config* config = &memory_read_packet_config;
2253 set_memory_packet_size (args, config, false);
2254 }
2255
2256 }
2257
2258 /* Display the memory-read-packet size of the currently selected target. If
2259 no target is available, the default configuration for future remote targets
2260 is shown. */
2261
2262 static void
2263 show_memory_read_packet_size (const char *args, int from_tty)
2264 {
2265 remote_target *remote = get_current_remote_target ();
2266 if (remote != nullptr)
2267 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2268 remote);
2269 else
2270 show_memory_packet_size (&memory_read_packet_config, nullptr);
2271 }
2272
2273 long
2274 remote_target::get_memory_read_packet_size ()
2275 {
2276 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2277
2278 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2279 extra buffer size argument before the memory read size can be
2280 increased beyond this. */
2281 if (size > get_remote_packet_size ())
2282 size = get_remote_packet_size ();
2283 return size;
2284 }
2285
2286 static enum packet_support packet_config_support (const packet_config *config);
2287
2288
2289 static void
2290 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2291 cmd_list_element *c)
2292 {
2293 remote_target *remote = get_current_remote_target ();
2294 gdb_assert (c->var.has_value ());
2295
2296 auto *default_config = static_cast<packet_config *> (c->context ());
2297 const int packet_idx = std::distance (remote_protocol_packets,
2298 default_config);
2299
2300 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2301 {
2302 const char *name = packets_descriptions[packet_idx].name;
2303 const auto_boolean value = c->var->get<auto_boolean> ();
2304 const char *support = get_packet_support_name (value);
2305 const char *target_type = get_target_type_name (remote != nullptr);
2306
2307 if (remote != nullptr)
2308 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2309 else
2310 remote_protocol_packets[packet_idx].detect = value;
2311
2312 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2313 target_type, support);
2314 return;
2315 }
2316
2317 internal_error (_("Could not find config for %s"), c->name);
2318 }
2319
2320 static void
2321 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2322 remote_target *remote)
2323 {
2324 const char *support = "internal-error";
2325 const char *target_type = get_target_type_name (remote != nullptr);
2326
2327 packet_config *config;
2328 if (remote != nullptr)
2329 config = &remote->m_features.m_protocol_packets[which_packet];
2330 else
2331 config = &remote_protocol_packets[which_packet];
2332
2333 switch (packet_config_support (config))
2334 {
2335 case PACKET_ENABLE:
2336 support = "enabled";
2337 break;
2338 case PACKET_DISABLE:
2339 support = "disabled";
2340 break;
2341 case PACKET_SUPPORT_UNKNOWN:
2342 support = "unknown";
2343 break;
2344 }
2345 switch (config->detect)
2346 {
2347 case AUTO_BOOLEAN_AUTO:
2348 gdb_printf (file,
2349 _("Support for the '%s' packet %s is \"auto\", "
2350 "currently %s.\n"),
2351 packets_descriptions[which_packet].name, target_type,
2352 support);
2353 break;
2354 case AUTO_BOOLEAN_TRUE:
2355 case AUTO_BOOLEAN_FALSE:
2356 gdb_printf (file,
2357 _("Support for the '%s' packet %s is \"%s\".\n"),
2358 packets_descriptions[which_packet].name, target_type,
2359 get_packet_support_name (config->detect));
2360 break;
2361 }
2362 }
2363
2364 static void
2365 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2366 const char *title, int legacy)
2367 {
2368 packets_descriptions[which_packet].name = name;
2369 packets_descriptions[which_packet].title = title;
2370
2371 packet_config *config = &remote_protocol_packets[which_packet];
2372
2373 gdb::unique_xmalloc_ptr<char> set_doc
2374 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2375 name, title);
2376 gdb::unique_xmalloc_ptr<char> show_doc
2377 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2378 name, title);
2379 /* set/show TITLE-packet {auto,on,off} */
2380 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2381 set_show_commands cmds
2382 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2383 &config->detect, set_doc.get (),
2384 show_doc.get (), NULL, /* help_doc */
2385 set_remote_protocol_packet_cmd,
2386 show_remote_protocol_packet_cmd,
2387 &remote_set_cmdlist, &remote_show_cmdlist);
2388 cmds.show->set_context (config);
2389 cmds.set->set_context (config);
2390
2391 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2392 if (legacy)
2393 {
2394 /* It's not clear who should take ownership of the LEGACY_NAME string
2395 created below, so, for now, place the string into a static vector
2396 which ensures the strings is released when GDB exits. */
2397 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2398 gdb::unique_xmalloc_ptr<char> legacy_name
2399 = xstrprintf ("%s-packet", name);
2400 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2401 &remote_set_cmdlist);
2402 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2403 &remote_show_cmdlist);
2404 legacy_names.emplace_back (std::move (legacy_name));
2405 }
2406 }
2407
2408 static enum packet_result
2409 packet_check_result (const char *buf)
2410 {
2411 if (buf[0] != '\0')
2412 {
2413 /* The stub recognized the packet request. Check that the
2414 operation succeeded. */
2415 if (buf[0] == 'E'
2416 && isxdigit (buf[1]) && isxdigit (buf[2])
2417 && buf[3] == '\0')
2418 /* "Enn" - definitely an error. */
2419 return PACKET_ERROR;
2420
2421 /* Always treat "E." as an error. This will be used for
2422 more verbose error messages, such as E.memtypes. */
2423 if (buf[0] == 'E' && buf[1] == '.')
2424 return PACKET_ERROR;
2425
2426 /* The packet may or may not be OK. Just assume it is. */
2427 return PACKET_OK;
2428 }
2429 else
2430 /* The stub does not support the packet. */
2431 return PACKET_UNKNOWN;
2432 }
2433
2434 static enum packet_result
2435 packet_check_result (const gdb::char_vector &buf)
2436 {
2437 return packet_check_result (buf.data ());
2438 }
2439
2440 packet_result
2441 remote_features::packet_ok (const char *buf, const int which_packet)
2442 {
2443 packet_config *config = &m_protocol_packets[which_packet];
2444 packet_description *descr = &packets_descriptions[which_packet];
2445
2446 enum packet_result result;
2447
2448 if (config->detect != AUTO_BOOLEAN_TRUE
2449 && config->support == PACKET_DISABLE)
2450 internal_error (_("packet_ok: attempt to use a disabled packet"));
2451
2452 result = packet_check_result (buf);
2453 switch (result)
2454 {
2455 case PACKET_OK:
2456 case PACKET_ERROR:
2457 /* The stub recognized the packet request. */
2458 if (config->support == PACKET_SUPPORT_UNKNOWN)
2459 {
2460 remote_debug_printf ("Packet %s (%s) is supported",
2461 descr->name, descr->title);
2462 config->support = PACKET_ENABLE;
2463 }
2464 break;
2465 case PACKET_UNKNOWN:
2466 /* The stub does not support the packet. */
2467 if (config->detect == AUTO_BOOLEAN_AUTO
2468 && config->support == PACKET_ENABLE)
2469 {
2470 /* If the stub previously indicated that the packet was
2471 supported then there is a protocol error. */
2472 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2473 descr->name, descr->title);
2474 }
2475 else if (config->detect == AUTO_BOOLEAN_TRUE)
2476 {
2477 /* The user set it wrong. */
2478 error (_("Enabled packet %s (%s) not recognized by stub"),
2479 descr->name, descr->title);
2480 }
2481
2482 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2483 descr->title);
2484 config->support = PACKET_DISABLE;
2485 break;
2486 }
2487
2488 return result;
2489 }
2490
2491 packet_result
2492 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2493 {
2494 return packet_ok (buf.data (), which_packet);
2495 }
2496
2497 /* Returns whether a given packet or feature is supported. This takes
2498 into account the state of the corresponding "set remote foo-packet"
2499 command, which may be used to bypass auto-detection. */
2500
2501 static enum packet_support
2502 packet_config_support (const packet_config *config)
2503 {
2504 switch (config->detect)
2505 {
2506 case AUTO_BOOLEAN_TRUE:
2507 return PACKET_ENABLE;
2508 case AUTO_BOOLEAN_FALSE:
2509 return PACKET_DISABLE;
2510 case AUTO_BOOLEAN_AUTO:
2511 return config->support;
2512 default:
2513 gdb_assert_not_reached ("bad switch");
2514 }
2515 }
2516
2517 packet_support
2518 remote_features::packet_support (int packet) const
2519 {
2520 const packet_config *config = &m_protocol_packets[packet];
2521 return packet_config_support (config);
2522 }
2523
2524 static void
2525 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2526 struct cmd_list_element *c,
2527 const char *value)
2528 {
2529 remote_target *remote = get_current_remote_target ();
2530 gdb_assert (c->var.has_value ());
2531
2532 auto *default_config = static_cast<packet_config *> (c->context ());
2533 const int packet_idx = std::distance (remote_protocol_packets,
2534 default_config);
2535
2536 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2537 {
2538 show_packet_config_cmd (file, packet_idx, remote);
2539 return;
2540 }
2541 internal_error (_("Could not find config for %s"), c->name);
2542 }
2543
2544 /* Should we try one of the 'Z' requests? */
2545
2546 enum Z_packet_type
2547 {
2548 Z_PACKET_SOFTWARE_BP,
2549 Z_PACKET_HARDWARE_BP,
2550 Z_PACKET_WRITE_WP,
2551 Z_PACKET_READ_WP,
2552 Z_PACKET_ACCESS_WP,
2553 NR_Z_PACKET_TYPES
2554 };
2555
2556 /* For compatibility with older distributions. Provide a ``set remote
2557 Z-packet ...'' command that updates all the Z packet types. */
2558
2559 static enum auto_boolean remote_Z_packet_detect;
2560
2561 static void
2562 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2563 struct cmd_list_element *c)
2564 {
2565 remote_target *remote = get_current_remote_target ();
2566 int i;
2567
2568 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2569 {
2570 if (remote != nullptr)
2571 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2572 = remote_Z_packet_detect;
2573 else
2574 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2575 }
2576
2577 const char *support = get_packet_support_name (remote_Z_packet_detect);
2578 const char *target_type = get_target_type_name (remote != nullptr);
2579 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2580 support);
2581
2582 }
2583
2584 static void
2585 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2586 struct cmd_list_element *c,
2587 const char *value)
2588 {
2589 remote_target *remote = get_current_remote_target ();
2590 int i;
2591
2592 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2593 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2594 }
2595
2596 /* Insert fork catchpoint target routine. If fork events are enabled
2597 then return success, nothing more to do. */
2598
2599 int
2600 remote_target::insert_fork_catchpoint (int pid)
2601 {
2602 return !m_features.remote_fork_event_p ();
2603 }
2604
2605 /* Remove fork catchpoint target routine. Nothing to do, just
2606 return success. */
2607
2608 int
2609 remote_target::remove_fork_catchpoint (int pid)
2610 {
2611 return 0;
2612 }
2613
2614 /* Insert vfork catchpoint target routine. If vfork events are enabled
2615 then return success, nothing more to do. */
2616
2617 int
2618 remote_target::insert_vfork_catchpoint (int pid)
2619 {
2620 return !m_features.remote_vfork_event_p ();
2621 }
2622
2623 /* Remove vfork catchpoint target routine. Nothing to do, just
2624 return success. */
2625
2626 int
2627 remote_target::remove_vfork_catchpoint (int pid)
2628 {
2629 return 0;
2630 }
2631
2632 /* Insert exec catchpoint target routine. If exec events are
2633 enabled, just return success. */
2634
2635 int
2636 remote_target::insert_exec_catchpoint (int pid)
2637 {
2638 return !m_features.remote_exec_event_p ();
2639 }
2640
2641 /* Remove exec catchpoint target routine. Nothing to do, just
2642 return success. */
2643
2644 int
2645 remote_target::remove_exec_catchpoint (int pid)
2646 {
2647 return 0;
2648 }
2649
2650 \f
2651
2652 /* Take advantage of the fact that the TID field is not used, to tag
2653 special ptids with it set to != 0. */
2654 static const ptid_t magic_null_ptid (42000, -1, 1);
2655 static const ptid_t not_sent_ptid (42000, -2, 1);
2656 static const ptid_t any_thread_ptid (42000, 0, 1);
2657
2658 /* Find out if the stub attached to PID (and hence GDB should offer to
2659 detach instead of killing it when bailing out). */
2660
2661 int
2662 remote_target::remote_query_attached (int pid)
2663 {
2664 struct remote_state *rs = get_remote_state ();
2665 size_t size = get_remote_packet_size ();
2666
2667 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2668 return 0;
2669
2670 if (m_features.remote_multi_process_p ())
2671 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2672 else
2673 xsnprintf (rs->buf.data (), size, "qAttached");
2674
2675 putpkt (rs->buf);
2676 getpkt (&rs->buf);
2677
2678 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2679 {
2680 case PACKET_OK:
2681 if (strcmp (rs->buf.data (), "1") == 0)
2682 return 1;
2683 break;
2684 case PACKET_ERROR:
2685 warning (_("Remote failure reply: %s"), rs->buf.data ());
2686 break;
2687 case PACKET_UNKNOWN:
2688 break;
2689 }
2690
2691 return 0;
2692 }
2693
2694 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2695 has been invented by GDB, instead of reported by the target. Since
2696 we can be connected to a remote system before before knowing about
2697 any inferior, mark the target with execution when we find the first
2698 inferior. If ATTACHED is 1, then we had just attached to this
2699 inferior. If it is 0, then we just created this inferior. If it
2700 is -1, then try querying the remote stub to find out if it had
2701 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2702 attempt to open this inferior's executable as the main executable
2703 if no main executable is open already. */
2704
2705 inferior *
2706 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2707 int try_open_exec)
2708 {
2709 struct inferior *inf;
2710
2711 /* Check whether this process we're learning about is to be
2712 considered attached, or if is to be considered to have been
2713 spawned by the stub. */
2714 if (attached == -1)
2715 attached = remote_query_attached (pid);
2716
2717 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2718 {
2719 /* If the target shares code across all inferiors, then every
2720 attach adds a new inferior. */
2721 inf = add_inferior (pid);
2722
2723 /* ... and every inferior is bound to the same program space.
2724 However, each inferior may still have its own address
2725 space. */
2726 inf->aspace = maybe_new_address_space ();
2727 inf->pspace = current_program_space;
2728 }
2729 else
2730 {
2731 /* In the traditional debugging scenario, there's a 1-1 match
2732 between program/address spaces. We simply bind the inferior
2733 to the program space's address space. */
2734 inf = current_inferior ();
2735
2736 /* However, if the current inferior is already bound to a
2737 process, find some other empty inferior. */
2738 if (inf->pid != 0)
2739 {
2740 inf = nullptr;
2741 for (inferior *it : all_inferiors ())
2742 if (it->pid == 0)
2743 {
2744 inf = it;
2745 break;
2746 }
2747 }
2748 if (inf == nullptr)
2749 {
2750 /* Since all inferiors were already bound to a process, add
2751 a new inferior. */
2752 inf = add_inferior_with_spaces ();
2753 }
2754 switch_to_inferior_no_thread (inf);
2755 inf->push_target (this);
2756 inferior_appeared (inf, pid);
2757 }
2758
2759 inf->attach_flag = attached;
2760 inf->fake_pid_p = fake_pid_p;
2761
2762 /* If no main executable is currently open then attempt to
2763 open the file that was executed to create this inferior. */
2764 if (try_open_exec && get_exec_file (0) == NULL)
2765 exec_file_locate_attach (pid, 0, 1);
2766
2767 /* Check for exec file mismatch, and let the user solve it. */
2768 validate_exec_file (1);
2769
2770 return inf;
2771 }
2772
2773 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2774 static remote_thread_info *get_remote_thread_info (remote_target *target,
2775 ptid_t ptid);
2776
2777 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2778 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2779 remote_state::starting_up flag) is true then the new thread is added
2780 silently, otherwise the new thread will be announced to the user. */
2781
2782 thread_info *
2783 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2784 bool silent_p)
2785 {
2786 struct remote_state *rs = get_remote_state ();
2787 struct thread_info *thread;
2788
2789 /* GDB historically didn't pull threads in the initial connection
2790 setup. If the remote target doesn't even have a concept of
2791 threads (e.g., a bare-metal target), even if internally we
2792 consider that a single-threaded target, mentioning a new thread
2793 might be confusing to the user. Be silent then, preserving the
2794 age old behavior. */
2795 if (rs->starting_up || silent_p)
2796 thread = add_thread_silent (this, ptid);
2797 else
2798 thread = add_thread (this, ptid);
2799
2800 if (executing)
2801 get_remote_thread_info (thread)->set_resumed ();
2802 set_executing (this, ptid, executing);
2803 set_running (this, ptid, running);
2804
2805 return thread;
2806 }
2807
2808 /* Come here when we learn about a thread id from the remote target.
2809 It may be the first time we hear about such thread, so take the
2810 opportunity to add it to GDB's thread list. In case this is the
2811 first time we're noticing its corresponding inferior, add it to
2812 GDB's inferior list as well. EXECUTING indicates whether the
2813 thread is (internally) executing or stopped. */
2814
2815 void
2816 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2817 {
2818 /* In non-stop mode, we assume new found threads are (externally)
2819 running until proven otherwise with a stop reply. In all-stop,
2820 we can only get here if all threads are stopped. */
2821 bool running = target_is_non_stop_p ();
2822
2823 /* If this is a new thread, add it to GDB's thread list.
2824 If we leave it up to WFI to do this, bad things will happen. */
2825
2826 thread_info *tp = this->find_thread (currthread);
2827 if (tp != NULL && tp->state == THREAD_EXITED)
2828 {
2829 /* We're seeing an event on a thread id we knew had exited.
2830 This has to be a new thread reusing the old id. Add it. */
2831 remote_add_thread (currthread, running, executing, false);
2832 return;
2833 }
2834
2835 if (!in_thread_list (this, currthread))
2836 {
2837 struct inferior *inf = NULL;
2838 int pid = currthread.pid ();
2839
2840 if (inferior_ptid.is_pid ()
2841 && pid == inferior_ptid.pid ())
2842 {
2843 /* inferior_ptid has no thread member yet. This can happen
2844 with the vAttach -> remote_wait,"TAAthread:" path if the
2845 stub doesn't support qC. This is the first stop reported
2846 after an attach, so this is the main thread. Update the
2847 ptid in the thread list. */
2848 if (in_thread_list (this, ptid_t (pid)))
2849 thread_change_ptid (this, inferior_ptid, currthread);
2850 else
2851 {
2852 thread_info *thr
2853 = remote_add_thread (currthread, running, executing, false);
2854 switch_to_thread (thr);
2855 }
2856 return;
2857 }
2858
2859 if (magic_null_ptid == inferior_ptid)
2860 {
2861 /* inferior_ptid is not set yet. This can happen with the
2862 vRun -> remote_wait,"TAAthread:" path if the stub
2863 doesn't support qC. This is the first stop reported
2864 after an attach, so this is the main thread. Update the
2865 ptid in the thread list. */
2866 thread_change_ptid (this, inferior_ptid, currthread);
2867 return;
2868 }
2869
2870 /* When connecting to a target remote, or to a target
2871 extended-remote which already was debugging an inferior, we
2872 may not know about it yet. Add it before adding its child
2873 thread, so notifications are emitted in a sensible order. */
2874 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2875 {
2876 bool fake_pid_p = !m_features.remote_multi_process_p ();
2877
2878 inf = remote_add_inferior (fake_pid_p,
2879 currthread.pid (), -1, 1);
2880 }
2881
2882 /* This is really a new thread. Add it. */
2883 thread_info *new_thr
2884 = remote_add_thread (currthread, running, executing, false);
2885
2886 /* If we found a new inferior, let the common code do whatever
2887 it needs to with it (e.g., read shared libraries, insert
2888 breakpoints), unless we're just setting up an all-stop
2889 connection. */
2890 if (inf != NULL)
2891 {
2892 struct remote_state *rs = get_remote_state ();
2893
2894 if (!rs->starting_up)
2895 notice_new_inferior (new_thr, executing, 0);
2896 }
2897 }
2898 }
2899
2900 /* Return THREAD's private thread data, creating it if necessary. */
2901
2902 static remote_thread_info *
2903 get_remote_thread_info (thread_info *thread)
2904 {
2905 gdb_assert (thread != NULL);
2906
2907 if (thread->priv == NULL)
2908 thread->priv.reset (new remote_thread_info);
2909
2910 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2911 }
2912
2913 /* Return PTID's private thread data, creating it if necessary. */
2914
2915 static remote_thread_info *
2916 get_remote_thread_info (remote_target *target, ptid_t ptid)
2917 {
2918 thread_info *thr = target->find_thread (ptid);
2919 return get_remote_thread_info (thr);
2920 }
2921
2922 /* Call this function as a result of
2923 1) A halt indication (T packet) containing a thread id
2924 2) A direct query of currthread
2925 3) Successful execution of set thread */
2926
2927 static void
2928 record_currthread (struct remote_state *rs, ptid_t currthread)
2929 {
2930 rs->general_thread = currthread;
2931 }
2932
2933 /* If 'QPassSignals' is supported, tell the remote stub what signals
2934 it can simply pass through to the inferior without reporting. */
2935
2936 void
2937 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2938 {
2939 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2940 {
2941 char *pass_packet, *p;
2942 int count = 0;
2943 struct remote_state *rs = get_remote_state ();
2944
2945 gdb_assert (pass_signals.size () < 256);
2946 for (size_t i = 0; i < pass_signals.size (); i++)
2947 {
2948 if (pass_signals[i])
2949 count++;
2950 }
2951 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2952 strcpy (pass_packet, "QPassSignals:");
2953 p = pass_packet + strlen (pass_packet);
2954 for (size_t i = 0; i < pass_signals.size (); i++)
2955 {
2956 if (pass_signals[i])
2957 {
2958 if (i >= 16)
2959 *p++ = tohex (i >> 4);
2960 *p++ = tohex (i & 15);
2961 if (count)
2962 *p++ = ';';
2963 else
2964 break;
2965 count--;
2966 }
2967 }
2968 *p = 0;
2969 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2970 {
2971 putpkt (pass_packet);
2972 getpkt (&rs->buf);
2973 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2974 xfree (rs->last_pass_packet);
2975 rs->last_pass_packet = pass_packet;
2976 }
2977 else
2978 xfree (pass_packet);
2979 }
2980 }
2981
2982 /* If 'QCatchSyscalls' is supported, tell the remote stub
2983 to report syscalls to GDB. */
2984
2985 int
2986 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2987 gdb::array_view<const int> syscall_counts)
2988 {
2989 const char *catch_packet;
2990 enum packet_result result;
2991 int n_sysno = 0;
2992
2993 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2994 {
2995 /* Not supported. */
2996 return 1;
2997 }
2998
2999 if (needed && any_count == 0)
3000 {
3001 /* Count how many syscalls are to be caught. */
3002 for (size_t i = 0; i < syscall_counts.size (); i++)
3003 {
3004 if (syscall_counts[i] != 0)
3005 n_sysno++;
3006 }
3007 }
3008
3009 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3010 pid, needed, any_count, n_sysno);
3011
3012 std::string built_packet;
3013 if (needed)
3014 {
3015 /* Prepare a packet with the sysno list, assuming max 8+1
3016 characters for a sysno. If the resulting packet size is too
3017 big, fallback on the non-selective packet. */
3018 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3019 built_packet.reserve (maxpktsz);
3020 built_packet = "QCatchSyscalls:1";
3021 if (any_count == 0)
3022 {
3023 /* Add in each syscall to be caught. */
3024 for (size_t i = 0; i < syscall_counts.size (); i++)
3025 {
3026 if (syscall_counts[i] != 0)
3027 string_appendf (built_packet, ";%zx", i);
3028 }
3029 }
3030 if (built_packet.size () > get_remote_packet_size ())
3031 {
3032 /* catch_packet too big. Fallback to less efficient
3033 non selective mode, with GDB doing the filtering. */
3034 catch_packet = "QCatchSyscalls:1";
3035 }
3036 else
3037 catch_packet = built_packet.c_str ();
3038 }
3039 else
3040 catch_packet = "QCatchSyscalls:0";
3041
3042 struct remote_state *rs = get_remote_state ();
3043
3044 putpkt (catch_packet);
3045 getpkt (&rs->buf);
3046 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3047 if (result == PACKET_OK)
3048 return 0;
3049 else
3050 return -1;
3051 }
3052
3053 /* If 'QProgramSignals' is supported, tell the remote stub what
3054 signals it should pass through to the inferior when detaching. */
3055
3056 void
3057 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3058 {
3059 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3060 {
3061 char *packet, *p;
3062 int count = 0;
3063 struct remote_state *rs = get_remote_state ();
3064
3065 gdb_assert (signals.size () < 256);
3066 for (size_t i = 0; i < signals.size (); i++)
3067 {
3068 if (signals[i])
3069 count++;
3070 }
3071 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3072 strcpy (packet, "QProgramSignals:");
3073 p = packet + strlen (packet);
3074 for (size_t i = 0; i < signals.size (); i++)
3075 {
3076 if (signal_pass_state (i))
3077 {
3078 if (i >= 16)
3079 *p++ = tohex (i >> 4);
3080 *p++ = tohex (i & 15);
3081 if (count)
3082 *p++ = ';';
3083 else
3084 break;
3085 count--;
3086 }
3087 }
3088 *p = 0;
3089 if (!rs->last_program_signals_packet
3090 || strcmp (rs->last_program_signals_packet, packet) != 0)
3091 {
3092 putpkt (packet);
3093 getpkt (&rs->buf);
3094 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3095 xfree (rs->last_program_signals_packet);
3096 rs->last_program_signals_packet = packet;
3097 }
3098 else
3099 xfree (packet);
3100 }
3101 }
3102
3103 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3104 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3105 thread. If GEN is set, set the general thread, if not, then set
3106 the step/continue thread. */
3107 void
3108 remote_target::set_thread (ptid_t ptid, int gen)
3109 {
3110 struct remote_state *rs = get_remote_state ();
3111 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3112 char *buf = rs->buf.data ();
3113 char *endbuf = buf + get_remote_packet_size ();
3114
3115 if (state == ptid)
3116 return;
3117
3118 *buf++ = 'H';
3119 *buf++ = gen ? 'g' : 'c';
3120 if (ptid == magic_null_ptid)
3121 xsnprintf (buf, endbuf - buf, "0");
3122 else if (ptid == any_thread_ptid)
3123 xsnprintf (buf, endbuf - buf, "0");
3124 else if (ptid == minus_one_ptid)
3125 xsnprintf (buf, endbuf - buf, "-1");
3126 else
3127 write_ptid (buf, endbuf, ptid);
3128 putpkt (rs->buf);
3129 getpkt (&rs->buf);
3130 if (gen)
3131 rs->general_thread = ptid;
3132 else
3133 rs->continue_thread = ptid;
3134 }
3135
3136 void
3137 remote_target::set_general_thread (ptid_t ptid)
3138 {
3139 set_thread (ptid, 1);
3140 }
3141
3142 void
3143 remote_target::set_continue_thread (ptid_t ptid)
3144 {
3145 set_thread (ptid, 0);
3146 }
3147
3148 /* Change the remote current process. Which thread within the process
3149 ends up selected isn't important, as long as it is the same process
3150 as what INFERIOR_PTID points to.
3151
3152 This comes from that fact that there is no explicit notion of
3153 "selected process" in the protocol. The selected process for
3154 general operations is the process the selected general thread
3155 belongs to. */
3156
3157 void
3158 remote_target::set_general_process ()
3159 {
3160 /* If the remote can't handle multiple processes, don't bother. */
3161 if (!m_features.remote_multi_process_p ())
3162 return;
3163
3164 remote_state *rs = get_remote_state ();
3165
3166 /* We only need to change the remote current thread if it's pointing
3167 at some other process. */
3168 if (rs->general_thread.pid () != inferior_ptid.pid ())
3169 set_general_thread (inferior_ptid);
3170 }
3171
3172 \f
3173 /* Return nonzero if this is the main thread that we made up ourselves
3174 to model non-threaded targets as single-threaded. */
3175
3176 static int
3177 remote_thread_always_alive (ptid_t ptid)
3178 {
3179 if (ptid == magic_null_ptid)
3180 /* The main thread is always alive. */
3181 return 1;
3182
3183 if (ptid.pid () != 0 && ptid.lwp () == 0)
3184 /* The main thread is always alive. This can happen after a
3185 vAttach, if the remote side doesn't support
3186 multi-threading. */
3187 return 1;
3188
3189 return 0;
3190 }
3191
3192 /* Return nonzero if the thread PTID is still alive on the remote
3193 system. */
3194
3195 bool
3196 remote_target::thread_alive (ptid_t ptid)
3197 {
3198 struct remote_state *rs = get_remote_state ();
3199 char *p, *endp;
3200
3201 /* Check if this is a thread that we made up ourselves to model
3202 non-threaded targets as single-threaded. */
3203 if (remote_thread_always_alive (ptid))
3204 return 1;
3205
3206 p = rs->buf.data ();
3207 endp = p + get_remote_packet_size ();
3208
3209 *p++ = 'T';
3210 write_ptid (p, endp, ptid);
3211
3212 putpkt (rs->buf);
3213 getpkt (&rs->buf);
3214 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3215 }
3216
3217 /* Return a pointer to a thread name if we know it and NULL otherwise.
3218 The thread_info object owns the memory for the name. */
3219
3220 const char *
3221 remote_target::thread_name (struct thread_info *info)
3222 {
3223 if (info->priv != NULL)
3224 {
3225 const std::string &name = get_remote_thread_info (info)->name;
3226 return !name.empty () ? name.c_str () : NULL;
3227 }
3228
3229 return NULL;
3230 }
3231
3232 /* About these extended threadlist and threadinfo packets. They are
3233 variable length packets but, the fields within them are often fixed
3234 length. They are redundant enough to send over UDP as is the
3235 remote protocol in general. There is a matching unit test module
3236 in libstub. */
3237
3238 /* WARNING: This threadref data structure comes from the remote O.S.,
3239 libstub protocol encoding, and remote.c. It is not particularly
3240 changeable. */
3241
3242 /* Right now, the internal structure is int. We want it to be bigger.
3243 Plan to fix this. */
3244
3245 typedef int gdb_threadref; /* Internal GDB thread reference. */
3246
3247 /* gdb_ext_thread_info is an internal GDB data structure which is
3248 equivalent to the reply of the remote threadinfo packet. */
3249
3250 struct gdb_ext_thread_info
3251 {
3252 threadref threadid; /* External form of thread reference. */
3253 int active; /* Has state interesting to GDB?
3254 regs, stack. */
3255 char display[256]; /* Brief state display, name,
3256 blocked/suspended. */
3257 char shortname[32]; /* To be used to name threads. */
3258 char more_display[256]; /* Long info, statistics, queue depth,
3259 whatever. */
3260 };
3261
3262 /* The volume of remote transfers can be limited by submitting
3263 a mask containing bits specifying the desired information.
3264 Use a union of these values as the 'selection' parameter to
3265 get_thread_info. FIXME: Make these TAG names more thread specific. */
3266
3267 #define TAG_THREADID 1
3268 #define TAG_EXISTS 2
3269 #define TAG_DISPLAY 4
3270 #define TAG_THREADNAME 8
3271 #define TAG_MOREDISPLAY 16
3272
3273 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3274
3275 static const char *unpack_nibble (const char *buf, int *val);
3276
3277 static const char *unpack_byte (const char *buf, int *value);
3278
3279 static char *pack_int (char *buf, int value);
3280
3281 static const char *unpack_int (const char *buf, int *value);
3282
3283 static const char *unpack_string (const char *src, char *dest, int length);
3284
3285 static char *pack_threadid (char *pkt, threadref *id);
3286
3287 static const char *unpack_threadid (const char *inbuf, threadref *id);
3288
3289 void int_to_threadref (threadref *id, int value);
3290
3291 static int threadref_to_int (threadref *ref);
3292
3293 static void copy_threadref (threadref *dest, threadref *src);
3294
3295 static int threadmatch (threadref *dest, threadref *src);
3296
3297 static char *pack_threadinfo_request (char *pkt, int mode,
3298 threadref *id);
3299
3300 static char *pack_threadlist_request (char *pkt, int startflag,
3301 int threadcount,
3302 threadref *nextthread);
3303
3304 static int remote_newthread_step (threadref *ref, void *context);
3305
3306
3307 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3308 buffer we're allowed to write to. Returns
3309 BUF+CHARACTERS_WRITTEN. */
3310
3311 char *
3312 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3313 {
3314 int pid, tid;
3315
3316 if (m_features.remote_multi_process_p ())
3317 {
3318 pid = ptid.pid ();
3319 if (pid < 0)
3320 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3321 else
3322 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3323 }
3324 tid = ptid.lwp ();
3325 if (tid < 0)
3326 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3327 else
3328 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3329
3330 return buf;
3331 }
3332
3333 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3334 last parsed char. Returns null_ptid if no thread id is found, and
3335 throws an error if the thread id has an invalid format. */
3336
3337 static ptid_t
3338 read_ptid (const char *buf, const char **obuf)
3339 {
3340 const char *p = buf;
3341 const char *pp;
3342 ULONGEST pid = 0, tid = 0;
3343
3344 if (*p == 'p')
3345 {
3346 /* Multi-process ptid. */
3347 pp = unpack_varlen_hex (p + 1, &pid);
3348 if (*pp != '.')
3349 error (_("invalid remote ptid: %s"), p);
3350
3351 p = pp;
3352 pp = unpack_varlen_hex (p + 1, &tid);
3353 if (obuf)
3354 *obuf = pp;
3355 return ptid_t (pid, tid);
3356 }
3357
3358 /* No multi-process. Just a tid. */
3359 pp = unpack_varlen_hex (p, &tid);
3360
3361 /* Return null_ptid when no thread id is found. */
3362 if (p == pp)
3363 {
3364 if (obuf)
3365 *obuf = pp;
3366 return null_ptid;
3367 }
3368
3369 /* Since the stub is not sending a process id, default to what's
3370 current_inferior, unless it doesn't have a PID yet. If so,
3371 then since there's no way to know the pid of the reported
3372 threads, use the magic number. */
3373 inferior *inf = current_inferior ();
3374 if (inf->pid == 0)
3375 pid = magic_null_ptid.pid ();
3376 else
3377 pid = inf->pid;
3378
3379 if (obuf)
3380 *obuf = pp;
3381 return ptid_t (pid, tid);
3382 }
3383
3384 static int
3385 stubhex (int ch)
3386 {
3387 if (ch >= 'a' && ch <= 'f')
3388 return ch - 'a' + 10;
3389 if (ch >= '0' && ch <= '9')
3390 return ch - '0';
3391 if (ch >= 'A' && ch <= 'F')
3392 return ch - 'A' + 10;
3393 return -1;
3394 }
3395
3396 static int
3397 stub_unpack_int (const char *buff, int fieldlength)
3398 {
3399 int nibble;
3400 int retval = 0;
3401
3402 while (fieldlength)
3403 {
3404 nibble = stubhex (*buff++);
3405 retval |= nibble;
3406 fieldlength--;
3407 if (fieldlength)
3408 retval = retval << 4;
3409 }
3410 return retval;
3411 }
3412
3413 static const char *
3414 unpack_nibble (const char *buf, int *val)
3415 {
3416 *val = fromhex (*buf++);
3417 return buf;
3418 }
3419
3420 static const char *
3421 unpack_byte (const char *buf, int *value)
3422 {
3423 *value = stub_unpack_int (buf, 2);
3424 return buf + 2;
3425 }
3426
3427 static char *
3428 pack_int (char *buf, int value)
3429 {
3430 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3431 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3432 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3433 buf = pack_hex_byte (buf, (value & 0xff));
3434 return buf;
3435 }
3436
3437 static const char *
3438 unpack_int (const char *buf, int *value)
3439 {
3440 *value = stub_unpack_int (buf, 8);
3441 return buf + 8;
3442 }
3443
3444 #if 0 /* Currently unused, uncomment when needed. */
3445 static char *pack_string (char *pkt, char *string);
3446
3447 static char *
3448 pack_string (char *pkt, char *string)
3449 {
3450 char ch;
3451 int len;
3452
3453 len = strlen (string);
3454 if (len > 200)
3455 len = 200; /* Bigger than most GDB packets, junk??? */
3456 pkt = pack_hex_byte (pkt, len);
3457 while (len-- > 0)
3458 {
3459 ch = *string++;
3460 if ((ch == '\0') || (ch == '#'))
3461 ch = '*'; /* Protect encapsulation. */
3462 *pkt++ = ch;
3463 }
3464 return pkt;
3465 }
3466 #endif /* 0 (unused) */
3467
3468 static const char *
3469 unpack_string (const char *src, char *dest, int length)
3470 {
3471 while (length--)
3472 *dest++ = *src++;
3473 *dest = '\0';
3474 return src;
3475 }
3476
3477 static char *
3478 pack_threadid (char *pkt, threadref *id)
3479 {
3480 char *limit;
3481 unsigned char *altid;
3482
3483 altid = (unsigned char *) id;
3484 limit = pkt + BUF_THREAD_ID_SIZE;
3485 while (pkt < limit)
3486 pkt = pack_hex_byte (pkt, *altid++);
3487 return pkt;
3488 }
3489
3490
3491 static const char *
3492 unpack_threadid (const char *inbuf, threadref *id)
3493 {
3494 char *altref;
3495 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3496 int x, y;
3497
3498 altref = (char *) id;
3499
3500 while (inbuf < limit)
3501 {
3502 x = stubhex (*inbuf++);
3503 y = stubhex (*inbuf++);
3504 *altref++ = (x << 4) | y;
3505 }
3506 return inbuf;
3507 }
3508
3509 /* Externally, threadrefs are 64 bits but internally, they are still
3510 ints. This is due to a mismatch of specifications. We would like
3511 to use 64bit thread references internally. This is an adapter
3512 function. */
3513
3514 void
3515 int_to_threadref (threadref *id, int value)
3516 {
3517 unsigned char *scan;
3518
3519 scan = (unsigned char *) id;
3520 {
3521 int i = 4;
3522 while (i--)
3523 *scan++ = 0;
3524 }
3525 *scan++ = (value >> 24) & 0xff;
3526 *scan++ = (value >> 16) & 0xff;
3527 *scan++ = (value >> 8) & 0xff;
3528 *scan++ = (value & 0xff);
3529 }
3530
3531 static int
3532 threadref_to_int (threadref *ref)
3533 {
3534 int i, value = 0;
3535 unsigned char *scan;
3536
3537 scan = *ref;
3538 scan += 4;
3539 i = 4;
3540 while (i-- > 0)
3541 value = (value << 8) | ((*scan++) & 0xff);
3542 return value;
3543 }
3544
3545 static void
3546 copy_threadref (threadref *dest, threadref *src)
3547 {
3548 int i;
3549 unsigned char *csrc, *cdest;
3550
3551 csrc = (unsigned char *) src;
3552 cdest = (unsigned char *) dest;
3553 i = 8;
3554 while (i--)
3555 *cdest++ = *csrc++;
3556 }
3557
3558 static int
3559 threadmatch (threadref *dest, threadref *src)
3560 {
3561 /* Things are broken right now, so just assume we got a match. */
3562 #if 0
3563 unsigned char *srcp, *destp;
3564 int i, result;
3565 srcp = (char *) src;
3566 destp = (char *) dest;
3567
3568 result = 1;
3569 while (i-- > 0)
3570 result &= (*srcp++ == *destp++) ? 1 : 0;
3571 return result;
3572 #endif
3573 return 1;
3574 }
3575
3576 /*
3577 threadid:1, # always request threadid
3578 context_exists:2,
3579 display:4,
3580 unique_name:8,
3581 more_display:16
3582 */
3583
3584 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3585
3586 static char *
3587 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3588 {
3589 *pkt++ = 'q'; /* Info Query */
3590 *pkt++ = 'P'; /* process or thread info */
3591 pkt = pack_int (pkt, mode); /* mode */
3592 pkt = pack_threadid (pkt, id); /* threadid */
3593 *pkt = '\0'; /* terminate */
3594 return pkt;
3595 }
3596
3597 /* These values tag the fields in a thread info response packet. */
3598 /* Tagging the fields allows us to request specific fields and to
3599 add more fields as time goes by. */
3600
3601 #define TAG_THREADID 1 /* Echo the thread identifier. */
3602 #define TAG_EXISTS 2 /* Is this process defined enough to
3603 fetch registers and its stack? */
3604 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3605 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3606 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3607 the process. */
3608
3609 int
3610 remote_target::remote_unpack_thread_info_response (const char *pkt,
3611 threadref *expectedref,
3612 gdb_ext_thread_info *info)
3613 {
3614 struct remote_state *rs = get_remote_state ();
3615 int mask, length;
3616 int tag;
3617 threadref ref;
3618 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3619 int retval = 1;
3620
3621 /* info->threadid = 0; FIXME: implement zero_threadref. */
3622 info->active = 0;
3623 info->display[0] = '\0';
3624 info->shortname[0] = '\0';
3625 info->more_display[0] = '\0';
3626
3627 /* Assume the characters indicating the packet type have been
3628 stripped. */
3629 pkt = unpack_int (pkt, &mask); /* arg mask */
3630 pkt = unpack_threadid (pkt, &ref);
3631
3632 if (mask == 0)
3633 warning (_("Incomplete response to threadinfo request."));
3634 if (!threadmatch (&ref, expectedref))
3635 { /* This is an answer to a different request. */
3636 warning (_("ERROR RMT Thread info mismatch."));
3637 return 0;
3638 }
3639 copy_threadref (&info->threadid, &ref);
3640
3641 /* Loop on tagged fields , try to bail if something goes wrong. */
3642
3643 /* Packets are terminated with nulls. */
3644 while ((pkt < limit) && mask && *pkt)
3645 {
3646 pkt = unpack_int (pkt, &tag); /* tag */
3647 pkt = unpack_byte (pkt, &length); /* length */
3648 if (!(tag & mask)) /* Tags out of synch with mask. */
3649 {
3650 warning (_("ERROR RMT: threadinfo tag mismatch."));
3651 retval = 0;
3652 break;
3653 }
3654 if (tag == TAG_THREADID)
3655 {
3656 if (length != 16)
3657 {
3658 warning (_("ERROR RMT: length of threadid is not 16."));
3659 retval = 0;
3660 break;
3661 }
3662 pkt = unpack_threadid (pkt, &ref);
3663 mask = mask & ~TAG_THREADID;
3664 continue;
3665 }
3666 if (tag == TAG_EXISTS)
3667 {
3668 info->active = stub_unpack_int (pkt, length);
3669 pkt += length;
3670 mask = mask & ~(TAG_EXISTS);
3671 if (length > 8)
3672 {
3673 warning (_("ERROR RMT: 'exists' length too long."));
3674 retval = 0;
3675 break;
3676 }
3677 continue;
3678 }
3679 if (tag == TAG_THREADNAME)
3680 {
3681 pkt = unpack_string (pkt, &info->shortname[0], length);
3682 mask = mask & ~TAG_THREADNAME;
3683 continue;
3684 }
3685 if (tag == TAG_DISPLAY)
3686 {
3687 pkt = unpack_string (pkt, &info->display[0], length);
3688 mask = mask & ~TAG_DISPLAY;
3689 continue;
3690 }
3691 if (tag == TAG_MOREDISPLAY)
3692 {
3693 pkt = unpack_string (pkt, &info->more_display[0], length);
3694 mask = mask & ~TAG_MOREDISPLAY;
3695 continue;
3696 }
3697 warning (_("ERROR RMT: unknown thread info tag."));
3698 break; /* Not a tag we know about. */
3699 }
3700 return retval;
3701 }
3702
3703 int
3704 remote_target::remote_get_threadinfo (threadref *threadid,
3705 int fieldset,
3706 gdb_ext_thread_info *info)
3707 {
3708 struct remote_state *rs = get_remote_state ();
3709 int result;
3710
3711 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3712 putpkt (rs->buf);
3713 getpkt (&rs->buf);
3714
3715 if (rs->buf[0] == '\0')
3716 return 0;
3717
3718 result = remote_unpack_thread_info_response (&rs->buf[2],
3719 threadid, info);
3720 return result;
3721 }
3722
3723 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3724
3725 static char *
3726 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3727 threadref *nextthread)
3728 {
3729 *pkt++ = 'q'; /* info query packet */
3730 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3731 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3732 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3733 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3734 *pkt = '\0';
3735 return pkt;
3736 }
3737
3738 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3739
3740 int
3741 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3742 threadref *original_echo,
3743 threadref *resultlist,
3744 int *doneflag)
3745 {
3746 struct remote_state *rs = get_remote_state ();
3747 int count, resultcount, done;
3748
3749 resultcount = 0;
3750 /* Assume the 'q' and 'M chars have been stripped. */
3751 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3752 /* done parse past here */
3753 pkt = unpack_byte (pkt, &count); /* count field */
3754 pkt = unpack_nibble (pkt, &done);
3755 /* The first threadid is the argument threadid. */
3756 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3757 while ((count-- > 0) && (pkt < limit))
3758 {
3759 pkt = unpack_threadid (pkt, resultlist++);
3760 if (resultcount++ >= result_limit)
3761 break;
3762 }
3763 if (doneflag)
3764 *doneflag = done;
3765 return resultcount;
3766 }
3767
3768 /* Fetch the next batch of threads from the remote. Returns -1 if the
3769 qL packet is not supported, 0 on error and 1 on success. */
3770
3771 int
3772 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3773 int result_limit, int *done, int *result_count,
3774 threadref *threadlist)
3775 {
3776 struct remote_state *rs = get_remote_state ();
3777 int result = 1;
3778
3779 /* Truncate result limit to be smaller than the packet size. */
3780 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3781 >= get_remote_packet_size ())
3782 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3783
3784 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3785 nextthread);
3786 putpkt (rs->buf);
3787 getpkt (&rs->buf);
3788 if (rs->buf[0] == '\0')
3789 {
3790 /* Packet not supported. */
3791 return -1;
3792 }
3793
3794 *result_count =
3795 parse_threadlist_response (&rs->buf[2], result_limit,
3796 &rs->echo_nextthread, threadlist, done);
3797
3798 if (!threadmatch (&rs->echo_nextthread, nextthread))
3799 {
3800 /* FIXME: This is a good reason to drop the packet. */
3801 /* Possibly, there is a duplicate response. */
3802 /* Possibilities :
3803 retransmit immediatly - race conditions
3804 retransmit after timeout - yes
3805 exit
3806 wait for packet, then exit
3807 */
3808 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3809 return 0; /* I choose simply exiting. */
3810 }
3811 if (*result_count <= 0)
3812 {
3813 if (*done != 1)
3814 {
3815 warning (_("RMT ERROR : failed to get remote thread list."));
3816 result = 0;
3817 }
3818 return result; /* break; */
3819 }
3820 if (*result_count > result_limit)
3821 {
3822 *result_count = 0;
3823 warning (_("RMT ERROR: threadlist response longer than requested."));
3824 return 0;
3825 }
3826 return result;
3827 }
3828
3829 /* Fetch the list of remote threads, with the qL packet, and call
3830 STEPFUNCTION for each thread found. Stops iterating and returns 1
3831 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3832 STEPFUNCTION returns false. If the packet is not supported,
3833 returns -1. */
3834
3835 int
3836 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3837 void *context, int looplimit)
3838 {
3839 struct remote_state *rs = get_remote_state ();
3840 int done, i, result_count;
3841 int startflag = 1;
3842 int result = 1;
3843 int loopcount = 0;
3844
3845 done = 0;
3846 while (!done)
3847 {
3848 if (loopcount++ > looplimit)
3849 {
3850 result = 0;
3851 warning (_("Remote fetch threadlist -infinite loop-."));
3852 break;
3853 }
3854 result = remote_get_threadlist (startflag, &rs->nextthread,
3855 MAXTHREADLISTRESULTS,
3856 &done, &result_count,
3857 rs->resultthreadlist);
3858 if (result <= 0)
3859 break;
3860 /* Clear for later iterations. */
3861 startflag = 0;
3862 /* Setup to resume next batch of thread references, set nextthread. */
3863 if (result_count >= 1)
3864 copy_threadref (&rs->nextthread,
3865 &rs->resultthreadlist[result_count - 1]);
3866 i = 0;
3867 while (result_count--)
3868 {
3869 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3870 {
3871 result = 0;
3872 break;
3873 }
3874 }
3875 }
3876 return result;
3877 }
3878
3879 /* A thread found on the remote target. */
3880
3881 struct thread_item
3882 {
3883 explicit thread_item (ptid_t ptid_)
3884 : ptid (ptid_)
3885 {}
3886
3887 thread_item (thread_item &&other) = default;
3888 thread_item &operator= (thread_item &&other) = default;
3889
3890 DISABLE_COPY_AND_ASSIGN (thread_item);
3891
3892 /* The thread's PTID. */
3893 ptid_t ptid;
3894
3895 /* The thread's extra info. */
3896 std::string extra;
3897
3898 /* The thread's name. */
3899 std::string name;
3900
3901 /* The core the thread was running on. -1 if not known. */
3902 int core = -1;
3903
3904 /* The thread handle associated with the thread. */
3905 gdb::byte_vector thread_handle;
3906 };
3907
3908 /* Context passed around to the various methods listing remote
3909 threads. As new threads are found, they're added to the ITEMS
3910 vector. */
3911
3912 struct threads_listing_context
3913 {
3914 /* Return true if this object contains an entry for a thread with ptid
3915 PTID. */
3916
3917 bool contains_thread (ptid_t ptid) const
3918 {
3919 auto match_ptid = [&] (const thread_item &item)
3920 {
3921 return item.ptid == ptid;
3922 };
3923
3924 auto it = std::find_if (this->items.begin (),
3925 this->items.end (),
3926 match_ptid);
3927
3928 return it != this->items.end ();
3929 }
3930
3931 /* Remove the thread with ptid PTID. */
3932
3933 void remove_thread (ptid_t ptid)
3934 {
3935 auto match_ptid = [&] (const thread_item &item)
3936 {
3937 return item.ptid == ptid;
3938 };
3939
3940 auto it = std::remove_if (this->items.begin (),
3941 this->items.end (),
3942 match_ptid);
3943
3944 if (it != this->items.end ())
3945 this->items.erase (it);
3946 }
3947
3948 /* The threads found on the remote target. */
3949 std::vector<thread_item> items;
3950 };
3951
3952 static int
3953 remote_newthread_step (threadref *ref, void *data)
3954 {
3955 struct threads_listing_context *context
3956 = (struct threads_listing_context *) data;
3957 int pid = inferior_ptid.pid ();
3958 int lwp = threadref_to_int (ref);
3959 ptid_t ptid (pid, lwp);
3960
3961 context->items.emplace_back (ptid);
3962
3963 return 1; /* continue iterator */
3964 }
3965
3966 #define CRAZY_MAX_THREADS 1000
3967
3968 ptid_t
3969 remote_target::remote_current_thread (ptid_t oldpid)
3970 {
3971 struct remote_state *rs = get_remote_state ();
3972
3973 putpkt ("qC");
3974 getpkt (&rs->buf);
3975 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3976 {
3977 const char *obuf;
3978 ptid_t result;
3979
3980 result = read_ptid (&rs->buf[2], &obuf);
3981 if (*obuf != '\0')
3982 remote_debug_printf ("warning: garbage in qC reply");
3983
3984 return result;
3985 }
3986 else
3987 return oldpid;
3988 }
3989
3990 /* List remote threads using the deprecated qL packet. */
3991
3992 int
3993 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3994 {
3995 if (remote_threadlist_iterator (remote_newthread_step, context,
3996 CRAZY_MAX_THREADS) >= 0)
3997 return 1;
3998
3999 return 0;
4000 }
4001
4002 #if defined(HAVE_LIBEXPAT)
4003
4004 static void
4005 start_thread (struct gdb_xml_parser *parser,
4006 const struct gdb_xml_element *element,
4007 void *user_data,
4008 std::vector<gdb_xml_value> &attributes)
4009 {
4010 struct threads_listing_context *data
4011 = (struct threads_listing_context *) user_data;
4012 struct gdb_xml_value *attr;
4013
4014 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4015 ptid_t ptid = read_ptid (id, NULL);
4016
4017 data->items.emplace_back (ptid);
4018 thread_item &item = data->items.back ();
4019
4020 attr = xml_find_attribute (attributes, "core");
4021 if (attr != NULL)
4022 item.core = *(ULONGEST *) attr->value.get ();
4023
4024 attr = xml_find_attribute (attributes, "name");
4025 if (attr != NULL)
4026 item.name = (const char *) attr->value.get ();
4027
4028 attr = xml_find_attribute (attributes, "handle");
4029 if (attr != NULL)
4030 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4031 }
4032
4033 static void
4034 end_thread (struct gdb_xml_parser *parser,
4035 const struct gdb_xml_element *element,
4036 void *user_data, const char *body_text)
4037 {
4038 struct threads_listing_context *data
4039 = (struct threads_listing_context *) user_data;
4040
4041 if (body_text != NULL && *body_text != '\0')
4042 data->items.back ().extra = body_text;
4043 }
4044
4045 const struct gdb_xml_attribute thread_attributes[] = {
4046 { "id", GDB_XML_AF_NONE, NULL, NULL },
4047 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4048 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4049 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4050 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4051 };
4052
4053 const struct gdb_xml_element thread_children[] = {
4054 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4055 };
4056
4057 const struct gdb_xml_element threads_children[] = {
4058 { "thread", thread_attributes, thread_children,
4059 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4060 start_thread, end_thread },
4061 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4062 };
4063
4064 const struct gdb_xml_element threads_elements[] = {
4065 { "threads", NULL, threads_children,
4066 GDB_XML_EF_NONE, NULL, NULL },
4067 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4068 };
4069
4070 #endif
4071
4072 /* List remote threads using qXfer:threads:read. */
4073
4074 int
4075 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4076 {
4077 #if defined(HAVE_LIBEXPAT)
4078 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4079 {
4080 gdb::optional<gdb::char_vector> xml
4081 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4082
4083 if (xml && (*xml)[0] != '\0')
4084 {
4085 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4086 threads_elements, xml->data (), context);
4087 }
4088
4089 return 1;
4090 }
4091 #endif
4092
4093 return 0;
4094 }
4095
4096 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4097
4098 int
4099 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4100 {
4101 struct remote_state *rs = get_remote_state ();
4102
4103 if (rs->use_threadinfo_query)
4104 {
4105 const char *bufp;
4106
4107 putpkt ("qfThreadInfo");
4108 getpkt (&rs->buf);
4109 bufp = rs->buf.data ();
4110 if (bufp[0] != '\0') /* q packet recognized */
4111 {
4112 while (*bufp++ == 'm') /* reply contains one or more TID */
4113 {
4114 do
4115 {
4116 ptid_t ptid = read_ptid (bufp, &bufp);
4117 context->items.emplace_back (ptid);
4118 }
4119 while (*bufp++ == ','); /* comma-separated list */
4120 putpkt ("qsThreadInfo");
4121 getpkt (&rs->buf);
4122 bufp = rs->buf.data ();
4123 }
4124 return 1;
4125 }
4126 else
4127 {
4128 /* Packet not recognized. */
4129 rs->use_threadinfo_query = 0;
4130 }
4131 }
4132
4133 return 0;
4134 }
4135
4136 /* Return true if INF only has one non-exited thread. */
4137
4138 static bool
4139 has_single_non_exited_thread (inferior *inf)
4140 {
4141 int count = 0;
4142 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4143 if (++count > 1)
4144 break;
4145 return count == 1;
4146 }
4147
4148 /* Implement the to_update_thread_list function for the remote
4149 targets. */
4150
4151 void
4152 remote_target::update_thread_list ()
4153 {
4154 struct threads_listing_context context;
4155 int got_list = 0;
4156
4157 /* We have a few different mechanisms to fetch the thread list. Try
4158 them all, starting with the most preferred one first, falling
4159 back to older methods. */
4160 if (remote_get_threads_with_qxfer (&context)
4161 || remote_get_threads_with_qthreadinfo (&context)
4162 || remote_get_threads_with_ql (&context))
4163 {
4164 got_list = 1;
4165
4166 if (context.items.empty ()
4167 && remote_thread_always_alive (inferior_ptid))
4168 {
4169 /* Some targets don't really support threads, but still
4170 reply an (empty) thread list in response to the thread
4171 listing packets, instead of replying "packet not
4172 supported". Exit early so we don't delete the main
4173 thread. */
4174 return;
4175 }
4176
4177 /* CONTEXT now holds the current thread list on the remote
4178 target end. Delete GDB-side threads no longer found on the
4179 target. */
4180 for (thread_info *tp : all_threads_safe ())
4181 {
4182 if (tp->inf->process_target () != this)
4183 continue;
4184
4185 if (!context.contains_thread (tp->ptid))
4186 {
4187 /* Do not remove the thread if it is the last thread in
4188 the inferior. This situation happens when we have a
4189 pending exit process status to process. Otherwise we
4190 may end up with a seemingly live inferior (i.e. pid
4191 != 0) that has no threads. */
4192 if (has_single_non_exited_thread (tp->inf))
4193 continue;
4194
4195 /* Not found. */
4196 delete_thread (tp);
4197 }
4198 }
4199
4200 /* Remove any unreported fork/vfork/clone child threads from
4201 CONTEXT so that we don't interfere with follow
4202 fork/vfork/clone, which is where creation of such threads is
4203 handled. */
4204 remove_new_children (&context);
4205
4206 /* And now add threads we don't know about yet to our list. */
4207 for (thread_item &item : context.items)
4208 {
4209 if (item.ptid != null_ptid)
4210 {
4211 /* In non-stop mode, we assume new found threads are
4212 executing until proven otherwise with a stop reply.
4213 In all-stop, we can only get here if all threads are
4214 stopped. */
4215 bool executing = target_is_non_stop_p ();
4216
4217 remote_notice_new_inferior (item.ptid, executing);
4218
4219 thread_info *tp = this->find_thread (item.ptid);
4220 remote_thread_info *info = get_remote_thread_info (tp);
4221 info->core = item.core;
4222 info->extra = std::move (item.extra);
4223 info->name = std::move (item.name);
4224 info->thread_handle = std::move (item.thread_handle);
4225 }
4226 }
4227 }
4228
4229 if (!got_list)
4230 {
4231 /* If no thread listing method is supported, then query whether
4232 each known thread is alive, one by one, with the T packet.
4233 If the target doesn't support threads at all, then this is a
4234 no-op. See remote_thread_alive. */
4235 prune_threads ();
4236 }
4237 }
4238
4239 /*
4240 * Collect a descriptive string about the given thread.
4241 * The target may say anything it wants to about the thread
4242 * (typically info about its blocked / runnable state, name, etc.).
4243 * This string will appear in the info threads display.
4244 *
4245 * Optional: targets are not required to implement this function.
4246 */
4247
4248 const char *
4249 remote_target::extra_thread_info (thread_info *tp)
4250 {
4251 struct remote_state *rs = get_remote_state ();
4252 int set;
4253 threadref id;
4254 struct gdb_ext_thread_info threadinfo;
4255
4256 if (rs->remote_desc == 0) /* paranoia */
4257 internal_error (_("remote_threads_extra_info"));
4258
4259 if (tp->ptid == magic_null_ptid
4260 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4261 /* This is the main thread which was added by GDB. The remote
4262 server doesn't know about it. */
4263 return NULL;
4264
4265 std::string &extra = get_remote_thread_info (tp)->extra;
4266
4267 /* If already have cached info, use it. */
4268 if (!extra.empty ())
4269 return extra.c_str ();
4270
4271 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4272 {
4273 /* If we're using qXfer:threads:read, then the extra info is
4274 included in the XML. So if we didn't have anything cached,
4275 it's because there's really no extra info. */
4276 return NULL;
4277 }
4278
4279 if (rs->use_threadextra_query)
4280 {
4281 char *b = rs->buf.data ();
4282 char *endb = b + get_remote_packet_size ();
4283
4284 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4285 b += strlen (b);
4286 write_ptid (b, endb, tp->ptid);
4287
4288 putpkt (rs->buf);
4289 getpkt (&rs->buf);
4290 if (rs->buf[0] != 0)
4291 {
4292 extra.resize (strlen (rs->buf.data ()) / 2);
4293 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4294 return extra.c_str ();
4295 }
4296 }
4297
4298 /* If the above query fails, fall back to the old method. */
4299 rs->use_threadextra_query = 0;
4300 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4301 | TAG_MOREDISPLAY | TAG_DISPLAY;
4302 int_to_threadref (&id, tp->ptid.lwp ());
4303 if (remote_get_threadinfo (&id, set, &threadinfo))
4304 if (threadinfo.active)
4305 {
4306 if (*threadinfo.shortname)
4307 string_appendf (extra, " Name: %s", threadinfo.shortname);
4308 if (*threadinfo.display)
4309 {
4310 if (!extra.empty ())
4311 extra += ',';
4312 string_appendf (extra, " State: %s", threadinfo.display);
4313 }
4314 if (*threadinfo.more_display)
4315 {
4316 if (!extra.empty ())
4317 extra += ',';
4318 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4319 }
4320 return extra.c_str ();
4321 }
4322 return NULL;
4323 }
4324 \f
4325
4326 bool
4327 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4328 struct static_tracepoint_marker *marker)
4329 {
4330 struct remote_state *rs = get_remote_state ();
4331 char *p = rs->buf.data ();
4332
4333 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4334 p += strlen (p);
4335 p += hexnumstr (p, addr);
4336 putpkt (rs->buf);
4337 getpkt (&rs->buf);
4338 p = rs->buf.data ();
4339
4340 if (*p == 'E')
4341 error (_("Remote failure reply: %s"), p);
4342
4343 if (*p++ == 'm')
4344 {
4345 parse_static_tracepoint_marker_definition (p, NULL, marker);
4346 return true;
4347 }
4348
4349 return false;
4350 }
4351
4352 std::vector<static_tracepoint_marker>
4353 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4354 {
4355 struct remote_state *rs = get_remote_state ();
4356 std::vector<static_tracepoint_marker> markers;
4357 const char *p;
4358 static_tracepoint_marker marker;
4359
4360 /* Ask for a first packet of static tracepoint marker
4361 definition. */
4362 putpkt ("qTfSTM");
4363 getpkt (&rs->buf);
4364 p = rs->buf.data ();
4365 if (*p == 'E')
4366 error (_("Remote failure reply: %s"), p);
4367
4368 while (*p++ == 'm')
4369 {
4370 do
4371 {
4372 parse_static_tracepoint_marker_definition (p, &p, &marker);
4373
4374 if (strid == NULL || marker.str_id == strid)
4375 markers.push_back (std::move (marker));
4376 }
4377 while (*p++ == ','); /* comma-separated list */
4378 /* Ask for another packet of static tracepoint definition. */
4379 putpkt ("qTsSTM");
4380 getpkt (&rs->buf);
4381 p = rs->buf.data ();
4382 }
4383
4384 return markers;
4385 }
4386
4387 \f
4388 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4389
4390 ptid_t
4391 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4392 {
4393 return ptid_t (inferior_ptid.pid (), lwp);
4394 }
4395 \f
4396
4397 /* Restart the remote side; this is an extended protocol operation. */
4398
4399 void
4400 remote_target::extended_remote_restart ()
4401 {
4402 struct remote_state *rs = get_remote_state ();
4403
4404 /* Send the restart command; for reasons I don't understand the
4405 remote side really expects a number after the "R". */
4406 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4407 putpkt (rs->buf);
4408
4409 remote_fileio_reset ();
4410 }
4411 \f
4412 /* Clean up connection to a remote debugger. */
4413
4414 void
4415 remote_target::close ()
4416 {
4417 /* Make sure we leave stdin registered in the event loop. */
4418 terminal_ours ();
4419
4420 trace_reset_local_state ();
4421
4422 delete this;
4423 }
4424
4425 remote_target::~remote_target ()
4426 {
4427 struct remote_state *rs = get_remote_state ();
4428
4429 /* Check for NULL because we may get here with a partially
4430 constructed target/connection. */
4431 if (rs->remote_desc == nullptr)
4432 return;
4433
4434 serial_close (rs->remote_desc);
4435
4436 /* We are destroying the remote target, so we should discard
4437 everything of this target. */
4438 discard_pending_stop_replies_in_queue ();
4439
4440 rs->delete_async_event_handler ();
4441
4442 delete rs->notif_state;
4443 }
4444
4445 /* Query the remote side for the text, data and bss offsets. */
4446
4447 void
4448 remote_target::get_offsets ()
4449 {
4450 struct remote_state *rs = get_remote_state ();
4451 char *buf;
4452 char *ptr;
4453 int lose, num_segments = 0, do_sections, do_segments;
4454 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4455
4456 if (current_program_space->symfile_object_file == NULL)
4457 return;
4458
4459 putpkt ("qOffsets");
4460 getpkt (&rs->buf);
4461 buf = rs->buf.data ();
4462
4463 if (buf[0] == '\000')
4464 return; /* Return silently. Stub doesn't support
4465 this command. */
4466 if (buf[0] == 'E')
4467 {
4468 warning (_("Remote failure reply: %s"), buf);
4469 return;
4470 }
4471
4472 /* Pick up each field in turn. This used to be done with scanf, but
4473 scanf will make trouble if CORE_ADDR size doesn't match
4474 conversion directives correctly. The following code will work
4475 with any size of CORE_ADDR. */
4476 text_addr = data_addr = bss_addr = 0;
4477 ptr = buf;
4478 lose = 0;
4479
4480 if (startswith (ptr, "Text="))
4481 {
4482 ptr += 5;
4483 /* Don't use strtol, could lose on big values. */
4484 while (*ptr && *ptr != ';')
4485 text_addr = (text_addr << 4) + fromhex (*ptr++);
4486
4487 if (startswith (ptr, ";Data="))
4488 {
4489 ptr += 6;
4490 while (*ptr && *ptr != ';')
4491 data_addr = (data_addr << 4) + fromhex (*ptr++);
4492 }
4493 else
4494 lose = 1;
4495
4496 if (!lose && startswith (ptr, ";Bss="))
4497 {
4498 ptr += 5;
4499 while (*ptr && *ptr != ';')
4500 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4501
4502 if (bss_addr != data_addr)
4503 warning (_("Target reported unsupported offsets: %s"), buf);
4504 }
4505 else
4506 lose = 1;
4507 }
4508 else if (startswith (ptr, "TextSeg="))
4509 {
4510 ptr += 8;
4511 /* Don't use strtol, could lose on big values. */
4512 while (*ptr && *ptr != ';')
4513 text_addr = (text_addr << 4) + fromhex (*ptr++);
4514 num_segments = 1;
4515
4516 if (startswith (ptr, ";DataSeg="))
4517 {
4518 ptr += 9;
4519 while (*ptr && *ptr != ';')
4520 data_addr = (data_addr << 4) + fromhex (*ptr++);
4521 num_segments++;
4522 }
4523 }
4524 else
4525 lose = 1;
4526
4527 if (lose)
4528 error (_("Malformed response to offset query, %s"), buf);
4529 else if (*ptr != '\0')
4530 warning (_("Target reported unsupported offsets: %s"), buf);
4531
4532 objfile *objf = current_program_space->symfile_object_file;
4533 section_offsets offs = objf->section_offsets;
4534
4535 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4536 do_segments = (data != NULL);
4537 do_sections = num_segments == 0;
4538
4539 if (num_segments > 0)
4540 {
4541 segments[0] = text_addr;
4542 segments[1] = data_addr;
4543 }
4544 /* If we have two segments, we can still try to relocate everything
4545 by assuming that the .text and .data offsets apply to the whole
4546 text and data segments. Convert the offsets given in the packet
4547 to base addresses for symfile_map_offsets_to_segments. */
4548 else if (data != nullptr && data->segments.size () == 2)
4549 {
4550 segments[0] = data->segments[0].base + text_addr;
4551 segments[1] = data->segments[1].base + data_addr;
4552 num_segments = 2;
4553 }
4554 /* If the object file has only one segment, assume that it is text
4555 rather than data; main programs with no writable data are rare,
4556 but programs with no code are useless. Of course the code might
4557 have ended up in the data segment... to detect that we would need
4558 the permissions here. */
4559 else if (data && data->segments.size () == 1)
4560 {
4561 segments[0] = data->segments[0].base + text_addr;
4562 num_segments = 1;
4563 }
4564 /* There's no way to relocate by segment. */
4565 else
4566 do_segments = 0;
4567
4568 if (do_segments)
4569 {
4570 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4571 data.get (), offs,
4572 num_segments, segments);
4573
4574 if (ret == 0 && !do_sections)
4575 error (_("Can not handle qOffsets TextSeg "
4576 "response with this symbol file"));
4577
4578 if (ret > 0)
4579 do_sections = 0;
4580 }
4581
4582 if (do_sections)
4583 {
4584 offs[SECT_OFF_TEXT (objf)] = text_addr;
4585
4586 /* This is a temporary kludge to force data and bss to use the
4587 same offsets because that's what nlmconv does now. The real
4588 solution requires changes to the stub and remote.c that I
4589 don't have time to do right now. */
4590
4591 offs[SECT_OFF_DATA (objf)] = data_addr;
4592 offs[SECT_OFF_BSS (objf)] = data_addr;
4593 }
4594
4595 objfile_relocate (objf, offs);
4596 }
4597
4598 /* Send interrupt_sequence to remote target. */
4599
4600 void
4601 remote_target::send_interrupt_sequence ()
4602 {
4603 struct remote_state *rs = get_remote_state ();
4604
4605 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4606 remote_serial_write ("\x03", 1);
4607 else if (interrupt_sequence_mode == interrupt_sequence_break)
4608 serial_send_break (rs->remote_desc);
4609 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4610 {
4611 serial_send_break (rs->remote_desc);
4612 remote_serial_write ("g", 1);
4613 }
4614 else
4615 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4616 interrupt_sequence_mode);
4617 }
4618
4619
4620 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4621 and extract the PTID. Returns NULL_PTID if not found. */
4622
4623 static ptid_t
4624 stop_reply_extract_thread (const char *stop_reply)
4625 {
4626 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4627 {
4628 const char *p;
4629
4630 /* Txx r:val ; r:val (...) */
4631 p = &stop_reply[3];
4632
4633 /* Look for "register" named "thread". */
4634 while (*p != '\0')
4635 {
4636 const char *p1;
4637
4638 p1 = strchr (p, ':');
4639 if (p1 == NULL)
4640 return null_ptid;
4641
4642 if (strncmp (p, "thread", p1 - p) == 0)
4643 return read_ptid (++p1, &p);
4644
4645 p1 = strchr (p, ';');
4646 if (p1 == NULL)
4647 return null_ptid;
4648 p1++;
4649
4650 p = p1;
4651 }
4652 }
4653
4654 return null_ptid;
4655 }
4656
4657 /* Determine the remote side's current thread. If we have a stop
4658 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4659 "thread" register we can extract the current thread from. If not,
4660 ask the remote which is the current thread with qC. The former
4661 method avoids a roundtrip. */
4662
4663 ptid_t
4664 remote_target::get_current_thread (const char *wait_status)
4665 {
4666 ptid_t ptid = null_ptid;
4667
4668 /* Note we don't use remote_parse_stop_reply as that makes use of
4669 the target architecture, which we haven't yet fully determined at
4670 this point. */
4671 if (wait_status != NULL)
4672 ptid = stop_reply_extract_thread (wait_status);
4673 if (ptid == null_ptid)
4674 ptid = remote_current_thread (inferior_ptid);
4675
4676 return ptid;
4677 }
4678
4679 /* Query the remote target for which is the current thread/process,
4680 add it to our tables, and update INFERIOR_PTID. The caller is
4681 responsible for setting the state such that the remote end is ready
4682 to return the current thread.
4683
4684 This function is called after handling the '?' or 'vRun' packets,
4685 whose response is a stop reply from which we can also try
4686 extracting the thread. If the target doesn't support the explicit
4687 qC query, we infer the current thread from that stop reply, passed
4688 in in WAIT_STATUS, which may be NULL.
4689
4690 The function returns pointer to the main thread of the inferior. */
4691
4692 thread_info *
4693 remote_target::add_current_inferior_and_thread (const char *wait_status)
4694 {
4695 bool fake_pid_p = false;
4696
4697 switch_to_no_thread ();
4698
4699 /* Now, if we have thread information, update the current thread's
4700 ptid. */
4701 ptid_t curr_ptid = get_current_thread (wait_status);
4702
4703 if (curr_ptid != null_ptid)
4704 {
4705 if (!m_features.remote_multi_process_p ())
4706 fake_pid_p = true;
4707 }
4708 else
4709 {
4710 /* Without this, some commands which require an active target
4711 (such as kill) won't work. This variable serves (at least)
4712 double duty as both the pid of the target process (if it has
4713 such), and as a flag indicating that a target is active. */
4714 curr_ptid = magic_null_ptid;
4715 fake_pid_p = true;
4716 }
4717
4718 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4719
4720 /* Add the main thread and switch to it. Don't try reading
4721 registers yet, since we haven't fetched the target description
4722 yet. */
4723 thread_info *tp = add_thread_silent (this, curr_ptid);
4724 switch_to_thread_no_regs (tp);
4725
4726 return tp;
4727 }
4728
4729 /* Print info about a thread that was found already stopped on
4730 connection. */
4731
4732 void
4733 remote_target::print_one_stopped_thread (thread_info *thread)
4734 {
4735 target_waitstatus ws;
4736
4737 /* If there is a pending waitstatus, use it. If there isn't it's because
4738 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4739 and process_initial_stop_replies decided it wasn't interesting to save
4740 and report to the core. */
4741 if (thread->has_pending_waitstatus ())
4742 {
4743 ws = thread->pending_waitstatus ();
4744 thread->clear_pending_waitstatus ();
4745 }
4746 else
4747 {
4748 ws.set_stopped (GDB_SIGNAL_0);
4749 }
4750
4751 switch_to_thread (thread);
4752 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4753 set_current_sal_from_frame (get_current_frame ());
4754
4755 /* For "info program". */
4756 set_last_target_status (this, thread->ptid, ws);
4757
4758 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4759 {
4760 enum gdb_signal sig = ws.sig ();
4761
4762 if (signal_print_state (sig))
4763 notify_signal_received (sig);
4764 }
4765
4766 notify_normal_stop (nullptr, 1);
4767 }
4768
4769 /* Process all initial stop replies the remote side sent in response
4770 to the ? packet. These indicate threads that were already stopped
4771 on initial connection. We mark these threads as stopped and print
4772 their current frame before giving the user the prompt. */
4773
4774 void
4775 remote_target::process_initial_stop_replies (int from_tty)
4776 {
4777 int pending_stop_replies = stop_reply_queue_length ();
4778 struct thread_info *selected = NULL;
4779 struct thread_info *lowest_stopped = NULL;
4780 struct thread_info *first = NULL;
4781
4782 /* This is only used when the target is non-stop. */
4783 gdb_assert (target_is_non_stop_p ());
4784
4785 /* Consume the initial pending events. */
4786 while (pending_stop_replies-- > 0)
4787 {
4788 ptid_t waiton_ptid = minus_one_ptid;
4789 ptid_t event_ptid;
4790 struct target_waitstatus ws;
4791 int ignore_event = 0;
4792
4793 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4794 if (remote_debug)
4795 print_target_wait_results (waiton_ptid, event_ptid, ws);
4796
4797 switch (ws.kind ())
4798 {
4799 case TARGET_WAITKIND_IGNORE:
4800 case TARGET_WAITKIND_NO_RESUMED:
4801 case TARGET_WAITKIND_SIGNALLED:
4802 case TARGET_WAITKIND_EXITED:
4803 /* We shouldn't see these, but if we do, just ignore. */
4804 remote_debug_printf ("event ignored");
4805 ignore_event = 1;
4806 break;
4807
4808 default:
4809 break;
4810 }
4811
4812 if (ignore_event)
4813 continue;
4814
4815 thread_info *evthread = this->find_thread (event_ptid);
4816
4817 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4818 {
4819 enum gdb_signal sig = ws.sig ();
4820
4821 /* Stubs traditionally report SIGTRAP as initial signal,
4822 instead of signal 0. Suppress it. */
4823 if (sig == GDB_SIGNAL_TRAP)
4824 sig = GDB_SIGNAL_0;
4825 evthread->set_stop_signal (sig);
4826 ws.set_stopped (sig);
4827 }
4828
4829 if (ws.kind () != TARGET_WAITKIND_STOPPED
4830 || ws.sig () != GDB_SIGNAL_0)
4831 evthread->set_pending_waitstatus (ws);
4832
4833 set_executing (this, event_ptid, false);
4834 set_running (this, event_ptid, false);
4835 get_remote_thread_info (evthread)->set_not_resumed ();
4836 }
4837
4838 /* "Notice" the new inferiors before anything related to
4839 registers/memory. */
4840 for (inferior *inf : all_non_exited_inferiors (this))
4841 {
4842 inf->needs_setup = true;
4843
4844 if (non_stop)
4845 {
4846 thread_info *thread = any_live_thread_of_inferior (inf);
4847 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4848 from_tty);
4849 }
4850 }
4851
4852 /* If all-stop on top of non-stop, pause all threads. Note this
4853 records the threads' stop pc, so must be done after "noticing"
4854 the inferiors. */
4855 if (!non_stop)
4856 {
4857 {
4858 /* At this point, the remote target is not async. It needs to be for
4859 the poll in stop_all_threads to consider events from it, so enable
4860 it temporarily. */
4861 gdb_assert (!this->is_async_p ());
4862 SCOPE_EXIT { target_async (false); };
4863 target_async (true);
4864 stop_all_threads ("remote connect in all-stop");
4865 }
4866
4867 /* If all threads of an inferior were already stopped, we
4868 haven't setup the inferior yet. */
4869 for (inferior *inf : all_non_exited_inferiors (this))
4870 {
4871 if (inf->needs_setup)
4872 {
4873 thread_info *thread = any_live_thread_of_inferior (inf);
4874 switch_to_thread_no_regs (thread);
4875 setup_inferior (0);
4876 }
4877 }
4878 }
4879
4880 /* Now go over all threads that are stopped, and print their current
4881 frame. If all-stop, then if there's a signalled thread, pick
4882 that as current. */
4883 for (thread_info *thread : all_non_exited_threads (this))
4884 {
4885 if (first == NULL)
4886 first = thread;
4887
4888 if (!non_stop)
4889 thread->set_running (false);
4890 else if (thread->state != THREAD_STOPPED)
4891 continue;
4892
4893 if (selected == nullptr && thread->has_pending_waitstatus ())
4894 selected = thread;
4895
4896 if (lowest_stopped == NULL
4897 || thread->inf->num < lowest_stopped->inf->num
4898 || thread->per_inf_num < lowest_stopped->per_inf_num)
4899 lowest_stopped = thread;
4900
4901 if (non_stop)
4902 print_one_stopped_thread (thread);
4903 }
4904
4905 /* In all-stop, we only print the status of one thread, and leave
4906 others with their status pending. */
4907 if (!non_stop)
4908 {
4909 thread_info *thread = selected;
4910 if (thread == NULL)
4911 thread = lowest_stopped;
4912 if (thread == NULL)
4913 thread = first;
4914
4915 print_one_stopped_thread (thread);
4916 }
4917 }
4918
4919 /* Mark a remote_target as starting (by setting the starting_up flag within
4920 its remote_state) for the lifetime of this object. The reference count
4921 on the remote target is temporarily incremented, to prevent the target
4922 being deleted under our feet. */
4923
4924 struct scoped_mark_target_starting
4925 {
4926 /* Constructor, TARGET is the target to be marked as starting, its
4927 reference count will be incremented. */
4928 scoped_mark_target_starting (remote_target *target)
4929 : m_remote_target (remote_target_ref::new_reference (target)),
4930 m_restore_starting_up (set_starting_up_flag (target))
4931 { /* Nothing. */ }
4932
4933 private:
4934
4935 /* Helper function, set the starting_up flag on TARGET and return an
4936 object which, when it goes out of scope, will restore the previous
4937 value of the starting_up flag. */
4938 static scoped_restore_tmpl<bool>
4939 set_starting_up_flag (remote_target *target)
4940 {
4941 remote_state *rs = target->get_remote_state ();
4942 gdb_assert (!rs->starting_up);
4943 return make_scoped_restore (&rs->starting_up, true);
4944 }
4945
4946 /* A gdb::ref_ptr pointer to a remote_target. */
4947 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4948
4949 /* A reference to the target on which we are operating. */
4950 remote_target_ref m_remote_target;
4951
4952 /* An object which restores the previous value of the starting_up flag
4953 when it goes out of scope. */
4954 scoped_restore_tmpl<bool> m_restore_starting_up;
4955 };
4956
4957 /* Helper for remote_target::start_remote, start the remote connection and
4958 sync state. Return true if everything goes OK, otherwise, return false.
4959 This function exists so that the scoped_restore created within it will
4960 expire before we return to remote_target::start_remote. */
4961
4962 bool
4963 remote_target::start_remote_1 (int from_tty, int extended_p)
4964 {
4965 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4966
4967 struct remote_state *rs = get_remote_state ();
4968
4969 /* Signal other parts that we're going through the initial setup,
4970 and so things may not be stable yet. E.g., we don't try to
4971 install tracepoints until we've relocated symbols. Also, a
4972 Ctrl-C before we're connected and synced up can't interrupt the
4973 target. Instead, it offers to drop the (potentially wedged)
4974 connection. */
4975 scoped_mark_target_starting target_is_starting (this);
4976
4977 QUIT;
4978
4979 if (interrupt_on_connect)
4980 send_interrupt_sequence ();
4981
4982 /* Ack any packet which the remote side has already sent. */
4983 remote_serial_write ("+", 1);
4984
4985 /* The first packet we send to the target is the optional "supported
4986 packets" request. If the target can answer this, it will tell us
4987 which later probes to skip. */
4988 remote_query_supported ();
4989
4990 /* Check vCont support and set the remote state's vCont_action_support
4991 attribute. */
4992 remote_vcont_probe ();
4993
4994 /* If the stub wants to get a QAllow, compose one and send it. */
4995 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4996 set_permissions ();
4997
4998 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4999 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5000 as a reply to known packet. For packet "vFile:setfs:" it is an
5001 invalid reply and GDB would return error in
5002 remote_hostio_set_filesystem, making remote files access impossible.
5003 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5004 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5005 {
5006 const char v_mustreplyempty[] = "vMustReplyEmpty";
5007
5008 putpkt (v_mustreplyempty);
5009 getpkt (&rs->buf);
5010 if (strcmp (rs->buf.data (), "OK") == 0)
5011 {
5012 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5013 = PACKET_DISABLE;
5014 }
5015 else if (strcmp (rs->buf.data (), "") != 0)
5016 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5017 rs->buf.data ());
5018 }
5019
5020 /* Next, we possibly activate noack mode.
5021
5022 If the QStartNoAckMode packet configuration is set to AUTO,
5023 enable noack mode if the stub reported a wish for it with
5024 qSupported.
5025
5026 If set to TRUE, then enable noack mode even if the stub didn't
5027 report it in qSupported. If the stub doesn't reply OK, the
5028 session ends with an error.
5029
5030 If FALSE, then don't activate noack mode, regardless of what the
5031 stub claimed should be the default with qSupported. */
5032
5033 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5034 {
5035 putpkt ("QStartNoAckMode");
5036 getpkt (&rs->buf);
5037 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5038 rs->noack_mode = 1;
5039 }
5040
5041 if (extended_p)
5042 {
5043 /* Tell the remote that we are using the extended protocol. */
5044 putpkt ("!");
5045 getpkt (&rs->buf);
5046 }
5047
5048 /* Let the target know which signals it is allowed to pass down to
5049 the program. */
5050 update_signals_program_target ();
5051
5052 /* Next, if the target can specify a description, read it. We do
5053 this before anything involving memory or registers. */
5054 target_find_description ();
5055
5056 /* Next, now that we know something about the target, update the
5057 address spaces in the program spaces. */
5058 update_address_spaces ();
5059
5060 /* On OSs where the list of libraries is global to all
5061 processes, we fetch them early. */
5062 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5063 solib_add (NULL, from_tty, auto_solib_add);
5064
5065 if (target_is_non_stop_p ())
5066 {
5067 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5068 error (_("Non-stop mode requested, but remote "
5069 "does not support non-stop"));
5070
5071 putpkt ("QNonStop:1");
5072 getpkt (&rs->buf);
5073
5074 if (strcmp (rs->buf.data (), "OK") != 0)
5075 error (_("Remote refused setting non-stop mode with: %s"),
5076 rs->buf.data ());
5077
5078 /* Find about threads and processes the stub is already
5079 controlling. We default to adding them in the running state.
5080 The '?' query below will then tell us about which threads are
5081 stopped. */
5082 this->update_thread_list ();
5083 }
5084 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5085 {
5086 /* Don't assume that the stub can operate in all-stop mode.
5087 Request it explicitly. */
5088 putpkt ("QNonStop:0");
5089 getpkt (&rs->buf);
5090
5091 if (strcmp (rs->buf.data (), "OK") != 0)
5092 error (_("Remote refused setting all-stop mode with: %s"),
5093 rs->buf.data ());
5094 }
5095
5096 /* Upload TSVs regardless of whether the target is running or not. The
5097 remote stub, such as GDBserver, may have some predefined or builtin
5098 TSVs, even if the target is not running. */
5099 if (get_trace_status (current_trace_status ()) != -1)
5100 {
5101 struct uploaded_tsv *uploaded_tsvs = NULL;
5102
5103 upload_trace_state_variables (&uploaded_tsvs);
5104 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5105 }
5106
5107 /* Check whether the target is running now. */
5108 putpkt ("?");
5109 getpkt (&rs->buf);
5110
5111 if (!target_is_non_stop_p ())
5112 {
5113 char *wait_status = NULL;
5114
5115 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5116 {
5117 if (!extended_p)
5118 error (_("The target is not running (try extended-remote?)"));
5119 return false;
5120 }
5121 else
5122 {
5123 /* Save the reply for later. */
5124 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5125 strcpy (wait_status, rs->buf.data ());
5126 }
5127
5128 /* Fetch thread list. */
5129 target_update_thread_list ();
5130
5131 /* Let the stub know that we want it to return the thread. */
5132 set_continue_thread (minus_one_ptid);
5133
5134 if (thread_count (this) == 0)
5135 {
5136 /* Target has no concept of threads at all. GDB treats
5137 non-threaded target as single-threaded; add a main
5138 thread. */
5139 thread_info *tp = add_current_inferior_and_thread (wait_status);
5140 get_remote_thread_info (tp)->set_resumed ();
5141 }
5142 else
5143 {
5144 /* We have thread information; select the thread the target
5145 says should be current. If we're reconnecting to a
5146 multi-threaded program, this will ideally be the thread
5147 that last reported an event before GDB disconnected. */
5148 ptid_t curr_thread = get_current_thread (wait_status);
5149 if (curr_thread == null_ptid)
5150 {
5151 /* Odd... The target was able to list threads, but not
5152 tell us which thread was current (no "thread"
5153 register in T stop reply?). Just pick the first
5154 thread in the thread list then. */
5155
5156 remote_debug_printf ("warning: couldn't determine remote "
5157 "current thread; picking first in list.");
5158
5159 for (thread_info *tp : all_non_exited_threads (this,
5160 minus_one_ptid))
5161 {
5162 switch_to_thread (tp);
5163 break;
5164 }
5165 }
5166 else
5167 switch_to_thread (this->find_thread (curr_thread));
5168
5169 get_remote_thread_info (inferior_thread ())->set_resumed ();
5170 }
5171
5172 /* init_wait_for_inferior should be called before get_offsets in order
5173 to manage `inserted' flag in bp loc in a correct state.
5174 breakpoint_init_inferior, called from init_wait_for_inferior, set
5175 `inserted' flag to 0, while before breakpoint_re_set, called from
5176 start_remote, set `inserted' flag to 1. In the initialization of
5177 inferior, breakpoint_init_inferior should be called first, and then
5178 breakpoint_re_set can be called. If this order is broken, state of
5179 `inserted' flag is wrong, and cause some problems on breakpoint
5180 manipulation. */
5181 init_wait_for_inferior ();
5182
5183 get_offsets (); /* Get text, data & bss offsets. */
5184
5185 /* If we could not find a description using qXfer, and we know
5186 how to do it some other way, try again. This is not
5187 supported for non-stop; it could be, but it is tricky if
5188 there are no stopped threads when we connect. */
5189 if (remote_read_description_p (this)
5190 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5191 {
5192 target_clear_description ();
5193 target_find_description ();
5194 }
5195
5196 /* Use the previously fetched status. */
5197 gdb_assert (wait_status != NULL);
5198 struct notif_event *reply
5199 = remote_notif_parse (this, &notif_client_stop, wait_status);
5200 push_stop_reply ((struct stop_reply *) reply);
5201
5202 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5203 }
5204 else
5205 {
5206 /* Clear WFI global state. Do this before finding about new
5207 threads and inferiors, and setting the current inferior.
5208 Otherwise we would clear the proceed status of the current
5209 inferior when we want its stop_soon state to be preserved
5210 (see notice_new_inferior). */
5211 init_wait_for_inferior ();
5212
5213 /* In non-stop, we will either get an "OK", meaning that there
5214 are no stopped threads at this time; or, a regular stop
5215 reply. In the latter case, there may be more than one thread
5216 stopped --- we pull them all out using the vStopped
5217 mechanism. */
5218 if (strcmp (rs->buf.data (), "OK") != 0)
5219 {
5220 const notif_client *notif = &notif_client_stop;
5221
5222 /* remote_notif_get_pending_replies acks this one, and gets
5223 the rest out. */
5224 rs->notif_state->pending_event[notif_client_stop.id]
5225 = remote_notif_parse (this, notif, rs->buf.data ());
5226 remote_notif_get_pending_events (notif);
5227 }
5228
5229 if (thread_count (this) == 0)
5230 {
5231 if (!extended_p)
5232 error (_("The target is not running (try extended-remote?)"));
5233 return false;
5234 }
5235
5236 /* Report all signals during attach/startup. */
5237 pass_signals ({});
5238
5239 /* If there are already stopped threads, mark them stopped and
5240 report their stops before giving the prompt to the user. */
5241 process_initial_stop_replies (from_tty);
5242
5243 if (target_can_async_p ())
5244 target_async (true);
5245 }
5246
5247 /* Give the target a chance to look up symbols. */
5248 for (inferior *inf : all_inferiors (this))
5249 {
5250 /* The inferiors that exist at this point were created from what
5251 was found already running on the remote side, so we know they
5252 have execution. */
5253 gdb_assert (this->has_execution (inf));
5254
5255 /* No use without a symbol-file. */
5256 if (inf->pspace->symfile_object_file == nullptr)
5257 continue;
5258
5259 /* Need to switch to a specific thread, because remote_check_symbols
5260 uses INFERIOR_PTID to set the general thread. */
5261 scoped_restore_current_thread restore_thread;
5262 thread_info *thread = any_thread_of_inferior (inf);
5263 switch_to_thread (thread);
5264 this->remote_check_symbols ();
5265 }
5266
5267 /* Possibly the target has been engaged in a trace run started
5268 previously; find out where things are at. */
5269 if (get_trace_status (current_trace_status ()) != -1)
5270 {
5271 struct uploaded_tp *uploaded_tps = NULL;
5272
5273 if (current_trace_status ()->running)
5274 gdb_printf (_("Trace is already running on the target.\n"));
5275
5276 upload_tracepoints (&uploaded_tps);
5277
5278 merge_uploaded_tracepoints (&uploaded_tps);
5279 }
5280
5281 /* Possibly the target has been engaged in a btrace record started
5282 previously; find out where things are at. */
5283 remote_btrace_maybe_reopen ();
5284
5285 return true;
5286 }
5287
5288 /* Start the remote connection and sync state. */
5289
5290 void
5291 remote_target::start_remote (int from_tty, int extended_p)
5292 {
5293 if (start_remote_1 (from_tty, extended_p)
5294 && breakpoints_should_be_inserted_now ())
5295 insert_breakpoints ();
5296 }
5297
5298 const char *
5299 remote_target::connection_string ()
5300 {
5301 remote_state *rs = get_remote_state ();
5302
5303 if (rs->remote_desc->name != NULL)
5304 return rs->remote_desc->name;
5305 else
5306 return NULL;
5307 }
5308
5309 /* Open a connection to a remote debugger.
5310 NAME is the filename used for communication. */
5311
5312 void
5313 remote_target::open (const char *name, int from_tty)
5314 {
5315 open_1 (name, from_tty, 0);
5316 }
5317
5318 /* Open a connection to a remote debugger using the extended
5319 remote gdb protocol. NAME is the filename used for communication. */
5320
5321 void
5322 extended_remote_target::open (const char *name, int from_tty)
5323 {
5324 open_1 (name, from_tty, 1 /*extended_p */);
5325 }
5326
5327 void
5328 remote_features::reset_all_packet_configs_support ()
5329 {
5330 int i;
5331
5332 for (i = 0; i < PACKET_MAX; i++)
5333 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5334 }
5335
5336 /* Initialize all packet configs. */
5337
5338 static void
5339 init_all_packet_configs (void)
5340 {
5341 int i;
5342
5343 for (i = 0; i < PACKET_MAX; i++)
5344 {
5345 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5346 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5347 }
5348 }
5349
5350 /* Symbol look-up. */
5351
5352 void
5353 remote_target::remote_check_symbols ()
5354 {
5355 char *tmp;
5356 int end;
5357
5358 /* It doesn't make sense to send a qSymbol packet for an inferior that
5359 doesn't have execution, because the remote side doesn't know about
5360 inferiors without execution. */
5361 gdb_assert (target_has_execution ());
5362
5363 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5364 return;
5365
5366 /* Make sure the remote is pointing at the right process. Note
5367 there's no way to select "no process". */
5368 set_general_process ();
5369
5370 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5371 because we need both at the same time. */
5372 gdb::char_vector msg (get_remote_packet_size ());
5373 gdb::char_vector reply (get_remote_packet_size ());
5374
5375 /* Invite target to request symbol lookups. */
5376
5377 putpkt ("qSymbol::");
5378 getpkt (&reply);
5379 m_features.packet_ok (reply, PACKET_qSymbol);
5380
5381 while (startswith (reply.data (), "qSymbol:"))
5382 {
5383 struct bound_minimal_symbol sym;
5384
5385 tmp = &reply[8];
5386 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5387 strlen (tmp) / 2);
5388 msg[end] = '\0';
5389 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5390 if (sym.minsym == NULL)
5391 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5392 &reply[8]);
5393 else
5394 {
5395 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5396 CORE_ADDR sym_addr = sym.value_address ();
5397
5398 /* If this is a function address, return the start of code
5399 instead of any data function descriptor. */
5400 sym_addr = gdbarch_convert_from_func_ptr_addr
5401 (current_inferior ()->arch (), sym_addr,
5402 current_inferior ()->top_target ());
5403
5404 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5405 phex_nz (sym_addr, addr_size), &reply[8]);
5406 }
5407
5408 putpkt (msg.data ());
5409 getpkt (&reply);
5410 }
5411 }
5412
5413 static struct serial *
5414 remote_serial_open (const char *name)
5415 {
5416 static int udp_warning = 0;
5417
5418 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5419 of in ser-tcp.c, because it is the remote protocol assuming that the
5420 serial connection is reliable and not the serial connection promising
5421 to be. */
5422 if (!udp_warning && startswith (name, "udp:"))
5423 {
5424 warning (_("The remote protocol may be unreliable over UDP.\n"
5425 "Some events may be lost, rendering further debugging "
5426 "impossible."));
5427 udp_warning = 1;
5428 }
5429
5430 return serial_open (name);
5431 }
5432
5433 /* Inform the target of our permission settings. The permission flags
5434 work without this, but if the target knows the settings, it can do
5435 a couple things. First, it can add its own check, to catch cases
5436 that somehow manage to get by the permissions checks in target
5437 methods. Second, if the target is wired to disallow particular
5438 settings (for instance, a system in the field that is not set up to
5439 be able to stop at a breakpoint), it can object to any unavailable
5440 permissions. */
5441
5442 void
5443 remote_target::set_permissions ()
5444 {
5445 struct remote_state *rs = get_remote_state ();
5446
5447 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5448 "WriteReg:%x;WriteMem:%x;"
5449 "InsertBreak:%x;InsertTrace:%x;"
5450 "InsertFastTrace:%x;Stop:%x",
5451 may_write_registers, may_write_memory,
5452 may_insert_breakpoints, may_insert_tracepoints,
5453 may_insert_fast_tracepoints, may_stop);
5454 putpkt (rs->buf);
5455 getpkt (&rs->buf);
5456
5457 /* If the target didn't like the packet, warn the user. Do not try
5458 to undo the user's settings, that would just be maddening. */
5459 if (strcmp (rs->buf.data (), "OK") != 0)
5460 warning (_("Remote refused setting permissions with: %s"),
5461 rs->buf.data ());
5462 }
5463
5464 /* This type describes each known response to the qSupported
5465 packet. */
5466 struct protocol_feature
5467 {
5468 /* The name of this protocol feature. */
5469 const char *name;
5470
5471 /* The default for this protocol feature. */
5472 enum packet_support default_support;
5473
5474 /* The function to call when this feature is reported, or after
5475 qSupported processing if the feature is not supported.
5476 The first argument points to this structure. The second
5477 argument indicates whether the packet requested support be
5478 enabled, disabled, or probed (or the default, if this function
5479 is being called at the end of processing and this feature was
5480 not reported). The third argument may be NULL; if not NULL, it
5481 is a NUL-terminated string taken from the packet following
5482 this feature's name and an equals sign. */
5483 void (*func) (remote_target *remote, const struct protocol_feature *,
5484 enum packet_support, const char *);
5485
5486 /* The corresponding packet for this feature. Only used if
5487 FUNC is remote_supported_packet. */
5488 int packet;
5489 };
5490
5491 static void
5492 remote_supported_packet (remote_target *remote,
5493 const struct protocol_feature *feature,
5494 enum packet_support support,
5495 const char *argument)
5496 {
5497 if (argument)
5498 {
5499 warning (_("Remote qSupported response supplied an unexpected value for"
5500 " \"%s\"."), feature->name);
5501 return;
5502 }
5503
5504 remote->m_features.m_protocol_packets[feature->packet].support = support;
5505 }
5506
5507 void
5508 remote_target::remote_packet_size (const protocol_feature *feature,
5509 enum packet_support support, const char *value)
5510 {
5511 struct remote_state *rs = get_remote_state ();
5512
5513 int packet_size;
5514 char *value_end;
5515
5516 if (support != PACKET_ENABLE)
5517 return;
5518
5519 if (value == NULL || *value == '\0')
5520 {
5521 warning (_("Remote target reported \"%s\" without a size."),
5522 feature->name);
5523 return;
5524 }
5525
5526 errno = 0;
5527 packet_size = strtol (value, &value_end, 16);
5528 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5529 {
5530 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5531 feature->name, value);
5532 return;
5533 }
5534
5535 /* Record the new maximum packet size. */
5536 rs->explicit_packet_size = packet_size;
5537 }
5538
5539 static void
5540 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5541 enum packet_support support, const char *value)
5542 {
5543 remote->remote_packet_size (feature, support, value);
5544 }
5545
5546 static const struct protocol_feature remote_protocol_features[] = {
5547 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5548 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5549 PACKET_qXfer_auxv },
5550 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5551 PACKET_qXfer_exec_file },
5552 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5553 PACKET_qXfer_features },
5554 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5555 PACKET_qXfer_libraries },
5556 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5557 PACKET_qXfer_libraries_svr4 },
5558 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5559 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5560 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5561 PACKET_qXfer_memory_map },
5562 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5563 PACKET_qXfer_osdata },
5564 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5565 PACKET_qXfer_threads },
5566 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_qXfer_traceframe_info },
5568 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_QPassSignals },
5570 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_QCatchSyscalls },
5572 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_QProgramSignals },
5574 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_QSetWorkingDir },
5576 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5577 PACKET_QStartupWithShell },
5578 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5579 PACKET_QEnvironmentHexEncoded },
5580 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5581 PACKET_QEnvironmentReset },
5582 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5583 PACKET_QEnvironmentUnset },
5584 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5585 PACKET_QStartNoAckMode },
5586 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5587 PACKET_multiprocess_feature },
5588 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5589 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5590 PACKET_qXfer_siginfo_read },
5591 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5592 PACKET_qXfer_siginfo_write },
5593 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5594 PACKET_ConditionalTracepoints },
5595 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5596 PACKET_ConditionalBreakpoints },
5597 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5598 PACKET_BreakpointCommands },
5599 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5600 PACKET_FastTracepoints },
5601 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5602 PACKET_StaticTracepoints },
5603 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5604 PACKET_InstallInTrace},
5605 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5606 PACKET_DisconnectedTracing_feature },
5607 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5608 PACKET_bc },
5609 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5610 PACKET_bs },
5611 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5612 PACKET_TracepointSource },
5613 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5614 PACKET_QAllow },
5615 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5616 PACKET_EnableDisableTracepoints_feature },
5617 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5618 PACKET_qXfer_fdpic },
5619 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5620 PACKET_qXfer_uib },
5621 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5622 PACKET_QDisableRandomization },
5623 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5624 { "QTBuffer:size", PACKET_DISABLE,
5625 remote_supported_packet, PACKET_QTBuffer_size},
5626 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5627 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5628 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5629 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5630 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5631 PACKET_qXfer_btrace },
5632 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5633 PACKET_qXfer_btrace_conf },
5634 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5635 PACKET_Qbtrace_conf_bts_size },
5636 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5637 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5638 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5639 PACKET_fork_event_feature },
5640 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5641 PACKET_vfork_event_feature },
5642 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5643 PACKET_exec_event_feature },
5644 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5645 PACKET_Qbtrace_conf_pt_size },
5646 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5647 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5648 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5649 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5650 PACKET_memory_tagging_feature },
5651 };
5652
5653 static char *remote_support_xml;
5654
5655 /* Register string appended to "xmlRegisters=" in qSupported query. */
5656
5657 void
5658 register_remote_support_xml (const char *xml)
5659 {
5660 #if defined(HAVE_LIBEXPAT)
5661 if (remote_support_xml == NULL)
5662 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5663 else
5664 {
5665 char *copy = xstrdup (remote_support_xml + 13);
5666 char *saveptr;
5667 char *p = strtok_r (copy, ",", &saveptr);
5668
5669 do
5670 {
5671 if (strcmp (p, xml) == 0)
5672 {
5673 /* already there */
5674 xfree (copy);
5675 return;
5676 }
5677 }
5678 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5679 xfree (copy);
5680
5681 remote_support_xml = reconcat (remote_support_xml,
5682 remote_support_xml, ",", xml,
5683 (char *) NULL);
5684 }
5685 #endif
5686 }
5687
5688 static void
5689 remote_query_supported_append (std::string *msg, const char *append)
5690 {
5691 if (!msg->empty ())
5692 msg->append (";");
5693 msg->append (append);
5694 }
5695
5696 void
5697 remote_target::remote_query_supported ()
5698 {
5699 struct remote_state *rs = get_remote_state ();
5700 char *next;
5701 int i;
5702 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5703
5704 /* The packet support flags are handled differently for this packet
5705 than for most others. We treat an error, a disabled packet, and
5706 an empty response identically: any features which must be reported
5707 to be used will be automatically disabled. An empty buffer
5708 accomplishes this, since that is also the representation for a list
5709 containing no features. */
5710
5711 rs->buf[0] = 0;
5712 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5713 {
5714 std::string q;
5715
5716 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5717 != AUTO_BOOLEAN_FALSE)
5718 remote_query_supported_append (&q, "multiprocess+");
5719
5720 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5721 != AUTO_BOOLEAN_FALSE)
5722 remote_query_supported_append (&q, "swbreak+");
5723
5724 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5725 != AUTO_BOOLEAN_FALSE)
5726 remote_query_supported_append (&q, "hwbreak+");
5727
5728 remote_query_supported_append (&q, "qRelocInsn+");
5729
5730 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5731 != AUTO_BOOLEAN_FALSE)
5732 remote_query_supported_append (&q, "fork-events+");
5733
5734 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5735 != AUTO_BOOLEAN_FALSE)
5736 remote_query_supported_append (&q, "vfork-events+");
5737
5738 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5739 != AUTO_BOOLEAN_FALSE)
5740 remote_query_supported_append (&q, "exec-events+");
5741
5742 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5743 != AUTO_BOOLEAN_FALSE)
5744 remote_query_supported_append (&q, "vContSupported+");
5745
5746 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5747 != AUTO_BOOLEAN_FALSE)
5748 remote_query_supported_append (&q, "QThreadEvents+");
5749
5750 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5751 != AUTO_BOOLEAN_FALSE)
5752 remote_query_supported_append (&q, "no-resumed+");
5753
5754 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5755 != AUTO_BOOLEAN_FALSE)
5756 remote_query_supported_append (&q, "memory-tagging+");
5757
5758 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5759 the qSupported:xmlRegisters=i386 handling. */
5760 if (remote_support_xml != NULL
5761 && (m_features.packet_support (PACKET_qXfer_features)
5762 != PACKET_DISABLE))
5763 remote_query_supported_append (&q, remote_support_xml);
5764
5765 q = "qSupported:" + q;
5766 putpkt (q.c_str ());
5767
5768 getpkt (&rs->buf);
5769
5770 /* If an error occurred, warn, but do not return - just reset the
5771 buffer to empty and go on to disable features. */
5772 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5773 {
5774 warning (_("Remote failure reply: %s"), rs->buf.data ());
5775 rs->buf[0] = 0;
5776 }
5777 }
5778
5779 memset (seen, 0, sizeof (seen));
5780
5781 next = rs->buf.data ();
5782 while (*next)
5783 {
5784 enum packet_support is_supported;
5785 char *p, *end, *name_end, *value;
5786
5787 /* First separate out this item from the rest of the packet. If
5788 there's another item after this, we overwrite the separator
5789 (terminated strings are much easier to work with). */
5790 p = next;
5791 end = strchr (p, ';');
5792 if (end == NULL)
5793 {
5794 end = p + strlen (p);
5795 next = end;
5796 }
5797 else
5798 {
5799 *end = '\0';
5800 next = end + 1;
5801
5802 if (end == p)
5803 {
5804 warning (_("empty item in \"qSupported\" response"));
5805 continue;
5806 }
5807 }
5808
5809 name_end = strchr (p, '=');
5810 if (name_end)
5811 {
5812 /* This is a name=value entry. */
5813 is_supported = PACKET_ENABLE;
5814 value = name_end + 1;
5815 *name_end = '\0';
5816 }
5817 else
5818 {
5819 value = NULL;
5820 switch (end[-1])
5821 {
5822 case '+':
5823 is_supported = PACKET_ENABLE;
5824 break;
5825
5826 case '-':
5827 is_supported = PACKET_DISABLE;
5828 break;
5829
5830 case '?':
5831 is_supported = PACKET_SUPPORT_UNKNOWN;
5832 break;
5833
5834 default:
5835 warning (_("unrecognized item \"%s\" "
5836 "in \"qSupported\" response"), p);
5837 continue;
5838 }
5839 end[-1] = '\0';
5840 }
5841
5842 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5843 if (strcmp (remote_protocol_features[i].name, p) == 0)
5844 {
5845 const struct protocol_feature *feature;
5846
5847 seen[i] = 1;
5848 feature = &remote_protocol_features[i];
5849 feature->func (this, feature, is_supported, value);
5850 break;
5851 }
5852 }
5853
5854 /* If we increased the packet size, make sure to increase the global
5855 buffer size also. We delay this until after parsing the entire
5856 qSupported packet, because this is the same buffer we were
5857 parsing. */
5858 if (rs->buf.size () < rs->explicit_packet_size)
5859 rs->buf.resize (rs->explicit_packet_size);
5860
5861 /* Handle the defaults for unmentioned features. */
5862 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5863 if (!seen[i])
5864 {
5865 const struct protocol_feature *feature;
5866
5867 feature = &remote_protocol_features[i];
5868 feature->func (this, feature, feature->default_support, NULL);
5869 }
5870 }
5871
5872 /* Serial QUIT handler for the remote serial descriptor.
5873
5874 Defers handling a Ctrl-C until we're done with the current
5875 command/response packet sequence, unless:
5876
5877 - We're setting up the connection. Don't send a remote interrupt
5878 request, as we're not fully synced yet. Quit immediately
5879 instead.
5880
5881 - The target has been resumed in the foreground
5882 (target_terminal::is_ours is false) with a synchronous resume
5883 packet, and we're blocked waiting for the stop reply, thus a
5884 Ctrl-C should be immediately sent to the target.
5885
5886 - We get a second Ctrl-C while still within the same serial read or
5887 write. In that case the serial is seemingly wedged --- offer to
5888 quit/disconnect.
5889
5890 - We see a second Ctrl-C without target response, after having
5891 previously interrupted the target. In that case the target/stub
5892 is probably wedged --- offer to quit/disconnect.
5893 */
5894
5895 void
5896 remote_target::remote_serial_quit_handler ()
5897 {
5898 struct remote_state *rs = get_remote_state ();
5899
5900 if (check_quit_flag ())
5901 {
5902 /* If we're starting up, we're not fully synced yet. Quit
5903 immediately. */
5904 if (rs->starting_up)
5905 quit ();
5906 else if (rs->got_ctrlc_during_io)
5907 {
5908 if (query (_("The target is not responding to GDB commands.\n"
5909 "Stop debugging it? ")))
5910 remote_unpush_and_throw (this);
5911 }
5912 /* If ^C has already been sent once, offer to disconnect. */
5913 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5914 interrupt_query ();
5915 /* All-stop protocol, and blocked waiting for stop reply. Send
5916 an interrupt request. */
5917 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5918 target_interrupt ();
5919 else
5920 rs->got_ctrlc_during_io = 1;
5921 }
5922 }
5923
5924 /* The remote_target that is current while the quit handler is
5925 overridden with remote_serial_quit_handler. */
5926 static remote_target *curr_quit_handler_target;
5927
5928 static void
5929 remote_serial_quit_handler ()
5930 {
5931 curr_quit_handler_target->remote_serial_quit_handler ();
5932 }
5933
5934 /* Remove the remote target from the target stack of each inferior
5935 that is using it. Upper targets depend on it so remove them
5936 first. */
5937
5938 static void
5939 remote_unpush_target (remote_target *target)
5940 {
5941 /* We have to unpush the target from all inferiors, even those that
5942 aren't running. */
5943 scoped_restore_current_inferior restore_current_inferior;
5944
5945 for (inferior *inf : all_inferiors (target))
5946 {
5947 switch_to_inferior_no_thread (inf);
5948 inf->pop_all_targets_at_and_above (process_stratum);
5949 generic_mourn_inferior ();
5950 }
5951
5952 /* Don't rely on target_close doing this when the target is popped
5953 from the last remote inferior above, because something may be
5954 holding a reference to the target higher up on the stack, meaning
5955 target_close won't be called yet. We lost the connection to the
5956 target, so clear these now, otherwise we may later throw
5957 TARGET_CLOSE_ERROR while trying to tell the remote target to
5958 close the file. */
5959 fileio_handles_invalidate_target (target);
5960 }
5961
5962 static void
5963 remote_unpush_and_throw (remote_target *target)
5964 {
5965 remote_unpush_target (target);
5966 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5967 }
5968
5969 void
5970 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5971 {
5972 remote_target *curr_remote = get_current_remote_target ();
5973
5974 if (name == 0)
5975 error (_("To open a remote debug connection, you need to specify what\n"
5976 "serial device is attached to the remote system\n"
5977 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5978
5979 /* If we're connected to a running target, target_preopen will kill it.
5980 Ask this question first, before target_preopen has a chance to kill
5981 anything. */
5982 if (curr_remote != NULL && !target_has_execution ())
5983 {
5984 if (from_tty
5985 && !query (_("Already connected to a remote target. Disconnect? ")))
5986 error (_("Still connected."));
5987 }
5988
5989 /* Here the possibly existing remote target gets unpushed. */
5990 target_preopen (from_tty);
5991
5992 remote_fileio_reset ();
5993 reopen_exec_file ();
5994 reread_symbols (from_tty);
5995
5996 remote_target *remote
5997 = (extended_p ? new extended_remote_target () : new remote_target ());
5998 target_ops_up target_holder (remote);
5999
6000 remote_state *rs = remote->get_remote_state ();
6001
6002 /* See FIXME above. */
6003 if (!target_async_permitted)
6004 rs->wait_forever_enabled_p = true;
6005
6006 rs->remote_desc = remote_serial_open (name);
6007 if (!rs->remote_desc)
6008 perror_with_name (name);
6009
6010 if (baud_rate != -1)
6011 {
6012 if (serial_setbaudrate (rs->remote_desc, baud_rate))
6013 {
6014 /* The requested speed could not be set. Error out to
6015 top level after closing remote_desc. Take care to
6016 set remote_desc to NULL to avoid closing remote_desc
6017 more than once. */
6018 serial_close (rs->remote_desc);
6019 rs->remote_desc = NULL;
6020 perror_with_name (name);
6021 }
6022 }
6023
6024 serial_setparity (rs->remote_desc, serial_parity);
6025 serial_raw (rs->remote_desc);
6026
6027 /* If there is something sitting in the buffer we might take it as a
6028 response to a command, which would be bad. */
6029 serial_flush_input (rs->remote_desc);
6030
6031 if (from_tty)
6032 {
6033 gdb_puts ("Remote debugging using ");
6034 gdb_puts (name);
6035 gdb_puts ("\n");
6036 }
6037
6038 /* Switch to using the remote target now. */
6039 current_inferior ()->push_target (std::move (target_holder));
6040
6041 /* Register extra event sources in the event loop. */
6042 rs->create_async_event_handler ();
6043
6044 rs->notif_state = remote_notif_state_allocate (remote);
6045
6046 /* Reset the target state; these things will be queried either by
6047 remote_query_supported or as they are needed. */
6048 remote->m_features.reset_all_packet_configs_support ();
6049 rs->explicit_packet_size = 0;
6050 rs->noack_mode = 0;
6051 rs->extended = extended_p;
6052 rs->waiting_for_stop_reply = 0;
6053 rs->ctrlc_pending_p = 0;
6054 rs->got_ctrlc_during_io = 0;
6055
6056 rs->general_thread = not_sent_ptid;
6057 rs->continue_thread = not_sent_ptid;
6058 rs->remote_traceframe_number = -1;
6059
6060 rs->last_resume_exec_dir = EXEC_FORWARD;
6061
6062 /* Probe for ability to use "ThreadInfo" query, as required. */
6063 rs->use_threadinfo_query = 1;
6064 rs->use_threadextra_query = 1;
6065
6066 rs->readahead_cache.invalidate ();
6067
6068 if (target_async_permitted)
6069 {
6070 /* FIXME: cagney/1999-09-23: During the initial connection it is
6071 assumed that the target is already ready and able to respond to
6072 requests. Unfortunately remote_start_remote() eventually calls
6073 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6074 around this. Eventually a mechanism that allows
6075 wait_for_inferior() to expect/get timeouts will be
6076 implemented. */
6077 rs->wait_forever_enabled_p = false;
6078 }
6079
6080 /* First delete any symbols previously loaded from shared libraries. */
6081 no_shared_libraries (NULL, 0);
6082
6083 /* Start the remote connection. If error() or QUIT, discard this
6084 target (we'd otherwise be in an inconsistent state) and then
6085 propogate the error on up the exception chain. This ensures that
6086 the caller doesn't stumble along blindly assuming that the
6087 function succeeded. The CLI doesn't have this problem but other
6088 UI's, such as MI do.
6089
6090 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6091 this function should return an error indication letting the
6092 caller restore the previous state. Unfortunately the command
6093 ``target remote'' is directly wired to this function making that
6094 impossible. On a positive note, the CLI side of this problem has
6095 been fixed - the function set_cmd_context() makes it possible for
6096 all the ``target ....'' commands to share a common callback
6097 function. See cli-dump.c. */
6098 {
6099
6100 try
6101 {
6102 remote->start_remote (from_tty, extended_p);
6103 }
6104 catch (const gdb_exception &ex)
6105 {
6106 /* Pop the partially set up target - unless something else did
6107 already before throwing the exception. */
6108 if (ex.error != TARGET_CLOSE_ERROR)
6109 remote_unpush_target (remote);
6110 throw;
6111 }
6112 }
6113
6114 remote_btrace_reset (rs);
6115
6116 if (target_async_permitted)
6117 rs->wait_forever_enabled_p = true;
6118 }
6119
6120 /* Determine if WS represents a fork status. */
6121
6122 static bool
6123 is_fork_status (target_waitkind kind)
6124 {
6125 return (kind == TARGET_WAITKIND_FORKED
6126 || kind == TARGET_WAITKIND_VFORKED);
6127 }
6128
6129 /* Return a reference to the field where a pending child status, if
6130 there's one, is recorded. If there's no child event pending, the
6131 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6132
6133 static const target_waitstatus &
6134 thread_pending_status (struct thread_info *thread)
6135 {
6136 return (thread->has_pending_waitstatus ()
6137 ? thread->pending_waitstatus ()
6138 : thread->pending_follow);
6139 }
6140
6141 /* Return THREAD's pending status if it is a pending fork/vfork (but
6142 not clone) parent, else return nullptr. */
6143
6144 static const target_waitstatus *
6145 thread_pending_fork_status (struct thread_info *thread)
6146 {
6147 const target_waitstatus &ws = thread_pending_status (thread);
6148
6149 if (!is_fork_status (ws.kind ()))
6150 return nullptr;
6151
6152 return &ws;
6153 }
6154
6155 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6156 event, else return nullptr. */
6157
6158 static const target_waitstatus *
6159 thread_pending_child_status (thread_info *thread)
6160 {
6161 const target_waitstatus &ws = thread_pending_status (thread);
6162
6163 if (!is_new_child_status (ws.kind ()))
6164 return nullptr;
6165
6166 return &ws;
6167 }
6168
6169 /* Detach the specified process. */
6170
6171 void
6172 remote_target::remote_detach_pid (int pid)
6173 {
6174 struct remote_state *rs = get_remote_state ();
6175
6176 /* This should not be necessary, but the handling for D;PID in
6177 GDBserver versions prior to 8.2 incorrectly assumes that the
6178 selected process points to the same process we're detaching,
6179 leading to misbehavior (and possibly GDBserver crashing) when it
6180 does not. Since it's easy and cheap, work around it by forcing
6181 GDBserver to select GDB's current process. */
6182 set_general_process ();
6183
6184 if (m_features.remote_multi_process_p ())
6185 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6186 else
6187 strcpy (rs->buf.data (), "D");
6188
6189 putpkt (rs->buf);
6190 getpkt (&rs->buf);
6191
6192 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6193 ;
6194 else if (rs->buf[0] == '\0')
6195 error (_("Remote doesn't know how to detach"));
6196 else
6197 {
6198 /* It is possible that we have an unprocessed exit event for this
6199 pid. If this is the case then we can ignore the failure to detach
6200 and just pretend that the detach worked, as far as the user is
6201 concerned, the process exited immediately after the detach. */
6202 bool process_has_already_exited = false;
6203 remote_notif_get_pending_events (&notif_client_stop);
6204 for (stop_reply_up &reply : rs->stop_reply_queue)
6205 {
6206 if (reply->ptid.pid () != pid)
6207 continue;
6208
6209 enum target_waitkind kind = reply->ws.kind ();
6210 if (kind == TARGET_WAITKIND_EXITED
6211 || kind == TARGET_WAITKIND_SIGNALLED)
6212 {
6213 process_has_already_exited = true;
6214 remote_debug_printf
6215 ("detach failed, but process already exited");
6216 break;
6217 }
6218 }
6219
6220 if (!process_has_already_exited)
6221 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6222 }
6223 }
6224
6225 /* This detaches a program to which we previously attached, using
6226 inferior_ptid to identify the process. After this is done, GDB
6227 can be used to debug some other program. We better not have left
6228 any breakpoints in the target program or it'll die when it hits
6229 one. */
6230
6231 void
6232 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6233 {
6234 int pid = inferior_ptid.pid ();
6235 struct remote_state *rs = get_remote_state ();
6236 int is_fork_parent;
6237
6238 if (!target_has_execution ())
6239 error (_("No process to detach from."));
6240
6241 target_announce_detach (from_tty);
6242
6243 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6244 {
6245 /* If we're in breakpoints-always-inserted mode, or the inferior
6246 is running, we have to remove breakpoints before detaching.
6247 We don't do this in common code instead because not all
6248 targets support removing breakpoints while the target is
6249 running. The remote target / gdbserver does, though. */
6250 remove_breakpoints_inf (current_inferior ());
6251 }
6252
6253 /* Tell the remote target to detach. */
6254 remote_detach_pid (pid);
6255
6256 /* Exit only if this is the only active inferior. */
6257 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6258 gdb_puts (_("Ending remote debugging.\n"));
6259
6260 /* See if any thread of the inferior we are detaching has a pending fork
6261 status. In that case, we must detach from the child resulting from
6262 that fork. */
6263 for (thread_info *thread : inf->non_exited_threads ())
6264 {
6265 const target_waitstatus *ws = thread_pending_fork_status (thread);
6266
6267 if (ws == nullptr)
6268 continue;
6269
6270 remote_detach_pid (ws->child_ptid ().pid ());
6271 }
6272
6273 /* Check also for any pending fork events in the stop reply queue. */
6274 remote_notif_get_pending_events (&notif_client_stop);
6275 for (stop_reply_up &reply : rs->stop_reply_queue)
6276 {
6277 if (reply->ptid.pid () != pid)
6278 continue;
6279
6280 if (!is_fork_status (reply->ws.kind ()))
6281 continue;
6282
6283 remote_detach_pid (reply->ws.child_ptid ().pid ());
6284 }
6285
6286 thread_info *tp = this->find_thread (inferior_ptid);
6287
6288 /* Check to see if we are detaching a fork parent. Note that if we
6289 are detaching a fork child, tp == NULL. */
6290 is_fork_parent = (tp != NULL
6291 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6292
6293 /* If doing detach-on-fork, we don't mourn, because that will delete
6294 breakpoints that should be available for the followed inferior. */
6295 if (!is_fork_parent)
6296 {
6297 /* Save the pid as a string before mourning, since that will
6298 unpush the remote target, and we need the string after. */
6299 std::string infpid = target_pid_to_str (ptid_t (pid));
6300
6301 target_mourn_inferior (inferior_ptid);
6302 if (print_inferior_events)
6303 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6304 inf->num, infpid.c_str ());
6305 }
6306 else
6307 {
6308 switch_to_no_thread ();
6309 detach_inferior (current_inferior ());
6310 }
6311 }
6312
6313 void
6314 remote_target::detach (inferior *inf, int from_tty)
6315 {
6316 remote_detach_1 (inf, from_tty);
6317 }
6318
6319 void
6320 extended_remote_target::detach (inferior *inf, int from_tty)
6321 {
6322 remote_detach_1 (inf, from_tty);
6323 }
6324
6325 /* Target follow-fork function for remote targets. On entry, and
6326 at return, the current inferior is the fork parent.
6327
6328 Note that although this is currently only used for extended-remote,
6329 it is named remote_follow_fork in anticipation of using it for the
6330 remote target as well. */
6331
6332 void
6333 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6334 target_waitkind fork_kind, bool follow_child,
6335 bool detach_fork)
6336 {
6337 process_stratum_target::follow_fork (child_inf, child_ptid,
6338 fork_kind, follow_child, detach_fork);
6339
6340 if ((fork_kind == TARGET_WAITKIND_FORKED
6341 && m_features.remote_fork_event_p ())
6342 || (fork_kind == TARGET_WAITKIND_VFORKED
6343 && m_features.remote_vfork_event_p ()))
6344 {
6345 /* When following the parent and detaching the child, we detach
6346 the child here. For the case of following the child and
6347 detaching the parent, the detach is done in the target-
6348 independent follow fork code in infrun.c. We can't use
6349 target_detach when detaching an unfollowed child because
6350 the client side doesn't know anything about the child. */
6351 if (detach_fork && !follow_child)
6352 {
6353 /* Detach the fork child. */
6354 remote_detach_pid (child_ptid.pid ());
6355 }
6356 }
6357 }
6358
6359 void
6360 remote_target::follow_clone (ptid_t child_ptid)
6361 {
6362 remote_add_thread (child_ptid, false, false, false);
6363 }
6364
6365 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6366 in the program space of the new inferior. */
6367
6368 void
6369 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6370 const char *execd_pathname)
6371 {
6372 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6373
6374 /* We know that this is a target file name, so if it has the "target:"
6375 prefix we strip it off before saving it in the program space. */
6376 if (is_target_filename (execd_pathname))
6377 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6378
6379 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6380 }
6381
6382 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6383
6384 void
6385 remote_target::disconnect (const char *args, int from_tty)
6386 {
6387 if (args)
6388 error (_("Argument given to \"disconnect\" when remotely debugging."));
6389
6390 /* Make sure we unpush even the extended remote targets. Calling
6391 target_mourn_inferior won't unpush, and
6392 remote_target::mourn_inferior won't unpush if there is more than
6393 one inferior left. */
6394 remote_unpush_target (this);
6395
6396 if (from_tty)
6397 gdb_puts ("Ending remote debugging.\n");
6398 }
6399
6400 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6401 be chatty about it. */
6402
6403 void
6404 extended_remote_target::attach (const char *args, int from_tty)
6405 {
6406 struct remote_state *rs = get_remote_state ();
6407 int pid;
6408 char *wait_status = NULL;
6409
6410 pid = parse_pid_to_attach (args);
6411
6412 /* Remote PID can be freely equal to getpid, do not check it here the same
6413 way as in other targets. */
6414
6415 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6416 error (_("This target does not support attaching to a process"));
6417
6418 target_announce_attach (from_tty, pid);
6419
6420 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6421 putpkt (rs->buf);
6422 getpkt (&rs->buf);
6423
6424 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6425 {
6426 case PACKET_OK:
6427 if (!target_is_non_stop_p ())
6428 {
6429 /* Save the reply for later. */
6430 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6431 strcpy (wait_status, rs->buf.data ());
6432 }
6433 else if (strcmp (rs->buf.data (), "OK") != 0)
6434 error (_("Attaching to %s failed with: %s"),
6435 target_pid_to_str (ptid_t (pid)).c_str (),
6436 rs->buf.data ());
6437 break;
6438 case PACKET_UNKNOWN:
6439 error (_("This target does not support attaching to a process"));
6440 default:
6441 error (_("Attaching to %s failed"),
6442 target_pid_to_str (ptid_t (pid)).c_str ());
6443 }
6444
6445 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6446
6447 inferior_ptid = ptid_t (pid);
6448
6449 if (target_is_non_stop_p ())
6450 {
6451 /* Get list of threads. */
6452 update_thread_list ();
6453
6454 thread_info *thread = first_thread_of_inferior (current_inferior ());
6455 if (thread != nullptr)
6456 switch_to_thread (thread);
6457
6458 /* Invalidate our notion of the remote current thread. */
6459 record_currthread (rs, minus_one_ptid);
6460 }
6461 else
6462 {
6463 /* Now, if we have thread information, update the main thread's
6464 ptid. */
6465 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6466
6467 /* Add the main thread to the thread list. We add the thread
6468 silently in this case (the final true parameter). */
6469 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6470
6471 switch_to_thread (thr);
6472 }
6473
6474 /* Next, if the target can specify a description, read it. We do
6475 this before anything involving memory or registers. */
6476 target_find_description ();
6477
6478 if (!target_is_non_stop_p ())
6479 {
6480 /* Use the previously fetched status. */
6481 gdb_assert (wait_status != NULL);
6482
6483 struct notif_event *reply
6484 = remote_notif_parse (this, &notif_client_stop, wait_status);
6485
6486 push_stop_reply ((struct stop_reply *) reply);
6487 }
6488 else
6489 {
6490 gdb_assert (wait_status == NULL);
6491
6492 gdb_assert (target_can_async_p ());
6493 }
6494 }
6495
6496 /* Implementation of the to_post_attach method. */
6497
6498 void
6499 extended_remote_target::post_attach (int pid)
6500 {
6501 /* Get text, data & bss offsets. */
6502 get_offsets ();
6503
6504 /* In certain cases GDB might not have had the chance to start
6505 symbol lookup up until now. This could happen if the debugged
6506 binary is not using shared libraries, the vsyscall page is not
6507 present (on Linux) and the binary itself hadn't changed since the
6508 debugging process was started. */
6509 if (current_program_space->symfile_object_file != NULL)
6510 remote_check_symbols();
6511 }
6512
6513 \f
6514 /* Check for the availability of vCont. This function should also check
6515 the response. */
6516
6517 void
6518 remote_target::remote_vcont_probe ()
6519 {
6520 remote_state *rs = get_remote_state ();
6521 char *buf;
6522
6523 strcpy (rs->buf.data (), "vCont?");
6524 putpkt (rs->buf);
6525 getpkt (&rs->buf);
6526 buf = rs->buf.data ();
6527
6528 /* Make sure that the features we assume are supported. */
6529 if (startswith (buf, "vCont"))
6530 {
6531 char *p = &buf[5];
6532 int support_c, support_C;
6533
6534 rs->supports_vCont.s = 0;
6535 rs->supports_vCont.S = 0;
6536 support_c = 0;
6537 support_C = 0;
6538 rs->supports_vCont.t = 0;
6539 rs->supports_vCont.r = 0;
6540 while (p && *p == ';')
6541 {
6542 p++;
6543 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6544 rs->supports_vCont.s = 1;
6545 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6546 rs->supports_vCont.S = 1;
6547 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6548 support_c = 1;
6549 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6550 support_C = 1;
6551 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6552 rs->supports_vCont.t = 1;
6553 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6554 rs->supports_vCont.r = 1;
6555
6556 p = strchr (p, ';');
6557 }
6558
6559 /* If c, and C are not all supported, we can't use vCont. Clearing
6560 BUF will make packet_ok disable the packet. */
6561 if (!support_c || !support_C)
6562 buf[0] = 0;
6563 }
6564
6565 m_features.packet_ok (rs->buf, PACKET_vCont);
6566 }
6567
6568 /* Helper function for building "vCont" resumptions. Write a
6569 resumption to P. ENDP points to one-passed-the-end of the buffer
6570 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6571 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6572 resumed thread should be single-stepped and/or signalled. If PTID
6573 equals minus_one_ptid, then all threads are resumed; if PTID
6574 represents a process, then all threads of the process are
6575 resumed. */
6576
6577 char *
6578 remote_target::append_resumption (char *p, char *endp,
6579 ptid_t ptid, int step, gdb_signal siggnal)
6580 {
6581 struct remote_state *rs = get_remote_state ();
6582
6583 if (step && siggnal != GDB_SIGNAL_0)
6584 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6585 else if (step
6586 /* GDB is willing to range step. */
6587 && use_range_stepping
6588 /* Target supports range stepping. */
6589 && rs->supports_vCont.r
6590 /* We don't currently support range stepping multiple
6591 threads with a wildcard (though the protocol allows it,
6592 so stubs shouldn't make an active effort to forbid
6593 it). */
6594 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6595 {
6596 struct thread_info *tp;
6597
6598 if (ptid == minus_one_ptid)
6599 {
6600 /* If we don't know about the target thread's tid, then
6601 we're resuming magic_null_ptid (see caller). */
6602 tp = this->find_thread (magic_null_ptid);
6603 }
6604 else
6605 tp = this->find_thread (ptid);
6606 gdb_assert (tp != NULL);
6607
6608 if (tp->control.may_range_step)
6609 {
6610 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6611
6612 p += xsnprintf (p, endp - p, ";r%s,%s",
6613 phex_nz (tp->control.step_range_start,
6614 addr_size),
6615 phex_nz (tp->control.step_range_end,
6616 addr_size));
6617 }
6618 else
6619 p += xsnprintf (p, endp - p, ";s");
6620 }
6621 else if (step)
6622 p += xsnprintf (p, endp - p, ";s");
6623 else if (siggnal != GDB_SIGNAL_0)
6624 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6625 else
6626 p += xsnprintf (p, endp - p, ";c");
6627
6628 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6629 {
6630 ptid_t nptid;
6631
6632 /* All (-1) threads of process. */
6633 nptid = ptid_t (ptid.pid (), -1);
6634
6635 p += xsnprintf (p, endp - p, ":");
6636 p = write_ptid (p, endp, nptid);
6637 }
6638 else if (ptid != minus_one_ptid)
6639 {
6640 p += xsnprintf (p, endp - p, ":");
6641 p = write_ptid (p, endp, ptid);
6642 }
6643
6644 return p;
6645 }
6646
6647 /* Clear the thread's private info on resume. */
6648
6649 static void
6650 resume_clear_thread_private_info (struct thread_info *thread)
6651 {
6652 if (thread->priv != NULL)
6653 {
6654 remote_thread_info *priv = get_remote_thread_info (thread);
6655
6656 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6657 priv->watch_data_address = 0;
6658 }
6659 }
6660
6661 /* Append a vCont continue-with-signal action for threads that have a
6662 non-zero stop signal. */
6663
6664 char *
6665 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6666 ptid_t ptid)
6667 {
6668 for (thread_info *thread : all_non_exited_threads (this, ptid))
6669 if (inferior_ptid != thread->ptid
6670 && thread->stop_signal () != GDB_SIGNAL_0)
6671 {
6672 p = append_resumption (p, endp, thread->ptid,
6673 0, thread->stop_signal ());
6674 thread->set_stop_signal (GDB_SIGNAL_0);
6675 resume_clear_thread_private_info (thread);
6676 }
6677
6678 return p;
6679 }
6680
6681 /* Set the target running, using the packets that use Hc
6682 (c/s/C/S). */
6683
6684 void
6685 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6686 gdb_signal siggnal)
6687 {
6688 struct remote_state *rs = get_remote_state ();
6689 char *buf;
6690
6691 rs->last_sent_signal = siggnal;
6692 rs->last_sent_step = step;
6693
6694 /* The c/s/C/S resume packets use Hc, so set the continue
6695 thread. */
6696 if (ptid == minus_one_ptid)
6697 set_continue_thread (any_thread_ptid);
6698 else
6699 set_continue_thread (ptid);
6700
6701 for (thread_info *thread : all_non_exited_threads (this))
6702 resume_clear_thread_private_info (thread);
6703
6704 buf = rs->buf.data ();
6705 if (::execution_direction == EXEC_REVERSE)
6706 {
6707 /* We don't pass signals to the target in reverse exec mode. */
6708 if (info_verbose && siggnal != GDB_SIGNAL_0)
6709 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6710 siggnal);
6711
6712 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6713 error (_("Remote reverse-step not supported."));
6714 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6715 error (_("Remote reverse-continue not supported."));
6716
6717 strcpy (buf, step ? "bs" : "bc");
6718 }
6719 else if (siggnal != GDB_SIGNAL_0)
6720 {
6721 buf[0] = step ? 'S' : 'C';
6722 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6723 buf[2] = tohex (((int) siggnal) & 0xf);
6724 buf[3] = '\0';
6725 }
6726 else
6727 strcpy (buf, step ? "s" : "c");
6728
6729 putpkt (buf);
6730 }
6731
6732 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6733 STEP, and SIGGNAL have the same meaning as in target_resume. This
6734 function returns non-zero iff it resumes the inferior.
6735
6736 This function issues a strict subset of all possible vCont commands
6737 at the moment. */
6738
6739 int
6740 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6741 enum gdb_signal siggnal)
6742 {
6743 struct remote_state *rs = get_remote_state ();
6744 char *p;
6745 char *endp;
6746
6747 /* No reverse execution actions defined for vCont. */
6748 if (::execution_direction == EXEC_REVERSE)
6749 return 0;
6750
6751 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6752 return 0;
6753
6754 p = rs->buf.data ();
6755 endp = p + get_remote_packet_size ();
6756
6757 /* If we could generate a wider range of packets, we'd have to worry
6758 about overflowing BUF. Should there be a generic
6759 "multi-part-packet" packet? */
6760
6761 p += xsnprintf (p, endp - p, "vCont");
6762
6763 if (scope_ptid == magic_null_ptid)
6764 {
6765 /* MAGIC_NULL_PTID means that we don't have any active threads,
6766 so we don't have any TID numbers the inferior will
6767 understand. Make sure to only send forms that do not specify
6768 a TID. */
6769 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6770 }
6771 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6772 {
6773 /* Resume all threads (of all processes, or of a single
6774 process), with preference for INFERIOR_PTID. This assumes
6775 inferior_ptid belongs to the set of all threads we are about
6776 to resume. */
6777 if (step || siggnal != GDB_SIGNAL_0)
6778 {
6779 /* Step inferior_ptid, with or without signal. */
6780 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6781 }
6782
6783 /* Also pass down any pending signaled resumption for other
6784 threads not the current. */
6785 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6786
6787 /* And continue others without a signal. */
6788 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6789 }
6790 else
6791 {
6792 /* Scheduler locking; resume only SCOPE_PTID. */
6793 append_resumption (p, endp, scope_ptid, step, siggnal);
6794 }
6795
6796 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6797 putpkt (rs->buf);
6798
6799 if (target_is_non_stop_p ())
6800 {
6801 /* In non-stop, the stub replies to vCont with "OK". The stop
6802 reply will be reported asynchronously by means of a `%Stop'
6803 notification. */
6804 getpkt (&rs->buf);
6805 if (strcmp (rs->buf.data (), "OK") != 0)
6806 error (_("Unexpected vCont reply in non-stop mode: %s"),
6807 rs->buf.data ());
6808 }
6809
6810 return 1;
6811 }
6812
6813 /* Tell the remote machine to resume. */
6814
6815 void
6816 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6817 {
6818 struct remote_state *rs = get_remote_state ();
6819
6820 /* When connected in non-stop mode, the core resumes threads
6821 individually. Resuming remote threads directly in target_resume
6822 would thus result in sending one packet per thread. Instead, to
6823 minimize roundtrip latency, here we just store the resume
6824 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6825 resumption will be done in remote_target::commit_resume, where we'll be
6826 able to do vCont action coalescing. */
6827 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6828 {
6829 remote_thread_info *remote_thr
6830 = get_remote_thread_info (inferior_thread ());
6831
6832 /* We don't expect the core to ask to resume an already resumed (from
6833 its point of view) thread. */
6834 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6835
6836 remote_thr->set_resumed_pending_vcont (step, siggnal);
6837
6838 /* There's actually nothing that says that the core can't
6839 request a wildcard resume in non-stop mode, though. It's
6840 just that we know it doesn't currently, so we don't bother
6841 with it. */
6842 gdb_assert (scope_ptid == inferior_ptid);
6843 return;
6844 }
6845
6846 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6847 (explained in remote-notif.c:handle_notification) so
6848 remote_notif_process is not called. We need find a place where
6849 it is safe to start a 'vNotif' sequence. It is good to do it
6850 before resuming inferior, because inferior was stopped and no RSP
6851 traffic at that moment. */
6852 if (!target_is_non_stop_p ())
6853 remote_notif_process (rs->notif_state, &notif_client_stop);
6854
6855 rs->last_resume_exec_dir = ::execution_direction;
6856
6857 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6858 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6859 remote_resume_with_hc (scope_ptid, step, siggnal);
6860
6861 /* Update resumed state tracked by the remote target. */
6862 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6863 get_remote_thread_info (tp)->set_resumed ();
6864
6865 /* We've just told the target to resume. The remote server will
6866 wait for the inferior to stop, and then send a stop reply. In
6867 the mean time, we can't start another command/query ourselves
6868 because the stub wouldn't be ready to process it. This applies
6869 only to the base all-stop protocol, however. In non-stop (which
6870 only supports vCont), the stub replies with an "OK", and is
6871 immediate able to process further serial input. */
6872 if (!target_is_non_stop_p ())
6873 rs->waiting_for_stop_reply = 1;
6874 }
6875
6876 /* Private per-inferior info for target remote processes. */
6877
6878 struct remote_inferior : public private_inferior
6879 {
6880 /* Whether we can send a wildcard vCont for this process. */
6881 bool may_wildcard_vcont = true;
6882 };
6883
6884 /* Get the remote private inferior data associated to INF. */
6885
6886 static remote_inferior *
6887 get_remote_inferior (inferior *inf)
6888 {
6889 if (inf->priv == NULL)
6890 inf->priv.reset (new remote_inferior);
6891
6892 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6893 }
6894
6895 /* Class used to track the construction of a vCont packet in the
6896 outgoing packet buffer. This is used to send multiple vCont
6897 packets if we have more actions than would fit a single packet. */
6898
6899 class vcont_builder
6900 {
6901 public:
6902 explicit vcont_builder (remote_target *remote)
6903 : m_remote (remote)
6904 {
6905 restart ();
6906 }
6907
6908 void flush ();
6909 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6910
6911 private:
6912 void restart ();
6913
6914 /* The remote target. */
6915 remote_target *m_remote;
6916
6917 /* Pointer to the first action. P points here if no action has been
6918 appended yet. */
6919 char *m_first_action;
6920
6921 /* Where the next action will be appended. */
6922 char *m_p;
6923
6924 /* The end of the buffer. Must never write past this. */
6925 char *m_endp;
6926 };
6927
6928 /* Prepare the outgoing buffer for a new vCont packet. */
6929
6930 void
6931 vcont_builder::restart ()
6932 {
6933 struct remote_state *rs = m_remote->get_remote_state ();
6934
6935 m_p = rs->buf.data ();
6936 m_endp = m_p + m_remote->get_remote_packet_size ();
6937 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6938 m_first_action = m_p;
6939 }
6940
6941 /* If the vCont packet being built has any action, send it to the
6942 remote end. */
6943
6944 void
6945 vcont_builder::flush ()
6946 {
6947 struct remote_state *rs;
6948
6949 if (m_p == m_first_action)
6950 return;
6951
6952 rs = m_remote->get_remote_state ();
6953 m_remote->putpkt (rs->buf);
6954 m_remote->getpkt (&rs->buf);
6955 if (strcmp (rs->buf.data (), "OK") != 0)
6956 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6957 }
6958
6959 /* The largest action is range-stepping, with its two addresses. This
6960 is more than sufficient. If a new, bigger action is created, it'll
6961 quickly trigger a failed assertion in append_resumption (and we'll
6962 just bump this). */
6963 #define MAX_ACTION_SIZE 200
6964
6965 /* Append a new vCont action in the outgoing packet being built. If
6966 the action doesn't fit the packet along with previous actions, push
6967 what we've got so far to the remote end and start over a new vCont
6968 packet (with the new action). */
6969
6970 void
6971 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6972 {
6973 char buf[MAX_ACTION_SIZE + 1];
6974
6975 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6976 ptid, step, siggnal);
6977
6978 /* Check whether this new action would fit in the vCont packet along
6979 with previous actions. If not, send what we've got so far and
6980 start a new vCont packet. */
6981 size_t rsize = endp - buf;
6982 if (rsize > m_endp - m_p)
6983 {
6984 flush ();
6985 restart ();
6986
6987 /* Should now fit. */
6988 gdb_assert (rsize <= m_endp - m_p);
6989 }
6990
6991 memcpy (m_p, buf, rsize);
6992 m_p += rsize;
6993 *m_p = '\0';
6994 }
6995
6996 /* to_commit_resume implementation. */
6997
6998 void
6999 remote_target::commit_resumed ()
7000 {
7001 /* If connected in all-stop mode, we'd send the remote resume
7002 request directly from remote_resume. Likewise if
7003 reverse-debugging, as there are no defined vCont actions for
7004 reverse execution. */
7005 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7006 return;
7007
7008 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7009 instead of resuming all threads of each process individually.
7010 However, if any thread of a process must remain halted, we can't
7011 send wildcard resumes and must send one action per thread.
7012
7013 Care must be taken to not resume threads/processes the server
7014 side already told us are stopped, but the core doesn't know about
7015 yet, because the events are still in the vStopped notification
7016 queue. For example:
7017
7018 #1 => vCont s:p1.1;c
7019 #2 <= OK
7020 #3 <= %Stopped T05 p1.1
7021 #4 => vStopped
7022 #5 <= T05 p1.2
7023 #6 => vStopped
7024 #7 <= OK
7025 #8 (infrun handles the stop for p1.1 and continues stepping)
7026 #9 => vCont s:p1.1;c
7027
7028 The last vCont above would resume thread p1.2 by mistake, because
7029 the server has no idea that the event for p1.2 had not been
7030 handled yet.
7031
7032 The server side must similarly ignore resume actions for the
7033 thread that has a pending %Stopped notification (and any other
7034 threads with events pending), until GDB acks the notification
7035 with vStopped. Otherwise, e.g., the following case is
7036 mishandled:
7037
7038 #1 => g (or any other packet)
7039 #2 <= [registers]
7040 #3 <= %Stopped T05 p1.2
7041 #4 => vCont s:p1.1;c
7042 #5 <= OK
7043
7044 Above, the server must not resume thread p1.2. GDB can't know
7045 that p1.2 stopped until it acks the %Stopped notification, and
7046 since from GDB's perspective all threads should be running, it
7047 sends a "c" action.
7048
7049 Finally, special care must also be given to handling fork/vfork
7050 events. A (v)fork event actually tells us that two processes
7051 stopped -- the parent and the child. Until we follow the fork,
7052 we must not resume the child. Therefore, if we have a pending
7053 fork follow, we must not send a global wildcard resume action
7054 (vCont;c). We can still send process-wide wildcards though. */
7055
7056 /* Start by assuming a global wildcard (vCont;c) is possible. */
7057 bool may_global_wildcard_vcont = true;
7058
7059 /* And assume every process is individually wildcard-able too. */
7060 for (inferior *inf : all_non_exited_inferiors (this))
7061 {
7062 remote_inferior *priv = get_remote_inferior (inf);
7063
7064 priv->may_wildcard_vcont = true;
7065 }
7066
7067 /* Check for any pending events (not reported or processed yet) and
7068 disable process and global wildcard resumes appropriately. */
7069 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7070
7071 bool any_pending_vcont_resume = false;
7072
7073 for (thread_info *tp : all_non_exited_threads (this))
7074 {
7075 remote_thread_info *priv = get_remote_thread_info (tp);
7076
7077 /* If a thread of a process is not meant to be resumed, then we
7078 can't wildcard that process. */
7079 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7080 {
7081 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7082
7083 /* And if we can't wildcard a process, we can't wildcard
7084 everything either. */
7085 may_global_wildcard_vcont = false;
7086 continue;
7087 }
7088
7089 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7090 any_pending_vcont_resume = true;
7091
7092 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7093 then we can't do a global wildcard, as that would resume the
7094 pending child. */
7095 if (thread_pending_child_status (tp) != nullptr)
7096 may_global_wildcard_vcont = false;
7097 }
7098
7099 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7100 do. */
7101 if (!any_pending_vcont_resume)
7102 return;
7103
7104 /* Now let's build the vCont packet(s). Actions must be appended
7105 from narrower to wider scopes (thread -> process -> global). If
7106 we end up with too many actions for a single packet vcont_builder
7107 flushes the current vCont packet to the remote side and starts a
7108 new one. */
7109 struct vcont_builder vcont_builder (this);
7110
7111 /* Threads first. */
7112 for (thread_info *tp : all_non_exited_threads (this))
7113 {
7114 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7115
7116 /* If the thread was previously vCont-resumed, no need to send a specific
7117 action for it. If we didn't receive a resume request for it, don't
7118 send an action for it either. */
7119 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7120 continue;
7121
7122 gdb_assert (!thread_is_in_step_over_chain (tp));
7123
7124 /* We should never be commit-resuming a thread that has a stop reply.
7125 Otherwise, we would end up reporting a stop event for a thread while
7126 it is running on the remote target. */
7127 remote_state *rs = get_remote_state ();
7128 for (const auto &stop_reply : rs->stop_reply_queue)
7129 gdb_assert (stop_reply->ptid != tp->ptid);
7130
7131 const resumed_pending_vcont_info &info
7132 = remote_thr->resumed_pending_vcont_info ();
7133
7134 /* Check if we need to send a specific action for this thread. If not,
7135 it will be included in a wildcard resume instead. */
7136 if (info.step || info.sig != GDB_SIGNAL_0
7137 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7138 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7139
7140 remote_thr->set_resumed ();
7141 }
7142
7143 /* Now check whether we can send any process-wide wildcard. This is
7144 to avoid sending a global wildcard in the case nothing is
7145 supposed to be resumed. */
7146 bool any_process_wildcard = false;
7147
7148 for (inferior *inf : all_non_exited_inferiors (this))
7149 {
7150 if (get_remote_inferior (inf)->may_wildcard_vcont)
7151 {
7152 any_process_wildcard = true;
7153 break;
7154 }
7155 }
7156
7157 if (any_process_wildcard)
7158 {
7159 /* If all processes are wildcard-able, then send a single "c"
7160 action, otherwise, send an "all (-1) threads of process"
7161 continue action for each running process, if any. */
7162 if (may_global_wildcard_vcont)
7163 {
7164 vcont_builder.push_action (minus_one_ptid,
7165 false, GDB_SIGNAL_0);
7166 }
7167 else
7168 {
7169 for (inferior *inf : all_non_exited_inferiors (this))
7170 {
7171 if (get_remote_inferior (inf)->may_wildcard_vcont)
7172 {
7173 vcont_builder.push_action (ptid_t (inf->pid),
7174 false, GDB_SIGNAL_0);
7175 }
7176 }
7177 }
7178 }
7179
7180 vcont_builder.flush ();
7181 }
7182
7183 /* Implementation of target_has_pending_events. */
7184
7185 bool
7186 remote_target::has_pending_events ()
7187 {
7188 if (target_can_async_p ())
7189 {
7190 remote_state *rs = get_remote_state ();
7191
7192 if (rs->async_event_handler_marked ())
7193 return true;
7194
7195 /* Note that BUFCNT can be negative, indicating sticky
7196 error. */
7197 if (rs->remote_desc->bufcnt != 0)
7198 return true;
7199 }
7200 return false;
7201 }
7202
7203 \f
7204
7205 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7206 thread, all threads of a remote process, or all threads of all
7207 processes. */
7208
7209 void
7210 remote_target::remote_stop_ns (ptid_t ptid)
7211 {
7212 struct remote_state *rs = get_remote_state ();
7213 char *p = rs->buf.data ();
7214 char *endp = p + get_remote_packet_size ();
7215
7216 /* If any thread that needs to stop was resumed but pending a vCont
7217 resume, generate a phony stop_reply. However, first check
7218 whether the thread wasn't resumed with a signal. Generating a
7219 phony stop in that case would result in losing the signal. */
7220 bool needs_commit = false;
7221 for (thread_info *tp : all_non_exited_threads (this, ptid))
7222 {
7223 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7224
7225 if (remote_thr->get_resume_state ()
7226 == resume_state::RESUMED_PENDING_VCONT)
7227 {
7228 const resumed_pending_vcont_info &info
7229 = remote_thr->resumed_pending_vcont_info ();
7230 if (info.sig != GDB_SIGNAL_0)
7231 {
7232 /* This signal must be forwarded to the inferior. We
7233 could commit-resume just this thread, but its simpler
7234 to just commit-resume everything. */
7235 needs_commit = true;
7236 break;
7237 }
7238 }
7239 }
7240
7241 if (needs_commit)
7242 commit_resumed ();
7243 else
7244 for (thread_info *tp : all_non_exited_threads (this, ptid))
7245 {
7246 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7247
7248 if (remote_thr->get_resume_state ()
7249 == resume_state::RESUMED_PENDING_VCONT)
7250 {
7251 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7252 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7253 tp->ptid.lwp (),
7254 pulongest (tp->ptid.tid ()));
7255
7256 /* Check that the thread wasn't resumed with a signal.
7257 Generating a phony stop would result in losing the
7258 signal. */
7259 const resumed_pending_vcont_info &info
7260 = remote_thr->resumed_pending_vcont_info ();
7261 gdb_assert (info.sig == GDB_SIGNAL_0);
7262
7263 stop_reply *sr = new stop_reply ();
7264 sr->ptid = tp->ptid;
7265 sr->rs = rs;
7266 sr->ws.set_stopped (GDB_SIGNAL_0);
7267 sr->arch = tp->inf->arch ();
7268 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7269 sr->watch_data_address = 0;
7270 sr->core = 0;
7271 this->push_stop_reply (sr);
7272
7273 /* Pretend that this thread was actually resumed on the
7274 remote target, then stopped. If we leave it in the
7275 RESUMED_PENDING_VCONT state and the commit_resumed
7276 method is called while the stop reply is still in the
7277 queue, we'll end up reporting a stop event to the core
7278 for that thread while it is running on the remote
7279 target... that would be bad. */
7280 remote_thr->set_resumed ();
7281 }
7282 }
7283
7284 if (!rs->supports_vCont.t)
7285 error (_("Remote server does not support stopping threads"));
7286
7287 if (ptid == minus_one_ptid
7288 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7289 p += xsnprintf (p, endp - p, "vCont;t");
7290 else
7291 {
7292 ptid_t nptid;
7293
7294 p += xsnprintf (p, endp - p, "vCont;t:");
7295
7296 if (ptid.is_pid ())
7297 /* All (-1) threads of process. */
7298 nptid = ptid_t (ptid.pid (), -1);
7299 else
7300 {
7301 /* Small optimization: if we already have a stop reply for
7302 this thread, no use in telling the stub we want this
7303 stopped. */
7304 if (peek_stop_reply (ptid))
7305 return;
7306
7307 nptid = ptid;
7308 }
7309
7310 write_ptid (p, endp, nptid);
7311 }
7312
7313 /* In non-stop, we get an immediate OK reply. The stop reply will
7314 come in asynchronously by notification. */
7315 putpkt (rs->buf);
7316 getpkt (&rs->buf);
7317 if (strcmp (rs->buf.data (), "OK") != 0)
7318 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7319 rs->buf.data ());
7320 }
7321
7322 /* All-stop version of target_interrupt. Sends a break or a ^C to
7323 interrupt the remote target. It is undefined which thread of which
7324 process reports the interrupt. */
7325
7326 void
7327 remote_target::remote_interrupt_as ()
7328 {
7329 struct remote_state *rs = get_remote_state ();
7330
7331 rs->ctrlc_pending_p = 1;
7332
7333 /* If the inferior is stopped already, but the core didn't know
7334 about it yet, just ignore the request. The pending stop events
7335 will be collected in remote_wait. */
7336 if (stop_reply_queue_length () > 0)
7337 return;
7338
7339 /* Send interrupt_sequence to remote target. */
7340 send_interrupt_sequence ();
7341 }
7342
7343 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7344 the remote target. It is undefined which thread of which process
7345 reports the interrupt. Throws an error if the packet is not
7346 supported by the server. */
7347
7348 void
7349 remote_target::remote_interrupt_ns ()
7350 {
7351 struct remote_state *rs = get_remote_state ();
7352 char *p = rs->buf.data ();
7353 char *endp = p + get_remote_packet_size ();
7354
7355 xsnprintf (p, endp - p, "vCtrlC");
7356
7357 /* In non-stop, we get an immediate OK reply. The stop reply will
7358 come in asynchronously by notification. */
7359 putpkt (rs->buf);
7360 getpkt (&rs->buf);
7361
7362 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7363 {
7364 case PACKET_OK:
7365 break;
7366 case PACKET_UNKNOWN:
7367 error (_("No support for interrupting the remote target."));
7368 case PACKET_ERROR:
7369 error (_("Interrupting target failed: %s"), rs->buf.data ());
7370 }
7371 }
7372
7373 /* Implement the to_stop function for the remote targets. */
7374
7375 void
7376 remote_target::stop (ptid_t ptid)
7377 {
7378 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7379
7380 if (target_is_non_stop_p ())
7381 remote_stop_ns (ptid);
7382 else
7383 {
7384 /* We don't currently have a way to transparently pause the
7385 remote target in all-stop mode. Interrupt it instead. */
7386 remote_interrupt_as ();
7387 }
7388 }
7389
7390 /* Implement the to_interrupt function for the remote targets. */
7391
7392 void
7393 remote_target::interrupt ()
7394 {
7395 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7396
7397 if (target_is_non_stop_p ())
7398 remote_interrupt_ns ();
7399 else
7400 remote_interrupt_as ();
7401 }
7402
7403 /* Implement the to_pass_ctrlc function for the remote targets. */
7404
7405 void
7406 remote_target::pass_ctrlc ()
7407 {
7408 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7409
7410 struct remote_state *rs = get_remote_state ();
7411
7412 /* If we're starting up, we're not fully synced yet. Quit
7413 immediately. */
7414 if (rs->starting_up)
7415 quit ();
7416 /* If ^C has already been sent once, offer to disconnect. */
7417 else if (rs->ctrlc_pending_p)
7418 interrupt_query ();
7419 else
7420 target_interrupt ();
7421 }
7422
7423 /* Ask the user what to do when an interrupt is received. */
7424
7425 void
7426 remote_target::interrupt_query ()
7427 {
7428 struct remote_state *rs = get_remote_state ();
7429
7430 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7431 {
7432 if (query (_("The target is not responding to interrupt requests.\n"
7433 "Stop debugging it? ")))
7434 {
7435 remote_unpush_target (this);
7436 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7437 }
7438 }
7439 else
7440 {
7441 if (query (_("Interrupted while waiting for the program.\n"
7442 "Give up waiting? ")))
7443 quit ();
7444 }
7445 }
7446
7447 /* Enable/disable target terminal ownership. Most targets can use
7448 terminal groups to control terminal ownership. Remote targets are
7449 different in that explicit transfer of ownership to/from GDB/target
7450 is required. */
7451
7452 void
7453 remote_target::terminal_inferior ()
7454 {
7455 /* NOTE: At this point we could also register our selves as the
7456 recipient of all input. Any characters typed could then be
7457 passed on down to the target. */
7458 }
7459
7460 void
7461 remote_target::terminal_ours ()
7462 {
7463 }
7464
7465 static void
7466 remote_console_output (const char *msg)
7467 {
7468 const char *p;
7469
7470 for (p = msg; p[0] && p[1]; p += 2)
7471 {
7472 char tb[2];
7473 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7474
7475 tb[0] = c;
7476 tb[1] = 0;
7477 gdb_stdtarg->puts (tb);
7478 }
7479 gdb_stdtarg->flush ();
7480 }
7481
7482 /* Return the length of the stop reply queue. */
7483
7484 int
7485 remote_target::stop_reply_queue_length ()
7486 {
7487 remote_state *rs = get_remote_state ();
7488 return rs->stop_reply_queue.size ();
7489 }
7490
7491 static void
7492 remote_notif_stop_parse (remote_target *remote,
7493 const notif_client *self, const char *buf,
7494 struct notif_event *event)
7495 {
7496 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7497 }
7498
7499 static void
7500 remote_notif_stop_ack (remote_target *remote,
7501 const notif_client *self, const char *buf,
7502 struct notif_event *event)
7503 {
7504 struct stop_reply *stop_reply = (struct stop_reply *) event;
7505
7506 /* acknowledge */
7507 putpkt (remote, self->ack_command);
7508
7509 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7510 the notification. It was left in the queue because we need to
7511 acknowledge it and pull the rest of the notifications out. */
7512 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7513 remote->push_stop_reply (stop_reply);
7514 }
7515
7516 static int
7517 remote_notif_stop_can_get_pending_events (remote_target *remote,
7518 const notif_client *self)
7519 {
7520 /* We can't get pending events in remote_notif_process for
7521 notification stop, and we have to do this in remote_wait_ns
7522 instead. If we fetch all queued events from stub, remote stub
7523 may exit and we have no chance to process them back in
7524 remote_wait_ns. */
7525 remote_state *rs = remote->get_remote_state ();
7526 rs->mark_async_event_handler ();
7527 return 0;
7528 }
7529
7530 stop_reply::~stop_reply ()
7531 {
7532 for (cached_reg_t &reg : regcache)
7533 xfree (reg.data);
7534 }
7535
7536 static notif_event_up
7537 remote_notif_stop_alloc_reply ()
7538 {
7539 return notif_event_up (new struct stop_reply ());
7540 }
7541
7542 /* A client of notification Stop. */
7543
7544 const notif_client notif_client_stop =
7545 {
7546 "Stop",
7547 "vStopped",
7548 remote_notif_stop_parse,
7549 remote_notif_stop_ack,
7550 remote_notif_stop_can_get_pending_events,
7551 remote_notif_stop_alloc_reply,
7552 REMOTE_NOTIF_STOP,
7553 };
7554
7555 /* If CONTEXT contains any fork/vfork/clone child threads that have
7556 not been reported yet, remove them from the CONTEXT list. If such
7557 a thread exists it is because we are stopped at a fork/vfork/clone
7558 catchpoint and have not yet called follow_fork/follow_clone, which
7559 will set up the host-side data structures for the new child. */
7560
7561 void
7562 remote_target::remove_new_children (threads_listing_context *context)
7563 {
7564 const notif_client *notif = &notif_client_stop;
7565
7566 /* For any threads stopped at a (v)fork/clone event, remove the
7567 corresponding child threads from the CONTEXT list. */
7568 for (thread_info *thread : all_non_exited_threads (this))
7569 {
7570 const target_waitstatus *ws = thread_pending_child_status (thread);
7571
7572 if (ws == nullptr)
7573 continue;
7574
7575 context->remove_thread (ws->child_ptid ());
7576 }
7577
7578 /* Check for any pending (v)fork/clone events (not reported or
7579 processed yet) in process PID and remove those child threads from
7580 the CONTEXT list as well. */
7581 remote_notif_get_pending_events (notif);
7582 for (auto &event : get_remote_state ()->stop_reply_queue)
7583 if (is_new_child_status (event->ws.kind ()))
7584 context->remove_thread (event->ws.child_ptid ());
7585 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7586 context->remove_thread (event->ptid);
7587 }
7588
7589 /* Check whether any event pending in the vStopped queue would prevent a
7590 global or process wildcard vCont action. Set *may_global_wildcard to
7591 false if we can't do a global wildcard (vCont;c), and clear the event
7592 inferior's may_wildcard_vcont flag if we can't do a process-wide
7593 wildcard resume (vCont;c:pPID.-1). */
7594
7595 void
7596 remote_target::check_pending_events_prevent_wildcard_vcont
7597 (bool *may_global_wildcard)
7598 {
7599 const notif_client *notif = &notif_client_stop;
7600
7601 remote_notif_get_pending_events (notif);
7602 for (auto &event : get_remote_state ()->stop_reply_queue)
7603 {
7604 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7605 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7606 continue;
7607
7608 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7609 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7610 *may_global_wildcard = false;
7611
7612 /* This may be the first time we heard about this process.
7613 Regardless, we must not do a global wildcard resume, otherwise
7614 we'd resume this process too. */
7615 *may_global_wildcard = false;
7616 if (event->ptid != null_ptid)
7617 {
7618 inferior *inf = find_inferior_ptid (this, event->ptid);
7619 if (inf != NULL)
7620 get_remote_inferior (inf)->may_wildcard_vcont = false;
7621 }
7622 }
7623 }
7624
7625 /* Discard all pending stop replies of inferior INF. */
7626
7627 void
7628 remote_target::discard_pending_stop_replies (struct inferior *inf)
7629 {
7630 struct stop_reply *reply;
7631 struct remote_state *rs = get_remote_state ();
7632 struct remote_notif_state *rns = rs->notif_state;
7633
7634 /* This function can be notified when an inferior exists. When the
7635 target is not remote, the notification state is NULL. */
7636 if (rs->remote_desc == NULL)
7637 return;
7638
7639 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7640
7641 /* Discard the in-flight notification. */
7642 if (reply != NULL && reply->ptid.pid () == inf->pid)
7643 {
7644 /* Leave the notification pending, since the server expects that
7645 we acknowledge it with vStopped. But clear its contents, so
7646 that later on when we acknowledge it, we also discard it. */
7647 remote_debug_printf
7648 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7649 reply->ptid.to_string().c_str(),
7650 reply->ws.to_string ().c_str ());
7651 reply->ws.set_ignore ();
7652 }
7653
7654 /* Discard the stop replies we have already pulled with
7655 vStopped. */
7656 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7657 rs->stop_reply_queue.end (),
7658 [=] (const stop_reply_up &event)
7659 {
7660 return event->ptid.pid () == inf->pid;
7661 });
7662 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7663 remote_debug_printf
7664 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7665 (*it)->ptid.to_string().c_str(),
7666 (*it)->ws.to_string ().c_str ());
7667 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7668 }
7669
7670 /* Discard the stop replies for RS in stop_reply_queue. */
7671
7672 void
7673 remote_target::discard_pending_stop_replies_in_queue ()
7674 {
7675 remote_state *rs = get_remote_state ();
7676
7677 /* Discard the stop replies we have already pulled with
7678 vStopped. */
7679 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7680 rs->stop_reply_queue.end (),
7681 [=] (const stop_reply_up &event)
7682 {
7683 return event->rs == rs;
7684 });
7685 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7686 }
7687
7688 /* Remove the first reply in 'stop_reply_queue' which matches
7689 PTID. */
7690
7691 struct stop_reply *
7692 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7693 {
7694 remote_state *rs = get_remote_state ();
7695
7696 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7697 rs->stop_reply_queue.end (),
7698 [=] (const stop_reply_up &event)
7699 {
7700 return event->ptid.matches (ptid);
7701 });
7702 struct stop_reply *result;
7703 if (iter == rs->stop_reply_queue.end ())
7704 result = nullptr;
7705 else
7706 {
7707 result = iter->release ();
7708 rs->stop_reply_queue.erase (iter);
7709 }
7710
7711 if (notif_debug)
7712 gdb_printf (gdb_stdlog,
7713 "notif: discard queued event: 'Stop' in %s\n",
7714 ptid.to_string ().c_str ());
7715
7716 return result;
7717 }
7718
7719 /* Look for a queued stop reply belonging to PTID. If one is found,
7720 remove it from the queue, and return it. Returns NULL if none is
7721 found. If there are still queued events left to process, tell the
7722 event loop to get back to target_wait soon. */
7723
7724 struct stop_reply *
7725 remote_target::queued_stop_reply (ptid_t ptid)
7726 {
7727 remote_state *rs = get_remote_state ();
7728 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7729
7730 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7731 {
7732 /* There's still at least an event left. */
7733 rs->mark_async_event_handler ();
7734 }
7735
7736 return r;
7737 }
7738
7739 /* Push a fully parsed stop reply in the stop reply queue. Since we
7740 know that we now have at least one queued event left to pass to the
7741 core side, tell the event loop to get back to target_wait soon. */
7742
7743 void
7744 remote_target::push_stop_reply (struct stop_reply *new_event)
7745 {
7746 remote_state *rs = get_remote_state ();
7747 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7748
7749 if (notif_debug)
7750 gdb_printf (gdb_stdlog,
7751 "notif: push 'Stop' %s to queue %d\n",
7752 new_event->ptid.to_string ().c_str (),
7753 int (rs->stop_reply_queue.size ()));
7754
7755 /* Mark the pending event queue only if async mode is currently enabled.
7756 If async mode is not currently enabled, then, if it later becomes
7757 enabled, and there are events in this queue, we will mark the event
7758 token at that point, see remote_target::async. */
7759 if (target_is_async_p ())
7760 rs->mark_async_event_handler ();
7761 }
7762
7763 /* Returns true if we have a stop reply for PTID. */
7764
7765 int
7766 remote_target::peek_stop_reply (ptid_t ptid)
7767 {
7768 remote_state *rs = get_remote_state ();
7769 for (auto &event : rs->stop_reply_queue)
7770 if (ptid == event->ptid
7771 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7772 return 1;
7773 return 0;
7774 }
7775
7776 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7777 starting with P and ending with PEND matches PREFIX. */
7778
7779 static int
7780 strprefix (const char *p, const char *pend, const char *prefix)
7781 {
7782 for ( ; p < pend; p++, prefix++)
7783 if (*p != *prefix)
7784 return 0;
7785 return *prefix == '\0';
7786 }
7787
7788 /* Parse the stop reply in BUF. Either the function succeeds, and the
7789 result is stored in EVENT, or throws an error. */
7790
7791 void
7792 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7793 {
7794 remote_arch_state *rsa = NULL;
7795 ULONGEST addr;
7796 const char *p;
7797 int skipregs = 0;
7798
7799 event->ptid = null_ptid;
7800 event->rs = get_remote_state ();
7801 event->ws.set_ignore ();
7802 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7803 event->regcache.clear ();
7804 event->core = -1;
7805
7806 switch (buf[0])
7807 {
7808 case 'T': /* Status with PC, SP, FP, ... */
7809 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7810 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7811 ss = signal number
7812 n... = register number
7813 r... = register contents
7814 */
7815
7816 p = &buf[3]; /* after Txx */
7817 while (*p)
7818 {
7819 const char *p1;
7820 int fieldsize;
7821
7822 p1 = strchr (p, ':');
7823 if (p1 == NULL)
7824 error (_("Malformed packet(a) (missing colon): %s\n\
7825 Packet: '%s'\n"),
7826 p, buf);
7827 if (p == p1)
7828 error (_("Malformed packet(a) (missing register number): %s\n\
7829 Packet: '%s'\n"),
7830 p, buf);
7831
7832 /* Some "registers" are actually extended stop information.
7833 Note if you're adding a new entry here: GDB 7.9 and
7834 earlier assume that all register "numbers" that start
7835 with an hex digit are real register numbers. Make sure
7836 the server only sends such a packet if it knows the
7837 client understands it. */
7838
7839 if (strprefix (p, p1, "thread"))
7840 event->ptid = read_ptid (++p1, &p);
7841 else if (strprefix (p, p1, "syscall_entry"))
7842 {
7843 ULONGEST sysno;
7844
7845 p = unpack_varlen_hex (++p1, &sysno);
7846 event->ws.set_syscall_entry ((int) sysno);
7847 }
7848 else if (strprefix (p, p1, "syscall_return"))
7849 {
7850 ULONGEST sysno;
7851
7852 p = unpack_varlen_hex (++p1, &sysno);
7853 event->ws.set_syscall_return ((int) sysno);
7854 }
7855 else if (strprefix (p, p1, "watch")
7856 || strprefix (p, p1, "rwatch")
7857 || strprefix (p, p1, "awatch"))
7858 {
7859 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7860 p = unpack_varlen_hex (++p1, &addr);
7861 event->watch_data_address = (CORE_ADDR) addr;
7862 }
7863 else if (strprefix (p, p1, "swbreak"))
7864 {
7865 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7866
7867 /* Make sure the stub doesn't forget to indicate support
7868 with qSupported. */
7869 if (m_features.packet_support (PACKET_swbreak_feature)
7870 != PACKET_ENABLE)
7871 error (_("Unexpected swbreak stop reason"));
7872
7873 /* The value part is documented as "must be empty",
7874 though we ignore it, in case we ever decide to make
7875 use of it in a backward compatible way. */
7876 p = strchrnul (p1 + 1, ';');
7877 }
7878 else if (strprefix (p, p1, "hwbreak"))
7879 {
7880 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7881
7882 /* Make sure the stub doesn't forget to indicate support
7883 with qSupported. */
7884 if (m_features.packet_support (PACKET_hwbreak_feature)
7885 != PACKET_ENABLE)
7886 error (_("Unexpected hwbreak stop reason"));
7887
7888 /* See above. */
7889 p = strchrnul (p1 + 1, ';');
7890 }
7891 else if (strprefix (p, p1, "library"))
7892 {
7893 event->ws.set_loaded ();
7894 p = strchrnul (p1 + 1, ';');
7895 }
7896 else if (strprefix (p, p1, "replaylog"))
7897 {
7898 event->ws.set_no_history ();
7899 /* p1 will indicate "begin" or "end", but it makes
7900 no difference for now, so ignore it. */
7901 p = strchrnul (p1 + 1, ';');
7902 }
7903 else if (strprefix (p, p1, "core"))
7904 {
7905 ULONGEST c;
7906
7907 p = unpack_varlen_hex (++p1, &c);
7908 event->core = c;
7909 }
7910 else if (strprefix (p, p1, "fork"))
7911 event->ws.set_forked (read_ptid (++p1, &p));
7912 else if (strprefix (p, p1, "vfork"))
7913 event->ws.set_vforked (read_ptid (++p1, &p));
7914 else if (strprefix (p, p1, "clone"))
7915 event->ws.set_thread_cloned (read_ptid (++p1, &p));
7916 else if (strprefix (p, p1, "vforkdone"))
7917 {
7918 event->ws.set_vfork_done ();
7919 p = strchrnul (p1 + 1, ';');
7920 }
7921 else if (strprefix (p, p1, "exec"))
7922 {
7923 ULONGEST ignored;
7924 int pathlen;
7925
7926 /* Determine the length of the execd pathname. */
7927 p = unpack_varlen_hex (++p1, &ignored);
7928 pathlen = (p - p1) / 2;
7929
7930 /* Save the pathname for event reporting and for
7931 the next run command. */
7932 gdb::unique_xmalloc_ptr<char> pathname
7933 ((char *) xmalloc (pathlen + 1));
7934 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7935 pathname.get ()[pathlen] = '\0';
7936
7937 /* This is freed during event handling. */
7938 event->ws.set_execd (std::move (pathname));
7939
7940 /* Skip the registers included in this packet, since
7941 they may be for an architecture different from the
7942 one used by the original program. */
7943 skipregs = 1;
7944 }
7945 else if (strprefix (p, p1, "create"))
7946 {
7947 event->ws.set_thread_created ();
7948 p = strchrnul (p1 + 1, ';');
7949 }
7950 else
7951 {
7952 ULONGEST pnum;
7953 const char *p_temp;
7954
7955 if (skipregs)
7956 {
7957 p = strchrnul (p1 + 1, ';');
7958 p++;
7959 continue;
7960 }
7961
7962 /* Maybe a real ``P'' register number. */
7963 p_temp = unpack_varlen_hex (p, &pnum);
7964 /* If the first invalid character is the colon, we got a
7965 register number. Otherwise, it's an unknown stop
7966 reason. */
7967 if (p_temp == p1)
7968 {
7969 /* If we haven't parsed the event's thread yet, find
7970 it now, in order to find the architecture of the
7971 reported expedited registers. */
7972 if (event->ptid == null_ptid)
7973 {
7974 /* If there is no thread-id information then leave
7975 the event->ptid as null_ptid. Later in
7976 process_stop_reply we will pick a suitable
7977 thread. */
7978 const char *thr = strstr (p1 + 1, ";thread:");
7979 if (thr != NULL)
7980 event->ptid = read_ptid (thr + strlen (";thread:"),
7981 NULL);
7982 }
7983
7984 if (rsa == NULL)
7985 {
7986 inferior *inf
7987 = (event->ptid == null_ptid
7988 ? NULL
7989 : find_inferior_ptid (this, event->ptid));
7990 /* If this is the first time we learn anything
7991 about this process, skip the registers
7992 included in this packet, since we don't yet
7993 know which architecture to use to parse them.
7994 We'll determine the architecture later when
7995 we process the stop reply and retrieve the
7996 target description, via
7997 remote_notice_new_inferior ->
7998 post_create_inferior. */
7999 if (inf == NULL)
8000 {
8001 p = strchrnul (p1 + 1, ';');
8002 p++;
8003 continue;
8004 }
8005
8006 event->arch = inf->arch ();
8007 rsa = event->rs->get_remote_arch_state (event->arch);
8008 }
8009
8010 packet_reg *reg
8011 = packet_reg_from_pnum (event->arch, rsa, pnum);
8012 cached_reg_t cached_reg;
8013
8014 if (reg == NULL)
8015 error (_("Remote sent bad register number %s: %s\n\
8016 Packet: '%s'\n"),
8017 hex_string (pnum), p, buf);
8018
8019 cached_reg.num = reg->regnum;
8020 cached_reg.data = (gdb_byte *)
8021 xmalloc (register_size (event->arch, reg->regnum));
8022
8023 p = p1 + 1;
8024 fieldsize = hex2bin (p, cached_reg.data,
8025 register_size (event->arch, reg->regnum));
8026 p += 2 * fieldsize;
8027 if (fieldsize < register_size (event->arch, reg->regnum))
8028 warning (_("Remote reply is too short: %s"), buf);
8029
8030 event->regcache.push_back (cached_reg);
8031 }
8032 else
8033 {
8034 /* Not a number. Silently skip unknown optional
8035 info. */
8036 p = strchrnul (p1 + 1, ';');
8037 }
8038 }
8039
8040 if (*p != ';')
8041 error (_("Remote register badly formatted: %s\nhere: %s"),
8042 buf, p);
8043 ++p;
8044 }
8045
8046 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8047 break;
8048
8049 /* fall through */
8050 case 'S': /* Old style status, just signal only. */
8051 {
8052 int sig;
8053
8054 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8055 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8056 event->ws.set_stopped ((enum gdb_signal) sig);
8057 else
8058 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8059 }
8060 break;
8061 case 'w': /* Thread exited. */
8062 {
8063 ULONGEST value;
8064
8065 p = unpack_varlen_hex (&buf[1], &value);
8066 event->ws.set_thread_exited (value);
8067 if (*p != ';')
8068 error (_("stop reply packet badly formatted: %s"), buf);
8069 event->ptid = read_ptid (++p, NULL);
8070 break;
8071 }
8072 case 'W': /* Target exited. */
8073 case 'X':
8074 {
8075 ULONGEST value;
8076
8077 /* GDB used to accept only 2 hex chars here. Stubs should
8078 only send more if they detect GDB supports multi-process
8079 support. */
8080 p = unpack_varlen_hex (&buf[1], &value);
8081
8082 if (buf[0] == 'W')
8083 {
8084 /* The remote process exited. */
8085 event->ws.set_exited (value);
8086 }
8087 else
8088 {
8089 /* The remote process exited with a signal. */
8090 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8091 event->ws.set_signalled ((enum gdb_signal) value);
8092 else
8093 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8094 }
8095
8096 /* If no process is specified, return null_ptid, and let the
8097 caller figure out the right process to use. */
8098 int pid = 0;
8099 if (*p == '\0')
8100 ;
8101 else if (*p == ';')
8102 {
8103 p++;
8104
8105 if (*p == '\0')
8106 ;
8107 else if (startswith (p, "process:"))
8108 {
8109 ULONGEST upid;
8110
8111 p += sizeof ("process:") - 1;
8112 unpack_varlen_hex (p, &upid);
8113 pid = upid;
8114 }
8115 else
8116 error (_("unknown stop reply packet: %s"), buf);
8117 }
8118 else
8119 error (_("unknown stop reply packet: %s"), buf);
8120 event->ptid = ptid_t (pid);
8121 }
8122 break;
8123 case 'N':
8124 event->ws.set_no_resumed ();
8125 event->ptid = minus_one_ptid;
8126 break;
8127 }
8128 }
8129
8130 /* When the stub wants to tell GDB about a new notification reply, it
8131 sends a notification (%Stop, for example). Those can come it at
8132 any time, hence, we have to make sure that any pending
8133 putpkt/getpkt sequence we're making is finished, before querying
8134 the stub for more events with the corresponding ack command
8135 (vStopped, for example). E.g., if we started a vStopped sequence
8136 immediately upon receiving the notification, something like this
8137 could happen:
8138
8139 1.1) --> Hg 1
8140 1.2) <-- OK
8141 1.3) --> g
8142 1.4) <-- %Stop
8143 1.5) --> vStopped
8144 1.6) <-- (registers reply to step #1.3)
8145
8146 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8147 query.
8148
8149 To solve this, whenever we parse a %Stop notification successfully,
8150 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8151 doing whatever we were doing:
8152
8153 2.1) --> Hg 1
8154 2.2) <-- OK
8155 2.3) --> g
8156 2.4) <-- %Stop
8157 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8158 2.5) <-- (registers reply to step #2.3)
8159
8160 Eventually after step #2.5, we return to the event loop, which
8161 notices there's an event on the
8162 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8163 associated callback --- the function below. At this point, we're
8164 always safe to start a vStopped sequence. :
8165
8166 2.6) --> vStopped
8167 2.7) <-- T05 thread:2
8168 2.8) --> vStopped
8169 2.9) --> OK
8170 */
8171
8172 void
8173 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8174 {
8175 struct remote_state *rs = get_remote_state ();
8176
8177 if (rs->notif_state->pending_event[nc->id] != NULL)
8178 {
8179 if (notif_debug)
8180 gdb_printf (gdb_stdlog,
8181 "notif: process: '%s' ack pending event\n",
8182 nc->name);
8183
8184 /* acknowledge */
8185 nc->ack (this, nc, rs->buf.data (),
8186 rs->notif_state->pending_event[nc->id]);
8187 rs->notif_state->pending_event[nc->id] = NULL;
8188
8189 while (1)
8190 {
8191 getpkt (&rs->buf);
8192 if (strcmp (rs->buf.data (), "OK") == 0)
8193 break;
8194 else
8195 remote_notif_ack (this, nc, rs->buf.data ());
8196 }
8197 }
8198 else
8199 {
8200 if (notif_debug)
8201 gdb_printf (gdb_stdlog,
8202 "notif: process: '%s' no pending reply\n",
8203 nc->name);
8204 }
8205 }
8206
8207 /* Wrapper around remote_target::remote_notif_get_pending_events to
8208 avoid having to export the whole remote_target class. */
8209
8210 void
8211 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8212 {
8213 remote->remote_notif_get_pending_events (nc);
8214 }
8215
8216 /* Called from process_stop_reply when the stop packet we are responding
8217 to didn't include a process-id or thread-id. STATUS is the stop event
8218 we are responding to.
8219
8220 It is the task of this function to select a suitable thread (or process)
8221 and return its ptid, this is the thread (or process) we will assume the
8222 stop event came from.
8223
8224 In some cases there isn't really any choice about which thread (or
8225 process) is selected, a basic remote with a single process containing a
8226 single thread might choose not to send any process-id or thread-id in
8227 its stop packets, this function will select and return the one and only
8228 thread.
8229
8230 However, if a target supports multiple threads (or processes) and still
8231 doesn't include a thread-id (or process-id) in its stop packet then
8232 first, this is a badly behaving target, and second, we're going to have
8233 to select a thread (or process) at random and use that. This function
8234 will print a warning to the user if it detects that there is the
8235 possibility that GDB is guessing which thread (or process) to
8236 report.
8237
8238 Note that this is called before GDB fetches the updated thread list from the
8239 target. So it's possible for the stop reply to be ambiguous and for GDB to
8240 not realize it. For example, if there's initially one thread, the target
8241 spawns a second thread, and then sends a stop reply without an id that
8242 concerns the first thread. GDB will assume the stop reply is about the
8243 first thread - the only thread it knows about - without printing a warning.
8244 Anyway, if the remote meant for the stop reply to be about the second thread,
8245 then it would be really broken, because GDB doesn't know about that thread
8246 yet. */
8247
8248 ptid_t
8249 remote_target::select_thread_for_ambiguous_stop_reply
8250 (const target_waitstatus &status)
8251 {
8252 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8253
8254 /* Some stop events apply to all threads in an inferior, while others
8255 only apply to a single thread. */
8256 bool process_wide_stop
8257 = (status.kind () == TARGET_WAITKIND_EXITED
8258 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8259
8260 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8261
8262 thread_info *first_resumed_thread = nullptr;
8263 bool ambiguous = false;
8264
8265 /* Consider all non-exited threads of the target, find the first resumed
8266 one. */
8267 for (thread_info *thr : all_non_exited_threads (this))
8268 {
8269 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8270
8271 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8272 continue;
8273
8274 if (first_resumed_thread == nullptr)
8275 first_resumed_thread = thr;
8276 else if (!process_wide_stop
8277 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8278 ambiguous = true;
8279 }
8280
8281 gdb_assert (first_resumed_thread != nullptr);
8282
8283 remote_debug_printf ("first resumed thread is %s",
8284 pid_to_str (first_resumed_thread->ptid).c_str ());
8285 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8286
8287 /* Warn if the remote target is sending ambiguous stop replies. */
8288 if (ambiguous)
8289 {
8290 static bool warned = false;
8291
8292 if (!warned)
8293 {
8294 /* If you are seeing this warning then the remote target has
8295 stopped without specifying a thread-id, but the target
8296 does have multiple threads (or inferiors), and so GDB is
8297 having to guess which thread stopped.
8298
8299 Examples of what might cause this are the target sending
8300 and 'S' stop packet, or a 'T' stop packet and not
8301 including a thread-id.
8302
8303 Additionally, the target might send a 'W' or 'X packet
8304 without including a process-id, when the target has
8305 multiple running inferiors. */
8306 if (process_wide_stop)
8307 warning (_("multi-inferior target stopped without "
8308 "sending a process-id, using first "
8309 "non-exited inferior"));
8310 else
8311 warning (_("multi-threaded target stopped without "
8312 "sending a thread-id, using first "
8313 "non-exited thread"));
8314 warned = true;
8315 }
8316 }
8317
8318 /* If this is a stop for all threads then don't use a particular threads
8319 ptid, instead create a new ptid where only the pid field is set. */
8320 if (process_wide_stop)
8321 return ptid_t (first_resumed_thread->ptid.pid ());
8322 else
8323 return first_resumed_thread->ptid;
8324 }
8325
8326 /* Called when it is decided that STOP_REPLY holds the info of the
8327 event that is to be returned to the core. This function always
8328 destroys STOP_REPLY. */
8329
8330 ptid_t
8331 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8332 struct target_waitstatus *status)
8333 {
8334 *status = stop_reply->ws;
8335 ptid_t ptid = stop_reply->ptid;
8336
8337 /* If no thread/process was reported by the stub then select a suitable
8338 thread/process. */
8339 if (ptid == null_ptid)
8340 ptid = select_thread_for_ambiguous_stop_reply (*status);
8341 gdb_assert (ptid != null_ptid);
8342
8343 if (status->kind () != TARGET_WAITKIND_EXITED
8344 && status->kind () != TARGET_WAITKIND_SIGNALLED
8345 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8346 {
8347 /* Expedited registers. */
8348 if (!stop_reply->regcache.empty ())
8349 {
8350 struct regcache *regcache
8351 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8352
8353 for (cached_reg_t &reg : stop_reply->regcache)
8354 {
8355 regcache->raw_supply (reg.num, reg.data);
8356 xfree (reg.data);
8357 }
8358
8359 stop_reply->regcache.clear ();
8360 }
8361
8362 remote_notice_new_inferior (ptid, false);
8363 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8364 remote_thr->core = stop_reply->core;
8365 remote_thr->stop_reason = stop_reply->stop_reason;
8366 remote_thr->watch_data_address = stop_reply->watch_data_address;
8367
8368 if (target_is_non_stop_p ())
8369 {
8370 /* If the target works in non-stop mode, a stop-reply indicates that
8371 only this thread stopped. */
8372 remote_thr->set_not_resumed ();
8373 }
8374 else
8375 {
8376 /* If the target works in all-stop mode, a stop-reply indicates that
8377 all the target's threads stopped. */
8378 for (thread_info *tp : all_non_exited_threads (this))
8379 get_remote_thread_info (tp)->set_not_resumed ();
8380 }
8381 }
8382
8383 delete stop_reply;
8384 return ptid;
8385 }
8386
8387 /* The non-stop mode version of target_wait. */
8388
8389 ptid_t
8390 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8391 target_wait_flags options)
8392 {
8393 struct remote_state *rs = get_remote_state ();
8394 struct stop_reply *stop_reply;
8395 int ret;
8396 bool is_notif = false;
8397
8398 /* If in non-stop mode, get out of getpkt even if a
8399 notification is received. */
8400
8401 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8402 while (1)
8403 {
8404 if (ret != -1 && !is_notif)
8405 switch (rs->buf[0])
8406 {
8407 case 'E': /* Error of some sort. */
8408 /* We're out of sync with the target now. Did it continue
8409 or not? We can't tell which thread it was in non-stop,
8410 so just ignore this. */
8411 warning (_("Remote failure reply: %s"), rs->buf.data ());
8412 break;
8413 case 'O': /* Console output. */
8414 remote_console_output (&rs->buf[1]);
8415 break;
8416 default:
8417 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8418 break;
8419 }
8420
8421 /* Acknowledge a pending stop reply that may have arrived in the
8422 mean time. */
8423 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8424 remote_notif_get_pending_events (&notif_client_stop);
8425
8426 /* If indeed we noticed a stop reply, we're done. */
8427 stop_reply = queued_stop_reply (ptid);
8428 if (stop_reply != NULL)
8429 return process_stop_reply (stop_reply, status);
8430
8431 /* Still no event. If we're just polling for an event, then
8432 return to the event loop. */
8433 if (options & TARGET_WNOHANG)
8434 {
8435 status->set_ignore ();
8436 return minus_one_ptid;
8437 }
8438
8439 /* Otherwise do a blocking wait. */
8440 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8441 }
8442 }
8443
8444 /* Return the first resumed thread. */
8445
8446 static ptid_t
8447 first_remote_resumed_thread (remote_target *target)
8448 {
8449 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8450 if (tp->resumed ())
8451 return tp->ptid;
8452 return null_ptid;
8453 }
8454
8455 /* Wait until the remote machine stops, then return, storing status in
8456 STATUS just as `wait' would. */
8457
8458 ptid_t
8459 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8460 target_wait_flags options)
8461 {
8462 struct remote_state *rs = get_remote_state ();
8463 ptid_t event_ptid = null_ptid;
8464 char *buf;
8465 struct stop_reply *stop_reply;
8466
8467 again:
8468
8469 status->set_ignore ();
8470
8471 stop_reply = queued_stop_reply (ptid);
8472 if (stop_reply != NULL)
8473 {
8474 /* None of the paths that push a stop reply onto the queue should
8475 have set the waiting_for_stop_reply flag. */
8476 gdb_assert (!rs->waiting_for_stop_reply);
8477 event_ptid = process_stop_reply (stop_reply, status);
8478 }
8479 else
8480 {
8481 bool forever = ((options & TARGET_WNOHANG) == 0
8482 && rs->wait_forever_enabled_p);
8483
8484 if (!rs->waiting_for_stop_reply)
8485 {
8486 status->set_no_resumed ();
8487 return minus_one_ptid;
8488 }
8489
8490 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8491 _never_ wait for ever -> test on target_is_async_p().
8492 However, before we do that we need to ensure that the caller
8493 knows how to take the target into/out of async mode. */
8494 bool is_notif;
8495 int ret = getpkt (&rs->buf, forever, &is_notif);
8496
8497 /* GDB gets a notification. Return to core as this event is
8498 not interesting. */
8499 if (ret != -1 && is_notif)
8500 return minus_one_ptid;
8501
8502 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8503 return minus_one_ptid;
8504
8505 buf = rs->buf.data ();
8506
8507 /* Assume that the target has acknowledged Ctrl-C unless we receive
8508 an 'F' or 'O' packet. */
8509 if (buf[0] != 'F' && buf[0] != 'O')
8510 rs->ctrlc_pending_p = 0;
8511
8512 switch (buf[0])
8513 {
8514 case 'E': /* Error of some sort. */
8515 /* We're out of sync with the target now. Did it continue or
8516 not? Not is more likely, so report a stop. */
8517 rs->waiting_for_stop_reply = 0;
8518
8519 warning (_("Remote failure reply: %s"), buf);
8520 status->set_stopped (GDB_SIGNAL_0);
8521 break;
8522 case 'F': /* File-I/O request. */
8523 /* GDB may access the inferior memory while handling the File-I/O
8524 request, but we don't want GDB accessing memory while waiting
8525 for a stop reply. See the comments in putpkt_binary. Set
8526 waiting_for_stop_reply to 0 temporarily. */
8527 rs->waiting_for_stop_reply = 0;
8528 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8529 rs->ctrlc_pending_p = 0;
8530 /* GDB handled the File-I/O request, and the target is running
8531 again. Keep waiting for events. */
8532 rs->waiting_for_stop_reply = 1;
8533 break;
8534 case 'N': case 'T': case 'S': case 'X': case 'W':
8535 {
8536 /* There is a stop reply to handle. */
8537 rs->waiting_for_stop_reply = 0;
8538
8539 stop_reply
8540 = (struct stop_reply *) remote_notif_parse (this,
8541 &notif_client_stop,
8542 rs->buf.data ());
8543
8544 event_ptid = process_stop_reply (stop_reply, status);
8545 break;
8546 }
8547 case 'O': /* Console output. */
8548 remote_console_output (buf + 1);
8549 break;
8550 case '\0':
8551 if (rs->last_sent_signal != GDB_SIGNAL_0)
8552 {
8553 /* Zero length reply means that we tried 'S' or 'C' and the
8554 remote system doesn't support it. */
8555 target_terminal::ours_for_output ();
8556 gdb_printf
8557 ("Can't send signals to this remote system. %s not sent.\n",
8558 gdb_signal_to_name (rs->last_sent_signal));
8559 rs->last_sent_signal = GDB_SIGNAL_0;
8560 target_terminal::inferior ();
8561
8562 strcpy (buf, rs->last_sent_step ? "s" : "c");
8563 putpkt (buf);
8564 break;
8565 }
8566 /* fallthrough */
8567 default:
8568 warning (_("Invalid remote reply: %s"), buf);
8569 break;
8570 }
8571 }
8572
8573 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8574 return minus_one_ptid;
8575 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8576 {
8577 /* Nothing interesting happened. If we're doing a non-blocking
8578 poll, we're done. Otherwise, go back to waiting. */
8579 if (options & TARGET_WNOHANG)
8580 return minus_one_ptid;
8581 else
8582 goto again;
8583 }
8584 else if (status->kind () != TARGET_WAITKIND_EXITED
8585 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8586 {
8587 if (event_ptid != null_ptid)
8588 record_currthread (rs, event_ptid);
8589 else
8590 event_ptid = first_remote_resumed_thread (this);
8591 }
8592 else
8593 {
8594 /* A process exit. Invalidate our notion of current thread. */
8595 record_currthread (rs, minus_one_ptid);
8596 /* It's possible that the packet did not include a pid. */
8597 if (event_ptid == null_ptid)
8598 event_ptid = first_remote_resumed_thread (this);
8599 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8600 if (event_ptid == null_ptid)
8601 event_ptid = magic_null_ptid;
8602 }
8603
8604 return event_ptid;
8605 }
8606
8607 /* Wait until the remote machine stops, then return, storing status in
8608 STATUS just as `wait' would. */
8609
8610 ptid_t
8611 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8612 target_wait_flags options)
8613 {
8614 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8615
8616 remote_state *rs = get_remote_state ();
8617
8618 /* Start by clearing the flag that asks for our wait method to be called,
8619 we'll mark it again at the end if needed. If the target is not in
8620 async mode then the async token should not be marked. */
8621 if (target_is_async_p ())
8622 rs->clear_async_event_handler ();
8623 else
8624 gdb_assert (!rs->async_event_handler_marked ());
8625
8626 ptid_t event_ptid;
8627
8628 if (target_is_non_stop_p ())
8629 event_ptid = wait_ns (ptid, status, options);
8630 else
8631 event_ptid = wait_as (ptid, status, options);
8632
8633 if (target_is_async_p ())
8634 {
8635 /* If there are events left in the queue, or unacknowledged
8636 notifications, then tell the event loop to call us again. */
8637 if (!rs->stop_reply_queue.empty ()
8638 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8639 rs->mark_async_event_handler ();
8640 }
8641
8642 return event_ptid;
8643 }
8644
8645 /* Fetch a single register using a 'p' packet. */
8646
8647 int
8648 remote_target::fetch_register_using_p (struct regcache *regcache,
8649 packet_reg *reg)
8650 {
8651 struct gdbarch *gdbarch = regcache->arch ();
8652 struct remote_state *rs = get_remote_state ();
8653 char *buf, *p;
8654 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8655 int i;
8656
8657 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8658 return 0;
8659
8660 if (reg->pnum == -1)
8661 return 0;
8662
8663 p = rs->buf.data ();
8664 *p++ = 'p';
8665 p += hexnumstr (p, reg->pnum);
8666 *p++ = '\0';
8667 putpkt (rs->buf);
8668 getpkt (&rs->buf);
8669
8670 buf = rs->buf.data ();
8671
8672 switch (m_features.packet_ok (rs->buf, PACKET_p))
8673 {
8674 case PACKET_OK:
8675 break;
8676 case PACKET_UNKNOWN:
8677 return 0;
8678 case PACKET_ERROR:
8679 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8680 gdbarch_register_name (regcache->arch (), reg->regnum),
8681 buf);
8682 }
8683
8684 /* If this register is unfetchable, tell the regcache. */
8685 if (buf[0] == 'x')
8686 {
8687 regcache->raw_supply (reg->regnum, NULL);
8688 return 1;
8689 }
8690
8691 /* Otherwise, parse and supply the value. */
8692 p = buf;
8693 i = 0;
8694 while (p[0] != 0)
8695 {
8696 if (p[1] == 0)
8697 error (_("fetch_register_using_p: early buf termination"));
8698
8699 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8700 p += 2;
8701 }
8702 regcache->raw_supply (reg->regnum, regp);
8703 return 1;
8704 }
8705
8706 /* Fetch the registers included in the target's 'g' packet. */
8707
8708 int
8709 remote_target::send_g_packet ()
8710 {
8711 struct remote_state *rs = get_remote_state ();
8712 int buf_len;
8713
8714 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8715 putpkt (rs->buf);
8716 getpkt (&rs->buf);
8717 if (packet_check_result (rs->buf) == PACKET_ERROR)
8718 error (_("Could not read registers; remote failure reply '%s'"),
8719 rs->buf.data ());
8720
8721 /* We can get out of synch in various cases. If the first character
8722 in the buffer is not a hex character, assume that has happened
8723 and try to fetch another packet to read. */
8724 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8725 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8726 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8727 && rs->buf[0] != 'x') /* New: unavailable register value. */
8728 {
8729 remote_debug_printf ("Bad register packet; fetching a new packet");
8730 getpkt (&rs->buf);
8731 }
8732
8733 buf_len = strlen (rs->buf.data ());
8734
8735 /* Sanity check the received packet. */
8736 if (buf_len % 2 != 0)
8737 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8738
8739 return buf_len / 2;
8740 }
8741
8742 void
8743 remote_target::process_g_packet (struct regcache *regcache)
8744 {
8745 struct gdbarch *gdbarch = regcache->arch ();
8746 struct remote_state *rs = get_remote_state ();
8747 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8748 int i, buf_len;
8749 char *p;
8750 char *regs;
8751
8752 buf_len = strlen (rs->buf.data ());
8753
8754 /* Further sanity checks, with knowledge of the architecture. */
8755 if (buf_len > 2 * rsa->sizeof_g_packet)
8756 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8757 "bytes): %s"),
8758 rsa->sizeof_g_packet, buf_len / 2,
8759 rs->buf.data ());
8760
8761 /* Save the size of the packet sent to us by the target. It is used
8762 as a heuristic when determining the max size of packets that the
8763 target can safely receive. */
8764 if (rsa->actual_register_packet_size == 0)
8765 rsa->actual_register_packet_size = buf_len;
8766
8767 /* If this is smaller than we guessed the 'g' packet would be,
8768 update our records. A 'g' reply that doesn't include a register's
8769 value implies either that the register is not available, or that
8770 the 'p' packet must be used. */
8771 if (buf_len < 2 * rsa->sizeof_g_packet)
8772 {
8773 long sizeof_g_packet = buf_len / 2;
8774
8775 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8776 {
8777 long offset = rsa->regs[i].offset;
8778 long reg_size = register_size (gdbarch, i);
8779
8780 if (rsa->regs[i].pnum == -1)
8781 continue;
8782
8783 if (offset >= sizeof_g_packet)
8784 rsa->regs[i].in_g_packet = 0;
8785 else if (offset + reg_size > sizeof_g_packet)
8786 error (_("Truncated register %d in remote 'g' packet"), i);
8787 else
8788 rsa->regs[i].in_g_packet = 1;
8789 }
8790
8791 /* Looks valid enough, we can assume this is the correct length
8792 for a 'g' packet. It's important not to adjust
8793 rsa->sizeof_g_packet if we have truncated registers otherwise
8794 this "if" won't be run the next time the method is called
8795 with a packet of the same size and one of the internal errors
8796 below will trigger instead. */
8797 rsa->sizeof_g_packet = sizeof_g_packet;
8798 }
8799
8800 regs = (char *) alloca (rsa->sizeof_g_packet);
8801
8802 /* Unimplemented registers read as all bits zero. */
8803 memset (regs, 0, rsa->sizeof_g_packet);
8804
8805 /* Reply describes registers byte by byte, each byte encoded as two
8806 hex characters. Suck them all up, then supply them to the
8807 register cacheing/storage mechanism. */
8808
8809 p = rs->buf.data ();
8810 for (i = 0; i < rsa->sizeof_g_packet; i++)
8811 {
8812 if (p[0] == 0 || p[1] == 0)
8813 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8814 internal_error (_("unexpected end of 'g' packet reply"));
8815
8816 if (p[0] == 'x' && p[1] == 'x')
8817 regs[i] = 0; /* 'x' */
8818 else
8819 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8820 p += 2;
8821 }
8822
8823 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8824 {
8825 struct packet_reg *r = &rsa->regs[i];
8826 long reg_size = register_size (gdbarch, i);
8827
8828 if (r->in_g_packet)
8829 {
8830 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8831 /* This shouldn't happen - we adjusted in_g_packet above. */
8832 internal_error (_("unexpected end of 'g' packet reply"));
8833 else if (rs->buf[r->offset * 2] == 'x')
8834 {
8835 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8836 /* The register isn't available, mark it as such (at
8837 the same time setting the value to zero). */
8838 regcache->raw_supply (r->regnum, NULL);
8839 }
8840 else
8841 regcache->raw_supply (r->regnum, regs + r->offset);
8842 }
8843 }
8844 }
8845
8846 void
8847 remote_target::fetch_registers_using_g (struct regcache *regcache)
8848 {
8849 send_g_packet ();
8850 process_g_packet (regcache);
8851 }
8852
8853 /* Make the remote selected traceframe match GDB's selected
8854 traceframe. */
8855
8856 void
8857 remote_target::set_remote_traceframe ()
8858 {
8859 int newnum;
8860 struct remote_state *rs = get_remote_state ();
8861
8862 if (rs->remote_traceframe_number == get_traceframe_number ())
8863 return;
8864
8865 /* Avoid recursion, remote_trace_find calls us again. */
8866 rs->remote_traceframe_number = get_traceframe_number ();
8867
8868 newnum = target_trace_find (tfind_number,
8869 get_traceframe_number (), 0, 0, NULL);
8870
8871 /* Should not happen. If it does, all bets are off. */
8872 if (newnum != get_traceframe_number ())
8873 warning (_("could not set remote traceframe"));
8874 }
8875
8876 void
8877 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8878 {
8879 struct gdbarch *gdbarch = regcache->arch ();
8880 struct remote_state *rs = get_remote_state ();
8881 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8882 int i;
8883
8884 set_remote_traceframe ();
8885 set_general_thread (regcache->ptid ());
8886
8887 if (regnum >= 0)
8888 {
8889 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8890
8891 gdb_assert (reg != NULL);
8892
8893 /* If this register might be in the 'g' packet, try that first -
8894 we are likely to read more than one register. If this is the
8895 first 'g' packet, we might be overly optimistic about its
8896 contents, so fall back to 'p'. */
8897 if (reg->in_g_packet)
8898 {
8899 fetch_registers_using_g (regcache);
8900 if (reg->in_g_packet)
8901 return;
8902 }
8903
8904 if (fetch_register_using_p (regcache, reg))
8905 return;
8906
8907 /* This register is not available. */
8908 regcache->raw_supply (reg->regnum, NULL);
8909
8910 return;
8911 }
8912
8913 fetch_registers_using_g (regcache);
8914
8915 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8916 if (!rsa->regs[i].in_g_packet)
8917 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8918 {
8919 /* This register is not available. */
8920 regcache->raw_supply (i, NULL);
8921 }
8922 }
8923
8924 /* Prepare to store registers. Since we may send them all (using a
8925 'G' request), we have to read out the ones we don't want to change
8926 first. */
8927
8928 void
8929 remote_target::prepare_to_store (struct regcache *regcache)
8930 {
8931 struct remote_state *rs = get_remote_state ();
8932 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8933 int i;
8934
8935 /* Make sure the entire registers array is valid. */
8936 switch (m_features.packet_support (PACKET_P))
8937 {
8938 case PACKET_DISABLE:
8939 case PACKET_SUPPORT_UNKNOWN:
8940 /* Make sure all the necessary registers are cached. */
8941 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8942 if (rsa->regs[i].in_g_packet)
8943 regcache->raw_update (rsa->regs[i].regnum);
8944 break;
8945 case PACKET_ENABLE:
8946 break;
8947 }
8948 }
8949
8950 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8951 packet was not recognized. */
8952
8953 int
8954 remote_target::store_register_using_P (const struct regcache *regcache,
8955 packet_reg *reg)
8956 {
8957 struct gdbarch *gdbarch = regcache->arch ();
8958 struct remote_state *rs = get_remote_state ();
8959 /* Try storing a single register. */
8960 char *buf = rs->buf.data ();
8961 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8962 char *p;
8963
8964 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8965 return 0;
8966
8967 if (reg->pnum == -1)
8968 return 0;
8969
8970 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8971 p = buf + strlen (buf);
8972 regcache->raw_collect (reg->regnum, regp);
8973 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8974 putpkt (rs->buf);
8975 getpkt (&rs->buf);
8976
8977 switch (m_features.packet_ok (rs->buf, PACKET_P))
8978 {
8979 case PACKET_OK:
8980 return 1;
8981 case PACKET_ERROR:
8982 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8983 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8984 case PACKET_UNKNOWN:
8985 return 0;
8986 default:
8987 internal_error (_("Bad result from packet_ok"));
8988 }
8989 }
8990
8991 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8992 contents of the register cache buffer. FIXME: ignores errors. */
8993
8994 void
8995 remote_target::store_registers_using_G (const struct regcache *regcache)
8996 {
8997 struct remote_state *rs = get_remote_state ();
8998 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8999 gdb_byte *regs;
9000 char *p;
9001
9002 /* Extract all the registers in the regcache copying them into a
9003 local buffer. */
9004 {
9005 int i;
9006
9007 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9008 memset (regs, 0, rsa->sizeof_g_packet);
9009 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9010 {
9011 struct packet_reg *r = &rsa->regs[i];
9012
9013 if (r->in_g_packet)
9014 regcache->raw_collect (r->regnum, regs + r->offset);
9015 }
9016 }
9017
9018 /* Command describes registers byte by byte,
9019 each byte encoded as two hex characters. */
9020 p = rs->buf.data ();
9021 *p++ = 'G';
9022 bin2hex (regs, p, rsa->sizeof_g_packet);
9023 putpkt (rs->buf);
9024 getpkt (&rs->buf);
9025 if (packet_check_result (rs->buf) == PACKET_ERROR)
9026 error (_("Could not write registers; remote failure reply '%s'"),
9027 rs->buf.data ());
9028 }
9029
9030 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9031 of the register cache buffer. FIXME: ignores errors. */
9032
9033 void
9034 remote_target::store_registers (struct regcache *regcache, int regnum)
9035 {
9036 struct gdbarch *gdbarch = regcache->arch ();
9037 struct remote_state *rs = get_remote_state ();
9038 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9039 int i;
9040
9041 set_remote_traceframe ();
9042 set_general_thread (regcache->ptid ());
9043
9044 if (regnum >= 0)
9045 {
9046 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9047
9048 gdb_assert (reg != NULL);
9049
9050 /* Always prefer to store registers using the 'P' packet if
9051 possible; we often change only a small number of registers.
9052 Sometimes we change a larger number; we'd need help from a
9053 higher layer to know to use 'G'. */
9054 if (store_register_using_P (regcache, reg))
9055 return;
9056
9057 /* For now, don't complain if we have no way to write the
9058 register. GDB loses track of unavailable registers too
9059 easily. Some day, this may be an error. We don't have
9060 any way to read the register, either... */
9061 if (!reg->in_g_packet)
9062 return;
9063
9064 store_registers_using_G (regcache);
9065 return;
9066 }
9067
9068 store_registers_using_G (regcache);
9069
9070 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9071 if (!rsa->regs[i].in_g_packet)
9072 if (!store_register_using_P (regcache, &rsa->regs[i]))
9073 /* See above for why we do not issue an error here. */
9074 continue;
9075 }
9076 \f
9077
9078 /* Return the number of hex digits in num. */
9079
9080 static int
9081 hexnumlen (ULONGEST num)
9082 {
9083 int i;
9084
9085 for (i = 0; num != 0; i++)
9086 num >>= 4;
9087
9088 return std::max (i, 1);
9089 }
9090
9091 /* Set BUF to the minimum number of hex digits representing NUM. */
9092
9093 static int
9094 hexnumstr (char *buf, ULONGEST num)
9095 {
9096 int len = hexnumlen (num);
9097
9098 return hexnumnstr (buf, num, len);
9099 }
9100
9101
9102 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9103
9104 static int
9105 hexnumnstr (char *buf, ULONGEST num, int width)
9106 {
9107 int i;
9108
9109 buf[width] = '\0';
9110
9111 for (i = width - 1; i >= 0; i--)
9112 {
9113 buf[i] = "0123456789abcdef"[(num & 0xf)];
9114 num >>= 4;
9115 }
9116
9117 return width;
9118 }
9119
9120 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9121
9122 static CORE_ADDR
9123 remote_address_masked (CORE_ADDR addr)
9124 {
9125 unsigned int address_size = remote_address_size;
9126
9127 /* If "remoteaddresssize" was not set, default to target address size. */
9128 if (!address_size)
9129 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9130
9131 if (address_size > 0
9132 && address_size < (sizeof (ULONGEST) * 8))
9133 {
9134 /* Only create a mask when that mask can safely be constructed
9135 in a ULONGEST variable. */
9136 ULONGEST mask = 1;
9137
9138 mask = (mask << address_size) - 1;
9139 addr &= mask;
9140 }
9141 return addr;
9142 }
9143
9144 /* Determine whether the remote target supports binary downloading.
9145 This is accomplished by sending a no-op memory write of zero length
9146 to the target at the specified address. It does not suffice to send
9147 the whole packet, since many stubs strip the eighth bit and
9148 subsequently compute a wrong checksum, which causes real havoc with
9149 remote_write_bytes.
9150
9151 NOTE: This can still lose if the serial line is not eight-bit
9152 clean. In cases like this, the user should clear "remote
9153 X-packet". */
9154
9155 void
9156 remote_target::check_binary_download (CORE_ADDR addr)
9157 {
9158 struct remote_state *rs = get_remote_state ();
9159
9160 switch (m_features.packet_support (PACKET_X))
9161 {
9162 case PACKET_DISABLE:
9163 break;
9164 case PACKET_ENABLE:
9165 break;
9166 case PACKET_SUPPORT_UNKNOWN:
9167 {
9168 char *p;
9169
9170 p = rs->buf.data ();
9171 *p++ = 'X';
9172 p += hexnumstr (p, (ULONGEST) addr);
9173 *p++ = ',';
9174 p += hexnumstr (p, (ULONGEST) 0);
9175 *p++ = ':';
9176 *p = '\0';
9177
9178 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9179 getpkt (&rs->buf);
9180
9181 if (rs->buf[0] == '\0')
9182 {
9183 remote_debug_printf ("binary downloading NOT supported by target");
9184 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9185 }
9186 else
9187 {
9188 remote_debug_printf ("binary downloading supported by target");
9189 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9190 }
9191 break;
9192 }
9193 }
9194 }
9195
9196 /* Helper function to resize the payload in order to try to get a good
9197 alignment. We try to write an amount of data such that the next write will
9198 start on an address aligned on REMOTE_ALIGN_WRITES. */
9199
9200 static int
9201 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9202 {
9203 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9204 }
9205
9206 /* Write memory data directly to the remote machine.
9207 This does not inform the data cache; the data cache uses this.
9208 HEADER is the starting part of the packet.
9209 MEMADDR is the address in the remote memory space.
9210 MYADDR is the address of the buffer in our space.
9211 LEN_UNITS is the number of addressable units to write.
9212 UNIT_SIZE is the length in bytes of an addressable unit.
9213 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9214 should send data as binary ('X'), or hex-encoded ('M').
9215
9216 The function creates packet of the form
9217 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9218
9219 where encoding of <DATA> is terminated by PACKET_FORMAT.
9220
9221 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9222 are omitted.
9223
9224 Return the transferred status, error or OK (an
9225 'enum target_xfer_status' value). Save the number of addressable units
9226 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9227
9228 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9229 exchange between gdb and the stub could look like (?? in place of the
9230 checksum):
9231
9232 -> $m1000,4#??
9233 <- aaaabbbbccccdddd
9234
9235 -> $M1000,3:eeeeffffeeee#??
9236 <- OK
9237
9238 -> $m1000,4#??
9239 <- eeeeffffeeeedddd */
9240
9241 target_xfer_status
9242 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9243 const gdb_byte *myaddr,
9244 ULONGEST len_units,
9245 int unit_size,
9246 ULONGEST *xfered_len_units,
9247 char packet_format, int use_length)
9248 {
9249 struct remote_state *rs = get_remote_state ();
9250 char *p;
9251 char *plen = NULL;
9252 int plenlen = 0;
9253 int todo_units;
9254 int units_written;
9255 int payload_capacity_bytes;
9256 int payload_length_bytes;
9257
9258 if (packet_format != 'X' && packet_format != 'M')
9259 internal_error (_("remote_write_bytes_aux: bad packet format"));
9260
9261 if (len_units == 0)
9262 return TARGET_XFER_EOF;
9263
9264 payload_capacity_bytes = get_memory_write_packet_size ();
9265
9266 /* The packet buffer will be large enough for the payload;
9267 get_memory_packet_size ensures this. */
9268 rs->buf[0] = '\0';
9269
9270 /* Compute the size of the actual payload by subtracting out the
9271 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9272
9273 payload_capacity_bytes -= strlen ("$,:#NN");
9274 if (!use_length)
9275 /* The comma won't be used. */
9276 payload_capacity_bytes += 1;
9277 payload_capacity_bytes -= strlen (header);
9278 payload_capacity_bytes -= hexnumlen (memaddr);
9279
9280 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9281
9282 strcat (rs->buf.data (), header);
9283 p = rs->buf.data () + strlen (header);
9284
9285 /* Compute a best guess of the number of bytes actually transfered. */
9286 if (packet_format == 'X')
9287 {
9288 /* Best guess at number of bytes that will fit. */
9289 todo_units = std::min (len_units,
9290 (ULONGEST) payload_capacity_bytes / unit_size);
9291 if (use_length)
9292 payload_capacity_bytes -= hexnumlen (todo_units);
9293 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9294 }
9295 else
9296 {
9297 /* Number of bytes that will fit. */
9298 todo_units
9299 = std::min (len_units,
9300 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9301 if (use_length)
9302 payload_capacity_bytes -= hexnumlen (todo_units);
9303 todo_units = std::min (todo_units,
9304 (payload_capacity_bytes / unit_size) / 2);
9305 }
9306
9307 if (todo_units <= 0)
9308 internal_error (_("minimum packet size too small to write data"));
9309
9310 /* If we already need another packet, then try to align the end
9311 of this packet to a useful boundary. */
9312 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9313 todo_units = align_for_efficient_write (todo_units, memaddr);
9314
9315 /* Append "<memaddr>". */
9316 memaddr = remote_address_masked (memaddr);
9317 p += hexnumstr (p, (ULONGEST) memaddr);
9318
9319 if (use_length)
9320 {
9321 /* Append ",". */
9322 *p++ = ',';
9323
9324 /* Append the length and retain its location and size. It may need to be
9325 adjusted once the packet body has been created. */
9326 plen = p;
9327 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9328 p += plenlen;
9329 }
9330
9331 /* Append ":". */
9332 *p++ = ':';
9333 *p = '\0';
9334
9335 /* Append the packet body. */
9336 if (packet_format == 'X')
9337 {
9338 /* Binary mode. Send target system values byte by byte, in
9339 increasing byte addresses. Only escape certain critical
9340 characters. */
9341 payload_length_bytes =
9342 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9343 &units_written, payload_capacity_bytes);
9344
9345 /* If not all TODO units fit, then we'll need another packet. Make
9346 a second try to keep the end of the packet aligned. Don't do
9347 this if the packet is tiny. */
9348 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9349 {
9350 int new_todo_units;
9351
9352 new_todo_units = align_for_efficient_write (units_written, memaddr);
9353
9354 if (new_todo_units != units_written)
9355 payload_length_bytes =
9356 remote_escape_output (myaddr, new_todo_units, unit_size,
9357 (gdb_byte *) p, &units_written,
9358 payload_capacity_bytes);
9359 }
9360
9361 p += payload_length_bytes;
9362 if (use_length && units_written < todo_units)
9363 {
9364 /* Escape chars have filled up the buffer prematurely,
9365 and we have actually sent fewer units than planned.
9366 Fix-up the length field of the packet. Use the same
9367 number of characters as before. */
9368 plen += hexnumnstr (plen, (ULONGEST) units_written,
9369 plenlen);
9370 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9371 }
9372 }
9373 else
9374 {
9375 /* Normal mode: Send target system values byte by byte, in
9376 increasing byte addresses. Each byte is encoded as a two hex
9377 value. */
9378 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9379 units_written = todo_units;
9380 }
9381
9382 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9383 getpkt (&rs->buf);
9384
9385 if (rs->buf[0] == 'E')
9386 return TARGET_XFER_E_IO;
9387
9388 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9389 send fewer units than we'd planned. */
9390 *xfered_len_units = (ULONGEST) units_written;
9391 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9392 }
9393
9394 /* Write memory data directly to the remote machine.
9395 This does not inform the data cache; the data cache uses this.
9396 MEMADDR is the address in the remote memory space.
9397 MYADDR is the address of the buffer in our space.
9398 LEN is the number of bytes.
9399
9400 Return the transferred status, error or OK (an
9401 'enum target_xfer_status' value). Save the number of bytes
9402 transferred in *XFERED_LEN. Only transfer a single packet. */
9403
9404 target_xfer_status
9405 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9406 ULONGEST len, int unit_size,
9407 ULONGEST *xfered_len)
9408 {
9409 const char *packet_format = NULL;
9410
9411 /* Check whether the target supports binary download. */
9412 check_binary_download (memaddr);
9413
9414 switch (m_features.packet_support (PACKET_X))
9415 {
9416 case PACKET_ENABLE:
9417 packet_format = "X";
9418 break;
9419 case PACKET_DISABLE:
9420 packet_format = "M";
9421 break;
9422 case PACKET_SUPPORT_UNKNOWN:
9423 internal_error (_("remote_write_bytes: bad internal state"));
9424 default:
9425 internal_error (_("bad switch"));
9426 }
9427
9428 return remote_write_bytes_aux (packet_format,
9429 memaddr, myaddr, len, unit_size, xfered_len,
9430 packet_format[0], 1);
9431 }
9432
9433 /* Read memory data directly from the remote machine.
9434 This does not use the data cache; the data cache uses this.
9435 MEMADDR is the address in the remote memory space.
9436 MYADDR is the address of the buffer in our space.
9437 LEN_UNITS is the number of addressable memory units to read..
9438 UNIT_SIZE is the length in bytes of an addressable unit.
9439
9440 Return the transferred status, error or OK (an
9441 'enum target_xfer_status' value). Save the number of bytes
9442 transferred in *XFERED_LEN_UNITS.
9443
9444 See the comment of remote_write_bytes_aux for an example of
9445 memory read/write exchange between gdb and the stub. */
9446
9447 target_xfer_status
9448 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9449 ULONGEST len_units,
9450 int unit_size, ULONGEST *xfered_len_units)
9451 {
9452 struct remote_state *rs = get_remote_state ();
9453 int buf_size_bytes; /* Max size of packet output buffer. */
9454 char *p;
9455 int todo_units;
9456 int decoded_bytes;
9457
9458 buf_size_bytes = get_memory_read_packet_size ();
9459 /* The packet buffer will be large enough for the payload;
9460 get_memory_packet_size ensures this. */
9461
9462 /* Number of units that will fit. */
9463 todo_units = std::min (len_units,
9464 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9465
9466 /* Construct "m"<memaddr>","<len>". */
9467 memaddr = remote_address_masked (memaddr);
9468 p = rs->buf.data ();
9469 *p++ = 'm';
9470 p += hexnumstr (p, (ULONGEST) memaddr);
9471 *p++ = ',';
9472 p += hexnumstr (p, (ULONGEST) todo_units);
9473 *p = '\0';
9474 putpkt (rs->buf);
9475 getpkt (&rs->buf);
9476 if (rs->buf[0] == 'E'
9477 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9478 && rs->buf[3] == '\0')
9479 return TARGET_XFER_E_IO;
9480 /* Reply describes memory byte by byte, each byte encoded as two hex
9481 characters. */
9482 p = rs->buf.data ();
9483 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9484 /* Return what we have. Let higher layers handle partial reads. */
9485 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9486 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9487 }
9488
9489 /* Using the set of read-only target sections of remote, read live
9490 read-only memory.
9491
9492 For interface/parameters/return description see target.h,
9493 to_xfer_partial. */
9494
9495 target_xfer_status
9496 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9497 ULONGEST memaddr,
9498 ULONGEST len,
9499 int unit_size,
9500 ULONGEST *xfered_len)
9501 {
9502 const struct target_section *secp;
9503
9504 secp = target_section_by_addr (this, memaddr);
9505 if (secp != NULL
9506 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9507 {
9508 ULONGEST memend = memaddr + len;
9509
9510 const std::vector<target_section> *table
9511 = target_get_section_table (this);
9512 for (const target_section &p : *table)
9513 {
9514 if (memaddr >= p.addr)
9515 {
9516 if (memend <= p.endaddr)
9517 {
9518 /* Entire transfer is within this section. */
9519 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9520 xfered_len);
9521 }
9522 else if (memaddr >= p.endaddr)
9523 {
9524 /* This section ends before the transfer starts. */
9525 continue;
9526 }
9527 else
9528 {
9529 /* This section overlaps the transfer. Just do half. */
9530 len = p.endaddr - memaddr;
9531 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9532 xfered_len);
9533 }
9534 }
9535 }
9536 }
9537
9538 return TARGET_XFER_EOF;
9539 }
9540
9541 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9542 first if the requested memory is unavailable in traceframe.
9543 Otherwise, fall back to remote_read_bytes_1. */
9544
9545 target_xfer_status
9546 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9547 gdb_byte *myaddr, ULONGEST len, int unit_size,
9548 ULONGEST *xfered_len)
9549 {
9550 if (len == 0)
9551 return TARGET_XFER_EOF;
9552
9553 if (get_traceframe_number () != -1)
9554 {
9555 std::vector<mem_range> available;
9556
9557 /* If we fail to get the set of available memory, then the
9558 target does not support querying traceframe info, and so we
9559 attempt reading from the traceframe anyway (assuming the
9560 target implements the old QTro packet then). */
9561 if (traceframe_available_memory (&available, memaddr, len))
9562 {
9563 if (available.empty () || available[0].start != memaddr)
9564 {
9565 enum target_xfer_status res;
9566
9567 /* Don't read into the traceframe's available
9568 memory. */
9569 if (!available.empty ())
9570 {
9571 LONGEST oldlen = len;
9572
9573 len = available[0].start - memaddr;
9574 gdb_assert (len <= oldlen);
9575 }
9576
9577 /* This goes through the topmost target again. */
9578 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9579 len, unit_size, xfered_len);
9580 if (res == TARGET_XFER_OK)
9581 return TARGET_XFER_OK;
9582 else
9583 {
9584 /* No use trying further, we know some memory starting
9585 at MEMADDR isn't available. */
9586 *xfered_len = len;
9587 return (*xfered_len != 0) ?
9588 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9589 }
9590 }
9591
9592 /* Don't try to read more than how much is available, in
9593 case the target implements the deprecated QTro packet to
9594 cater for older GDBs (the target's knowledge of read-only
9595 sections may be outdated by now). */
9596 len = available[0].length;
9597 }
9598 }
9599
9600 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9601 }
9602
9603 \f
9604
9605 /* Sends a packet with content determined by the printf format string
9606 FORMAT and the remaining arguments, then gets the reply. Returns
9607 whether the packet was a success, a failure, or unknown. */
9608
9609 packet_result
9610 remote_target::remote_send_printf (const char *format, ...)
9611 {
9612 struct remote_state *rs = get_remote_state ();
9613 int max_size = get_remote_packet_size ();
9614 va_list ap;
9615
9616 va_start (ap, format);
9617
9618 rs->buf[0] = '\0';
9619 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9620
9621 va_end (ap);
9622
9623 if (size >= max_size)
9624 internal_error (_("Too long remote packet."));
9625
9626 if (putpkt (rs->buf) < 0)
9627 error (_("Communication problem with target."));
9628
9629 rs->buf[0] = '\0';
9630 getpkt (&rs->buf);
9631
9632 return packet_check_result (rs->buf);
9633 }
9634
9635 /* Flash writing can take quite some time. We'll set
9636 effectively infinite timeout for flash operations.
9637 In future, we'll need to decide on a better approach. */
9638 static const int remote_flash_timeout = 1000;
9639
9640 void
9641 remote_target::flash_erase (ULONGEST address, LONGEST length)
9642 {
9643 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9644 enum packet_result ret;
9645 scoped_restore restore_timeout
9646 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9647
9648 ret = remote_send_printf ("vFlashErase:%s,%s",
9649 phex (address, addr_size),
9650 phex (length, 4));
9651 switch (ret)
9652 {
9653 case PACKET_UNKNOWN:
9654 error (_("Remote target does not support flash erase"));
9655 case PACKET_ERROR:
9656 error (_("Error erasing flash with vFlashErase packet"));
9657 default:
9658 break;
9659 }
9660 }
9661
9662 target_xfer_status
9663 remote_target::remote_flash_write (ULONGEST address,
9664 ULONGEST length, ULONGEST *xfered_len,
9665 const gdb_byte *data)
9666 {
9667 scoped_restore restore_timeout
9668 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9669 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9670 xfered_len,'X', 0);
9671 }
9672
9673 void
9674 remote_target::flash_done ()
9675 {
9676 int ret;
9677
9678 scoped_restore restore_timeout
9679 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9680
9681 ret = remote_send_printf ("vFlashDone");
9682
9683 switch (ret)
9684 {
9685 case PACKET_UNKNOWN:
9686 error (_("Remote target does not support vFlashDone"));
9687 case PACKET_ERROR:
9688 error (_("Error finishing flash operation"));
9689 default:
9690 break;
9691 }
9692 }
9693
9694 \f
9695 /* Stuff for dealing with the packets which are part of this protocol.
9696 See comment at top of file for details. */
9697
9698 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9699 error to higher layers. Called when a serial error is detected.
9700 The exception message is STRING, followed by a colon and a blank,
9701 the system error message for errno at function entry and final dot
9702 for output compatibility with throw_perror_with_name. */
9703
9704 static void
9705 unpush_and_perror (remote_target *target, const char *string)
9706 {
9707 int saved_errno = errno;
9708
9709 remote_unpush_target (target);
9710 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9711 safe_strerror (saved_errno));
9712 }
9713
9714 /* Read a single character from the remote end. The current quit
9715 handler is overridden to avoid quitting in the middle of packet
9716 sequence, as that would break communication with the remote server.
9717 See remote_serial_quit_handler for more detail. */
9718
9719 int
9720 remote_target::readchar (int timeout)
9721 {
9722 int ch;
9723 struct remote_state *rs = get_remote_state ();
9724
9725 {
9726 scoped_restore restore_quit_target
9727 = make_scoped_restore (&curr_quit_handler_target, this);
9728 scoped_restore restore_quit
9729 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9730
9731 rs->got_ctrlc_during_io = 0;
9732
9733 ch = serial_readchar (rs->remote_desc, timeout);
9734
9735 if (rs->got_ctrlc_during_io)
9736 set_quit_flag ();
9737 }
9738
9739 if (ch >= 0)
9740 return ch;
9741
9742 switch ((enum serial_rc) ch)
9743 {
9744 case SERIAL_EOF:
9745 remote_unpush_target (this);
9746 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9747 /* no return */
9748 case SERIAL_ERROR:
9749 unpush_and_perror (this, _("Remote communication error. "
9750 "Target disconnected"));
9751 /* no return */
9752 case SERIAL_TIMEOUT:
9753 break;
9754 }
9755 return ch;
9756 }
9757
9758 /* Wrapper for serial_write that closes the target and throws if
9759 writing fails. The current quit handler is overridden to avoid
9760 quitting in the middle of packet sequence, as that would break
9761 communication with the remote server. See
9762 remote_serial_quit_handler for more detail. */
9763
9764 void
9765 remote_target::remote_serial_write (const char *str, int len)
9766 {
9767 struct remote_state *rs = get_remote_state ();
9768
9769 scoped_restore restore_quit_target
9770 = make_scoped_restore (&curr_quit_handler_target, this);
9771 scoped_restore restore_quit
9772 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9773
9774 rs->got_ctrlc_during_io = 0;
9775
9776 if (serial_write (rs->remote_desc, str, len))
9777 {
9778 unpush_and_perror (this, _("Remote communication error. "
9779 "Target disconnected"));
9780 }
9781
9782 if (rs->got_ctrlc_during_io)
9783 set_quit_flag ();
9784 }
9785
9786 /* Return a string representing an escaped version of BUF, of len N.
9787 E.g. \n is converted to \\n, \t to \\t, etc. */
9788
9789 static std::string
9790 escape_buffer (const char *buf, int n)
9791 {
9792 string_file stb;
9793
9794 stb.putstrn (buf, n, '\\');
9795 return stb.release ();
9796 }
9797
9798 int
9799 remote_target::putpkt (const char *buf)
9800 {
9801 return putpkt_binary (buf, strlen (buf));
9802 }
9803
9804 /* Wrapper around remote_target::putpkt to avoid exporting
9805 remote_target. */
9806
9807 int
9808 putpkt (remote_target *remote, const char *buf)
9809 {
9810 return remote->putpkt (buf);
9811 }
9812
9813 /* Send a packet to the remote machine, with error checking. The data
9814 of the packet is in BUF. The string in BUF can be at most
9815 get_remote_packet_size () - 5 to account for the $, # and checksum,
9816 and for a possible /0 if we are debugging (remote_debug) and want
9817 to print the sent packet as a string. */
9818
9819 int
9820 remote_target::putpkt_binary (const char *buf, int cnt)
9821 {
9822 struct remote_state *rs = get_remote_state ();
9823 int i;
9824 unsigned char csum = 0;
9825 gdb::def_vector<char> data (cnt + 6);
9826 char *buf2 = data.data ();
9827
9828 int ch;
9829 int tcount = 0;
9830 char *p;
9831
9832 /* Catch cases like trying to read memory or listing threads while
9833 we're waiting for a stop reply. The remote server wouldn't be
9834 ready to handle this request, so we'd hang and timeout. We don't
9835 have to worry about this in synchronous mode, because in that
9836 case it's not possible to issue a command while the target is
9837 running. This is not a problem in non-stop mode, because in that
9838 case, the stub is always ready to process serial input. */
9839 if (!target_is_non_stop_p ()
9840 && target_is_async_p ()
9841 && rs->waiting_for_stop_reply)
9842 {
9843 error (_("Cannot execute this command while the target is running.\n"
9844 "Use the \"interrupt\" command to stop the target\n"
9845 "and then try again."));
9846 }
9847
9848 /* Copy the packet into buffer BUF2, encapsulating it
9849 and giving it a checksum. */
9850
9851 p = buf2;
9852 *p++ = '$';
9853
9854 for (i = 0; i < cnt; i++)
9855 {
9856 csum += buf[i];
9857 *p++ = buf[i];
9858 }
9859 *p++ = '#';
9860 *p++ = tohex ((csum >> 4) & 0xf);
9861 *p++ = tohex (csum & 0xf);
9862
9863 /* Send it over and over until we get a positive ack. */
9864
9865 while (1)
9866 {
9867 if (remote_debug)
9868 {
9869 *p = '\0';
9870
9871 int len = (int) (p - buf2);
9872 int max_chars;
9873
9874 if (remote_packet_max_chars < 0)
9875 max_chars = len;
9876 else
9877 max_chars = remote_packet_max_chars;
9878
9879 std::string str
9880 = escape_buffer (buf2, std::min (len, max_chars));
9881
9882 if (len > max_chars)
9883 remote_debug_printf_nofunc
9884 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9885 len - max_chars);
9886 else
9887 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9888 }
9889 remote_serial_write (buf2, p - buf2);
9890
9891 /* If this is a no acks version of the remote protocol, send the
9892 packet and move on. */
9893 if (rs->noack_mode)
9894 break;
9895
9896 /* Read until either a timeout occurs (-2) or '+' is read.
9897 Handle any notification that arrives in the mean time. */
9898 while (1)
9899 {
9900 ch = readchar (remote_timeout);
9901
9902 switch (ch)
9903 {
9904 case '+':
9905 remote_debug_printf_nofunc ("Received Ack");
9906 return 1;
9907 case '-':
9908 remote_debug_printf_nofunc ("Received Nak");
9909 /* FALLTHROUGH */
9910 case SERIAL_TIMEOUT:
9911 tcount++;
9912 if (tcount > 3)
9913 return 0;
9914 break; /* Retransmit buffer. */
9915 case '$':
9916 {
9917 remote_debug_printf ("Packet instead of Ack, ignoring it");
9918 /* It's probably an old response sent because an ACK
9919 was lost. Gobble up the packet and ack it so it
9920 doesn't get retransmitted when we resend this
9921 packet. */
9922 skip_frame ();
9923 remote_serial_write ("+", 1);
9924 continue; /* Now, go look for +. */
9925 }
9926
9927 case '%':
9928 {
9929 int val;
9930
9931 /* If we got a notification, handle it, and go back to looking
9932 for an ack. */
9933 /* We've found the start of a notification. Now
9934 collect the data. */
9935 val = read_frame (&rs->buf);
9936 if (val >= 0)
9937 {
9938 remote_debug_printf_nofunc
9939 (" Notification received: %s",
9940 escape_buffer (rs->buf.data (), val).c_str ());
9941
9942 handle_notification (rs->notif_state, rs->buf.data ());
9943 /* We're in sync now, rewait for the ack. */
9944 tcount = 0;
9945 }
9946 else
9947 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9948 rs->buf.data ());
9949 continue;
9950 }
9951 /* fall-through */
9952 default:
9953 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9954 rs->buf.data ());
9955 continue;
9956 }
9957 break; /* Here to retransmit. */
9958 }
9959
9960 #if 0
9961 /* This is wrong. If doing a long backtrace, the user should be
9962 able to get out next time we call QUIT, without anything as
9963 violent as interrupt_query. If we want to provide a way out of
9964 here without getting to the next QUIT, it should be based on
9965 hitting ^C twice as in remote_wait. */
9966 if (quit_flag)
9967 {
9968 quit_flag = 0;
9969 interrupt_query ();
9970 }
9971 #endif
9972 }
9973
9974 return 0;
9975 }
9976
9977 /* Come here after finding the start of a frame when we expected an
9978 ack. Do our best to discard the rest of this packet. */
9979
9980 void
9981 remote_target::skip_frame ()
9982 {
9983 int c;
9984
9985 while (1)
9986 {
9987 c = readchar (remote_timeout);
9988 switch (c)
9989 {
9990 case SERIAL_TIMEOUT:
9991 /* Nothing we can do. */
9992 return;
9993 case '#':
9994 /* Discard the two bytes of checksum and stop. */
9995 c = readchar (remote_timeout);
9996 if (c >= 0)
9997 c = readchar (remote_timeout);
9998
9999 return;
10000 case '*': /* Run length encoding. */
10001 /* Discard the repeat count. */
10002 c = readchar (remote_timeout);
10003 if (c < 0)
10004 return;
10005 break;
10006 default:
10007 /* A regular character. */
10008 break;
10009 }
10010 }
10011 }
10012
10013 /* Come here after finding the start of the frame. Collect the rest
10014 into *BUF, verifying the checksum, length, and handling run-length
10015 compression. NUL terminate the buffer. If there is not enough room,
10016 expand *BUF.
10017
10018 Returns -1 on error, number of characters in buffer (ignoring the
10019 trailing NULL) on success. (could be extended to return one of the
10020 SERIAL status indications). */
10021
10022 long
10023 remote_target::read_frame (gdb::char_vector *buf_p)
10024 {
10025 unsigned char csum;
10026 long bc;
10027 int c;
10028 char *buf = buf_p->data ();
10029 struct remote_state *rs = get_remote_state ();
10030
10031 csum = 0;
10032 bc = 0;
10033
10034 while (1)
10035 {
10036 c = readchar (remote_timeout);
10037 switch (c)
10038 {
10039 case SERIAL_TIMEOUT:
10040 remote_debug_printf ("Timeout in mid-packet, retrying");
10041 return -1;
10042
10043 case '$':
10044 remote_debug_printf ("Saw new packet start in middle of old one");
10045 return -1; /* Start a new packet, count retries. */
10046
10047 case '#':
10048 {
10049 unsigned char pktcsum;
10050 int check_0 = 0;
10051 int check_1 = 0;
10052
10053 buf[bc] = '\0';
10054
10055 check_0 = readchar (remote_timeout);
10056 if (check_0 >= 0)
10057 check_1 = readchar (remote_timeout);
10058
10059 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10060 {
10061 remote_debug_printf ("Timeout in checksum, retrying");
10062 return -1;
10063 }
10064 else if (check_0 < 0 || check_1 < 0)
10065 {
10066 remote_debug_printf ("Communication error in checksum");
10067 return -1;
10068 }
10069
10070 /* Don't recompute the checksum; with no ack packets we
10071 don't have any way to indicate a packet retransmission
10072 is necessary. */
10073 if (rs->noack_mode)
10074 return bc;
10075
10076 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10077 if (csum == pktcsum)
10078 return bc;
10079
10080 remote_debug_printf
10081 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10082 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10083
10084 /* Number of characters in buffer ignoring trailing
10085 NULL. */
10086 return -1;
10087 }
10088 case '*': /* Run length encoding. */
10089 {
10090 int repeat;
10091
10092 csum += c;
10093 c = readchar (remote_timeout);
10094 csum += c;
10095 repeat = c - ' ' + 3; /* Compute repeat count. */
10096
10097 /* The character before ``*'' is repeated. */
10098
10099 if (repeat > 0 && repeat <= 255 && bc > 0)
10100 {
10101 if (bc + repeat - 1 >= buf_p->size () - 1)
10102 {
10103 /* Make some more room in the buffer. */
10104 buf_p->resize (buf_p->size () + repeat);
10105 buf = buf_p->data ();
10106 }
10107
10108 memset (&buf[bc], buf[bc - 1], repeat);
10109 bc += repeat;
10110 continue;
10111 }
10112
10113 buf[bc] = '\0';
10114 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10115 return -1;
10116 }
10117 default:
10118 if (bc >= buf_p->size () - 1)
10119 {
10120 /* Make some more room in the buffer. */
10121 buf_p->resize (buf_p->size () * 2);
10122 buf = buf_p->data ();
10123 }
10124
10125 buf[bc++] = c;
10126 csum += c;
10127 continue;
10128 }
10129 }
10130 }
10131
10132 /* Set this to the maximum number of seconds to wait instead of waiting forever
10133 in target_wait(). If this timer times out, then it generates an error and
10134 the command is aborted. This replaces most of the need for timeouts in the
10135 GDB test suite, and makes it possible to distinguish between a hung target
10136 and one with slow communications. */
10137
10138 static int watchdog = 0;
10139 static void
10140 show_watchdog (struct ui_file *file, int from_tty,
10141 struct cmd_list_element *c, const char *value)
10142 {
10143 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10144 }
10145
10146 /* Read a packet from the remote machine, with error checking, and
10147 store it in *BUF. Resize *BUF if necessary to hold the result. If
10148 FOREVER, wait forever rather than timing out; this is used (in
10149 synchronous mode) to wait for a target that is is executing user
10150 code to stop. If FOREVER == false, this function is allowed to time
10151 out gracefully and return an indication of this to the caller.
10152 Otherwise return the number of bytes read. If IS_NOTIF is not
10153 NULL, then consider receiving a notification enough reason to
10154 return to the caller. In this case, *IS_NOTIF is an output boolean
10155 that indicates whether *BUF holds a notification or not (a regular
10156 packet). */
10157
10158 int
10159 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10160 {
10161 struct remote_state *rs = get_remote_state ();
10162 int c;
10163 int tries;
10164 int timeout;
10165 int val = -1;
10166
10167 strcpy (buf->data (), "timeout");
10168
10169 if (forever)
10170 timeout = watchdog > 0 ? watchdog : -1;
10171 else if (is_notif != nullptr)
10172 timeout = 0; /* There should already be a char in the buffer. If
10173 not, bail out. */
10174 else
10175 timeout = remote_timeout;
10176
10177 #define MAX_TRIES 3
10178
10179 /* Process any number of notifications, and then return when
10180 we get a packet. */
10181 for (;;)
10182 {
10183 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10184 times. */
10185 for (tries = 1; tries <= MAX_TRIES; tries++)
10186 {
10187 /* This can loop forever if the remote side sends us
10188 characters continuously, but if it pauses, we'll get
10189 SERIAL_TIMEOUT from readchar because of timeout. Then
10190 we'll count that as a retry.
10191
10192 Note that even when forever is set, we will only wait
10193 forever prior to the start of a packet. After that, we
10194 expect characters to arrive at a brisk pace. They should
10195 show up within remote_timeout intervals. */
10196 do
10197 c = readchar (timeout);
10198 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10199
10200 if (c == SERIAL_TIMEOUT)
10201 {
10202 if (is_notif != nullptr)
10203 return -1; /* Don't complain, it's normal to not get
10204 anything in this case. */
10205
10206 if (forever) /* Watchdog went off? Kill the target. */
10207 {
10208 remote_unpush_target (this);
10209 throw_error (TARGET_CLOSE_ERROR,
10210 _("Watchdog timeout has expired. "
10211 "Target detached."));
10212 }
10213
10214 remote_debug_printf ("Timed out.");
10215 }
10216 else
10217 {
10218 /* We've found the start of a packet or notification.
10219 Now collect the data. */
10220 val = read_frame (buf);
10221 if (val >= 0)
10222 break;
10223 }
10224
10225 remote_serial_write ("-", 1);
10226 }
10227
10228 if (tries > MAX_TRIES)
10229 {
10230 /* We have tried hard enough, and just can't receive the
10231 packet/notification. Give up. */
10232 gdb_printf (_("Ignoring packet error, continuing...\n"));
10233
10234 /* Skip the ack char if we're in no-ack mode. */
10235 if (!rs->noack_mode)
10236 remote_serial_write ("+", 1);
10237 return -1;
10238 }
10239
10240 /* If we got an ordinary packet, return that to our caller. */
10241 if (c == '$')
10242 {
10243 if (remote_debug)
10244 {
10245 int max_chars;
10246
10247 if (remote_packet_max_chars < 0)
10248 max_chars = val;
10249 else
10250 max_chars = remote_packet_max_chars;
10251
10252 std::string str
10253 = escape_buffer (buf->data (),
10254 std::min (val, max_chars));
10255
10256 if (val > max_chars)
10257 remote_debug_printf_nofunc
10258 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10259 val - max_chars);
10260 else
10261 remote_debug_printf_nofunc ("Packet received: %s",
10262 str.c_str ());
10263 }
10264
10265 /* Skip the ack char if we're in no-ack mode. */
10266 if (!rs->noack_mode)
10267 remote_serial_write ("+", 1);
10268 if (is_notif != NULL)
10269 *is_notif = false;
10270 return val;
10271 }
10272
10273 /* If we got a notification, handle it, and go back to looking
10274 for a packet. */
10275 else
10276 {
10277 gdb_assert (c == '%');
10278
10279 remote_debug_printf_nofunc
10280 (" Notification received: %s",
10281 escape_buffer (buf->data (), val).c_str ());
10282
10283 if (is_notif != NULL)
10284 *is_notif = true;
10285
10286 handle_notification (rs->notif_state, buf->data ());
10287
10288 /* Notifications require no acknowledgement. */
10289
10290 if (is_notif != nullptr)
10291 return val;
10292 }
10293 }
10294 }
10295
10296 /* Kill any new fork children of inferior INF that haven't been
10297 processed by follow_fork. */
10298
10299 void
10300 remote_target::kill_new_fork_children (inferior *inf)
10301 {
10302 remote_state *rs = get_remote_state ();
10303 const notif_client *notif = &notif_client_stop;
10304
10305 /* Kill the fork child threads of any threads in inferior INF that are stopped
10306 at a fork event. */
10307 for (thread_info *thread : inf->non_exited_threads ())
10308 {
10309 const target_waitstatus *ws = thread_pending_fork_status (thread);
10310
10311 if (ws == nullptr)
10312 continue;
10313
10314 int child_pid = ws->child_ptid ().pid ();
10315 int res = remote_vkill (child_pid);
10316
10317 if (res != 0)
10318 error (_("Can't kill fork child process %d"), child_pid);
10319 }
10320
10321 /* Check for any pending fork events (not reported or processed yet)
10322 in inferior INF and kill those fork child threads as well. */
10323 remote_notif_get_pending_events (notif);
10324 for (auto &event : rs->stop_reply_queue)
10325 {
10326 if (event->ptid.pid () != inf->pid)
10327 continue;
10328
10329 if (!is_fork_status (event->ws.kind ()))
10330 continue;
10331
10332 int child_pid = event->ws.child_ptid ().pid ();
10333 int res = remote_vkill (child_pid);
10334
10335 if (res != 0)
10336 error (_("Can't kill fork child process %d"), child_pid);
10337 }
10338 }
10339
10340 \f
10341 /* Target hook to kill the current inferior. */
10342
10343 void
10344 remote_target::kill ()
10345 {
10346 int res = -1;
10347 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10348
10349 gdb_assert (inf != nullptr);
10350
10351 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10352 {
10353 /* If we're stopped while forking and we haven't followed yet,
10354 kill the child task. We need to do this before killing the
10355 parent task because if this is a vfork then the parent will
10356 be sleeping. */
10357 kill_new_fork_children (inf);
10358
10359 res = remote_vkill (inf->pid);
10360 if (res == 0)
10361 {
10362 target_mourn_inferior (inferior_ptid);
10363 return;
10364 }
10365 }
10366
10367 /* If we are in 'target remote' mode and we are killing the only
10368 inferior, then we will tell gdbserver to exit and unpush the
10369 target. */
10370 if (res == -1 && !m_features.remote_multi_process_p ()
10371 && number_of_live_inferiors (this) == 1)
10372 {
10373 remote_kill_k ();
10374
10375 /* We've killed the remote end, we get to mourn it. If we are
10376 not in extended mode, mourning the inferior also unpushes
10377 remote_ops from the target stack, which closes the remote
10378 connection. */
10379 target_mourn_inferior (inferior_ptid);
10380
10381 return;
10382 }
10383
10384 error (_("Can't kill process"));
10385 }
10386
10387 /* Send a kill request to the target using the 'vKill' packet. */
10388
10389 int
10390 remote_target::remote_vkill (int pid)
10391 {
10392 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10393 return -1;
10394
10395 remote_state *rs = get_remote_state ();
10396
10397 /* Tell the remote target to detach. */
10398 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10399 putpkt (rs->buf);
10400 getpkt (&rs->buf);
10401
10402 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10403 {
10404 case PACKET_OK:
10405 return 0;
10406 case PACKET_ERROR:
10407 return 1;
10408 case PACKET_UNKNOWN:
10409 return -1;
10410 default:
10411 internal_error (_("Bad result from packet_ok"));
10412 }
10413 }
10414
10415 /* Send a kill request to the target using the 'k' packet. */
10416
10417 void
10418 remote_target::remote_kill_k ()
10419 {
10420 /* Catch errors so the user can quit from gdb even when we
10421 aren't on speaking terms with the remote system. */
10422 try
10423 {
10424 putpkt ("k");
10425 }
10426 catch (const gdb_exception_error &ex)
10427 {
10428 if (ex.error == TARGET_CLOSE_ERROR)
10429 {
10430 /* If we got an (EOF) error that caused the target
10431 to go away, then we're done, that's what we wanted.
10432 "k" is susceptible to cause a premature EOF, given
10433 that the remote server isn't actually required to
10434 reply to "k", and it can happen that it doesn't
10435 even get to reply ACK to the "k". */
10436 return;
10437 }
10438
10439 /* Otherwise, something went wrong. We didn't actually kill
10440 the target. Just propagate the exception, and let the
10441 user or higher layers decide what to do. */
10442 throw;
10443 }
10444 }
10445
10446 void
10447 remote_target::mourn_inferior ()
10448 {
10449 struct remote_state *rs = get_remote_state ();
10450
10451 /* We're no longer interested in notification events of an inferior
10452 that exited or was killed/detached. */
10453 discard_pending_stop_replies (current_inferior ());
10454
10455 /* In 'target remote' mode with one inferior, we close the connection. */
10456 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10457 {
10458 remote_unpush_target (this);
10459 return;
10460 }
10461
10462 /* In case we got here due to an error, but we're going to stay
10463 connected. */
10464 rs->waiting_for_stop_reply = 0;
10465
10466 /* If the current general thread belonged to the process we just
10467 detached from or has exited, the remote side current general
10468 thread becomes undefined. Considering a case like this:
10469
10470 - We just got here due to a detach.
10471 - The process that we're detaching from happens to immediately
10472 report a global breakpoint being hit in non-stop mode, in the
10473 same thread we had selected before.
10474 - GDB attaches to this process again.
10475 - This event happens to be the next event we handle.
10476
10477 GDB would consider that the current general thread didn't need to
10478 be set on the stub side (with Hg), since for all it knew,
10479 GENERAL_THREAD hadn't changed.
10480
10481 Notice that although in all-stop mode, the remote server always
10482 sets the current thread to the thread reporting the stop event,
10483 that doesn't happen in non-stop mode; in non-stop, the stub *must
10484 not* change the current thread when reporting a breakpoint hit,
10485 due to the decoupling of event reporting and event handling.
10486
10487 To keep things simple, we always invalidate our notion of the
10488 current thread. */
10489 record_currthread (rs, minus_one_ptid);
10490
10491 /* Call common code to mark the inferior as not running. */
10492 generic_mourn_inferior ();
10493 }
10494
10495 bool
10496 extended_remote_target::supports_disable_randomization ()
10497 {
10498 return (m_features.packet_support (PACKET_QDisableRandomization)
10499 == PACKET_ENABLE);
10500 }
10501
10502 void
10503 remote_target::extended_remote_disable_randomization (int val)
10504 {
10505 struct remote_state *rs = get_remote_state ();
10506 char *reply;
10507
10508 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10509 "QDisableRandomization:%x", val);
10510 putpkt (rs->buf);
10511 reply = remote_get_noisy_reply ();
10512 if (*reply == '\0')
10513 error (_("Target does not support QDisableRandomization."));
10514 if (strcmp (reply, "OK") != 0)
10515 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10516 }
10517
10518 int
10519 remote_target::extended_remote_run (const std::string &args)
10520 {
10521 struct remote_state *rs = get_remote_state ();
10522 int len;
10523 const char *remote_exec_file = get_remote_exec_file ();
10524
10525 /* If the user has disabled vRun support, or we have detected that
10526 support is not available, do not try it. */
10527 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10528 return -1;
10529
10530 strcpy (rs->buf.data (), "vRun;");
10531 len = strlen (rs->buf.data ());
10532
10533 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10534 error (_("Remote file name too long for run packet"));
10535 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10536 strlen (remote_exec_file));
10537
10538 if (!args.empty ())
10539 {
10540 int i;
10541
10542 gdb_argv argv (args.c_str ());
10543 for (i = 0; argv[i] != NULL; i++)
10544 {
10545 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10546 error (_("Argument list too long for run packet"));
10547 rs->buf[len++] = ';';
10548 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10549 strlen (argv[i]));
10550 }
10551 }
10552
10553 rs->buf[len++] = '\0';
10554
10555 putpkt (rs->buf);
10556 getpkt (&rs->buf);
10557
10558 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10559 {
10560 case PACKET_OK:
10561 /* We have a wait response. All is well. */
10562 return 0;
10563 case PACKET_UNKNOWN:
10564 return -1;
10565 case PACKET_ERROR:
10566 if (remote_exec_file[0] == '\0')
10567 error (_("Running the default executable on the remote target failed; "
10568 "try \"set remote exec-file\"?"));
10569 else
10570 error (_("Running \"%s\" on the remote target failed"),
10571 remote_exec_file);
10572 default:
10573 gdb_assert_not_reached ("bad switch");
10574 }
10575 }
10576
10577 /* Helper function to send set/unset environment packets. ACTION is
10578 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10579 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10580 sent. */
10581
10582 void
10583 remote_target::send_environment_packet (const char *action,
10584 const char *packet,
10585 const char *value)
10586 {
10587 remote_state *rs = get_remote_state ();
10588
10589 /* Convert the environment variable to an hex string, which
10590 is the best format to be transmitted over the wire. */
10591 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10592 strlen (value));
10593
10594 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10595 "%s:%s", packet, encoded_value.c_str ());
10596
10597 putpkt (rs->buf);
10598 getpkt (&rs->buf);
10599 if (strcmp (rs->buf.data (), "OK") != 0)
10600 warning (_("Unable to %s environment variable '%s' on remote."),
10601 action, value);
10602 }
10603
10604 /* Helper function to handle the QEnvironment* packets. */
10605
10606 void
10607 remote_target::extended_remote_environment_support ()
10608 {
10609 remote_state *rs = get_remote_state ();
10610
10611 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10612 {
10613 putpkt ("QEnvironmentReset");
10614 getpkt (&rs->buf);
10615 if (strcmp (rs->buf.data (), "OK") != 0)
10616 warning (_("Unable to reset environment on remote."));
10617 }
10618
10619 gdb_environ *e = &current_inferior ()->environment;
10620
10621 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10622 != PACKET_DISABLE)
10623 {
10624 for (const std::string &el : e->user_set_env ())
10625 send_environment_packet ("set", "QEnvironmentHexEncoded",
10626 el.c_str ());
10627 }
10628
10629
10630 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10631 for (const std::string &el : e->user_unset_env ())
10632 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10633 }
10634
10635 /* Helper function to set the current working directory for the
10636 inferior in the remote target. */
10637
10638 void
10639 remote_target::extended_remote_set_inferior_cwd ()
10640 {
10641 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10642 {
10643 const std::string &inferior_cwd = current_inferior ()->cwd ();
10644 remote_state *rs = get_remote_state ();
10645
10646 if (!inferior_cwd.empty ())
10647 {
10648 std::string hexpath
10649 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10650 inferior_cwd.size ());
10651
10652 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10653 "QSetWorkingDir:%s", hexpath.c_str ());
10654 }
10655 else
10656 {
10657 /* An empty inferior_cwd means that the user wants us to
10658 reset the remote server's inferior's cwd. */
10659 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10660 "QSetWorkingDir:");
10661 }
10662
10663 putpkt (rs->buf);
10664 getpkt (&rs->buf);
10665 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10666 error (_("\
10667 Remote replied unexpectedly while setting the inferior's working\n\
10668 directory: %s"),
10669 rs->buf.data ());
10670
10671 }
10672 }
10673
10674 /* In the extended protocol we want to be able to do things like
10675 "run" and have them basically work as expected. So we need
10676 a special create_inferior function. We support changing the
10677 executable file and the command line arguments, but not the
10678 environment. */
10679
10680 void
10681 extended_remote_target::create_inferior (const char *exec_file,
10682 const std::string &args,
10683 char **env, int from_tty)
10684 {
10685 int run_worked;
10686 char *stop_reply;
10687 struct remote_state *rs = get_remote_state ();
10688 const char *remote_exec_file = get_remote_exec_file ();
10689
10690 /* If running asynchronously, register the target file descriptor
10691 with the event loop. */
10692 if (target_can_async_p ())
10693 target_async (true);
10694
10695 /* Disable address space randomization if requested (and supported). */
10696 if (supports_disable_randomization ())
10697 extended_remote_disable_randomization (disable_randomization);
10698
10699 /* If startup-with-shell is on, we inform gdbserver to start the
10700 remote inferior using a shell. */
10701 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10702 {
10703 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10704 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10705 putpkt (rs->buf);
10706 getpkt (&rs->buf);
10707 if (strcmp (rs->buf.data (), "OK") != 0)
10708 error (_("\
10709 Remote replied unexpectedly while setting startup-with-shell: %s"),
10710 rs->buf.data ());
10711 }
10712
10713 extended_remote_environment_support ();
10714
10715 extended_remote_set_inferior_cwd ();
10716
10717 /* Now restart the remote server. */
10718 run_worked = extended_remote_run (args) != -1;
10719 if (!run_worked)
10720 {
10721 /* vRun was not supported. Fail if we need it to do what the
10722 user requested. */
10723 if (remote_exec_file[0])
10724 error (_("Remote target does not support \"set remote exec-file\""));
10725 if (!args.empty ())
10726 error (_("Remote target does not support \"set args\" or run ARGS"));
10727
10728 /* Fall back to "R". */
10729 extended_remote_restart ();
10730 }
10731
10732 /* vRun's success return is a stop reply. */
10733 stop_reply = run_worked ? rs->buf.data () : NULL;
10734 add_current_inferior_and_thread (stop_reply);
10735
10736 /* Get updated offsets, if the stub uses qOffsets. */
10737 get_offsets ();
10738 }
10739 \f
10740
10741 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10742 the list of conditions (in agent expression bytecode format), if any, the
10743 target needs to evaluate. The output is placed into the packet buffer
10744 started from BUF and ended at BUF_END. */
10745
10746 static int
10747 remote_add_target_side_condition (struct gdbarch *gdbarch,
10748 struct bp_target_info *bp_tgt, char *buf,
10749 char *buf_end)
10750 {
10751 if (bp_tgt->conditions.empty ())
10752 return 0;
10753
10754 buf += strlen (buf);
10755 xsnprintf (buf, buf_end - buf, "%s", ";");
10756 buf++;
10757
10758 /* Send conditions to the target. */
10759 for (agent_expr *aexpr : bp_tgt->conditions)
10760 {
10761 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10762 buf += strlen (buf);
10763 for (int i = 0; i < aexpr->buf.size (); ++i)
10764 buf = pack_hex_byte (buf, aexpr->buf[i]);
10765 *buf = '\0';
10766 }
10767 return 0;
10768 }
10769
10770 static void
10771 remote_add_target_side_commands (struct gdbarch *gdbarch,
10772 struct bp_target_info *bp_tgt, char *buf)
10773 {
10774 if (bp_tgt->tcommands.empty ())
10775 return;
10776
10777 buf += strlen (buf);
10778
10779 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10780 buf += strlen (buf);
10781
10782 /* Concatenate all the agent expressions that are commands into the
10783 cmds parameter. */
10784 for (agent_expr *aexpr : bp_tgt->tcommands)
10785 {
10786 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10787 buf += strlen (buf);
10788 for (int i = 0; i < aexpr->buf.size (); ++i)
10789 buf = pack_hex_byte (buf, aexpr->buf[i]);
10790 *buf = '\0';
10791 }
10792 }
10793
10794 /* Insert a breakpoint. On targets that have software breakpoint
10795 support, we ask the remote target to do the work; on targets
10796 which don't, we insert a traditional memory breakpoint. */
10797
10798 int
10799 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10800 struct bp_target_info *bp_tgt)
10801 {
10802 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10803 If it succeeds, then set the support to PACKET_ENABLE. If it
10804 fails, and the user has explicitly requested the Z support then
10805 report an error, otherwise, mark it disabled and go on. */
10806
10807 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10808 {
10809 CORE_ADDR addr = bp_tgt->reqstd_address;
10810 struct remote_state *rs;
10811 char *p, *endbuf;
10812
10813 /* Make sure the remote is pointing at the right process, if
10814 necessary. */
10815 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10816 set_general_process ();
10817
10818 rs = get_remote_state ();
10819 p = rs->buf.data ();
10820 endbuf = p + get_remote_packet_size ();
10821
10822 *(p++) = 'Z';
10823 *(p++) = '0';
10824 *(p++) = ',';
10825 addr = (ULONGEST) remote_address_masked (addr);
10826 p += hexnumstr (p, addr);
10827 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10828
10829 if (supports_evaluation_of_breakpoint_conditions ())
10830 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10831
10832 if (can_run_breakpoint_commands ())
10833 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10834
10835 putpkt (rs->buf);
10836 getpkt (&rs->buf);
10837
10838 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10839 {
10840 case PACKET_ERROR:
10841 return -1;
10842 case PACKET_OK:
10843 return 0;
10844 case PACKET_UNKNOWN:
10845 break;
10846 }
10847 }
10848
10849 /* If this breakpoint has target-side commands but this stub doesn't
10850 support Z0 packets, throw error. */
10851 if (!bp_tgt->tcommands.empty ())
10852 throw_error (NOT_SUPPORTED_ERROR, _("\
10853 Target doesn't support breakpoints that have target side commands."));
10854
10855 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10856 }
10857
10858 int
10859 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10860 struct bp_target_info *bp_tgt,
10861 enum remove_bp_reason reason)
10862 {
10863 CORE_ADDR addr = bp_tgt->placed_address;
10864 struct remote_state *rs = get_remote_state ();
10865
10866 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10867 {
10868 char *p = rs->buf.data ();
10869 char *endbuf = p + get_remote_packet_size ();
10870
10871 /* Make sure the remote is pointing at the right process, if
10872 necessary. */
10873 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10874 set_general_process ();
10875
10876 *(p++) = 'z';
10877 *(p++) = '0';
10878 *(p++) = ',';
10879
10880 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10881 p += hexnumstr (p, addr);
10882 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10883
10884 putpkt (rs->buf);
10885 getpkt (&rs->buf);
10886
10887 return (rs->buf[0] == 'E');
10888 }
10889
10890 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10891 }
10892
10893 static enum Z_packet_type
10894 watchpoint_to_Z_packet (int type)
10895 {
10896 switch (type)
10897 {
10898 case hw_write:
10899 return Z_PACKET_WRITE_WP;
10900 break;
10901 case hw_read:
10902 return Z_PACKET_READ_WP;
10903 break;
10904 case hw_access:
10905 return Z_PACKET_ACCESS_WP;
10906 break;
10907 default:
10908 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10909 }
10910 }
10911
10912 int
10913 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10914 enum target_hw_bp_type type, struct expression *cond)
10915 {
10916 struct remote_state *rs = get_remote_state ();
10917 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10918 char *p;
10919 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10920
10921 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10922 + to_underlying (packet))) == PACKET_DISABLE)
10923 return 1;
10924
10925 /* Make sure the remote is pointing at the right process, if
10926 necessary. */
10927 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10928 set_general_process ();
10929
10930 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10931 p = strchr (rs->buf.data (), '\0');
10932 addr = remote_address_masked (addr);
10933 p += hexnumstr (p, (ULONGEST) addr);
10934 xsnprintf (p, endbuf - p, ",%x", len);
10935
10936 putpkt (rs->buf);
10937 getpkt (&rs->buf);
10938
10939 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10940 + to_underlying (packet))))
10941 {
10942 case PACKET_ERROR:
10943 return -1;
10944 case PACKET_UNKNOWN:
10945 return 1;
10946 case PACKET_OK:
10947 return 0;
10948 }
10949 internal_error (_("remote_insert_watchpoint: reached end of function"));
10950 }
10951
10952 bool
10953 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10954 CORE_ADDR start, int length)
10955 {
10956 CORE_ADDR diff = remote_address_masked (addr - start);
10957
10958 return diff < length;
10959 }
10960
10961
10962 int
10963 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10964 enum target_hw_bp_type type, struct expression *cond)
10965 {
10966 struct remote_state *rs = get_remote_state ();
10967 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10968 char *p;
10969 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10970
10971 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10972 + to_underlying (packet))) == PACKET_DISABLE)
10973 return -1;
10974
10975 /* Make sure the remote is pointing at the right process, if
10976 necessary. */
10977 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10978 set_general_process ();
10979
10980 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10981 p = strchr (rs->buf.data (), '\0');
10982 addr = remote_address_masked (addr);
10983 p += hexnumstr (p, (ULONGEST) addr);
10984 xsnprintf (p, endbuf - p, ",%x", len);
10985 putpkt (rs->buf);
10986 getpkt (&rs->buf);
10987
10988 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10989 + to_underlying (packet))))
10990 {
10991 case PACKET_ERROR:
10992 case PACKET_UNKNOWN:
10993 return -1;
10994 case PACKET_OK:
10995 return 0;
10996 }
10997 internal_error (_("remote_remove_watchpoint: reached end of function"));
10998 }
10999
11000
11001 static int remote_hw_watchpoint_limit = -1;
11002 static int remote_hw_watchpoint_length_limit = -1;
11003 static int remote_hw_breakpoint_limit = -1;
11004
11005 int
11006 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11007 {
11008 if (remote_hw_watchpoint_length_limit == 0)
11009 return 0;
11010 else if (remote_hw_watchpoint_length_limit < 0)
11011 return 1;
11012 else if (len <= remote_hw_watchpoint_length_limit)
11013 return 1;
11014 else
11015 return 0;
11016 }
11017
11018 int
11019 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11020 {
11021 if (type == bp_hardware_breakpoint)
11022 {
11023 if (remote_hw_breakpoint_limit == 0)
11024 return 0;
11025 else if (remote_hw_breakpoint_limit < 0)
11026 return 1;
11027 else if (cnt <= remote_hw_breakpoint_limit)
11028 return 1;
11029 }
11030 else
11031 {
11032 if (remote_hw_watchpoint_limit == 0)
11033 return 0;
11034 else if (remote_hw_watchpoint_limit < 0)
11035 return 1;
11036 else if (ot)
11037 return -1;
11038 else if (cnt <= remote_hw_watchpoint_limit)
11039 return 1;
11040 }
11041 return -1;
11042 }
11043
11044 /* The to_stopped_by_sw_breakpoint method of target remote. */
11045
11046 bool
11047 remote_target::stopped_by_sw_breakpoint ()
11048 {
11049 struct thread_info *thread = inferior_thread ();
11050
11051 return (thread->priv != NULL
11052 && (get_remote_thread_info (thread)->stop_reason
11053 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11054 }
11055
11056 /* The to_supports_stopped_by_sw_breakpoint method of target
11057 remote. */
11058
11059 bool
11060 remote_target::supports_stopped_by_sw_breakpoint ()
11061 {
11062 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11063 }
11064
11065 /* The to_stopped_by_hw_breakpoint method of target remote. */
11066
11067 bool
11068 remote_target::stopped_by_hw_breakpoint ()
11069 {
11070 struct thread_info *thread = inferior_thread ();
11071
11072 return (thread->priv != NULL
11073 && (get_remote_thread_info (thread)->stop_reason
11074 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11075 }
11076
11077 /* The to_supports_stopped_by_hw_breakpoint method of target
11078 remote. */
11079
11080 bool
11081 remote_target::supports_stopped_by_hw_breakpoint ()
11082 {
11083 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11084 }
11085
11086 bool
11087 remote_target::stopped_by_watchpoint ()
11088 {
11089 struct thread_info *thread = inferior_thread ();
11090
11091 return (thread->priv != NULL
11092 && (get_remote_thread_info (thread)->stop_reason
11093 == TARGET_STOPPED_BY_WATCHPOINT));
11094 }
11095
11096 bool
11097 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11098 {
11099 struct thread_info *thread = inferior_thread ();
11100
11101 if (thread->priv != NULL
11102 && (get_remote_thread_info (thread)->stop_reason
11103 == TARGET_STOPPED_BY_WATCHPOINT))
11104 {
11105 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11106 return true;
11107 }
11108
11109 return false;
11110 }
11111
11112
11113 int
11114 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11115 struct bp_target_info *bp_tgt)
11116 {
11117 CORE_ADDR addr = bp_tgt->reqstd_address;
11118 struct remote_state *rs;
11119 char *p, *endbuf;
11120 char *message;
11121
11122 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11123 return -1;
11124
11125 /* Make sure the remote is pointing at the right process, if
11126 necessary. */
11127 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11128 set_general_process ();
11129
11130 rs = get_remote_state ();
11131 p = rs->buf.data ();
11132 endbuf = p + get_remote_packet_size ();
11133
11134 *(p++) = 'Z';
11135 *(p++) = '1';
11136 *(p++) = ',';
11137
11138 addr = remote_address_masked (addr);
11139 p += hexnumstr (p, (ULONGEST) addr);
11140 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11141
11142 if (supports_evaluation_of_breakpoint_conditions ())
11143 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11144
11145 if (can_run_breakpoint_commands ())
11146 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11147
11148 putpkt (rs->buf);
11149 getpkt (&rs->buf);
11150
11151 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11152 {
11153 case PACKET_ERROR:
11154 if (rs->buf[1] == '.')
11155 {
11156 message = strchr (&rs->buf[2], '.');
11157 if (message)
11158 error (_("Remote failure reply: %s"), message + 1);
11159 }
11160 return -1;
11161 case PACKET_UNKNOWN:
11162 return -1;
11163 case PACKET_OK:
11164 return 0;
11165 }
11166 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11167 }
11168
11169
11170 int
11171 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11172 struct bp_target_info *bp_tgt)
11173 {
11174 CORE_ADDR addr;
11175 struct remote_state *rs = get_remote_state ();
11176 char *p = rs->buf.data ();
11177 char *endbuf = p + get_remote_packet_size ();
11178
11179 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11180 return -1;
11181
11182 /* Make sure the remote is pointing at the right process, if
11183 necessary. */
11184 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11185 set_general_process ();
11186
11187 *(p++) = 'z';
11188 *(p++) = '1';
11189 *(p++) = ',';
11190
11191 addr = remote_address_masked (bp_tgt->placed_address);
11192 p += hexnumstr (p, (ULONGEST) addr);
11193 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11194
11195 putpkt (rs->buf);
11196 getpkt (&rs->buf);
11197
11198 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11199 {
11200 case PACKET_ERROR:
11201 case PACKET_UNKNOWN:
11202 return -1;
11203 case PACKET_OK:
11204 return 0;
11205 }
11206 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11207 }
11208
11209 /* Verify memory using the "qCRC:" request. */
11210
11211 int
11212 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11213 {
11214 struct remote_state *rs = get_remote_state ();
11215 unsigned long host_crc, target_crc;
11216 char *tmp;
11217
11218 /* It doesn't make sense to use qCRC if the remote target is
11219 connected but not running. */
11220 if (target_has_execution ()
11221 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11222 {
11223 enum packet_result result;
11224
11225 /* Make sure the remote is pointing at the right process. */
11226 set_general_process ();
11227
11228 /* FIXME: assumes lma can fit into long. */
11229 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11230 (long) lma, (long) size);
11231 putpkt (rs->buf);
11232
11233 /* Be clever; compute the host_crc before waiting for target
11234 reply. */
11235 host_crc = xcrc32 (data, size, 0xffffffff);
11236
11237 getpkt (&rs->buf);
11238
11239 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11240 if (result == PACKET_ERROR)
11241 return -1;
11242 else if (result == PACKET_OK)
11243 {
11244 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11245 target_crc = target_crc * 16 + fromhex (*tmp);
11246
11247 return (host_crc == target_crc);
11248 }
11249 }
11250
11251 return simple_verify_memory (this, data, lma, size);
11252 }
11253
11254 /* compare-sections command
11255
11256 With no arguments, compares each loadable section in the exec bfd
11257 with the same memory range on the target, and reports mismatches.
11258 Useful for verifying the image on the target against the exec file. */
11259
11260 static void
11261 compare_sections_command (const char *args, int from_tty)
11262 {
11263 asection *s;
11264 const char *sectname;
11265 bfd_size_type size;
11266 bfd_vma lma;
11267 int matched = 0;
11268 int mismatched = 0;
11269 int res;
11270 int read_only = 0;
11271
11272 if (!current_program_space->exec_bfd ())
11273 error (_("command cannot be used without an exec file"));
11274
11275 if (args != NULL && strcmp (args, "-r") == 0)
11276 {
11277 read_only = 1;
11278 args = NULL;
11279 }
11280
11281 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11282 {
11283 if (!(s->flags & SEC_LOAD))
11284 continue; /* Skip non-loadable section. */
11285
11286 if (read_only && (s->flags & SEC_READONLY) == 0)
11287 continue; /* Skip writeable sections */
11288
11289 size = bfd_section_size (s);
11290 if (size == 0)
11291 continue; /* Skip zero-length section. */
11292
11293 sectname = bfd_section_name (s);
11294 if (args && strcmp (args, sectname) != 0)
11295 continue; /* Not the section selected by user. */
11296
11297 matched = 1; /* Do this section. */
11298 lma = s->lma;
11299
11300 gdb::byte_vector sectdata (size);
11301 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11302 sectdata.data (), 0, size);
11303
11304 res = target_verify_memory (sectdata.data (), lma, size);
11305
11306 if (res == -1)
11307 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11308 paddress (current_inferior ()->arch (), lma),
11309 paddress (current_inferior ()->arch (), lma + size));
11310
11311 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11312 paddress (current_inferior ()->arch (), lma),
11313 paddress (current_inferior ()->arch (), lma + size));
11314 if (res)
11315 gdb_printf ("matched.\n");
11316 else
11317 {
11318 gdb_printf ("MIS-MATCHED!\n");
11319 mismatched++;
11320 }
11321 }
11322 if (mismatched > 0)
11323 warning (_("One or more sections of the target image does "
11324 "not match the loaded file"));
11325 if (args && !matched)
11326 gdb_printf (_("No loaded section named '%s'.\n"), args);
11327 }
11328
11329 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11330 into remote target. The number of bytes written to the remote
11331 target is returned, or -1 for error. */
11332
11333 target_xfer_status
11334 remote_target::remote_write_qxfer (const char *object_name,
11335 const char *annex, const gdb_byte *writebuf,
11336 ULONGEST offset, LONGEST len,
11337 ULONGEST *xfered_len,
11338 const unsigned int which_packet)
11339 {
11340 int i, buf_len;
11341 ULONGEST n;
11342 struct remote_state *rs = get_remote_state ();
11343 int max_size = get_memory_write_packet_size ();
11344
11345 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11346 return TARGET_XFER_E_IO;
11347
11348 /* Insert header. */
11349 i = snprintf (rs->buf.data (), max_size,
11350 "qXfer:%s:write:%s:%s:",
11351 object_name, annex ? annex : "",
11352 phex_nz (offset, sizeof offset));
11353 max_size -= (i + 1);
11354
11355 /* Escape as much data as fits into rs->buf. */
11356 buf_len = remote_escape_output
11357 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11358
11359 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11360 || getpkt (&rs->buf) < 0
11361 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11362 return TARGET_XFER_E_IO;
11363
11364 unpack_varlen_hex (rs->buf.data (), &n);
11365
11366 *xfered_len = n;
11367 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11368 }
11369
11370 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11371 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11372 number of bytes read is returned, or 0 for EOF, or -1 for error.
11373 The number of bytes read may be less than LEN without indicating an
11374 EOF. PACKET is checked and updated to indicate whether the remote
11375 target supports this object. */
11376
11377 target_xfer_status
11378 remote_target::remote_read_qxfer (const char *object_name,
11379 const char *annex,
11380 gdb_byte *readbuf, ULONGEST offset,
11381 LONGEST len,
11382 ULONGEST *xfered_len,
11383 const unsigned int which_packet)
11384 {
11385 struct remote_state *rs = get_remote_state ();
11386 LONGEST i, n, packet_len;
11387
11388 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11389 return TARGET_XFER_E_IO;
11390
11391 /* Check whether we've cached an end-of-object packet that matches
11392 this request. */
11393 if (rs->finished_object)
11394 {
11395 if (strcmp (object_name, rs->finished_object) == 0
11396 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11397 && offset == rs->finished_offset)
11398 return TARGET_XFER_EOF;
11399
11400
11401 /* Otherwise, we're now reading something different. Discard
11402 the cache. */
11403 xfree (rs->finished_object);
11404 xfree (rs->finished_annex);
11405 rs->finished_object = NULL;
11406 rs->finished_annex = NULL;
11407 }
11408
11409 /* Request only enough to fit in a single packet. The actual data
11410 may not, since we don't know how much of it will need to be escaped;
11411 the target is free to respond with slightly less data. We subtract
11412 five to account for the response type and the protocol frame. */
11413 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11414 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11415 "qXfer:%s:read:%s:%s,%s",
11416 object_name, annex ? annex : "",
11417 phex_nz (offset, sizeof offset),
11418 phex_nz (n, sizeof n));
11419 i = putpkt (rs->buf);
11420 if (i < 0)
11421 return TARGET_XFER_E_IO;
11422
11423 rs->buf[0] = '\0';
11424 packet_len = getpkt (&rs->buf);
11425 if (packet_len < 0
11426 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11427 return TARGET_XFER_E_IO;
11428
11429 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11430 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11431
11432 /* 'm' means there is (or at least might be) more data after this
11433 batch. That does not make sense unless there's at least one byte
11434 of data in this reply. */
11435 if (rs->buf[0] == 'm' && packet_len == 1)
11436 error (_("Remote qXfer reply contained no data."));
11437
11438 /* Got some data. */
11439 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11440 packet_len - 1, readbuf, n);
11441
11442 /* 'l' is an EOF marker, possibly including a final block of data,
11443 or possibly empty. If we have the final block of a non-empty
11444 object, record this fact to bypass a subsequent partial read. */
11445 if (rs->buf[0] == 'l' && offset + i > 0)
11446 {
11447 rs->finished_object = xstrdup (object_name);
11448 rs->finished_annex = xstrdup (annex ? annex : "");
11449 rs->finished_offset = offset + i;
11450 }
11451
11452 if (i == 0)
11453 return TARGET_XFER_EOF;
11454 else
11455 {
11456 *xfered_len = i;
11457 return TARGET_XFER_OK;
11458 }
11459 }
11460
11461 enum target_xfer_status
11462 remote_target::xfer_partial (enum target_object object,
11463 const char *annex, gdb_byte *readbuf,
11464 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11465 ULONGEST *xfered_len)
11466 {
11467 struct remote_state *rs;
11468 int i;
11469 char *p2;
11470 char query_type;
11471 int unit_size
11472 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11473
11474 set_remote_traceframe ();
11475 set_general_thread (inferior_ptid);
11476
11477 rs = get_remote_state ();
11478
11479 /* Handle memory using the standard memory routines. */
11480 if (object == TARGET_OBJECT_MEMORY)
11481 {
11482 /* If the remote target is connected but not running, we should
11483 pass this request down to a lower stratum (e.g. the executable
11484 file). */
11485 if (!target_has_execution ())
11486 return TARGET_XFER_EOF;
11487
11488 if (writebuf != NULL)
11489 return remote_write_bytes (offset, writebuf, len, unit_size,
11490 xfered_len);
11491 else
11492 return remote_read_bytes (offset, readbuf, len, unit_size,
11493 xfered_len);
11494 }
11495
11496 /* Handle extra signal info using qxfer packets. */
11497 if (object == TARGET_OBJECT_SIGNAL_INFO)
11498 {
11499 if (readbuf)
11500 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11501 xfered_len, PACKET_qXfer_siginfo_read);
11502 else
11503 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11504 xfered_len, PACKET_qXfer_siginfo_write);
11505 }
11506
11507 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11508 {
11509 if (readbuf)
11510 return remote_read_qxfer ("statictrace", annex,
11511 readbuf, offset, len, xfered_len,
11512 PACKET_qXfer_statictrace_read);
11513 else
11514 return TARGET_XFER_E_IO;
11515 }
11516
11517 /* Only handle flash writes. */
11518 if (writebuf != NULL)
11519 {
11520 switch (object)
11521 {
11522 case TARGET_OBJECT_FLASH:
11523 return remote_flash_write (offset, len, xfered_len,
11524 writebuf);
11525
11526 default:
11527 return TARGET_XFER_E_IO;
11528 }
11529 }
11530
11531 /* Map pre-existing objects onto letters. DO NOT do this for new
11532 objects!!! Instead specify new query packets. */
11533 switch (object)
11534 {
11535 case TARGET_OBJECT_AVR:
11536 query_type = 'R';
11537 break;
11538
11539 case TARGET_OBJECT_AUXV:
11540 gdb_assert (annex == NULL);
11541 return remote_read_qxfer
11542 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11543
11544 case TARGET_OBJECT_AVAILABLE_FEATURES:
11545 return remote_read_qxfer
11546 ("features", annex, readbuf, offset, len, xfered_len,
11547 PACKET_qXfer_features);
11548
11549 case TARGET_OBJECT_LIBRARIES:
11550 return remote_read_qxfer
11551 ("libraries", annex, readbuf, offset, len, xfered_len,
11552 PACKET_qXfer_libraries);
11553
11554 case TARGET_OBJECT_LIBRARIES_SVR4:
11555 return remote_read_qxfer
11556 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11557 PACKET_qXfer_libraries_svr4);
11558
11559 case TARGET_OBJECT_MEMORY_MAP:
11560 gdb_assert (annex == NULL);
11561 return remote_read_qxfer
11562 ("memory-map", annex, readbuf, offset, len, xfered_len,
11563 PACKET_qXfer_memory_map);
11564
11565 case TARGET_OBJECT_OSDATA:
11566 /* Should only get here if we're connected. */
11567 gdb_assert (rs->remote_desc);
11568 return remote_read_qxfer
11569 ("osdata", annex, readbuf, offset, len, xfered_len,
11570 PACKET_qXfer_osdata);
11571
11572 case TARGET_OBJECT_THREADS:
11573 gdb_assert (annex == NULL);
11574 return remote_read_qxfer
11575 ("threads", annex, readbuf, offset, len, xfered_len,
11576 PACKET_qXfer_threads);
11577
11578 case TARGET_OBJECT_TRACEFRAME_INFO:
11579 gdb_assert (annex == NULL);
11580 return remote_read_qxfer
11581 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11582 PACKET_qXfer_traceframe_info);
11583
11584 case TARGET_OBJECT_FDPIC:
11585 return remote_read_qxfer
11586 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11587
11588 case TARGET_OBJECT_OPENVMS_UIB:
11589 return remote_read_qxfer
11590 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11591
11592 case TARGET_OBJECT_BTRACE:
11593 return remote_read_qxfer
11594 ("btrace", annex, readbuf, offset, len, xfered_len,
11595 PACKET_qXfer_btrace);
11596
11597 case TARGET_OBJECT_BTRACE_CONF:
11598 return remote_read_qxfer
11599 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11600 PACKET_qXfer_btrace_conf);
11601
11602 case TARGET_OBJECT_EXEC_FILE:
11603 return remote_read_qxfer
11604 ("exec-file", annex, readbuf, offset, len, xfered_len,
11605 PACKET_qXfer_exec_file);
11606
11607 default:
11608 return TARGET_XFER_E_IO;
11609 }
11610
11611 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11612 large enough let the caller deal with it. */
11613 if (len < get_remote_packet_size ())
11614 return TARGET_XFER_E_IO;
11615 len = get_remote_packet_size ();
11616
11617 /* Except for querying the minimum buffer size, target must be open. */
11618 if (!rs->remote_desc)
11619 error (_("remote query is only available after target open"));
11620
11621 gdb_assert (annex != NULL);
11622 gdb_assert (readbuf != NULL);
11623
11624 p2 = rs->buf.data ();
11625 *p2++ = 'q';
11626 *p2++ = query_type;
11627
11628 /* We used one buffer char for the remote protocol q command and
11629 another for the query type. As the remote protocol encapsulation
11630 uses 4 chars plus one extra in case we are debugging
11631 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11632 string. */
11633 i = 0;
11634 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11635 {
11636 /* Bad caller may have sent forbidden characters. */
11637 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11638 *p2++ = annex[i];
11639 i++;
11640 }
11641 *p2 = '\0';
11642 gdb_assert (annex[i] == '\0');
11643
11644 i = putpkt (rs->buf);
11645 if (i < 0)
11646 return TARGET_XFER_E_IO;
11647
11648 getpkt (&rs->buf);
11649 strcpy ((char *) readbuf, rs->buf.data ());
11650
11651 *xfered_len = strlen ((char *) readbuf);
11652 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11653 }
11654
11655 /* Implementation of to_get_memory_xfer_limit. */
11656
11657 ULONGEST
11658 remote_target::get_memory_xfer_limit ()
11659 {
11660 return get_memory_write_packet_size ();
11661 }
11662
11663 int
11664 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11665 const gdb_byte *pattern, ULONGEST pattern_len,
11666 CORE_ADDR *found_addrp)
11667 {
11668 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11669 struct remote_state *rs = get_remote_state ();
11670 int max_size = get_memory_write_packet_size ();
11671
11672 /* Number of packet bytes used to encode the pattern;
11673 this could be more than PATTERN_LEN due to escape characters. */
11674 int escaped_pattern_len;
11675 /* Amount of pattern that was encodable in the packet. */
11676 int used_pattern_len;
11677 int i;
11678 int found;
11679 ULONGEST found_addr;
11680
11681 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11682 {
11683 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11684 == len);
11685 };
11686
11687 /* Don't go to the target if we don't have to. This is done before
11688 checking packet_support to avoid the possibility that a success for this
11689 edge case means the facility works in general. */
11690 if (pattern_len > search_space_len)
11691 return 0;
11692 if (pattern_len == 0)
11693 {
11694 *found_addrp = start_addr;
11695 return 1;
11696 }
11697
11698 /* If we already know the packet isn't supported, fall back to the simple
11699 way of searching memory. */
11700
11701 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11702 {
11703 /* Target doesn't provided special support, fall back and use the
11704 standard support (copy memory and do the search here). */
11705 return simple_search_memory (read_memory, start_addr, search_space_len,
11706 pattern, pattern_len, found_addrp);
11707 }
11708
11709 /* Make sure the remote is pointing at the right process. */
11710 set_general_process ();
11711
11712 /* Insert header. */
11713 i = snprintf (rs->buf.data (), max_size,
11714 "qSearch:memory:%s;%s;",
11715 phex_nz (start_addr, addr_size),
11716 phex_nz (search_space_len, sizeof (search_space_len)));
11717 max_size -= (i + 1);
11718
11719 /* Escape as much data as fits into rs->buf. */
11720 escaped_pattern_len =
11721 remote_escape_output (pattern, pattern_len, 1,
11722 (gdb_byte *) rs->buf.data () + i,
11723 &used_pattern_len, max_size);
11724
11725 /* Bail if the pattern is too large. */
11726 if (used_pattern_len != pattern_len)
11727 error (_("Pattern is too large to transmit to remote target."));
11728
11729 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11730 || getpkt (&rs->buf) < 0
11731 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11732 {
11733 /* The request may not have worked because the command is not
11734 supported. If so, fall back to the simple way. */
11735 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11736 {
11737 return simple_search_memory (read_memory, start_addr, search_space_len,
11738 pattern, pattern_len, found_addrp);
11739 }
11740 return -1;
11741 }
11742
11743 if (rs->buf[0] == '0')
11744 found = 0;
11745 else if (rs->buf[0] == '1')
11746 {
11747 found = 1;
11748 if (rs->buf[1] != ',')
11749 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11750 unpack_varlen_hex (&rs->buf[2], &found_addr);
11751 *found_addrp = found_addr;
11752 }
11753 else
11754 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11755
11756 return found;
11757 }
11758
11759 void
11760 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11761 {
11762 struct remote_state *rs = get_remote_state ();
11763 char *p = rs->buf.data ();
11764
11765 if (!rs->remote_desc)
11766 error (_("remote rcmd is only available after target open"));
11767
11768 /* Send a NULL command across as an empty command. */
11769 if (command == NULL)
11770 command = "";
11771
11772 /* The query prefix. */
11773 strcpy (rs->buf.data (), "qRcmd,");
11774 p = strchr (rs->buf.data (), '\0');
11775
11776 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11777 > get_remote_packet_size ())
11778 error (_("\"monitor\" command ``%s'' is too long."), command);
11779
11780 /* Encode the actual command. */
11781 bin2hex ((const gdb_byte *) command, p, strlen (command));
11782
11783 if (putpkt (rs->buf) < 0)
11784 error (_("Communication problem with target."));
11785
11786 /* get/display the response */
11787 while (1)
11788 {
11789 char *buf;
11790
11791 /* XXX - see also remote_get_noisy_reply(). */
11792 QUIT; /* Allow user to bail out with ^C. */
11793 rs->buf[0] = '\0';
11794 if (getpkt (&rs->buf) == -1)
11795 {
11796 /* Timeout. Continue to (try to) read responses.
11797 This is better than stopping with an error, assuming the stub
11798 is still executing the (long) monitor command.
11799 If needed, the user can interrupt gdb using C-c, obtaining
11800 an effect similar to stop on timeout. */
11801 continue;
11802 }
11803 buf = rs->buf.data ();
11804 if (buf[0] == '\0')
11805 error (_("Target does not support this command."));
11806 if (buf[0] == 'O' && buf[1] != 'K')
11807 {
11808 remote_console_output (buf + 1); /* 'O' message from stub. */
11809 continue;
11810 }
11811 if (strcmp (buf, "OK") == 0)
11812 break;
11813 if (strlen (buf) == 3 && buf[0] == 'E'
11814 && isxdigit (buf[1]) && isxdigit (buf[2]))
11815 {
11816 error (_("Protocol error with Rcmd"));
11817 }
11818 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11819 {
11820 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11821
11822 gdb_putc (c, outbuf);
11823 }
11824 break;
11825 }
11826 }
11827
11828 std::vector<mem_region>
11829 remote_target::memory_map ()
11830 {
11831 std::vector<mem_region> result;
11832 gdb::optional<gdb::char_vector> text
11833 = target_read_stralloc (current_inferior ()->top_target (),
11834 TARGET_OBJECT_MEMORY_MAP, NULL);
11835
11836 if (text)
11837 result = parse_memory_map (text->data ());
11838
11839 return result;
11840 }
11841
11842 /* Set of callbacks used to implement the 'maint packet' command. */
11843
11844 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11845 {
11846 /* Called before the packet is sent. BUF is the packet content before
11847 the protocol specific prefix, suffix, and escaping is added. */
11848
11849 void sending (gdb::array_view<const char> &buf) override
11850 {
11851 gdb_puts ("sending: ");
11852 print_packet (buf);
11853 gdb_puts ("\n");
11854 }
11855
11856 /* Called with BUF, the reply from the remote target. */
11857
11858 void received (gdb::array_view<const char> &buf) override
11859 {
11860 gdb_puts ("received: \"");
11861 print_packet (buf);
11862 gdb_puts ("\"\n");
11863 }
11864
11865 private:
11866
11867 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11868 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11869
11870 static void
11871 print_packet (gdb::array_view<const char> &buf)
11872 {
11873 string_file stb;
11874
11875 for (int i = 0; i < buf.size (); ++i)
11876 {
11877 gdb_byte c = buf[i];
11878 if (isprint (c))
11879 gdb_putc (c, &stb);
11880 else
11881 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11882 }
11883
11884 gdb_puts (stb.string ().c_str ());
11885 }
11886 };
11887
11888 /* See remote.h. */
11889
11890 void
11891 send_remote_packet (gdb::array_view<const char> &buf,
11892 send_remote_packet_callbacks *callbacks)
11893 {
11894 if (buf.size () == 0 || buf.data ()[0] == '\0')
11895 error (_("a remote packet must not be empty"));
11896
11897 remote_target *remote = get_current_remote_target ();
11898 if (remote == nullptr)
11899 error (_("packets can only be sent to a remote target"));
11900
11901 callbacks->sending (buf);
11902
11903 remote->putpkt_binary (buf.data (), buf.size ());
11904 remote_state *rs = remote->get_remote_state ();
11905 int bytes = remote->getpkt (&rs->buf);
11906
11907 if (bytes < 0)
11908 error (_("error while fetching packet from remote target"));
11909
11910 gdb::array_view<const char> view (&rs->buf[0], bytes);
11911 callbacks->received (view);
11912 }
11913
11914 /* Entry point for the 'maint packet' command. */
11915
11916 static void
11917 cli_packet_command (const char *args, int from_tty)
11918 {
11919 cli_packet_command_callbacks cb;
11920 gdb::array_view<const char> view
11921 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11922 send_remote_packet (view, &cb);
11923 }
11924
11925 #if 0
11926 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11927
11928 static void display_thread_info (struct gdb_ext_thread_info *info);
11929
11930 static void threadset_test_cmd (char *cmd, int tty);
11931
11932 static void threadalive_test (char *cmd, int tty);
11933
11934 static void threadlist_test_cmd (char *cmd, int tty);
11935
11936 int get_and_display_threadinfo (threadref *ref);
11937
11938 static void threadinfo_test_cmd (char *cmd, int tty);
11939
11940 static int thread_display_step (threadref *ref, void *context);
11941
11942 static void threadlist_update_test_cmd (char *cmd, int tty);
11943
11944 static void init_remote_threadtests (void);
11945
11946 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11947
11948 static void
11949 threadset_test_cmd (const char *cmd, int tty)
11950 {
11951 int sample_thread = SAMPLE_THREAD;
11952
11953 gdb_printf (_("Remote threadset test\n"));
11954 set_general_thread (sample_thread);
11955 }
11956
11957
11958 static void
11959 threadalive_test (const char *cmd, int tty)
11960 {
11961 int sample_thread = SAMPLE_THREAD;
11962 int pid = inferior_ptid.pid ();
11963 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11964
11965 if (remote_thread_alive (ptid))
11966 gdb_printf ("PASS: Thread alive test\n");
11967 else
11968 gdb_printf ("FAIL: Thread alive test\n");
11969 }
11970
11971 void output_threadid (char *title, threadref *ref);
11972
11973 void
11974 output_threadid (char *title, threadref *ref)
11975 {
11976 char hexid[20];
11977
11978 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11979 hexid[16] = 0;
11980 gdb_printf ("%s %s\n", title, (&hexid[0]));
11981 }
11982
11983 static void
11984 threadlist_test_cmd (const char *cmd, int tty)
11985 {
11986 int startflag = 1;
11987 threadref nextthread;
11988 int done, result_count;
11989 threadref threadlist[3];
11990
11991 gdb_printf ("Remote Threadlist test\n");
11992 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11993 &result_count, &threadlist[0]))
11994 gdb_printf ("FAIL: threadlist test\n");
11995 else
11996 {
11997 threadref *scan = threadlist;
11998 threadref *limit = scan + result_count;
11999
12000 while (scan < limit)
12001 output_threadid (" thread ", scan++);
12002 }
12003 }
12004
12005 void
12006 display_thread_info (struct gdb_ext_thread_info *info)
12007 {
12008 output_threadid ("Threadid: ", &info->threadid);
12009 gdb_printf ("Name: %s\n ", info->shortname);
12010 gdb_printf ("State: %s\n", info->display);
12011 gdb_printf ("other: %s\n\n", info->more_display);
12012 }
12013
12014 int
12015 get_and_display_threadinfo (threadref *ref)
12016 {
12017 int result;
12018 int set;
12019 struct gdb_ext_thread_info threadinfo;
12020
12021 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12022 | TAG_MOREDISPLAY | TAG_DISPLAY;
12023 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12024 display_thread_info (&threadinfo);
12025 return result;
12026 }
12027
12028 static void
12029 threadinfo_test_cmd (const char *cmd, int tty)
12030 {
12031 int athread = SAMPLE_THREAD;
12032 threadref thread;
12033 int set;
12034
12035 int_to_threadref (&thread, athread);
12036 gdb_printf ("Remote Threadinfo test\n");
12037 if (!get_and_display_threadinfo (&thread))
12038 gdb_printf ("FAIL cannot get thread info\n");
12039 }
12040
12041 static int
12042 thread_display_step (threadref *ref, void *context)
12043 {
12044 /* output_threadid(" threadstep ",ref); *//* simple test */
12045 return get_and_display_threadinfo (ref);
12046 }
12047
12048 static void
12049 threadlist_update_test_cmd (const char *cmd, int tty)
12050 {
12051 gdb_printf ("Remote Threadlist update test\n");
12052 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12053 }
12054
12055 static void
12056 init_remote_threadtests (void)
12057 {
12058 add_com ("tlist", class_obscure, threadlist_test_cmd,
12059 _("Fetch and print the remote list of "
12060 "thread identifiers, one pkt only."));
12061 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12062 _("Fetch and display info about one thread."));
12063 add_com ("tset", class_obscure, threadset_test_cmd,
12064 _("Test setting to a different thread."));
12065 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12066 _("Iterate through updating all remote thread info."));
12067 add_com ("talive", class_obscure, threadalive_test,
12068 _("Remote thread alive test."));
12069 }
12070
12071 #endif /* 0 */
12072
12073 /* Convert a thread ID to a string. */
12074
12075 std::string
12076 remote_target::pid_to_str (ptid_t ptid)
12077 {
12078 if (ptid == null_ptid)
12079 return normal_pid_to_str (ptid);
12080 else if (ptid.is_pid ())
12081 {
12082 /* Printing an inferior target id. */
12083
12084 /* When multi-process extensions are off, there's no way in the
12085 remote protocol to know the remote process id, if there's any
12086 at all. There's one exception --- when we're connected with
12087 target extended-remote, and we manually attached to a process
12088 with "attach PID". We don't record anywhere a flag that
12089 allows us to distinguish that case from the case of
12090 connecting with extended-remote and the stub already being
12091 attached to a process, and reporting yes to qAttached, hence
12092 no smart special casing here. */
12093 if (!m_features.remote_multi_process_p ())
12094 return "Remote target";
12095
12096 return normal_pid_to_str (ptid);
12097 }
12098 else
12099 {
12100 if (magic_null_ptid == ptid)
12101 return "Thread <main>";
12102 else if (m_features.remote_multi_process_p ())
12103 if (ptid.lwp () == 0)
12104 return normal_pid_to_str (ptid);
12105 else
12106 return string_printf ("Thread %d.%ld",
12107 ptid.pid (), ptid.lwp ());
12108 else
12109 return string_printf ("Thread %ld", ptid.lwp ());
12110 }
12111 }
12112
12113 /* Get the address of the thread local variable in OBJFILE which is
12114 stored at OFFSET within the thread local storage for thread PTID. */
12115
12116 CORE_ADDR
12117 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12118 CORE_ADDR offset)
12119 {
12120 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12121 {
12122 struct remote_state *rs = get_remote_state ();
12123 char *p = rs->buf.data ();
12124 char *endp = p + get_remote_packet_size ();
12125 enum packet_result result;
12126
12127 strcpy (p, "qGetTLSAddr:");
12128 p += strlen (p);
12129 p = write_ptid (p, endp, ptid);
12130 *p++ = ',';
12131 p += hexnumstr (p, offset);
12132 *p++ = ',';
12133 p += hexnumstr (p, lm);
12134 *p++ = '\0';
12135
12136 putpkt (rs->buf);
12137 getpkt (&rs->buf);
12138 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12139 if (result == PACKET_OK)
12140 {
12141 ULONGEST addr;
12142
12143 unpack_varlen_hex (rs->buf.data (), &addr);
12144 return addr;
12145 }
12146 else if (result == PACKET_UNKNOWN)
12147 throw_error (TLS_GENERIC_ERROR,
12148 _("Remote target doesn't support qGetTLSAddr packet"));
12149 else
12150 throw_error (TLS_GENERIC_ERROR,
12151 _("Remote target failed to process qGetTLSAddr request"));
12152 }
12153 else
12154 throw_error (TLS_GENERIC_ERROR,
12155 _("TLS not supported or disabled on this target"));
12156 /* Not reached. */
12157 return 0;
12158 }
12159
12160 /* Provide thread local base, i.e. Thread Information Block address.
12161 Returns 1 if ptid is found and thread_local_base is non zero. */
12162
12163 bool
12164 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12165 {
12166 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12167 {
12168 struct remote_state *rs = get_remote_state ();
12169 char *p = rs->buf.data ();
12170 char *endp = p + get_remote_packet_size ();
12171 enum packet_result result;
12172
12173 strcpy (p, "qGetTIBAddr:");
12174 p += strlen (p);
12175 p = write_ptid (p, endp, ptid);
12176 *p++ = '\0';
12177
12178 putpkt (rs->buf);
12179 getpkt (&rs->buf);
12180 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12181 if (result == PACKET_OK)
12182 {
12183 ULONGEST val;
12184 unpack_varlen_hex (rs->buf.data (), &val);
12185 if (addr)
12186 *addr = (CORE_ADDR) val;
12187 return true;
12188 }
12189 else if (result == PACKET_UNKNOWN)
12190 error (_("Remote target doesn't support qGetTIBAddr packet"));
12191 else
12192 error (_("Remote target failed to process qGetTIBAddr request"));
12193 }
12194 else
12195 error (_("qGetTIBAddr not supported or disabled on this target"));
12196 /* Not reached. */
12197 return false;
12198 }
12199
12200 /* Support for inferring a target description based on the current
12201 architecture and the size of a 'g' packet. While the 'g' packet
12202 can have any size (since optional registers can be left off the
12203 end), some sizes are easily recognizable given knowledge of the
12204 approximate architecture. */
12205
12206 struct remote_g_packet_guess
12207 {
12208 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12209 : bytes (bytes_),
12210 tdesc (tdesc_)
12211 {
12212 }
12213
12214 int bytes;
12215 const struct target_desc *tdesc;
12216 };
12217
12218 struct remote_g_packet_data
12219 {
12220 std::vector<remote_g_packet_guess> guesses;
12221 };
12222
12223 static const registry<gdbarch>::key<struct remote_g_packet_data>
12224 remote_g_packet_data_handle;
12225
12226 static struct remote_g_packet_data *
12227 get_g_packet_data (struct gdbarch *gdbarch)
12228 {
12229 struct remote_g_packet_data *data
12230 = remote_g_packet_data_handle.get (gdbarch);
12231 if (data == nullptr)
12232 data = remote_g_packet_data_handle.emplace (gdbarch);
12233 return data;
12234 }
12235
12236 void
12237 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12238 const struct target_desc *tdesc)
12239 {
12240 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12241
12242 gdb_assert (tdesc != NULL);
12243
12244 for (const remote_g_packet_guess &guess : data->guesses)
12245 if (guess.bytes == bytes)
12246 internal_error (_("Duplicate g packet description added for size %d"),
12247 bytes);
12248
12249 data->guesses.emplace_back (bytes, tdesc);
12250 }
12251
12252 /* Return true if remote_read_description would do anything on this target
12253 and architecture, false otherwise. */
12254
12255 static bool
12256 remote_read_description_p (struct target_ops *target)
12257 {
12258 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12259
12260 return !data->guesses.empty ();
12261 }
12262
12263 const struct target_desc *
12264 remote_target::read_description ()
12265 {
12266 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12267
12268 /* Do not try this during initial connection, when we do not know
12269 whether there is a running but stopped thread. */
12270 if (!target_has_execution () || inferior_ptid == null_ptid)
12271 return beneath ()->read_description ();
12272
12273 if (!data->guesses.empty ())
12274 {
12275 int bytes = send_g_packet ();
12276
12277 for (const remote_g_packet_guess &guess : data->guesses)
12278 if (guess.bytes == bytes)
12279 return guess.tdesc;
12280
12281 /* We discard the g packet. A minor optimization would be to
12282 hold on to it, and fill the register cache once we have selected
12283 an architecture, but it's too tricky to do safely. */
12284 }
12285
12286 return beneath ()->read_description ();
12287 }
12288
12289 /* Remote file transfer support. This is host-initiated I/O, not
12290 target-initiated; for target-initiated, see remote-fileio.c. */
12291
12292 /* If *LEFT is at least the length of STRING, copy STRING to
12293 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12294 decrease *LEFT. Otherwise raise an error. */
12295
12296 static void
12297 remote_buffer_add_string (char **buffer, int *left, const char *string)
12298 {
12299 int len = strlen (string);
12300
12301 if (len > *left)
12302 error (_("Packet too long for target."));
12303
12304 memcpy (*buffer, string, len);
12305 *buffer += len;
12306 *left -= len;
12307
12308 /* NUL-terminate the buffer as a convenience, if there is
12309 room. */
12310 if (*left)
12311 **buffer = '\0';
12312 }
12313
12314 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12315 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12316 decrease *LEFT. Otherwise raise an error. */
12317
12318 static void
12319 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12320 int len)
12321 {
12322 if (2 * len > *left)
12323 error (_("Packet too long for target."));
12324
12325 bin2hex (bytes, *buffer, len);
12326 *buffer += 2 * len;
12327 *left -= 2 * len;
12328
12329 /* NUL-terminate the buffer as a convenience, if there is
12330 room. */
12331 if (*left)
12332 **buffer = '\0';
12333 }
12334
12335 /* If *LEFT is large enough, convert VALUE to hex and add it to
12336 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12337 decrease *LEFT. Otherwise raise an error. */
12338
12339 static void
12340 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12341 {
12342 int len = hexnumlen (value);
12343
12344 if (len > *left)
12345 error (_("Packet too long for target."));
12346
12347 hexnumstr (*buffer, value);
12348 *buffer += len;
12349 *left -= len;
12350
12351 /* NUL-terminate the buffer as a convenience, if there is
12352 room. */
12353 if (*left)
12354 **buffer = '\0';
12355 }
12356
12357 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12358 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12359 was included, and *ATTACHMENT to point to the start of the annex
12360 if any. The length of the packet isn't needed here; there may
12361 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12362
12363 Return 0 if the packet could be parsed, -1 if it could not. If
12364 -1 is returned, the other variables may not be initialized. */
12365
12366 static int
12367 remote_hostio_parse_result (const char *buffer, int *retcode,
12368 fileio_error *remote_errno, const char **attachment)
12369 {
12370 char *p, *p2;
12371
12372 *remote_errno = FILEIO_SUCCESS;
12373 *attachment = NULL;
12374
12375 if (buffer[0] != 'F')
12376 return -1;
12377
12378 errno = 0;
12379 *retcode = strtol (&buffer[1], &p, 16);
12380 if (errno != 0 || p == &buffer[1])
12381 return -1;
12382
12383 /* Check for ",errno". */
12384 if (*p == ',')
12385 {
12386 errno = 0;
12387 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12388 if (errno != 0 || p + 1 == p2)
12389 return -1;
12390 p = p2;
12391 }
12392
12393 /* Check for ";attachment". If there is no attachment, the
12394 packet should end here. */
12395 if (*p == ';')
12396 {
12397 *attachment = p + 1;
12398 return 0;
12399 }
12400 else if (*p == '\0')
12401 return 0;
12402 else
12403 return -1;
12404 }
12405
12406 /* Send a prepared I/O packet to the target and read its response.
12407 The prepared packet is in the global RS->BUF before this function
12408 is called, and the answer is there when we return.
12409
12410 COMMAND_BYTES is the length of the request to send, which may include
12411 binary data. WHICH_PACKET is the packet configuration to check
12412 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12413 is set to the error number and -1 is returned. Otherwise the value
12414 returned by the function is returned.
12415
12416 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12417 attachment is expected; an error will be reported if there's a
12418 mismatch. If one is found, *ATTACHMENT will be set to point into
12419 the packet buffer and *ATTACHMENT_LEN will be set to the
12420 attachment's length. */
12421
12422 int
12423 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12424 fileio_error *remote_errno, const char **attachment,
12425 int *attachment_len)
12426 {
12427 struct remote_state *rs = get_remote_state ();
12428 int ret, bytes_read;
12429 const char *attachment_tmp;
12430
12431 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12432 {
12433 *remote_errno = FILEIO_ENOSYS;
12434 return -1;
12435 }
12436
12437 putpkt_binary (rs->buf.data (), command_bytes);
12438 bytes_read = getpkt (&rs->buf);
12439
12440 /* If it timed out, something is wrong. Don't try to parse the
12441 buffer. */
12442 if (bytes_read < 0)
12443 {
12444 *remote_errno = FILEIO_EINVAL;
12445 return -1;
12446 }
12447
12448 switch (m_features.packet_ok (rs->buf, which_packet))
12449 {
12450 case PACKET_ERROR:
12451 *remote_errno = FILEIO_EINVAL;
12452 return -1;
12453 case PACKET_UNKNOWN:
12454 *remote_errno = FILEIO_ENOSYS;
12455 return -1;
12456 case PACKET_OK:
12457 break;
12458 }
12459
12460 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12461 &attachment_tmp))
12462 {
12463 *remote_errno = FILEIO_EINVAL;
12464 return -1;
12465 }
12466
12467 /* Make sure we saw an attachment if and only if we expected one. */
12468 if ((attachment_tmp == NULL && attachment != NULL)
12469 || (attachment_tmp != NULL && attachment == NULL))
12470 {
12471 *remote_errno = FILEIO_EINVAL;
12472 return -1;
12473 }
12474
12475 /* If an attachment was found, it must point into the packet buffer;
12476 work out how many bytes there were. */
12477 if (attachment_tmp != NULL)
12478 {
12479 *attachment = attachment_tmp;
12480 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12481 }
12482
12483 return ret;
12484 }
12485
12486 /* See declaration.h. */
12487
12488 void
12489 readahead_cache::invalidate ()
12490 {
12491 this->fd = -1;
12492 }
12493
12494 /* See declaration.h. */
12495
12496 void
12497 readahead_cache::invalidate_fd (int fd)
12498 {
12499 if (this->fd == fd)
12500 this->fd = -1;
12501 }
12502
12503 /* Set the filesystem remote_hostio functions that take FILENAME
12504 arguments will use. Return 0 on success, or -1 if an error
12505 occurs (and set *REMOTE_ERRNO). */
12506
12507 int
12508 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12509 fileio_error *remote_errno)
12510 {
12511 struct remote_state *rs = get_remote_state ();
12512 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12513 char *p = rs->buf.data ();
12514 int left = get_remote_packet_size () - 1;
12515 char arg[9];
12516 int ret;
12517
12518 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12519 return 0;
12520
12521 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12522 return 0;
12523
12524 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12525
12526 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12527 remote_buffer_add_string (&p, &left, arg);
12528
12529 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12530 remote_errno, NULL, NULL);
12531
12532 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12533 return 0;
12534
12535 if (ret == 0)
12536 rs->fs_pid = required_pid;
12537
12538 return ret;
12539 }
12540
12541 /* Implementation of to_fileio_open. */
12542
12543 int
12544 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12545 int flags, int mode, int warn_if_slow,
12546 fileio_error *remote_errno)
12547 {
12548 struct remote_state *rs = get_remote_state ();
12549 char *p = rs->buf.data ();
12550 int left = get_remote_packet_size () - 1;
12551
12552 if (warn_if_slow)
12553 {
12554 static int warning_issued = 0;
12555
12556 gdb_printf (_("Reading %s from remote target...\n"),
12557 filename);
12558
12559 if (!warning_issued)
12560 {
12561 warning (_("File transfers from remote targets can be slow."
12562 " Use \"set sysroot\" to access files locally"
12563 " instead."));
12564 warning_issued = 1;
12565 }
12566 }
12567
12568 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12569 return -1;
12570
12571 remote_buffer_add_string (&p, &left, "vFile:open:");
12572
12573 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12574 strlen (filename));
12575 remote_buffer_add_string (&p, &left, ",");
12576
12577 remote_buffer_add_int (&p, &left, flags);
12578 remote_buffer_add_string (&p, &left, ",");
12579
12580 remote_buffer_add_int (&p, &left, mode);
12581
12582 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12583 remote_errno, NULL, NULL);
12584 }
12585
12586 int
12587 remote_target::fileio_open (struct inferior *inf, const char *filename,
12588 int flags, int mode, int warn_if_slow,
12589 fileio_error *remote_errno)
12590 {
12591 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12592 remote_errno);
12593 }
12594
12595 /* Implementation of to_fileio_pwrite. */
12596
12597 int
12598 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12599 ULONGEST offset, fileio_error *remote_errno)
12600 {
12601 struct remote_state *rs = get_remote_state ();
12602 char *p = rs->buf.data ();
12603 int left = get_remote_packet_size ();
12604 int out_len;
12605
12606 rs->readahead_cache.invalidate_fd (fd);
12607
12608 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12609
12610 remote_buffer_add_int (&p, &left, fd);
12611 remote_buffer_add_string (&p, &left, ",");
12612
12613 remote_buffer_add_int (&p, &left, offset);
12614 remote_buffer_add_string (&p, &left, ",");
12615
12616 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12617 (get_remote_packet_size ()
12618 - (p - rs->buf.data ())));
12619
12620 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12621 remote_errno, NULL, NULL);
12622 }
12623
12624 int
12625 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12626 ULONGEST offset, fileio_error *remote_errno)
12627 {
12628 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12629 }
12630
12631 /* Helper for the implementation of to_fileio_pread. Read the file
12632 from the remote side with vFile:pread. */
12633
12634 int
12635 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12636 ULONGEST offset, fileio_error *remote_errno)
12637 {
12638 struct remote_state *rs = get_remote_state ();
12639 char *p = rs->buf.data ();
12640 const char *attachment;
12641 int left = get_remote_packet_size ();
12642 int ret, attachment_len;
12643 int read_len;
12644
12645 remote_buffer_add_string (&p, &left, "vFile:pread:");
12646
12647 remote_buffer_add_int (&p, &left, fd);
12648 remote_buffer_add_string (&p, &left, ",");
12649
12650 remote_buffer_add_int (&p, &left, len);
12651 remote_buffer_add_string (&p, &left, ",");
12652
12653 remote_buffer_add_int (&p, &left, offset);
12654
12655 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12656 remote_errno, &attachment,
12657 &attachment_len);
12658
12659 if (ret < 0)
12660 return ret;
12661
12662 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12663 read_buf, len);
12664 if (read_len != ret)
12665 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12666
12667 return ret;
12668 }
12669
12670 /* See declaration.h. */
12671
12672 int
12673 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12674 ULONGEST offset)
12675 {
12676 if (this->fd == fd
12677 && this->offset <= offset
12678 && offset < this->offset + this->buf.size ())
12679 {
12680 ULONGEST max = this->offset + this->buf.size ();
12681
12682 if (offset + len > max)
12683 len = max - offset;
12684
12685 memcpy (read_buf, &this->buf[offset - this->offset], len);
12686 return len;
12687 }
12688
12689 return 0;
12690 }
12691
12692 /* Implementation of to_fileio_pread. */
12693
12694 int
12695 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12696 ULONGEST offset, fileio_error *remote_errno)
12697 {
12698 int ret;
12699 struct remote_state *rs = get_remote_state ();
12700 readahead_cache *cache = &rs->readahead_cache;
12701
12702 ret = cache->pread (fd, read_buf, len, offset);
12703 if (ret > 0)
12704 {
12705 cache->hit_count++;
12706
12707 remote_debug_printf ("readahead cache hit %s",
12708 pulongest (cache->hit_count));
12709 return ret;
12710 }
12711
12712 cache->miss_count++;
12713
12714 remote_debug_printf ("readahead cache miss %s",
12715 pulongest (cache->miss_count));
12716
12717 cache->fd = fd;
12718 cache->offset = offset;
12719 cache->buf.resize (get_remote_packet_size ());
12720
12721 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12722 cache->buf.size (),
12723 cache->offset, remote_errno);
12724 if (ret <= 0)
12725 {
12726 cache->invalidate_fd (fd);
12727 return ret;
12728 }
12729
12730 cache->buf.resize (ret);
12731 return cache->pread (fd, read_buf, len, offset);
12732 }
12733
12734 int
12735 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12736 ULONGEST offset, fileio_error *remote_errno)
12737 {
12738 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12739 }
12740
12741 /* Implementation of to_fileio_close. */
12742
12743 int
12744 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12745 {
12746 struct remote_state *rs = get_remote_state ();
12747 char *p = rs->buf.data ();
12748 int left = get_remote_packet_size () - 1;
12749
12750 rs->readahead_cache.invalidate_fd (fd);
12751
12752 remote_buffer_add_string (&p, &left, "vFile:close:");
12753
12754 remote_buffer_add_int (&p, &left, fd);
12755
12756 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12757 remote_errno, NULL, NULL);
12758 }
12759
12760 int
12761 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12762 {
12763 return remote_hostio_close (fd, remote_errno);
12764 }
12765
12766 /* Implementation of to_fileio_unlink. */
12767
12768 int
12769 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12770 fileio_error *remote_errno)
12771 {
12772 struct remote_state *rs = get_remote_state ();
12773 char *p = rs->buf.data ();
12774 int left = get_remote_packet_size () - 1;
12775
12776 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12777 return -1;
12778
12779 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12780
12781 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12782 strlen (filename));
12783
12784 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12785 remote_errno, NULL, NULL);
12786 }
12787
12788 int
12789 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12790 fileio_error *remote_errno)
12791 {
12792 return remote_hostio_unlink (inf, filename, remote_errno);
12793 }
12794
12795 /* Implementation of to_fileio_readlink. */
12796
12797 gdb::optional<std::string>
12798 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12799 fileio_error *remote_errno)
12800 {
12801 struct remote_state *rs = get_remote_state ();
12802 char *p = rs->buf.data ();
12803 const char *attachment;
12804 int left = get_remote_packet_size ();
12805 int len, attachment_len;
12806 int read_len;
12807
12808 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12809 return {};
12810
12811 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12812
12813 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12814 strlen (filename));
12815
12816 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12817 remote_errno, &attachment,
12818 &attachment_len);
12819
12820 if (len < 0)
12821 return {};
12822
12823 std::string ret (len, '\0');
12824
12825 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12826 (gdb_byte *) &ret[0], len);
12827 if (read_len != len)
12828 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12829
12830 return ret;
12831 }
12832
12833 /* Implementation of to_fileio_fstat. */
12834
12835 int
12836 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12837 {
12838 struct remote_state *rs = get_remote_state ();
12839 char *p = rs->buf.data ();
12840 int left = get_remote_packet_size ();
12841 int attachment_len, ret;
12842 const char *attachment;
12843 struct fio_stat fst;
12844 int read_len;
12845
12846 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12847
12848 remote_buffer_add_int (&p, &left, fd);
12849
12850 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12851 remote_errno, &attachment,
12852 &attachment_len);
12853 if (ret < 0)
12854 {
12855 if (*remote_errno != FILEIO_ENOSYS)
12856 return ret;
12857
12858 /* Strictly we should return -1, ENOSYS here, but when
12859 "set sysroot remote:" was implemented in August 2008
12860 BFD's need for a stat function was sidestepped with
12861 this hack. This was not remedied until March 2015
12862 so we retain the previous behavior to avoid breaking
12863 compatibility.
12864
12865 Note that the memset is a March 2015 addition; older
12866 GDBs set st_size *and nothing else* so the structure
12867 would have garbage in all other fields. This might
12868 break something but retaining the previous behavior
12869 here would be just too wrong. */
12870
12871 memset (st, 0, sizeof (struct stat));
12872 st->st_size = INT_MAX;
12873 return 0;
12874 }
12875
12876 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12877 (gdb_byte *) &fst, sizeof (fst));
12878
12879 if (read_len != ret)
12880 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12881
12882 if (read_len != sizeof (fst))
12883 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12884 read_len, (int) sizeof (fst));
12885
12886 remote_fileio_to_host_stat (&fst, st);
12887
12888 return 0;
12889 }
12890
12891 /* Implementation of to_filesystem_is_local. */
12892
12893 bool
12894 remote_target::filesystem_is_local ()
12895 {
12896 /* Valgrind GDB presents itself as a remote target but works
12897 on the local filesystem: it does not implement remote get
12898 and users are not expected to set a sysroot. To handle
12899 this case we treat the remote filesystem as local if the
12900 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12901 does not support vFile:open. */
12902 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12903 {
12904 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12905
12906 if (ps == PACKET_SUPPORT_UNKNOWN)
12907 {
12908 int fd;
12909 fileio_error remote_errno;
12910
12911 /* Try opening a file to probe support. The supplied
12912 filename is irrelevant, we only care about whether
12913 the stub recognizes the packet or not. */
12914 fd = remote_hostio_open (NULL, "just probing",
12915 FILEIO_O_RDONLY, 0700, 0,
12916 &remote_errno);
12917
12918 if (fd >= 0)
12919 remote_hostio_close (fd, &remote_errno);
12920
12921 ps = m_features.packet_support (PACKET_vFile_open);
12922 }
12923
12924 if (ps == PACKET_DISABLE)
12925 {
12926 static int warning_issued = 0;
12927
12928 if (!warning_issued)
12929 {
12930 warning (_("remote target does not support file"
12931 " transfer, attempting to access files"
12932 " from local filesystem."));
12933 warning_issued = 1;
12934 }
12935
12936 return true;
12937 }
12938 }
12939
12940 return false;
12941 }
12942
12943 static char *
12944 remote_hostio_error (fileio_error errnum)
12945 {
12946 int host_error = fileio_error_to_host (errnum);
12947
12948 if (host_error == -1)
12949 error (_("Unknown remote I/O error %d"), errnum);
12950 else
12951 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12952 }
12953
12954 /* A RAII wrapper around a remote file descriptor. */
12955
12956 class scoped_remote_fd
12957 {
12958 public:
12959 scoped_remote_fd (remote_target *remote, int fd)
12960 : m_remote (remote), m_fd (fd)
12961 {
12962 }
12963
12964 ~scoped_remote_fd ()
12965 {
12966 if (m_fd != -1)
12967 {
12968 try
12969 {
12970 fileio_error remote_errno;
12971 m_remote->remote_hostio_close (m_fd, &remote_errno);
12972 }
12973 catch (...)
12974 {
12975 /* Swallow exception before it escapes the dtor. If
12976 something goes wrong, likely the connection is gone,
12977 and there's nothing else that can be done. */
12978 }
12979 }
12980 }
12981
12982 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12983
12984 /* Release ownership of the file descriptor, and return it. */
12985 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12986 {
12987 int fd = m_fd;
12988 m_fd = -1;
12989 return fd;
12990 }
12991
12992 /* Return the owned file descriptor. */
12993 int get () const noexcept
12994 {
12995 return m_fd;
12996 }
12997
12998 private:
12999 /* The remote target. */
13000 remote_target *m_remote;
13001
13002 /* The owned remote I/O file descriptor. */
13003 int m_fd;
13004 };
13005
13006 void
13007 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13008 {
13009 remote_target *remote = get_current_remote_target ();
13010
13011 if (remote == nullptr)
13012 error (_("command can only be used with remote target"));
13013
13014 remote->remote_file_put (local_file, remote_file, from_tty);
13015 }
13016
13017 void
13018 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13019 int from_tty)
13020 {
13021 int retcode, bytes, io_size;
13022 fileio_error remote_errno;
13023 int bytes_in_buffer;
13024 int saw_eof;
13025 ULONGEST offset;
13026
13027 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13028 if (file == NULL)
13029 perror_with_name (local_file);
13030
13031 scoped_remote_fd fd
13032 (this, remote_hostio_open (NULL,
13033 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13034 | FILEIO_O_TRUNC),
13035 0700, 0, &remote_errno));
13036 if (fd.get () == -1)
13037 remote_hostio_error (remote_errno);
13038
13039 /* Send up to this many bytes at once. They won't all fit in the
13040 remote packet limit, so we'll transfer slightly fewer. */
13041 io_size = get_remote_packet_size ();
13042 gdb::byte_vector buffer (io_size);
13043
13044 bytes_in_buffer = 0;
13045 saw_eof = 0;
13046 offset = 0;
13047 while (bytes_in_buffer || !saw_eof)
13048 {
13049 if (!saw_eof)
13050 {
13051 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13052 io_size - bytes_in_buffer,
13053 file.get ());
13054 if (bytes == 0)
13055 {
13056 if (ferror (file.get ()))
13057 error (_("Error reading %s."), local_file);
13058 else
13059 {
13060 /* EOF. Unless there is something still in the
13061 buffer from the last iteration, we are done. */
13062 saw_eof = 1;
13063 if (bytes_in_buffer == 0)
13064 break;
13065 }
13066 }
13067 }
13068 else
13069 bytes = 0;
13070
13071 bytes += bytes_in_buffer;
13072 bytes_in_buffer = 0;
13073
13074 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13075 offset, &remote_errno);
13076
13077 if (retcode < 0)
13078 remote_hostio_error (remote_errno);
13079 else if (retcode == 0)
13080 error (_("Remote write of %d bytes returned 0!"), bytes);
13081 else if (retcode < bytes)
13082 {
13083 /* Short write. Save the rest of the read data for the next
13084 write. */
13085 bytes_in_buffer = bytes - retcode;
13086 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13087 }
13088
13089 offset += retcode;
13090 }
13091
13092 if (remote_hostio_close (fd.release (), &remote_errno))
13093 remote_hostio_error (remote_errno);
13094
13095 if (from_tty)
13096 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13097 }
13098
13099 void
13100 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13101 {
13102 remote_target *remote = get_current_remote_target ();
13103
13104 if (remote == nullptr)
13105 error (_("command can only be used with remote target"));
13106
13107 remote->remote_file_get (remote_file, local_file, from_tty);
13108 }
13109
13110 void
13111 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13112 int from_tty)
13113 {
13114 fileio_error remote_errno;
13115 int bytes, io_size;
13116 ULONGEST offset;
13117
13118 scoped_remote_fd fd
13119 (this, remote_hostio_open (NULL,
13120 remote_file, FILEIO_O_RDONLY, 0, 0,
13121 &remote_errno));
13122 if (fd.get () == -1)
13123 remote_hostio_error (remote_errno);
13124
13125 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13126 if (file == NULL)
13127 perror_with_name (local_file);
13128
13129 /* Send up to this many bytes at once. They won't all fit in the
13130 remote packet limit, so we'll transfer slightly fewer. */
13131 io_size = get_remote_packet_size ();
13132 gdb::byte_vector buffer (io_size);
13133
13134 offset = 0;
13135 while (1)
13136 {
13137 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13138 &remote_errno);
13139 if (bytes == 0)
13140 /* Success, but no bytes, means end-of-file. */
13141 break;
13142 if (bytes == -1)
13143 remote_hostio_error (remote_errno);
13144
13145 offset += bytes;
13146
13147 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13148 if (bytes == 0)
13149 perror_with_name (local_file);
13150 }
13151
13152 if (remote_hostio_close (fd.release (), &remote_errno))
13153 remote_hostio_error (remote_errno);
13154
13155 if (from_tty)
13156 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13157 }
13158
13159 void
13160 remote_file_delete (const char *remote_file, int from_tty)
13161 {
13162 remote_target *remote = get_current_remote_target ();
13163
13164 if (remote == nullptr)
13165 error (_("command can only be used with remote target"));
13166
13167 remote->remote_file_delete (remote_file, from_tty);
13168 }
13169
13170 void
13171 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13172 {
13173 int retcode;
13174 fileio_error remote_errno;
13175
13176 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13177 if (retcode == -1)
13178 remote_hostio_error (remote_errno);
13179
13180 if (from_tty)
13181 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13182 }
13183
13184 static void
13185 remote_put_command (const char *args, int from_tty)
13186 {
13187 if (args == NULL)
13188 error_no_arg (_("file to put"));
13189
13190 gdb_argv argv (args);
13191 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13192 error (_("Invalid parameters to remote put"));
13193
13194 remote_file_put (argv[0], argv[1], from_tty);
13195 }
13196
13197 static void
13198 remote_get_command (const char *args, int from_tty)
13199 {
13200 if (args == NULL)
13201 error_no_arg (_("file to get"));
13202
13203 gdb_argv argv (args);
13204 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13205 error (_("Invalid parameters to remote get"));
13206
13207 remote_file_get (argv[0], argv[1], from_tty);
13208 }
13209
13210 static void
13211 remote_delete_command (const char *args, int from_tty)
13212 {
13213 if (args == NULL)
13214 error_no_arg (_("file to delete"));
13215
13216 gdb_argv argv (args);
13217 if (argv[0] == NULL || argv[1] != NULL)
13218 error (_("Invalid parameters to remote delete"));
13219
13220 remote_file_delete (argv[0], from_tty);
13221 }
13222
13223 bool
13224 remote_target::can_execute_reverse ()
13225 {
13226 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13227 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13228 return true;
13229 else
13230 return false;
13231 }
13232
13233 bool
13234 remote_target::supports_non_stop ()
13235 {
13236 return true;
13237 }
13238
13239 bool
13240 remote_target::supports_disable_randomization ()
13241 {
13242 /* Only supported in extended mode. */
13243 return false;
13244 }
13245
13246 bool
13247 remote_target::supports_multi_process ()
13248 {
13249 return m_features.remote_multi_process_p ();
13250 }
13251
13252 int
13253 remote_target::remote_supports_cond_tracepoints ()
13254 {
13255 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13256 == PACKET_ENABLE);
13257 }
13258
13259 bool
13260 remote_target::supports_evaluation_of_breakpoint_conditions ()
13261 {
13262 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13263 == PACKET_ENABLE);
13264 }
13265
13266 int
13267 remote_target::remote_supports_fast_tracepoints ()
13268 {
13269 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13270 }
13271
13272 int
13273 remote_target::remote_supports_static_tracepoints ()
13274 {
13275 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13276 }
13277
13278 int
13279 remote_target::remote_supports_install_in_trace ()
13280 {
13281 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13282 }
13283
13284 bool
13285 remote_target::supports_enable_disable_tracepoint ()
13286 {
13287 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13288 == PACKET_ENABLE);
13289 }
13290
13291 bool
13292 remote_target::supports_string_tracing ()
13293 {
13294 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13295 }
13296
13297 bool
13298 remote_target::can_run_breakpoint_commands ()
13299 {
13300 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13301 }
13302
13303 void
13304 remote_target::trace_init ()
13305 {
13306 struct remote_state *rs = get_remote_state ();
13307
13308 putpkt ("QTinit");
13309 remote_get_noisy_reply ();
13310 if (strcmp (rs->buf.data (), "OK") != 0)
13311 error (_("Target does not support this command."));
13312 }
13313
13314 /* Recursive routine to walk through command list including loops, and
13315 download packets for each command. */
13316
13317 void
13318 remote_target::remote_download_command_source (int num, ULONGEST addr,
13319 struct command_line *cmds)
13320 {
13321 struct remote_state *rs = get_remote_state ();
13322 struct command_line *cmd;
13323
13324 for (cmd = cmds; cmd; cmd = cmd->next)
13325 {
13326 QUIT; /* Allow user to bail out with ^C. */
13327 strcpy (rs->buf.data (), "QTDPsrc:");
13328 encode_source_string (num, addr, "cmd", cmd->line,
13329 rs->buf.data () + strlen (rs->buf.data ()),
13330 rs->buf.size () - strlen (rs->buf.data ()));
13331 putpkt (rs->buf);
13332 remote_get_noisy_reply ();
13333 if (strcmp (rs->buf.data (), "OK"))
13334 warning (_("Target does not support source download."));
13335
13336 if (cmd->control_type == while_control
13337 || cmd->control_type == while_stepping_control)
13338 {
13339 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13340
13341 QUIT; /* Allow user to bail out with ^C. */
13342 strcpy (rs->buf.data (), "QTDPsrc:");
13343 encode_source_string (num, addr, "cmd", "end",
13344 rs->buf.data () + strlen (rs->buf.data ()),
13345 rs->buf.size () - strlen (rs->buf.data ()));
13346 putpkt (rs->buf);
13347 remote_get_noisy_reply ();
13348 if (strcmp (rs->buf.data (), "OK"))
13349 warning (_("Target does not support source download."));
13350 }
13351 }
13352 }
13353
13354 void
13355 remote_target::download_tracepoint (struct bp_location *loc)
13356 {
13357 CORE_ADDR tpaddr;
13358 char addrbuf[40];
13359 std::vector<std::string> tdp_actions;
13360 std::vector<std::string> stepping_actions;
13361 char *pkt;
13362 struct breakpoint *b = loc->owner;
13363 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13364 struct remote_state *rs = get_remote_state ();
13365 int ret;
13366 const char *err_msg = _("Tracepoint packet too large for target.");
13367 size_t size_left;
13368
13369 /* We use a buffer other than rs->buf because we'll build strings
13370 across multiple statements, and other statements in between could
13371 modify rs->buf. */
13372 gdb::char_vector buf (get_remote_packet_size ());
13373
13374 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13375
13376 tpaddr = loc->address;
13377 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13378 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13379 b->number, addrbuf, /* address */
13380 (b->enable_state == bp_enabled ? 'E' : 'D'),
13381 t->step_count, t->pass_count);
13382
13383 if (ret < 0 || ret >= buf.size ())
13384 error ("%s", err_msg);
13385
13386 /* Fast tracepoints are mostly handled by the target, but we can
13387 tell the target how big of an instruction block should be moved
13388 around. */
13389 if (b->type == bp_fast_tracepoint)
13390 {
13391 /* Only test for support at download time; we may not know
13392 target capabilities at definition time. */
13393 if (remote_supports_fast_tracepoints ())
13394 {
13395 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13396 NULL))
13397 {
13398 size_left = buf.size () - strlen (buf.data ());
13399 ret = snprintf (buf.data () + strlen (buf.data ()),
13400 size_left, ":F%x",
13401 gdb_insn_length (loc->gdbarch, tpaddr));
13402
13403 if (ret < 0 || ret >= size_left)
13404 error ("%s", err_msg);
13405 }
13406 else
13407 /* If it passed validation at definition but fails now,
13408 something is very wrong. */
13409 internal_error (_("Fast tracepoint not valid during download"));
13410 }
13411 else
13412 /* Fast tracepoints are functionally identical to regular
13413 tracepoints, so don't take lack of support as a reason to
13414 give up on the trace run. */
13415 warning (_("Target does not support fast tracepoints, "
13416 "downloading %d as regular tracepoint"), b->number);
13417 }
13418 else if (b->type == bp_static_tracepoint
13419 || b->type == bp_static_marker_tracepoint)
13420 {
13421 /* Only test for support at download time; we may not know
13422 target capabilities at definition time. */
13423 if (remote_supports_static_tracepoints ())
13424 {
13425 struct static_tracepoint_marker marker;
13426
13427 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13428 {
13429 size_left = buf.size () - strlen (buf.data ());
13430 ret = snprintf (buf.data () + strlen (buf.data ()),
13431 size_left, ":S");
13432
13433 if (ret < 0 || ret >= size_left)
13434 error ("%s", err_msg);
13435 }
13436 else
13437 error (_("Static tracepoint not valid during download"));
13438 }
13439 else
13440 /* Fast tracepoints are functionally identical to regular
13441 tracepoints, so don't take lack of support as a reason
13442 to give up on the trace run. */
13443 error (_("Target does not support static tracepoints"));
13444 }
13445 /* If the tracepoint has a conditional, make it into an agent
13446 expression and append to the definition. */
13447 if (loc->cond)
13448 {
13449 /* Only test support at download time, we may not know target
13450 capabilities at definition time. */
13451 if (remote_supports_cond_tracepoints ())
13452 {
13453 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13454 loc->cond.get ());
13455
13456 size_left = buf.size () - strlen (buf.data ());
13457
13458 ret = snprintf (buf.data () + strlen (buf.data ()),
13459 size_left, ":X%x,", (int) aexpr->buf.size ());
13460
13461 if (ret < 0 || ret >= size_left)
13462 error ("%s", err_msg);
13463
13464 size_left = buf.size () - strlen (buf.data ());
13465
13466 /* Two bytes to encode each aexpr byte, plus the terminating
13467 null byte. */
13468 if (aexpr->buf.size () * 2 + 1 > size_left)
13469 error ("%s", err_msg);
13470
13471 pkt = buf.data () + strlen (buf.data ());
13472
13473 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13474 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13475 *pkt = '\0';
13476 }
13477 else
13478 warning (_("Target does not support conditional tracepoints, "
13479 "ignoring tp %d cond"), b->number);
13480 }
13481
13482 if (b->commands || !default_collect.empty ())
13483 {
13484 size_left = buf.size () - strlen (buf.data ());
13485
13486 ret = snprintf (buf.data () + strlen (buf.data ()),
13487 size_left, "-");
13488
13489 if (ret < 0 || ret >= size_left)
13490 error ("%s", err_msg);
13491 }
13492
13493 putpkt (buf.data ());
13494 remote_get_noisy_reply ();
13495 if (strcmp (rs->buf.data (), "OK"))
13496 error (_("Target does not support tracepoints."));
13497
13498 /* do_single_steps (t); */
13499 for (auto action_it = tdp_actions.begin ();
13500 action_it != tdp_actions.end (); action_it++)
13501 {
13502 QUIT; /* Allow user to bail out with ^C. */
13503
13504 bool has_more = ((action_it + 1) != tdp_actions.end ()
13505 || !stepping_actions.empty ());
13506
13507 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13508 b->number, addrbuf, /* address */
13509 action_it->c_str (),
13510 has_more ? '-' : 0);
13511
13512 if (ret < 0 || ret >= buf.size ())
13513 error ("%s", err_msg);
13514
13515 putpkt (buf.data ());
13516 remote_get_noisy_reply ();
13517 if (strcmp (rs->buf.data (), "OK"))
13518 error (_("Error on target while setting tracepoints."));
13519 }
13520
13521 for (auto action_it = stepping_actions.begin ();
13522 action_it != stepping_actions.end (); action_it++)
13523 {
13524 QUIT; /* Allow user to bail out with ^C. */
13525
13526 bool is_first = action_it == stepping_actions.begin ();
13527 bool has_more = (action_it + 1) != stepping_actions.end ();
13528
13529 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13530 b->number, addrbuf, /* address */
13531 is_first ? "S" : "",
13532 action_it->c_str (),
13533 has_more ? "-" : "");
13534
13535 if (ret < 0 || ret >= buf.size ())
13536 error ("%s", err_msg);
13537
13538 putpkt (buf.data ());
13539 remote_get_noisy_reply ();
13540 if (strcmp (rs->buf.data (), "OK"))
13541 error (_("Error on target while setting tracepoints."));
13542 }
13543
13544 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13545 {
13546 if (b->locspec != nullptr)
13547 {
13548 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13549
13550 if (ret < 0 || ret >= buf.size ())
13551 error ("%s", err_msg);
13552
13553 const char *str = b->locspec->to_string ();
13554 encode_source_string (b->number, loc->address, "at", str,
13555 buf.data () + strlen (buf.data ()),
13556 buf.size () - strlen (buf.data ()));
13557 putpkt (buf.data ());
13558 remote_get_noisy_reply ();
13559 if (strcmp (rs->buf.data (), "OK"))
13560 warning (_("Target does not support source download."));
13561 }
13562 if (b->cond_string)
13563 {
13564 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13565
13566 if (ret < 0 || ret >= buf.size ())
13567 error ("%s", err_msg);
13568
13569 encode_source_string (b->number, loc->address,
13570 "cond", b->cond_string.get (),
13571 buf.data () + strlen (buf.data ()),
13572 buf.size () - strlen (buf.data ()));
13573 putpkt (buf.data ());
13574 remote_get_noisy_reply ();
13575 if (strcmp (rs->buf.data (), "OK"))
13576 warning (_("Target does not support source download."));
13577 }
13578 remote_download_command_source (b->number, loc->address,
13579 breakpoint_commands (b));
13580 }
13581 }
13582
13583 bool
13584 remote_target::can_download_tracepoint ()
13585 {
13586 struct remote_state *rs = get_remote_state ();
13587 struct trace_status *ts;
13588 int status;
13589
13590 /* Don't try to install tracepoints until we've relocated our
13591 symbols, and fetched and merged the target's tracepoint list with
13592 ours. */
13593 if (rs->starting_up)
13594 return false;
13595
13596 ts = current_trace_status ();
13597 status = get_trace_status (ts);
13598
13599 if (status == -1 || !ts->running_known || !ts->running)
13600 return false;
13601
13602 /* If we are in a tracing experiment, but remote stub doesn't support
13603 installing tracepoint in trace, we have to return. */
13604 if (!remote_supports_install_in_trace ())
13605 return false;
13606
13607 return true;
13608 }
13609
13610
13611 void
13612 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13613 {
13614 struct remote_state *rs = get_remote_state ();
13615 char *p;
13616
13617 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13618 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13619 tsv.builtin);
13620 p = rs->buf.data () + strlen (rs->buf.data ());
13621 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13622 >= get_remote_packet_size ())
13623 error (_("Trace state variable name too long for tsv definition packet"));
13624 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13625 *p++ = '\0';
13626 putpkt (rs->buf);
13627 remote_get_noisy_reply ();
13628 if (rs->buf[0] == '\0')
13629 error (_("Target does not support this command."));
13630 if (strcmp (rs->buf.data (), "OK") != 0)
13631 error (_("Error on target while downloading trace state variable."));
13632 }
13633
13634 void
13635 remote_target::enable_tracepoint (struct bp_location *location)
13636 {
13637 struct remote_state *rs = get_remote_state ();
13638
13639 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13640 location->owner->number,
13641 phex (location->address, sizeof (CORE_ADDR)));
13642 putpkt (rs->buf);
13643 remote_get_noisy_reply ();
13644 if (rs->buf[0] == '\0')
13645 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13646 if (strcmp (rs->buf.data (), "OK") != 0)
13647 error (_("Error on target while enabling tracepoint."));
13648 }
13649
13650 void
13651 remote_target::disable_tracepoint (struct bp_location *location)
13652 {
13653 struct remote_state *rs = get_remote_state ();
13654
13655 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13656 location->owner->number,
13657 phex (location->address, sizeof (CORE_ADDR)));
13658 putpkt (rs->buf);
13659 remote_get_noisy_reply ();
13660 if (rs->buf[0] == '\0')
13661 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13662 if (strcmp (rs->buf.data (), "OK") != 0)
13663 error (_("Error on target while disabling tracepoint."));
13664 }
13665
13666 void
13667 remote_target::trace_set_readonly_regions ()
13668 {
13669 asection *s;
13670 bfd_size_type size;
13671 bfd_vma vma;
13672 int anysecs = 0;
13673 int offset = 0;
13674 bfd *abfd = current_program_space->exec_bfd ();
13675
13676 if (!abfd)
13677 return; /* No information to give. */
13678
13679 struct remote_state *rs = get_remote_state ();
13680
13681 strcpy (rs->buf.data (), "QTro");
13682 offset = strlen (rs->buf.data ());
13683 for (s = abfd->sections; s; s = s->next)
13684 {
13685 char tmp1[40], tmp2[40];
13686 int sec_length;
13687
13688 if ((s->flags & SEC_LOAD) == 0
13689 /* || (s->flags & SEC_CODE) == 0 */
13690 || (s->flags & SEC_READONLY) == 0)
13691 continue;
13692
13693 anysecs = 1;
13694 vma = bfd_section_vma (s);
13695 size = bfd_section_size (s);
13696 bfd_sprintf_vma (abfd, tmp1, vma);
13697 bfd_sprintf_vma (abfd, tmp2, vma + size);
13698 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13699 if (offset + sec_length + 1 > rs->buf.size ())
13700 {
13701 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13702 != PACKET_ENABLE)
13703 warning (_("\
13704 Too many sections for read-only sections definition packet."));
13705 break;
13706 }
13707 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13708 tmp1, tmp2);
13709 offset += sec_length;
13710 }
13711 if (anysecs)
13712 {
13713 putpkt (rs->buf);
13714 getpkt (&rs->buf);
13715 }
13716 }
13717
13718 void
13719 remote_target::trace_start ()
13720 {
13721 struct remote_state *rs = get_remote_state ();
13722
13723 putpkt ("QTStart");
13724 remote_get_noisy_reply ();
13725 if (rs->buf[0] == '\0')
13726 error (_("Target does not support this command."));
13727 if (strcmp (rs->buf.data (), "OK") != 0)
13728 error (_("Bogus reply from target: %s"), rs->buf.data ());
13729 }
13730
13731 int
13732 remote_target::get_trace_status (struct trace_status *ts)
13733 {
13734 /* Initialize it just to avoid a GCC false warning. */
13735 char *p = NULL;
13736 enum packet_result result;
13737 struct remote_state *rs = get_remote_state ();
13738
13739 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13740 return -1;
13741
13742 /* FIXME we need to get register block size some other way. */
13743 trace_regblock_size
13744 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13745
13746 putpkt ("qTStatus");
13747
13748 try
13749 {
13750 p = remote_get_noisy_reply ();
13751 }
13752 catch (const gdb_exception_error &ex)
13753 {
13754 if (ex.error != TARGET_CLOSE_ERROR)
13755 {
13756 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13757 return -1;
13758 }
13759 throw;
13760 }
13761
13762 result = m_features.packet_ok (p, PACKET_qTStatus);
13763
13764 /* If the remote target doesn't do tracing, flag it. */
13765 if (result == PACKET_UNKNOWN)
13766 return -1;
13767
13768 /* We're working with a live target. */
13769 ts->filename = NULL;
13770
13771 if (*p++ != 'T')
13772 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13773
13774 /* Function 'parse_trace_status' sets default value of each field of
13775 'ts' at first, so we don't have to do it here. */
13776 parse_trace_status (p, ts);
13777
13778 return ts->running;
13779 }
13780
13781 void
13782 remote_target::get_tracepoint_status (tracepoint *tp,
13783 struct uploaded_tp *utp)
13784 {
13785 struct remote_state *rs = get_remote_state ();
13786 char *reply;
13787 size_t size = get_remote_packet_size ();
13788
13789 if (tp)
13790 {
13791 tp->hit_count = 0;
13792 tp->traceframe_usage = 0;
13793 for (bp_location &loc : tp->locations ())
13794 {
13795 /* If the tracepoint was never downloaded, don't go asking for
13796 any status. */
13797 if (tp->number_on_target == 0)
13798 continue;
13799 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13800 phex_nz (loc.address, 0));
13801 putpkt (rs->buf);
13802 reply = remote_get_noisy_reply ();
13803 if (reply && *reply)
13804 {
13805 if (*reply == 'V')
13806 parse_tracepoint_status (reply + 1, tp, utp);
13807 }
13808 }
13809 }
13810 else if (utp)
13811 {
13812 utp->hit_count = 0;
13813 utp->traceframe_usage = 0;
13814 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13815 phex_nz (utp->addr, 0));
13816 putpkt (rs->buf);
13817 reply = remote_get_noisy_reply ();
13818 if (reply && *reply)
13819 {
13820 if (*reply == 'V')
13821 parse_tracepoint_status (reply + 1, tp, utp);
13822 }
13823 }
13824 }
13825
13826 void
13827 remote_target::trace_stop ()
13828 {
13829 struct remote_state *rs = get_remote_state ();
13830
13831 putpkt ("QTStop");
13832 remote_get_noisy_reply ();
13833 if (rs->buf[0] == '\0')
13834 error (_("Target does not support this command."));
13835 if (strcmp (rs->buf.data (), "OK") != 0)
13836 error (_("Bogus reply from target: %s"), rs->buf.data ());
13837 }
13838
13839 int
13840 remote_target::trace_find (enum trace_find_type type, int num,
13841 CORE_ADDR addr1, CORE_ADDR addr2,
13842 int *tpp)
13843 {
13844 struct remote_state *rs = get_remote_state ();
13845 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13846 char *p, *reply;
13847 int target_frameno = -1, target_tracept = -1;
13848
13849 /* Lookups other than by absolute frame number depend on the current
13850 trace selected, so make sure it is correct on the remote end
13851 first. */
13852 if (type != tfind_number)
13853 set_remote_traceframe ();
13854
13855 p = rs->buf.data ();
13856 strcpy (p, "QTFrame:");
13857 p = strchr (p, '\0');
13858 switch (type)
13859 {
13860 case tfind_number:
13861 xsnprintf (p, endbuf - p, "%x", num);
13862 break;
13863 case tfind_pc:
13864 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13865 break;
13866 case tfind_tp:
13867 xsnprintf (p, endbuf - p, "tdp:%x", num);
13868 break;
13869 case tfind_range:
13870 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13871 phex_nz (addr2, 0));
13872 break;
13873 case tfind_outside:
13874 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13875 phex_nz (addr2, 0));
13876 break;
13877 default:
13878 error (_("Unknown trace find type %d"), type);
13879 }
13880
13881 putpkt (rs->buf);
13882 reply = remote_get_noisy_reply ();
13883 if (*reply == '\0')
13884 error (_("Target does not support this command."));
13885
13886 while (reply && *reply)
13887 switch (*reply)
13888 {
13889 case 'F':
13890 p = ++reply;
13891 target_frameno = (int) strtol (p, &reply, 16);
13892 if (reply == p)
13893 error (_("Unable to parse trace frame number"));
13894 /* Don't update our remote traceframe number cache on failure
13895 to select a remote traceframe. */
13896 if (target_frameno == -1)
13897 return -1;
13898 break;
13899 case 'T':
13900 p = ++reply;
13901 target_tracept = (int) strtol (p, &reply, 16);
13902 if (reply == p)
13903 error (_("Unable to parse tracepoint number"));
13904 break;
13905 case 'O': /* "OK"? */
13906 if (reply[1] == 'K' && reply[2] == '\0')
13907 reply += 2;
13908 else
13909 error (_("Bogus reply from target: %s"), reply);
13910 break;
13911 default:
13912 error (_("Bogus reply from target: %s"), reply);
13913 }
13914 if (tpp)
13915 *tpp = target_tracept;
13916
13917 rs->remote_traceframe_number = target_frameno;
13918 return target_frameno;
13919 }
13920
13921 bool
13922 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13923 {
13924 struct remote_state *rs = get_remote_state ();
13925 char *reply;
13926 ULONGEST uval;
13927
13928 set_remote_traceframe ();
13929
13930 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13931 putpkt (rs->buf);
13932 reply = remote_get_noisy_reply ();
13933 if (reply && *reply)
13934 {
13935 if (*reply == 'V')
13936 {
13937 unpack_varlen_hex (reply + 1, &uval);
13938 *val = (LONGEST) uval;
13939 return true;
13940 }
13941 }
13942 return false;
13943 }
13944
13945 int
13946 remote_target::save_trace_data (const char *filename)
13947 {
13948 struct remote_state *rs = get_remote_state ();
13949 char *p, *reply;
13950
13951 p = rs->buf.data ();
13952 strcpy (p, "QTSave:");
13953 p += strlen (p);
13954 if ((p - rs->buf.data ()) + strlen (filename) * 2
13955 >= get_remote_packet_size ())
13956 error (_("Remote file name too long for trace save packet"));
13957 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13958 *p++ = '\0';
13959 putpkt (rs->buf);
13960 reply = remote_get_noisy_reply ();
13961 if (*reply == '\0')
13962 error (_("Target does not support this command."));
13963 if (strcmp (reply, "OK") != 0)
13964 error (_("Bogus reply from target: %s"), reply);
13965 return 0;
13966 }
13967
13968 /* This is basically a memory transfer, but needs to be its own packet
13969 because we don't know how the target actually organizes its trace
13970 memory, plus we want to be able to ask for as much as possible, but
13971 not be unhappy if we don't get as much as we ask for. */
13972
13973 LONGEST
13974 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13975 {
13976 struct remote_state *rs = get_remote_state ();
13977 char *reply;
13978 char *p;
13979 int rslt;
13980
13981 p = rs->buf.data ();
13982 strcpy (p, "qTBuffer:");
13983 p += strlen (p);
13984 p += hexnumstr (p, offset);
13985 *p++ = ',';
13986 p += hexnumstr (p, len);
13987 *p++ = '\0';
13988
13989 putpkt (rs->buf);
13990 reply = remote_get_noisy_reply ();
13991 if (reply && *reply)
13992 {
13993 /* 'l' by itself means we're at the end of the buffer and
13994 there is nothing more to get. */
13995 if (*reply == 'l')
13996 return 0;
13997
13998 /* Convert the reply into binary. Limit the number of bytes to
13999 convert according to our passed-in buffer size, rather than
14000 what was returned in the packet; if the target is
14001 unexpectedly generous and gives us a bigger reply than we
14002 asked for, we don't want to crash. */
14003 rslt = hex2bin (reply, buf, len);
14004 return rslt;
14005 }
14006
14007 /* Something went wrong, flag as an error. */
14008 return -1;
14009 }
14010
14011 void
14012 remote_target::set_disconnected_tracing (int val)
14013 {
14014 struct remote_state *rs = get_remote_state ();
14015
14016 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14017 == PACKET_ENABLE)
14018 {
14019 char *reply;
14020
14021 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14022 "QTDisconnected:%x", val);
14023 putpkt (rs->buf);
14024 reply = remote_get_noisy_reply ();
14025 if (*reply == '\0')
14026 error (_("Target does not support this command."));
14027 if (strcmp (reply, "OK") != 0)
14028 error (_("Bogus reply from target: %s"), reply);
14029 }
14030 else if (val)
14031 warning (_("Target does not support disconnected tracing."));
14032 }
14033
14034 int
14035 remote_target::core_of_thread (ptid_t ptid)
14036 {
14037 thread_info *info = this->find_thread (ptid);
14038
14039 if (info != NULL && info->priv != NULL)
14040 return get_remote_thread_info (info)->core;
14041
14042 return -1;
14043 }
14044
14045 void
14046 remote_target::set_circular_trace_buffer (int val)
14047 {
14048 struct remote_state *rs = get_remote_state ();
14049 char *reply;
14050
14051 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14052 "QTBuffer:circular:%x", val);
14053 putpkt (rs->buf);
14054 reply = remote_get_noisy_reply ();
14055 if (*reply == '\0')
14056 error (_("Target does not support this command."));
14057 if (strcmp (reply, "OK") != 0)
14058 error (_("Bogus reply from target: %s"), reply);
14059 }
14060
14061 traceframe_info_up
14062 remote_target::traceframe_info ()
14063 {
14064 gdb::optional<gdb::char_vector> text
14065 = target_read_stralloc (current_inferior ()->top_target (),
14066 TARGET_OBJECT_TRACEFRAME_INFO,
14067 NULL);
14068 if (text)
14069 return parse_traceframe_info (text->data ());
14070
14071 return NULL;
14072 }
14073
14074 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14075 instruction on which a fast tracepoint may be placed. Returns -1
14076 if the packet is not supported, and 0 if the minimum instruction
14077 length is unknown. */
14078
14079 int
14080 remote_target::get_min_fast_tracepoint_insn_len ()
14081 {
14082 struct remote_state *rs = get_remote_state ();
14083 char *reply;
14084
14085 /* If we're not debugging a process yet, the IPA can't be
14086 loaded. */
14087 if (!target_has_execution ())
14088 return 0;
14089
14090 /* Make sure the remote is pointing at the right process. */
14091 set_general_process ();
14092
14093 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14094 putpkt (rs->buf);
14095 reply = remote_get_noisy_reply ();
14096 if (*reply == '\0')
14097 return -1;
14098 else
14099 {
14100 ULONGEST min_insn_len;
14101
14102 unpack_varlen_hex (reply, &min_insn_len);
14103
14104 return (int) min_insn_len;
14105 }
14106 }
14107
14108 void
14109 remote_target::set_trace_buffer_size (LONGEST val)
14110 {
14111 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14112 {
14113 struct remote_state *rs = get_remote_state ();
14114 char *buf = rs->buf.data ();
14115 char *endbuf = buf + get_remote_packet_size ();
14116 enum packet_result result;
14117
14118 gdb_assert (val >= 0 || val == -1);
14119 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14120 /* Send -1 as literal "-1" to avoid host size dependency. */
14121 if (val < 0)
14122 {
14123 *buf++ = '-';
14124 buf += hexnumstr (buf, (ULONGEST) -val);
14125 }
14126 else
14127 buf += hexnumstr (buf, (ULONGEST) val);
14128
14129 putpkt (rs->buf);
14130 remote_get_noisy_reply ();
14131 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14132
14133 if (result != PACKET_OK)
14134 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14135 }
14136 }
14137
14138 bool
14139 remote_target::set_trace_notes (const char *user, const char *notes,
14140 const char *stop_notes)
14141 {
14142 struct remote_state *rs = get_remote_state ();
14143 char *reply;
14144 char *buf = rs->buf.data ();
14145 char *endbuf = buf + get_remote_packet_size ();
14146 int nbytes;
14147
14148 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14149 if (user)
14150 {
14151 buf += xsnprintf (buf, endbuf - buf, "user:");
14152 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14153 buf += 2 * nbytes;
14154 *buf++ = ';';
14155 }
14156 if (notes)
14157 {
14158 buf += xsnprintf (buf, endbuf - buf, "notes:");
14159 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14160 buf += 2 * nbytes;
14161 *buf++ = ';';
14162 }
14163 if (stop_notes)
14164 {
14165 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14166 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14167 buf += 2 * nbytes;
14168 *buf++ = ';';
14169 }
14170 /* Ensure the buffer is terminated. */
14171 *buf = '\0';
14172
14173 putpkt (rs->buf);
14174 reply = remote_get_noisy_reply ();
14175 if (*reply == '\0')
14176 return false;
14177
14178 if (strcmp (reply, "OK") != 0)
14179 error (_("Bogus reply from target: %s"), reply);
14180
14181 return true;
14182 }
14183
14184 bool
14185 remote_target::use_agent (bool use)
14186 {
14187 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14188 {
14189 struct remote_state *rs = get_remote_state ();
14190
14191 /* If the stub supports QAgent. */
14192 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14193 putpkt (rs->buf);
14194 getpkt (&rs->buf);
14195
14196 if (strcmp (rs->buf.data (), "OK") == 0)
14197 {
14198 ::use_agent = use;
14199 return true;
14200 }
14201 }
14202
14203 return false;
14204 }
14205
14206 bool
14207 remote_target::can_use_agent ()
14208 {
14209 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14210 }
14211
14212 #if defined (HAVE_LIBEXPAT)
14213
14214 /* Check the btrace document version. */
14215
14216 static void
14217 check_xml_btrace_version (struct gdb_xml_parser *parser,
14218 const struct gdb_xml_element *element,
14219 void *user_data,
14220 std::vector<gdb_xml_value> &attributes)
14221 {
14222 const char *version
14223 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14224
14225 if (strcmp (version, "1.0") != 0)
14226 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14227 }
14228
14229 /* Parse a btrace "block" xml record. */
14230
14231 static void
14232 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14233 const struct gdb_xml_element *element,
14234 void *user_data,
14235 std::vector<gdb_xml_value> &attributes)
14236 {
14237 struct btrace_data *btrace;
14238 ULONGEST *begin, *end;
14239
14240 btrace = (struct btrace_data *) user_data;
14241
14242 switch (btrace->format)
14243 {
14244 case BTRACE_FORMAT_BTS:
14245 break;
14246
14247 case BTRACE_FORMAT_NONE:
14248 btrace->format = BTRACE_FORMAT_BTS;
14249 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14250 break;
14251
14252 default:
14253 gdb_xml_error (parser, _("Btrace format error."));
14254 }
14255
14256 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14257 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14258 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14259 }
14260
14261 /* Parse a "raw" xml record. */
14262
14263 static void
14264 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14265 gdb_byte **pdata, size_t *psize)
14266 {
14267 gdb_byte *bin;
14268 size_t len, size;
14269
14270 len = strlen (body_text);
14271 if (len % 2 != 0)
14272 gdb_xml_error (parser, _("Bad raw data size."));
14273
14274 size = len / 2;
14275
14276 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14277 bin = data.get ();
14278
14279 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14280 while (len > 0)
14281 {
14282 char hi, lo;
14283
14284 hi = *body_text++;
14285 lo = *body_text++;
14286
14287 if (hi == 0 || lo == 0)
14288 gdb_xml_error (parser, _("Bad hex encoding."));
14289
14290 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14291 len -= 2;
14292 }
14293
14294 *pdata = data.release ();
14295 *psize = size;
14296 }
14297
14298 /* Parse a btrace pt-config "cpu" xml record. */
14299
14300 static void
14301 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14302 const struct gdb_xml_element *element,
14303 void *user_data,
14304 std::vector<gdb_xml_value> &attributes)
14305 {
14306 struct btrace_data *btrace;
14307 const char *vendor;
14308 ULONGEST *family, *model, *stepping;
14309
14310 vendor
14311 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14312 family
14313 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14314 model
14315 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14316 stepping
14317 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14318
14319 btrace = (struct btrace_data *) user_data;
14320
14321 if (strcmp (vendor, "GenuineIntel") == 0)
14322 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14323
14324 btrace->variant.pt.config.cpu.family = *family;
14325 btrace->variant.pt.config.cpu.model = *model;
14326 btrace->variant.pt.config.cpu.stepping = *stepping;
14327 }
14328
14329 /* Parse a btrace pt "raw" xml record. */
14330
14331 static void
14332 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14333 const struct gdb_xml_element *element,
14334 void *user_data, const char *body_text)
14335 {
14336 struct btrace_data *btrace;
14337
14338 btrace = (struct btrace_data *) user_data;
14339 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14340 &btrace->variant.pt.size);
14341 }
14342
14343 /* Parse a btrace "pt" xml record. */
14344
14345 static void
14346 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14347 const struct gdb_xml_element *element,
14348 void *user_data,
14349 std::vector<gdb_xml_value> &attributes)
14350 {
14351 struct btrace_data *btrace;
14352
14353 btrace = (struct btrace_data *) user_data;
14354 btrace->format = BTRACE_FORMAT_PT;
14355 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14356 btrace->variant.pt.data = NULL;
14357 btrace->variant.pt.size = 0;
14358 }
14359
14360 static const struct gdb_xml_attribute block_attributes[] = {
14361 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14362 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14363 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14364 };
14365
14366 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14367 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14368 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14369 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14370 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14371 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14372 };
14373
14374 static const struct gdb_xml_element btrace_pt_config_children[] = {
14375 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14376 parse_xml_btrace_pt_config_cpu, NULL },
14377 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14378 };
14379
14380 static const struct gdb_xml_element btrace_pt_children[] = {
14381 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14382 NULL },
14383 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14384 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14385 };
14386
14387 static const struct gdb_xml_attribute btrace_attributes[] = {
14388 { "version", GDB_XML_AF_NONE, NULL, NULL },
14389 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14390 };
14391
14392 static const struct gdb_xml_element btrace_children[] = {
14393 { "block", block_attributes, NULL,
14394 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14395 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14396 NULL },
14397 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14398 };
14399
14400 static const struct gdb_xml_element btrace_elements[] = {
14401 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14402 check_xml_btrace_version, NULL },
14403 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14404 };
14405
14406 #endif /* defined (HAVE_LIBEXPAT) */
14407
14408 /* Parse a branch trace xml document XML into DATA. */
14409
14410 static void
14411 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14412 {
14413 #if defined (HAVE_LIBEXPAT)
14414
14415 int errcode;
14416 btrace_data result;
14417 result.format = BTRACE_FORMAT_NONE;
14418
14419 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14420 buffer, &result);
14421 if (errcode != 0)
14422 error (_("Error parsing branch trace."));
14423
14424 /* Keep parse results. */
14425 *btrace = std::move (result);
14426
14427 #else /* !defined (HAVE_LIBEXPAT) */
14428
14429 error (_("Cannot process branch trace. XML support was disabled at "
14430 "compile time."));
14431
14432 #endif /* !defined (HAVE_LIBEXPAT) */
14433 }
14434
14435 #if defined (HAVE_LIBEXPAT)
14436
14437 /* Parse a btrace-conf "bts" xml record. */
14438
14439 static void
14440 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14441 const struct gdb_xml_element *element,
14442 void *user_data,
14443 std::vector<gdb_xml_value> &attributes)
14444 {
14445 struct btrace_config *conf;
14446 struct gdb_xml_value *size;
14447
14448 conf = (struct btrace_config *) user_data;
14449 conf->format = BTRACE_FORMAT_BTS;
14450 conf->bts.size = 0;
14451
14452 size = xml_find_attribute (attributes, "size");
14453 if (size != NULL)
14454 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14455 }
14456
14457 /* Parse a btrace-conf "pt" xml record. */
14458
14459 static void
14460 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14461 const struct gdb_xml_element *element,
14462 void *user_data,
14463 std::vector<gdb_xml_value> &attributes)
14464 {
14465 struct btrace_config *conf;
14466 struct gdb_xml_value *size;
14467
14468 conf = (struct btrace_config *) user_data;
14469 conf->format = BTRACE_FORMAT_PT;
14470 conf->pt.size = 0;
14471
14472 size = xml_find_attribute (attributes, "size");
14473 if (size != NULL)
14474 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14475 }
14476
14477 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14478 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14479 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14480 };
14481
14482 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14483 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14484 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14485 };
14486
14487 static const struct gdb_xml_element btrace_conf_children[] = {
14488 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14489 parse_xml_btrace_conf_bts, NULL },
14490 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14491 parse_xml_btrace_conf_pt, NULL },
14492 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14493 };
14494
14495 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14496 { "version", GDB_XML_AF_NONE, NULL, NULL },
14497 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14498 };
14499
14500 static const struct gdb_xml_element btrace_conf_elements[] = {
14501 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14502 GDB_XML_EF_NONE, NULL, NULL },
14503 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14504 };
14505
14506 #endif /* defined (HAVE_LIBEXPAT) */
14507
14508 /* Parse a branch trace configuration xml document XML into CONF. */
14509
14510 static void
14511 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14512 {
14513 #if defined (HAVE_LIBEXPAT)
14514
14515 int errcode;
14516 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14517 btrace_conf_elements, xml, conf);
14518 if (errcode != 0)
14519 error (_("Error parsing branch trace configuration."));
14520
14521 #else /* !defined (HAVE_LIBEXPAT) */
14522
14523 error (_("Cannot process the branch trace configuration. XML support "
14524 "was disabled at compile time."));
14525
14526 #endif /* !defined (HAVE_LIBEXPAT) */
14527 }
14528
14529 /* Reset our idea of our target's btrace configuration. */
14530
14531 static void
14532 remote_btrace_reset (remote_state *rs)
14533 {
14534 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14535 }
14536
14537 /* Synchronize the configuration with the target. */
14538
14539 void
14540 remote_target::btrace_sync_conf (const btrace_config *conf)
14541 {
14542 struct remote_state *rs;
14543 char *buf, *pos, *endbuf;
14544
14545 rs = get_remote_state ();
14546 buf = rs->buf.data ();
14547 endbuf = buf + get_remote_packet_size ();
14548
14549 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14550 && conf->bts.size != rs->btrace_config.bts.size)
14551 {
14552 pos = buf;
14553 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14554 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14555 conf->bts.size);
14556
14557 putpkt (buf);
14558 getpkt (&rs->buf);
14559
14560 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14561 == PACKET_ERROR)
14562 {
14563 if (buf[0] == 'E' && buf[1] == '.')
14564 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14565 else
14566 error (_("Failed to configure the BTS buffer size."));
14567 }
14568
14569 rs->btrace_config.bts.size = conf->bts.size;
14570 }
14571
14572 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14573 && conf->pt.size != rs->btrace_config.pt.size)
14574 {
14575 pos = buf;
14576 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14577 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14578 conf->pt.size);
14579
14580 putpkt (buf);
14581 getpkt (&rs->buf);
14582
14583 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14584 == PACKET_ERROR)
14585 {
14586 if (buf[0] == 'E' && buf[1] == '.')
14587 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14588 else
14589 error (_("Failed to configure the trace buffer size."));
14590 }
14591
14592 rs->btrace_config.pt.size = conf->pt.size;
14593 }
14594 }
14595
14596 /* Read TP's btrace configuration from the target and store it into CONF. */
14597
14598 static void
14599 btrace_read_config (thread_info *tp, btrace_config *conf)
14600 {
14601 /* target_read_stralloc relies on INFERIOR_PTID. */
14602 scoped_restore_current_thread restore_thread;
14603 switch_to_thread (tp);
14604
14605 gdb::optional<gdb::char_vector> xml
14606 = target_read_stralloc (current_inferior ()->top_target (),
14607 TARGET_OBJECT_BTRACE_CONF, "");
14608 if (xml)
14609 parse_xml_btrace_conf (conf, xml->data ());
14610 }
14611
14612 /* Maybe reopen target btrace. */
14613
14614 void
14615 remote_target::remote_btrace_maybe_reopen ()
14616 {
14617 struct remote_state *rs = get_remote_state ();
14618 int btrace_target_pushed = 0;
14619 #if !defined (HAVE_LIBIPT)
14620 int warned = 0;
14621 #endif
14622
14623 /* Don't bother walking the entirety of the remote thread list when
14624 we know the feature isn't supported by the remote. */
14625 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14626 return;
14627
14628 for (thread_info *tp : all_non_exited_threads (this))
14629 {
14630 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14631 btrace_read_config (tp, &rs->btrace_config);
14632
14633 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14634 continue;
14635
14636 #if !defined (HAVE_LIBIPT)
14637 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14638 {
14639 if (!warned)
14640 {
14641 warned = 1;
14642 warning (_("Target is recording using Intel Processor Trace "
14643 "but support was disabled at compile time."));
14644 }
14645
14646 continue;
14647 }
14648 #endif /* !defined (HAVE_LIBIPT) */
14649
14650 /* Push target, once, but before anything else happens. This way our
14651 changes to the threads will be cleaned up by unpushing the target
14652 in case btrace_read_config () throws. */
14653 if (!btrace_target_pushed)
14654 {
14655 btrace_target_pushed = 1;
14656 record_btrace_push_target ();
14657 gdb_printf (_("Target is recording using %s.\n"),
14658 btrace_format_string (rs->btrace_config.format));
14659 }
14660
14661 tp->btrace.target
14662 = new btrace_target_info { tp->ptid, rs->btrace_config };
14663 }
14664 }
14665
14666 /* Enable branch tracing. */
14667
14668 struct btrace_target_info *
14669 remote_target::enable_btrace (thread_info *tp,
14670 const struct btrace_config *conf)
14671 {
14672 struct packet_config *packet = NULL;
14673 struct remote_state *rs = get_remote_state ();
14674 char *buf = rs->buf.data ();
14675 char *endbuf = buf + get_remote_packet_size ();
14676
14677 unsigned int which_packet;
14678 switch (conf->format)
14679 {
14680 case BTRACE_FORMAT_BTS:
14681 which_packet = PACKET_Qbtrace_bts;
14682 break;
14683 case BTRACE_FORMAT_PT:
14684 which_packet = PACKET_Qbtrace_pt;
14685 break;
14686 default:
14687 internal_error (_("Bad branch btrace format: %u."),
14688 (unsigned int) conf->format);
14689 }
14690
14691 packet = &m_features.m_protocol_packets[which_packet];
14692 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14693 error (_("Target does not support branch tracing."));
14694
14695 btrace_sync_conf (conf);
14696
14697 ptid_t ptid = tp->ptid;
14698 set_general_thread (ptid);
14699
14700 buf += xsnprintf (buf, endbuf - buf, "%s",
14701 packets_descriptions[which_packet].name);
14702 putpkt (rs->buf);
14703 getpkt (&rs->buf);
14704
14705 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14706 {
14707 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14708 error (_("Could not enable branch tracing for %s: %s"),
14709 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14710 else
14711 error (_("Could not enable branch tracing for %s."),
14712 target_pid_to_str (ptid).c_str ());
14713 }
14714
14715 btrace_target_info *tinfo = new btrace_target_info { ptid };
14716
14717 /* If we fail to read the configuration, we lose some information, but the
14718 tracing itself is not impacted. */
14719 try
14720 {
14721 btrace_read_config (tp, &tinfo->conf);
14722 }
14723 catch (const gdb_exception_error &err)
14724 {
14725 if (err.message != NULL)
14726 warning ("%s", err.what ());
14727 }
14728
14729 return tinfo;
14730 }
14731
14732 /* Disable branch tracing. */
14733
14734 void
14735 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14736 {
14737 struct remote_state *rs = get_remote_state ();
14738 char *buf = rs->buf.data ();
14739 char *endbuf = buf + get_remote_packet_size ();
14740
14741 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14742 error (_("Target does not support branch tracing."));
14743
14744 set_general_thread (tinfo->ptid);
14745
14746 buf += xsnprintf (buf, endbuf - buf, "%s",
14747 packets_descriptions[PACKET_Qbtrace_off].name);
14748 putpkt (rs->buf);
14749 getpkt (&rs->buf);
14750
14751 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14752 {
14753 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14754 error (_("Could not disable branch tracing for %s: %s"),
14755 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14756 else
14757 error (_("Could not disable branch tracing for %s."),
14758 target_pid_to_str (tinfo->ptid).c_str ());
14759 }
14760
14761 delete tinfo;
14762 }
14763
14764 /* Teardown branch tracing. */
14765
14766 void
14767 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14768 {
14769 /* We must not talk to the target during teardown. */
14770 delete tinfo;
14771 }
14772
14773 /* Read the branch trace. */
14774
14775 enum btrace_error
14776 remote_target::read_btrace (struct btrace_data *btrace,
14777 struct btrace_target_info *tinfo,
14778 enum btrace_read_type type)
14779 {
14780 const char *annex;
14781
14782 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14783 error (_("Target does not support branch tracing."));
14784
14785 #if !defined(HAVE_LIBEXPAT)
14786 error (_("Cannot process branch tracing result. XML parsing not supported."));
14787 #endif
14788
14789 switch (type)
14790 {
14791 case BTRACE_READ_ALL:
14792 annex = "all";
14793 break;
14794 case BTRACE_READ_NEW:
14795 annex = "new";
14796 break;
14797 case BTRACE_READ_DELTA:
14798 annex = "delta";
14799 break;
14800 default:
14801 internal_error (_("Bad branch tracing read type: %u."),
14802 (unsigned int) type);
14803 }
14804
14805 gdb::optional<gdb::char_vector> xml
14806 = target_read_stralloc (current_inferior ()->top_target (),
14807 TARGET_OBJECT_BTRACE, annex);
14808 if (!xml)
14809 return BTRACE_ERR_UNKNOWN;
14810
14811 parse_xml_btrace (btrace, xml->data ());
14812
14813 return BTRACE_ERR_NONE;
14814 }
14815
14816 const struct btrace_config *
14817 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14818 {
14819 return &tinfo->conf;
14820 }
14821
14822 bool
14823 remote_target::augmented_libraries_svr4_read ()
14824 {
14825 return
14826 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14827 == PACKET_ENABLE);
14828 }
14829
14830 /* Implementation of to_load. */
14831
14832 void
14833 remote_target::load (const char *name, int from_tty)
14834 {
14835 generic_load (name, from_tty);
14836 }
14837
14838 /* Accepts an integer PID; returns a string representing a file that
14839 can be opened on the remote side to get the symbols for the child
14840 process. Returns NULL if the operation is not supported. */
14841
14842 const char *
14843 remote_target::pid_to_exec_file (int pid)
14844 {
14845 static gdb::optional<gdb::char_vector> filename;
14846 char *annex = NULL;
14847
14848 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14849 return NULL;
14850
14851 inferior *inf = find_inferior_pid (this, pid);
14852 if (inf == NULL)
14853 internal_error (_("not currently attached to process %d"), pid);
14854
14855 if (!inf->fake_pid_p)
14856 {
14857 const int annex_size = 9;
14858
14859 annex = (char *) alloca (annex_size);
14860 xsnprintf (annex, annex_size, "%x", pid);
14861 }
14862
14863 filename = target_read_stralloc (current_inferior ()->top_target (),
14864 TARGET_OBJECT_EXEC_FILE, annex);
14865
14866 return filename ? filename->data () : nullptr;
14867 }
14868
14869 /* Implement the to_can_do_single_step target_ops method. */
14870
14871 int
14872 remote_target::can_do_single_step ()
14873 {
14874 /* We can only tell whether target supports single step or not by
14875 supported s and S vCont actions if the stub supports vContSupported
14876 feature. If the stub doesn't support vContSupported feature,
14877 we have conservatively to think target doesn't supports single
14878 step. */
14879 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14880 {
14881 struct remote_state *rs = get_remote_state ();
14882
14883 return rs->supports_vCont.s && rs->supports_vCont.S;
14884 }
14885 else
14886 return 0;
14887 }
14888
14889 /* Implementation of the to_execution_direction method for the remote
14890 target. */
14891
14892 enum exec_direction_kind
14893 remote_target::execution_direction ()
14894 {
14895 struct remote_state *rs = get_remote_state ();
14896
14897 return rs->last_resume_exec_dir;
14898 }
14899
14900 /* Return pointer to the thread_info struct which corresponds to
14901 THREAD_HANDLE (having length HANDLE_LEN). */
14902
14903 thread_info *
14904 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14905 int handle_len,
14906 inferior *inf)
14907 {
14908 for (thread_info *tp : all_non_exited_threads (this))
14909 {
14910 remote_thread_info *priv = get_remote_thread_info (tp);
14911
14912 if (tp->inf == inf && priv != NULL)
14913 {
14914 if (handle_len != priv->thread_handle.size ())
14915 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14916 handle_len, priv->thread_handle.size ());
14917 if (memcmp (thread_handle, priv->thread_handle.data (),
14918 handle_len) == 0)
14919 return tp;
14920 }
14921 }
14922
14923 return NULL;
14924 }
14925
14926 gdb::array_view<const gdb_byte>
14927 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14928 {
14929 remote_thread_info *priv = get_remote_thread_info (tp);
14930 return priv->thread_handle;
14931 }
14932
14933 bool
14934 remote_target::can_async_p ()
14935 {
14936 /* This flag should be checked in the common target.c code. */
14937 gdb_assert (target_async_permitted);
14938
14939 /* We're async whenever the serial device can. */
14940 return get_remote_state ()->can_async_p ();
14941 }
14942
14943 bool
14944 remote_target::is_async_p ()
14945 {
14946 /* We're async whenever the serial device is. */
14947 return get_remote_state ()->is_async_p ();
14948 }
14949
14950 /* Pass the SERIAL event on and up to the client. One day this code
14951 will be able to delay notifying the client of an event until the
14952 point where an entire packet has been received. */
14953
14954 static serial_event_ftype remote_async_serial_handler;
14955
14956 static void
14957 remote_async_serial_handler (struct serial *scb, void *context)
14958 {
14959 /* Don't propogate error information up to the client. Instead let
14960 the client find out about the error by querying the target. */
14961 inferior_event_handler (INF_REG_EVENT);
14962 }
14963
14964 int
14965 remote_target::async_wait_fd ()
14966 {
14967 struct remote_state *rs = get_remote_state ();
14968 return rs->remote_desc->fd;
14969 }
14970
14971 void
14972 remote_target::async (bool enable)
14973 {
14974 struct remote_state *rs = get_remote_state ();
14975
14976 if (enable)
14977 {
14978 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14979
14980 /* If there are pending events in the stop reply queue tell the
14981 event loop to process them. */
14982 if (!rs->stop_reply_queue.empty ())
14983 rs->mark_async_event_handler ();
14984
14985 /* For simplicity, below we clear the pending events token
14986 without remembering whether it is marked, so here we always
14987 mark it. If there's actually no pending notification to
14988 process, this ends up being a no-op (other than a spurious
14989 event-loop wakeup). */
14990 if (target_is_non_stop_p ())
14991 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14992 }
14993 else
14994 {
14995 serial_async (rs->remote_desc, NULL, NULL);
14996 /* If the core is disabling async, it doesn't want to be
14997 disturbed with target events. Clear all async event sources
14998 too. */
14999 rs->clear_async_event_handler ();
15000
15001 if (target_is_non_stop_p ())
15002 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15003 }
15004 }
15005
15006 /* Implementation of the to_thread_events method. */
15007
15008 void
15009 remote_target::thread_events (int enable)
15010 {
15011 struct remote_state *rs = get_remote_state ();
15012 size_t size = get_remote_packet_size ();
15013
15014 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15015 return;
15016
15017 if (rs->last_thread_events == enable)
15018 return;
15019
15020 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15021 putpkt (rs->buf);
15022 getpkt (&rs->buf);
15023
15024 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
15025 {
15026 case PACKET_OK:
15027 if (strcmp (rs->buf.data (), "OK") != 0)
15028 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15029 rs->last_thread_events = enable;
15030 break;
15031 case PACKET_ERROR:
15032 warning (_("Remote failure reply: %s"), rs->buf.data ());
15033 break;
15034 case PACKET_UNKNOWN:
15035 break;
15036 }
15037 }
15038
15039 static void
15040 show_remote_cmd (const char *args, int from_tty)
15041 {
15042 /* We can't just use cmd_show_list here, because we want to skip
15043 the redundant "show remote Z-packet" and the legacy aliases. */
15044 struct cmd_list_element *list = remote_show_cmdlist;
15045 struct ui_out *uiout = current_uiout;
15046
15047 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15048 for (; list != NULL; list = list->next)
15049 if (strcmp (list->name, "Z-packet") == 0)
15050 continue;
15051 else if (list->type == not_set_cmd)
15052 /* Alias commands are exactly like the original, except they
15053 don't have the normal type. */
15054 continue;
15055 else
15056 {
15057 ui_out_emit_tuple option_emitter (uiout, "option");
15058
15059 uiout->field_string ("name", list->name);
15060 uiout->text (": ");
15061 if (list->type == show_cmd)
15062 do_show_command (NULL, from_tty, list);
15063 else
15064 cmd_func (list, NULL, from_tty);
15065 }
15066 }
15067
15068 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15069 offer all inferiors using that program space a change to look up symbols. */
15070
15071 static void
15072 remote_objfile_changed_check_symbols (program_space *pspace)
15073 {
15074 /* The affected program space is possibly shared by multiple inferiors.
15075 Consider sending a qSymbol packet for each of the inferiors using that
15076 program space. */
15077 for (inferior *inf : all_inferiors ())
15078 {
15079 if (inf->pspace != pspace)
15080 continue;
15081
15082 /* Check whether the inferior's process target is a remote target. */
15083 remote_target *remote = as_remote_target (inf->process_target ());
15084 if (remote == nullptr)
15085 continue;
15086
15087 /* When we are attaching or handling a fork child and the shared library
15088 subsystem reads the list of loaded libraries, we receive new objfile
15089 events in between each found library. The libraries are read in an
15090 undefined order, so if we gave the remote side a chance to look up
15091 symbols between each objfile, we might give it an inconsistent picture
15092 of the inferior. It could appear that a library A appears loaded but
15093 a library B does not, even though library A requires library B. That
15094 would present a state that couldn't normally exist in the inferior.
15095
15096 So, skip these events, we'll give the remote a chance to look up
15097 symbols once all the loaded libraries and their symbols are known to
15098 GDB. */
15099 if (inf->in_initial_library_scan)
15100 continue;
15101
15102 if (!remote->has_execution (inf))
15103 continue;
15104
15105 /* Need to switch to a specific thread, because remote_check_symbols will
15106 set the general thread using INFERIOR_PTID.
15107
15108 It's possible to have inferiors with no thread here, because we are
15109 called very early in the connection process, while the inferior is
15110 being set up, before threads are added. Just skip it, start_remote_1
15111 also calls remote_check_symbols when it's done setting things up. */
15112 thread_info *thread = any_thread_of_inferior (inf);
15113 if (thread != nullptr)
15114 {
15115 scoped_restore_current_thread restore_thread;
15116 switch_to_thread (thread);
15117 remote->remote_check_symbols ();
15118 }
15119 }
15120 }
15121
15122 /* Function to be called whenever a new objfile (shlib) is detected. */
15123
15124 static void
15125 remote_new_objfile (struct objfile *objfile)
15126 {
15127 remote_objfile_changed_check_symbols (objfile->pspace);
15128 }
15129
15130 /* Pull all the tracepoints defined on the target and create local
15131 data structures representing them. We don't want to create real
15132 tracepoints yet, we don't want to mess up the user's existing
15133 collection. */
15134
15135 int
15136 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15137 {
15138 struct remote_state *rs = get_remote_state ();
15139 char *p;
15140
15141 /* Ask for a first packet of tracepoint definition. */
15142 putpkt ("qTfP");
15143 getpkt (&rs->buf);
15144 p = rs->buf.data ();
15145 while (*p && *p != 'l')
15146 {
15147 parse_tracepoint_definition (p, utpp);
15148 /* Ask for another packet of tracepoint definition. */
15149 putpkt ("qTsP");
15150 getpkt (&rs->buf);
15151 p = rs->buf.data ();
15152 }
15153 return 0;
15154 }
15155
15156 int
15157 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15158 {
15159 struct remote_state *rs = get_remote_state ();
15160 char *p;
15161
15162 /* Ask for a first packet of variable definition. */
15163 putpkt ("qTfV");
15164 getpkt (&rs->buf);
15165 p = rs->buf.data ();
15166 while (*p && *p != 'l')
15167 {
15168 parse_tsv_definition (p, utsvp);
15169 /* Ask for another packet of variable definition. */
15170 putpkt ("qTsV");
15171 getpkt (&rs->buf);
15172 p = rs->buf.data ();
15173 }
15174 return 0;
15175 }
15176
15177 /* The "set/show range-stepping" show hook. */
15178
15179 static void
15180 show_range_stepping (struct ui_file *file, int from_tty,
15181 struct cmd_list_element *c,
15182 const char *value)
15183 {
15184 gdb_printf (file,
15185 _("Debugger's willingness to use range stepping "
15186 "is %s.\n"), value);
15187 }
15188
15189 /* Return true if the vCont;r action is supported by the remote
15190 stub. */
15191
15192 bool
15193 remote_target::vcont_r_supported ()
15194 {
15195 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15196 && get_remote_state ()->supports_vCont.r);
15197 }
15198
15199 /* The "set/show range-stepping" set hook. */
15200
15201 static void
15202 set_range_stepping (const char *ignore_args, int from_tty,
15203 struct cmd_list_element *c)
15204 {
15205 /* When enabling, check whether range stepping is actually supported
15206 by the target, and warn if not. */
15207 if (use_range_stepping)
15208 {
15209 remote_target *remote = get_current_remote_target ();
15210 if (remote == NULL
15211 || !remote->vcont_r_supported ())
15212 warning (_("Range stepping is not supported by the current target"));
15213 }
15214 }
15215
15216 static void
15217 show_remote_debug (struct ui_file *file, int from_tty,
15218 struct cmd_list_element *c, const char *value)
15219 {
15220 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15221 value);
15222 }
15223
15224 static void
15225 show_remote_timeout (struct ui_file *file, int from_tty,
15226 struct cmd_list_element *c, const char *value)
15227 {
15228 gdb_printf (file,
15229 _("Timeout limit to wait for target to respond is %s.\n"),
15230 value);
15231 }
15232
15233 /* Implement the "supports_memory_tagging" target_ops method. */
15234
15235 bool
15236 remote_target::supports_memory_tagging ()
15237 {
15238 return m_features.remote_memory_tagging_p ();
15239 }
15240
15241 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15242
15243 static void
15244 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15245 size_t len, int type)
15246 {
15247 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15248
15249 std::string request = string_printf ("qMemTags:%s,%s:%s",
15250 phex_nz (address, addr_size),
15251 phex_nz (len, sizeof (len)),
15252 phex_nz (type, sizeof (type)));
15253
15254 strcpy (packet.data (), request.c_str ());
15255 }
15256
15257 /* Parse the qMemTags packet reply into TAGS.
15258
15259 Return true if successful, false otherwise. */
15260
15261 static bool
15262 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15263 gdb::byte_vector &tags)
15264 {
15265 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15266 return false;
15267
15268 /* Copy the tag data. */
15269 tags = hex2bin (reply.data () + 1);
15270
15271 return true;
15272 }
15273
15274 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15275
15276 static void
15277 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15278 size_t len, int type,
15279 const gdb::byte_vector &tags)
15280 {
15281 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15282
15283 /* Put together the main packet, address and length. */
15284 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15285 phex_nz (address, addr_size),
15286 phex_nz (len, sizeof (len)),
15287 phex_nz (type, sizeof (type)));
15288 request += bin2hex (tags.data (), tags.size ());
15289
15290 /* Check if we have exceeded the maximum packet size. */
15291 if (packet.size () < request.length ())
15292 error (_("Contents too big for packet QMemTags."));
15293
15294 strcpy (packet.data (), request.c_str ());
15295 }
15296
15297 /* Implement the "fetch_memtags" target_ops method. */
15298
15299 bool
15300 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15301 gdb::byte_vector &tags, int type)
15302 {
15303 /* Make sure the qMemTags packet is supported. */
15304 if (!m_features.remote_memory_tagging_p ())
15305 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15306
15307 struct remote_state *rs = get_remote_state ();
15308
15309 create_fetch_memtags_request (rs->buf, address, len, type);
15310
15311 putpkt (rs->buf);
15312 getpkt (&rs->buf);
15313
15314 return parse_fetch_memtags_reply (rs->buf, tags);
15315 }
15316
15317 /* Implement the "store_memtags" target_ops method. */
15318
15319 bool
15320 remote_target::store_memtags (CORE_ADDR address, size_t len,
15321 const gdb::byte_vector &tags, int type)
15322 {
15323 /* Make sure the QMemTags packet is supported. */
15324 if (!m_features.remote_memory_tagging_p ())
15325 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15326
15327 struct remote_state *rs = get_remote_state ();
15328
15329 create_store_memtags_request (rs->buf, address, len, type, tags);
15330
15331 putpkt (rs->buf);
15332 getpkt (&rs->buf);
15333
15334 /* Verify if the request was successful. */
15335 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15336 }
15337
15338 /* Return true if remote target T is non-stop. */
15339
15340 bool
15341 remote_target_is_non_stop_p (remote_target *t)
15342 {
15343 scoped_restore_current_thread restore_thread;
15344 switch_to_target_no_thread (t);
15345
15346 return target_is_non_stop_p ();
15347 }
15348
15349 #if GDB_SELF_TEST
15350
15351 namespace selftests {
15352
15353 static void
15354 test_memory_tagging_functions ()
15355 {
15356 remote_target remote;
15357
15358 struct packet_config *config
15359 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15360
15361 scoped_restore restore_memtag_support_
15362 = make_scoped_restore (&config->support);
15363
15364 /* Test memory tagging packet support. */
15365 config->support = PACKET_SUPPORT_UNKNOWN;
15366 SELF_CHECK (remote.supports_memory_tagging () == false);
15367 config->support = PACKET_DISABLE;
15368 SELF_CHECK (remote.supports_memory_tagging () == false);
15369 config->support = PACKET_ENABLE;
15370 SELF_CHECK (remote.supports_memory_tagging () == true);
15371
15372 /* Setup testing. */
15373 gdb::char_vector packet;
15374 gdb::byte_vector tags, bv;
15375 std::string expected, reply;
15376 packet.resize (32000);
15377
15378 /* Test creating a qMemTags request. */
15379
15380 expected = "qMemTags:0,0:0";
15381 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15382 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15383
15384 expected = "qMemTags:deadbeef,10:1";
15385 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15386 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15387
15388 /* Test parsing a qMemTags reply. */
15389
15390 /* Error reply, tags vector unmodified. */
15391 reply = "E00";
15392 strcpy (packet.data (), reply.c_str ());
15393 tags.resize (0);
15394 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15395 SELF_CHECK (tags.size () == 0);
15396
15397 /* Valid reply, tags vector updated. */
15398 tags.resize (0);
15399 bv.resize (0);
15400
15401 for (int i = 0; i < 5; i++)
15402 bv.push_back (i);
15403
15404 reply = "m" + bin2hex (bv.data (), bv.size ());
15405 strcpy (packet.data (), reply.c_str ());
15406
15407 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15408 SELF_CHECK (tags.size () == 5);
15409
15410 for (int i = 0; i < 5; i++)
15411 SELF_CHECK (tags[i] == i);
15412
15413 /* Test creating a QMemTags request. */
15414
15415 /* Empty tag data. */
15416 tags.resize (0);
15417 expected = "QMemTags:0,0:0:";
15418 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15419 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15420 expected.length ()) == 0);
15421
15422 /* Non-empty tag data. */
15423 tags.resize (0);
15424 for (int i = 0; i < 5; i++)
15425 tags.push_back (i);
15426 expected = "QMemTags:deadbeef,ff:1:0001020304";
15427 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15428 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15429 expected.length ()) == 0);
15430 }
15431
15432 } // namespace selftests
15433 #endif /* GDB_SELF_TEST */
15434
15435 void _initialize_remote ();
15436 void
15437 _initialize_remote ()
15438 {
15439 add_target (remote_target_info, remote_target::open);
15440 add_target (extended_remote_target_info, extended_remote_target::open);
15441
15442 /* Hook into new objfile notification. */
15443 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15444 gdb::observers::all_objfiles_removed.attach
15445 (remote_objfile_changed_check_symbols, "remote");
15446
15447 #if 0
15448 init_remote_threadtests ();
15449 #endif
15450
15451 /* set/show remote ... */
15452
15453 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15454 Remote protocol specific variables.\n\
15455 Configure various remote-protocol specific variables such as\n\
15456 the packets being used."),
15457 &remote_set_cmdlist,
15458 0 /* allow-unknown */, &setlist);
15459 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15460 Remote protocol specific variables.\n\
15461 Configure various remote-protocol specific variables such as\n\
15462 the packets being used."),
15463 &remote_show_cmdlist,
15464 0 /* allow-unknown */, &showlist);
15465
15466 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15467 Compare section data on target to the exec file.\n\
15468 Argument is a single section name (default: all loaded sections).\n\
15469 To compare only read-only loaded sections, specify the -r option."),
15470 &cmdlist);
15471
15472 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15473 Send an arbitrary packet to a remote target.\n\
15474 maintenance packet TEXT\n\
15475 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15476 this command sends the string TEXT to the inferior, and displays the\n\
15477 response packet. GDB supplies the initial `$' character, and the\n\
15478 terminating `#' character and checksum."),
15479 &maintenancelist);
15480
15481 set_show_commands remotebreak_cmds
15482 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15483 Set whether to send break if interrupted."), _("\
15484 Show whether to send break if interrupted."), _("\
15485 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15486 set_remotebreak, show_remotebreak,
15487 &setlist, &showlist);
15488 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15489 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15490
15491 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15492 interrupt_sequence_modes, &interrupt_sequence_mode,
15493 _("\
15494 Set interrupt sequence to remote target."), _("\
15495 Show interrupt sequence to remote target."), _("\
15496 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15497 NULL, show_interrupt_sequence,
15498 &remote_set_cmdlist,
15499 &remote_show_cmdlist);
15500
15501 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15502 &interrupt_on_connect, _("\
15503 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15504 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15505 If set, interrupt sequence is sent to remote target."),
15506 NULL, NULL,
15507 &remote_set_cmdlist, &remote_show_cmdlist);
15508
15509 /* Install commands for configuring memory read/write packets. */
15510
15511 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15512 Set the maximum number of bytes per memory write packet (deprecated)."),
15513 &setlist);
15514 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15515 Show the maximum number of bytes per memory write packet (deprecated)."),
15516 &showlist);
15517 add_cmd ("memory-write-packet-size", no_class,
15518 set_memory_write_packet_size, _("\
15519 Set the maximum number of bytes per memory-write 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-read-packet-size", no_class,
15526 set_memory_read_packet_size, _("\
15527 Set the maximum number of bytes per memory-read packet.\n\
15528 Specify the number of bytes in a packet or 0 (zero) for the\n\
15529 default packet size. The actual limit is further reduced\n\
15530 dependent on the target. Specify \"fixed\" to disable the\n\
15531 further restriction and \"limit\" to enable that restriction."),
15532 &remote_set_cmdlist);
15533 add_cmd ("memory-write-packet-size", no_class,
15534 show_memory_write_packet_size,
15535 _("Show the maximum number of bytes per memory-write packet."),
15536 &remote_show_cmdlist);
15537 add_cmd ("memory-read-packet-size", no_class,
15538 show_memory_read_packet_size,
15539 _("Show the maximum number of bytes per memory-read packet."),
15540 &remote_show_cmdlist);
15541
15542 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15543 &remote_hw_watchpoint_limit, _("\
15544 Set the maximum number of target hardware watchpoints."), _("\
15545 Show the maximum number of target hardware watchpoints."), _("\
15546 Specify \"unlimited\" for unlimited hardware watchpoints."),
15547 NULL, show_hardware_watchpoint_limit,
15548 &remote_set_cmdlist,
15549 &remote_show_cmdlist);
15550 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15551 no_class,
15552 &remote_hw_watchpoint_length_limit, _("\
15553 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15554 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15555 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15556 NULL, show_hardware_watchpoint_length_limit,
15557 &remote_set_cmdlist, &remote_show_cmdlist);
15558 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15559 &remote_hw_breakpoint_limit, _("\
15560 Set the maximum number of target hardware breakpoints."), _("\
15561 Show the maximum number of target hardware breakpoints."), _("\
15562 Specify \"unlimited\" for unlimited hardware breakpoints."),
15563 NULL, show_hardware_breakpoint_limit,
15564 &remote_set_cmdlist, &remote_show_cmdlist);
15565
15566 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15567 &remote_address_size, _("\
15568 Set the maximum size of the address (in bits) in a memory packet."), _("\
15569 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15570 NULL,
15571 NULL, /* FIXME: i18n: */
15572 &setlist, &showlist);
15573
15574 init_all_packet_configs ();
15575
15576 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15577
15578 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15579
15580 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15581 0);
15582
15583 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15584 "catch-syscalls", 0);
15585
15586 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15587 "program-signals", 0);
15588
15589 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15590 "set-working-dir", 0);
15591
15592 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15593 "startup-with-shell", 0);
15594
15595 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15596 "environment-hex-encoded", 0);
15597
15598 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15599 "environment-reset", 0);
15600
15601 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15602 "environment-unset", 0);
15603
15604 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15605
15606 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15607
15608 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15609
15610 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15611
15612 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15613
15614 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15615
15616 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15617
15618 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15619
15620 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15621 "read-aux-vector", 0);
15622
15623 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15624 "pid-to-exec-file", 0);
15625
15626 add_packet_config_cmd (PACKET_qXfer_features,
15627 "qXfer:features:read", "target-features", 0);
15628
15629 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15630 "library-info", 0);
15631
15632 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15633 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15634
15635 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15636 "memory-map", 0);
15637
15638 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15639
15640 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15641 0);
15642
15643 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15644 "read-siginfo-object", 0);
15645
15646 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15647 "write-siginfo-object", 0);
15648
15649 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15650 "qXfer:traceframe-info:read", "traceframe-info", 0);
15651
15652 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15653 "unwind-info-block", 0);
15654
15655 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15656 "get-thread-local-storage-address", 0);
15657
15658 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15659 "get-thread-information-block-address", 0);
15660
15661 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15662
15663 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15664
15665 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15666 0);
15667
15668 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15669 "search-memory", 0);
15670
15671 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15672
15673 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15674
15675 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15676
15677 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15678
15679 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15680 0);
15681
15682 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15683
15684 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15685 0);
15686
15687 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15688 "hostio-readlink", 0);
15689
15690 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15691
15692 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15693
15694 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15695
15696 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15697
15698 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15699
15700 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15701
15702 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15703 "ConditionalTracepoints", "conditional-tracepoints",
15704 0);
15705
15706 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15707 "ConditionalBreakpoints", "conditional-breakpoints",
15708 0);
15709
15710 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15711 "breakpoint-commands", 0);
15712
15713 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15714 "fast-tracepoints", 0);
15715
15716 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15717 "TracepointSource", 0);
15718
15719 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15720
15721 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15722 "static-tracepoints", 0);
15723
15724 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15725 "install-in-trace", 0);
15726
15727 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15728 "qXfer:statictrace:read", "read-sdata-object", 0);
15729
15730 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15731 "read-fdpic-loadmap", 0);
15732
15733 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15734 "disable-randomization", 0);
15735
15736 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15737
15738 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15739 "trace-buffer-size", 0);
15740
15741 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15742 0);
15743
15744 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15745 0);
15746
15747 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15748 0);
15749
15750 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15751
15752 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15753 "read-btrace-conf", 0);
15754
15755 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15756 "btrace-conf-bts-size", 0);
15757
15758 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15759 "multiprocess-feature", 0);
15760
15761 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15762 "swbreak-feature", 0);
15763
15764 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15765 "hwbreak-feature", 0);
15766
15767 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15768 "fork-event-feature", 0);
15769
15770 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15771 "vfork-event-feature", 0);
15772
15773 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15774 "btrace-conf-pt-size", 0);
15775
15776 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15777 "verbose-resume-supported", 0);
15778
15779 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15780 "exec-event-feature", 0);
15781
15782 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15783
15784 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15785 0);
15786
15787 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15788 "no-resumed-stop-reply", 0);
15789
15790 add_packet_config_cmd (PACKET_memory_tagging_feature,
15791 "memory-tagging-feature", "memory-tagging-feature", 0);
15792
15793 /* Assert that we've registered "set remote foo-packet" commands
15794 for all packet configs. */
15795 {
15796 int i;
15797
15798 for (i = 0; i < PACKET_MAX; i++)
15799 {
15800 /* Ideally all configs would have a command associated. Some
15801 still don't though. */
15802 int excepted;
15803
15804 switch (i)
15805 {
15806 case PACKET_QNonStop:
15807 case PACKET_EnableDisableTracepoints_feature:
15808 case PACKET_tracenz_feature:
15809 case PACKET_DisconnectedTracing_feature:
15810 case PACKET_augmented_libraries_svr4_read_feature:
15811 case PACKET_qCRC:
15812 /* Additions to this list need to be well justified:
15813 pre-existing packets are OK; new packets are not. */
15814 excepted = 1;
15815 break;
15816 default:
15817 excepted = 0;
15818 break;
15819 }
15820
15821 /* This catches both forgetting to add a config command, and
15822 forgetting to remove a packet from the exception list. */
15823 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15824 }
15825 }
15826
15827 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15828 Z sub-packet has its own set and show commands, but users may
15829 have sets to this variable in their .gdbinit files (or in their
15830 documentation). */
15831 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15832 &remote_Z_packet_detect, _("\
15833 Set use of remote protocol `Z' packets."), _("\
15834 Show use of remote protocol `Z' packets."), _("\
15835 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15836 packets."),
15837 set_remote_protocol_Z_packet_cmd,
15838 show_remote_protocol_Z_packet_cmd,
15839 /* FIXME: i18n: Use of remote protocol
15840 `Z' packets is %s. */
15841 &remote_set_cmdlist, &remote_show_cmdlist);
15842
15843 add_basic_prefix_cmd ("remote", class_files, _("\
15844 Manipulate files on the remote system.\n\
15845 Transfer files to and from the remote target system."),
15846 &remote_cmdlist,
15847 0 /* allow-unknown */, &cmdlist);
15848
15849 add_cmd ("put", class_files, remote_put_command,
15850 _("Copy a local file to the remote system."),
15851 &remote_cmdlist);
15852
15853 add_cmd ("get", class_files, remote_get_command,
15854 _("Copy a remote file to the local system."),
15855 &remote_cmdlist);
15856
15857 add_cmd ("delete", class_files, remote_delete_command,
15858 _("Delete a remote file."),
15859 &remote_cmdlist);
15860
15861 add_setshow_string_noescape_cmd ("exec-file", class_files,
15862 &remote_exec_file_var, _("\
15863 Set the remote pathname for \"run\"."), _("\
15864 Show the remote pathname for \"run\"."), NULL,
15865 set_remote_exec_file,
15866 show_remote_exec_file,
15867 &remote_set_cmdlist,
15868 &remote_show_cmdlist);
15869
15870 add_setshow_boolean_cmd ("range-stepping", class_run,
15871 &use_range_stepping, _("\
15872 Enable or disable range stepping."), _("\
15873 Show whether target-assisted range stepping is enabled."), _("\
15874 If on, and the target supports it, when stepping a source line, GDB\n\
15875 tells the target to step the corresponding range of addresses itself instead\n\
15876 of issuing multiple single-steps. This speeds up source level\n\
15877 stepping. If off, GDB always issues single-steps, even if range\n\
15878 stepping is supported by the target. The default is on."),
15879 set_range_stepping,
15880 show_range_stepping,
15881 &setlist,
15882 &showlist);
15883
15884 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15885 Set watchdog timer."), _("\
15886 Show watchdog timer."), _("\
15887 When non-zero, this timeout is used instead of waiting forever for a target\n\
15888 to finish a low-level step or continue operation. If the specified amount\n\
15889 of time passes without a response from the target, an error occurs."),
15890 NULL,
15891 show_watchdog,
15892 &setlist, &showlist);
15893
15894 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15895 &remote_packet_max_chars, _("\
15896 Set the maximum number of characters to display for each remote packet."), _("\
15897 Show the maximum number of characters to display for each remote packet."), _("\
15898 Specify \"unlimited\" to display all the characters."),
15899 NULL, show_remote_packet_max_chars,
15900 &setdebuglist, &showdebuglist);
15901
15902 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15903 _("Set debugging of remote protocol."),
15904 _("Show debugging of remote protocol."),
15905 _("\
15906 When enabled, each packet sent or received with the remote target\n\
15907 is displayed."),
15908 NULL,
15909 show_remote_debug,
15910 &setdebuglist, &showdebuglist);
15911
15912 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15913 &remote_timeout, _("\
15914 Set timeout limit to wait for target to respond."), _("\
15915 Show timeout limit to wait for target to respond."), _("\
15916 This value is used to set the time limit for gdb to wait for a response\n\
15917 from the target."),
15918 NULL,
15919 show_remote_timeout,
15920 &setlist, &showlist);
15921
15922 /* Eventually initialize fileio. See fileio.c */
15923 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15924
15925 #if GDB_SELF_TEST
15926 selftests::register_test ("remote_memory_tagging",
15927 selftests::test_memory_tagging_functions);
15928 #endif
15929 }