all-stop/synchronous RSP support thread-exit events
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2023 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdbthread.h"
34 #include "remote.h"
35 #include "remote-notif.h"
36 #include "regcache.h"
37 #include "value.h"
38 #include "observable.h"
39 #include "solib.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "target-descriptions.h"
43 #include "gdb_bfd.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
46 #include "disasm.h"
47 #include "location.h"
48
49 #include "gdbsupport/gdb_sys_time.h"
50
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
54
55 #include <signal.h>
56 #include "serial.h"
57
58 #include "gdbcore.h"
59
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
62 #include <sys/stat.h>
63 #include "xml-support.h"
64
65 #include "memory-map.h"
66
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70 #include "gdbsupport/agent.h"
71 #include "btrace.h"
72 #include "record-btrace.h"
73 #include "gdbsupport/scoped_restore.h"
74 #include "gdbsupport/environ.h"
75 #include "gdbsupport/byte-vector.h"
76 #include "gdbsupport/search.h"
77 #include <algorithm>
78 #include <iterator>
79 #include <unordered_map>
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
82
83 /* The remote target. */
84
85 static const char remote_doc[] = N_("\
86 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87 Specify the serial device it is connected to\n\
88 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
90 /* See remote.h */
91
92 bool remote_debug = false;
93
94 #define OPAQUETHREADBYTES 8
95
96 /* a 64 bit opaque identifier */
97 typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99 struct gdb_ext_thread_info;
100 struct threads_listing_context;
101 typedef int (*rmt_thread_action) (threadref *ref, void *context);
102 struct protocol_feature;
103 struct packet_reg;
104
105 struct stop_reply;
106 typedef std::unique_ptr<stop_reply> stop_reply_up;
107
108 /* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
111
112 enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121 static const char *
122 get_packet_support_name (auto_boolean support)
123 {
124 switch (support)
125 {
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
134 }
135 }
136
137 /* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
139
140 static const char *
141 get_target_type_name (bool target_connected)
142 {
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
147 }
148
149 /* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152 enum packet_result
153 {
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157 };
158
159 /* Enumeration of packets for a remote target. */
160
161 enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
212
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints,
215
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints,
218
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands,
221
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints,
224
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints,
227
228 /* Support for installing tracepoints while a trace experiment is
229 running. */
230 PACKET_InstallInTrace,
231
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
244
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
247
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents,
250
251 /* Support for the QThreadOptions packet. */
252 PACKET_QThreadOptions,
253
254 /* Support for multi-process extensions. */
255 PACKET_multiprocess_feature,
256
257 /* Support for enabling and disabling tracepoints while a trace
258 experiment is running. */
259 PACKET_EnableDisableTracepoints_feature,
260
261 /* Support for collecting strings using the tracenz bytecode. */
262 PACKET_tracenz_feature,
263
264 /* Support for continuing to run a trace experiment while GDB is
265 disconnected. */
266 PACKET_DisconnectedTracing_feature,
267
268 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
269 PACKET_augmented_libraries_svr4_read_feature,
270
271 /* Support for the qXfer:btrace-conf:read packet. */
272 PACKET_qXfer_btrace_conf,
273
274 /* Support for the Qbtrace-conf:bts:size packet. */
275 PACKET_Qbtrace_conf_bts_size,
276
277 /* Support for swbreak+ feature. */
278 PACKET_swbreak_feature,
279
280 /* Support for hwbreak+ feature. */
281 PACKET_hwbreak_feature,
282
283 /* Support for fork events. */
284 PACKET_fork_event_feature,
285
286 /* Support for vfork events. */
287 PACKET_vfork_event_feature,
288
289 /* Support for the Qbtrace-conf:pt:size packet. */
290 PACKET_Qbtrace_conf_pt_size,
291
292 /* Support for exec events. */
293 PACKET_exec_event_feature,
294
295 /* Support for query supported vCont actions. */
296 PACKET_vContSupported,
297
298 /* Support remote CTRL-C. */
299 PACKET_vCtrlC,
300
301 /* Support TARGET_WAITKIND_NO_RESUMED. */
302 PACKET_no_resumed,
303
304 /* Support for memory tagging, allocation tag fetch/store
305 packets and the tag violation stop replies. */
306 PACKET_memory_tagging_feature,
307
308 PACKET_MAX
309 };
310
311 struct threads_listing_context;
312
313 /* Stub vCont actions support.
314
315 Each field is a boolean flag indicating whether the stub reports
316 support for the corresponding action. */
317
318 struct vCont_action_support
319 {
320 /* vCont;t */
321 bool t = false;
322
323 /* vCont;r */
324 bool r = false;
325
326 /* vCont;s */
327 bool s = false;
328
329 /* vCont;S */
330 bool S = false;
331 };
332
333 /* About this many threadids fit in a packet. */
334
335 #define MAXTHREADLISTRESULTS 32
336
337 /* Data for the vFile:pread readahead cache. */
338
339 struct readahead_cache
340 {
341 /* Invalidate the readahead cache. */
342 void invalidate ();
343
344 /* Invalidate the readahead cache if it is holding data for FD. */
345 void invalidate_fd (int fd);
346
347 /* Serve pread from the readahead cache. Returns number of bytes
348 read, or 0 if the request can't be served from the cache. */
349 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
350
351 /* The file descriptor for the file that is being cached. -1 if the
352 cache is invalid. */
353 int fd = -1;
354
355 /* The offset into the file that the cache buffer corresponds
356 to. */
357 ULONGEST offset = 0;
358
359 /* The buffer holding the cache contents. */
360 gdb::byte_vector buf;
361
362 /* Cache hit and miss counters. */
363 ULONGEST hit_count = 0;
364 ULONGEST miss_count = 0;
365 };
366
367 /* Description of the remote protocol for a given architecture. */
368
369 struct packet_reg
370 {
371 long offset; /* Offset into G packet. */
372 long regnum; /* GDB's internal register number. */
373 LONGEST pnum; /* Remote protocol register number. */
374 int in_g_packet; /* Always part of G packet. */
375 /* long size in bytes; == register_size (arch, regnum);
376 at present. */
377 /* char *name; == gdbarch_register_name (arch, regnum);
378 at present. */
379 };
380
381 struct remote_arch_state
382 {
383 explicit remote_arch_state (struct gdbarch *gdbarch);
384
385 /* Description of the remote protocol registers. */
386 long sizeof_g_packet;
387
388 /* Description of the remote protocol registers indexed by REGNUM
389 (making an array gdbarch_num_regs in size). */
390 std::unique_ptr<packet_reg[]> regs;
391
392 /* This is the size (in chars) of the first response to the ``g''
393 packet. It is used as a heuristic when determining the maximum
394 size of memory-read and memory-write packets. A target will
395 typically only reserve a buffer large enough to hold the ``g''
396 packet. The size does not include packet overhead (headers and
397 trailers). */
398 long actual_register_packet_size;
399
400 /* This is the maximum size (in chars) of a non read/write packet.
401 It is also used as a cap on the size of read/write packets. */
402 long remote_packet_size;
403 };
404
405 /* Description of the remote protocol state for the currently
406 connected target. This is per-target state, and independent of the
407 selected architecture. */
408
409 class remote_state
410 {
411 public:
412
413 remote_state ();
414 ~remote_state ();
415
416 /* Get the remote arch state for GDBARCH. */
417 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
418
419 void create_async_event_handler ()
420 {
421 gdb_assert (m_async_event_handler_token == nullptr);
422 m_async_event_handler_token
423 = ::create_async_event_handler ([] (gdb_client_data data)
424 {
425 inferior_event_handler (INF_REG_EVENT);
426 },
427 nullptr, "remote");
428 }
429
430 void mark_async_event_handler ()
431 {
432 gdb_assert (this->is_async_p ());
433 ::mark_async_event_handler (m_async_event_handler_token);
434 }
435
436 void clear_async_event_handler ()
437 { ::clear_async_event_handler (m_async_event_handler_token); }
438
439 bool async_event_handler_marked () const
440 { return ::async_event_handler_marked (m_async_event_handler_token); }
441
442 void delete_async_event_handler ()
443 {
444 if (m_async_event_handler_token != nullptr)
445 ::delete_async_event_handler (&m_async_event_handler_token);
446 }
447
448 bool is_async_p () const
449 {
450 /* We're async whenever the serial device is. */
451 gdb_assert (this->remote_desc != nullptr);
452 return serial_is_async_p (this->remote_desc);
453 }
454
455 bool can_async_p () const
456 {
457 /* We can async whenever the serial device can. */
458 gdb_assert (this->remote_desc != nullptr);
459 return serial_can_async_p (this->remote_desc);
460 }
461
462 public: /* data */
463
464 /* A buffer to use for incoming packets, and its current size. The
465 buffer is grown dynamically for larger incoming packets.
466 Outgoing packets may also be constructed in this buffer.
467 The size of the buffer is always at least REMOTE_PACKET_SIZE;
468 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
469 packets. */
470 gdb::char_vector buf;
471
472 /* True if we're going through initial connection setup (finding out
473 about the remote side's threads, relocating symbols, etc.). */
474 bool starting_up = false;
475
476 /* If we negotiated packet size explicitly (and thus can bypass
477 heuristics for the largest packet size that will not overflow
478 a buffer in the stub), this will be set to that packet size.
479 Otherwise zero, meaning to use the guessed size. */
480 long explicit_packet_size = 0;
481
482 /* True, if in no ack mode. That is, neither GDB nor the stub will
483 expect acks from each other. The connection is assumed to be
484 reliable. */
485 bool noack_mode = false;
486
487 /* True if we're connected in extended remote mode. */
488 bool extended = false;
489
490 /* True if we resumed the target and we're waiting for the target to
491 stop. In the mean time, we can't start another command/query.
492 The remote server wouldn't be ready to process it, so we'd
493 timeout waiting for a reply that would never come and eventually
494 we'd close the connection. This can happen in asynchronous mode
495 because we allow GDB commands while the target is running. */
496 bool waiting_for_stop_reply = false;
497
498 /* The status of the stub support for the various vCont actions. */
499 vCont_action_support supports_vCont;
500
501 /* True if the user has pressed Ctrl-C, but the target hasn't
502 responded to that. */
503 bool ctrlc_pending_p = false;
504
505 /* True if we saw a Ctrl-C while reading or writing from/to the
506 remote descriptor. At that point it is not safe to send a remote
507 interrupt packet, so we instead remember we saw the Ctrl-C and
508 process it once we're done with sending/receiving the current
509 packet, which should be shortly. If however that takes too long,
510 and the user presses Ctrl-C again, we offer to disconnect. */
511 bool got_ctrlc_during_io = false;
512
513 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
514 remote_open knows that we don't have a file open when the program
515 starts. */
516 struct serial *remote_desc = nullptr;
517
518 /* These are the threads which we last sent to the remote system. The
519 TID member will be -1 for all or -2 for not sent yet. */
520 ptid_t general_thread = null_ptid;
521 ptid_t continue_thread = null_ptid;
522
523 /* This is the traceframe which we last selected on the remote system.
524 It will be -1 if no traceframe is selected. */
525 int remote_traceframe_number = -1;
526
527 char *last_pass_packet = nullptr;
528
529 /* The last QProgramSignals packet sent to the target. We bypass
530 sending a new program signals list down to the target if the new
531 packet is exactly the same as the last we sent. IOW, we only let
532 the target know about program signals list changes. */
533 char *last_program_signals_packet = nullptr;
534
535 /* Similarly, the last QThreadEvents state we sent to the
536 target. */
537 bool last_thread_events = false;
538
539 gdb_signal last_sent_signal = GDB_SIGNAL_0;
540
541 bool last_sent_step = false;
542
543 /* The execution direction of the last resume we got. */
544 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
545
546 char *finished_object = nullptr;
547 char *finished_annex = nullptr;
548 ULONGEST finished_offset = 0;
549
550 /* Should we try the 'ThreadInfo' query packet?
551
552 This variable (NOT available to the user: auto-detect only!)
553 determines whether GDB will use the new, simpler "ThreadInfo"
554 query or the older, more complex syntax for thread queries.
555 This is an auto-detect variable (set to true at each connect,
556 and set to false when the target fails to recognize it). */
557 bool use_threadinfo_query = false;
558 bool use_threadextra_query = false;
559
560 threadref echo_nextthread {};
561 threadref nextthread {};
562 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
563
564 /* The state of remote notification. */
565 struct remote_notif_state *notif_state = nullptr;
566
567 /* The branch trace configuration. */
568 struct btrace_config btrace_config {};
569
570 /* The argument to the last "vFile:setfs:" packet we sent, used
571 to avoid sending repeated unnecessary "vFile:setfs:" packets.
572 Initialized to -1 to indicate that no "vFile:setfs:" packet
573 has yet been sent. */
574 int fs_pid = -1;
575
576 /* A readahead cache for vFile:pread. Often, reading a binary
577 involves a sequence of small reads. E.g., when parsing an ELF
578 file. A readahead cache helps mostly the case of remote
579 debugging on a connection with higher latency, due to the
580 request/reply nature of the RSP. We only cache data for a single
581 file descriptor at a time. */
582 struct readahead_cache readahead_cache;
583
584 /* The list of already fetched and acknowledged stop events. This
585 queue is used for notification Stop, and other notifications
586 don't need queue for their events, because the notification
587 events of Stop can't be consumed immediately, so that events
588 should be queued first, and be consumed by remote_wait_{ns,as}
589 one per time. Other notifications can consume their events
590 immediately, so queue is not needed for them. */
591 std::vector<stop_reply_up> stop_reply_queue;
592
593 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
594 ``forever'' still use the normal timeout mechanism. This is
595 currently used by the ASYNC code to guarentee that target reads
596 during the initial connect always time-out. Once getpkt has been
597 modified to return a timeout indication and, in turn
598 remote_wait()/wait_for_inferior() have gained a timeout parameter
599 this can go away. */
600 bool wait_forever_enabled_p = true;
601
602 /* The set of thread options the target reported it supports, via
603 qSupported. */
604 gdb_thread_options supported_thread_options = 0;
605
606 private:
607 /* Asynchronous signal handle registered as event loop source for
608 when we have pending events ready to be passed to the core. */
609 async_event_handler *m_async_event_handler_token = nullptr;
610
611 /* Mapping of remote protocol data for each gdbarch. Usually there
612 is only one entry here, though we may see more with stubs that
613 support multi-process. */
614 std::unordered_map<struct gdbarch *, remote_arch_state>
615 m_arch_states;
616 };
617
618 static const target_info remote_target_info = {
619 "remote",
620 N_("Remote target using gdb-specific protocol"),
621 remote_doc
622 };
623
624 /* Description of a remote packet. */
625
626 struct packet_description
627 {
628 /* Name of the packet used for gdb output. */
629 const char *name;
630
631 /* Title of the packet, used by the set/show remote name-packet
632 commands to identify the individual packages and gdb output. */
633 const char *title;
634 };
635
636 /* Configuration of a remote packet. */
637
638 struct packet_config
639 {
640 /* If auto, GDB auto-detects support for this packet or feature,
641 either through qSupported, or by trying the packet and looking
642 at the response. If true, GDB assumes the target supports this
643 packet. If false, the packet is disabled. Configs that don't
644 have an associated command always have this set to auto. */
645 enum auto_boolean detect;
646
647 /* Does the target support this packet? */
648 enum packet_support support;
649 };
650
651 /* User configurable variables for the number of characters in a
652 memory read/write packet. MIN (rsa->remote_packet_size,
653 rsa->sizeof_g_packet) is the default. Some targets need smaller
654 values (fifo overruns, et.al.) and some users need larger values
655 (speed up transfers). The variables ``preferred_*'' (the user
656 request), ``current_*'' (what was actually set) and ``forced_*''
657 (Positive - a soft limit, negative - a hard limit). */
658
659 struct memory_packet_config
660 {
661 const char *name;
662 long size;
663 int fixed_p;
664 };
665
666 /* These global variables contain the default configuration for every new
667 remote_feature object. */
668 static memory_packet_config memory_read_packet_config =
669 {
670 "memory-read-packet-size",
671 };
672 static memory_packet_config memory_write_packet_config =
673 {
674 "memory-write-packet-size",
675 };
676
677 /* This global array contains packet descriptions (name and title). */
678 static packet_description packets_descriptions[PACKET_MAX];
679 /* This global array contains the default configuration for every new
680 per-remote target array. */
681 static packet_config remote_protocol_packets[PACKET_MAX];
682
683 /* Description of a remote target's features. It stores the configuration
684 and provides functions to determine supported features of the target. */
685
686 struct remote_features
687 {
688 remote_features ()
689 {
690 m_memory_read_packet_config = memory_read_packet_config;
691 m_memory_write_packet_config = memory_write_packet_config;
692
693 std::copy (std::begin (remote_protocol_packets),
694 std::end (remote_protocol_packets),
695 std::begin (m_protocol_packets));
696 }
697 ~remote_features () = default;
698
699 DISABLE_COPY_AND_ASSIGN (remote_features);
700
701 /* Returns whether a given packet defined by its enum value is supported. */
702 enum packet_support packet_support (int) const;
703
704 /* Returns the packet's corresponding "set remote foo-packet" command
705 state. See struct packet_config for more details. */
706 enum auto_boolean packet_set_cmd_state (int packet) const
707 { return m_protocol_packets[packet].detect; }
708
709 /* Returns true if the multi-process extensions are in effect. */
710 int remote_multi_process_p () const
711 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
712
713 /* Returns true if fork events are supported. */
714 int remote_fork_event_p () const
715 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
716
717 /* Returns true if vfork events are supported. */
718 int remote_vfork_event_p () const
719 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
720
721 /* Returns true if exec events are supported. */
722 int remote_exec_event_p () const
723 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
724
725 /* Returns true if memory tagging is supported, false otherwise. */
726 bool remote_memory_tagging_p () const
727 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
728
729 /* Reset all packets back to "unknown support". Called when opening a
730 new connection to a remote target. */
731 void reset_all_packet_configs_support ();
732
733 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
734 support configuration accordingly. */
735 packet_result packet_ok (const char *buf, const int which_packet);
736 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
737
738 /* Configuration of a remote target's memory read packet. */
739 memory_packet_config m_memory_read_packet_config;
740 /* Configuration of a remote target's memory write packet. */
741 memory_packet_config m_memory_write_packet_config;
742
743 /* The per-remote target array which stores a remote's packet
744 configurations. */
745 packet_config m_protocol_packets[PACKET_MAX];
746 };
747
748 class remote_target : public process_stratum_target
749 {
750 public:
751 remote_target () = default;
752 ~remote_target () override;
753
754 const target_info &info () const override
755 { return remote_target_info; }
756
757 const char *connection_string () override;
758
759 thread_control_capabilities get_thread_control_capabilities () override
760 { return tc_schedlock; }
761
762 /* Open a remote connection. */
763 static void open (const char *, int);
764
765 void close () override;
766
767 void detach (inferior *, int) override;
768 void disconnect (const char *, int) override;
769
770 void commit_requested_thread_options ();
771
772 void commit_resumed () override;
773 void resume (ptid_t, int, enum gdb_signal) override;
774 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
775 bool has_pending_events () override;
776
777 void fetch_registers (struct regcache *, int) override;
778 void store_registers (struct regcache *, int) override;
779 void prepare_to_store (struct regcache *) override;
780
781 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
782
783 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
784 enum remove_bp_reason) override;
785
786
787 bool stopped_by_sw_breakpoint () override;
788 bool supports_stopped_by_sw_breakpoint () override;
789
790 bool stopped_by_hw_breakpoint () override;
791
792 bool supports_stopped_by_hw_breakpoint () override;
793
794 bool stopped_by_watchpoint () override;
795
796 bool stopped_data_address (CORE_ADDR *) override;
797
798 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
799
800 int can_use_hw_breakpoint (enum bptype, int, int) override;
801
802 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
803
804 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
805
806 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
807
808 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
809 struct expression *) override;
810
811 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
812 struct expression *) override;
813
814 void kill () override;
815
816 void load (const char *, int) override;
817
818 void mourn_inferior () override;
819
820 void pass_signals (gdb::array_view<const unsigned char>) override;
821
822 int set_syscall_catchpoint (int, bool, int,
823 gdb::array_view<const int>) override;
824
825 void program_signals (gdb::array_view<const unsigned char>) override;
826
827 bool thread_alive (ptid_t ptid) override;
828
829 const char *thread_name (struct thread_info *) override;
830
831 void update_thread_list () override;
832
833 std::string pid_to_str (ptid_t) override;
834
835 const char *extra_thread_info (struct thread_info *) override;
836
837 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
838
839 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
840 int handle_len,
841 inferior *inf) override;
842
843 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
844 override;
845
846 void stop (ptid_t) override;
847
848 void interrupt () override;
849
850 void pass_ctrlc () override;
851
852 enum target_xfer_status xfer_partial (enum target_object object,
853 const char *annex,
854 gdb_byte *readbuf,
855 const gdb_byte *writebuf,
856 ULONGEST offset, ULONGEST len,
857 ULONGEST *xfered_len) override;
858
859 ULONGEST get_memory_xfer_limit () override;
860
861 void rcmd (const char *command, struct ui_file *output) override;
862
863 const char *pid_to_exec_file (int pid) override;
864
865 void log_command (const char *cmd) override
866 {
867 serial_log_command (this, cmd);
868 }
869
870 CORE_ADDR get_thread_local_address (ptid_t ptid,
871 CORE_ADDR load_module_addr,
872 CORE_ADDR offset) override;
873
874 bool can_execute_reverse () override;
875
876 std::vector<mem_region> memory_map () override;
877
878 void flash_erase (ULONGEST address, LONGEST length) override;
879
880 void flash_done () override;
881
882 const struct target_desc *read_description () override;
883
884 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
885 const gdb_byte *pattern, ULONGEST pattern_len,
886 CORE_ADDR *found_addrp) override;
887
888 bool can_async_p () override;
889
890 bool is_async_p () override;
891
892 void async (bool) override;
893
894 int async_wait_fd () override;
895
896 void thread_events (int) override;
897
898 bool supports_set_thread_options (gdb_thread_options) override;
899
900 int can_do_single_step () override;
901
902 void terminal_inferior () override;
903
904 void terminal_ours () override;
905
906 bool supports_non_stop () override;
907
908 bool supports_multi_process () override;
909
910 bool supports_disable_randomization () override;
911
912 bool filesystem_is_local () override;
913
914
915 int fileio_open (struct inferior *inf, const char *filename,
916 int flags, int mode, int warn_if_slow,
917 fileio_error *target_errno) override;
918
919 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
920 ULONGEST offset, fileio_error *target_errno) override;
921
922 int fileio_pread (int fd, gdb_byte *read_buf, int len,
923 ULONGEST offset, fileio_error *target_errno) override;
924
925 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
926
927 int fileio_close (int fd, fileio_error *target_errno) override;
928
929 int fileio_unlink (struct inferior *inf,
930 const char *filename,
931 fileio_error *target_errno) override;
932
933 gdb::optional<std::string>
934 fileio_readlink (struct inferior *inf,
935 const char *filename,
936 fileio_error *target_errno) override;
937
938 bool supports_enable_disable_tracepoint () override;
939
940 bool supports_string_tracing () override;
941
942 int remote_supports_cond_tracepoints ();
943
944 bool supports_evaluation_of_breakpoint_conditions () override;
945
946 int remote_supports_fast_tracepoints ();
947
948 int remote_supports_static_tracepoints ();
949
950 int remote_supports_install_in_trace ();
951
952 bool can_run_breakpoint_commands () override;
953
954 void trace_init () override;
955
956 void download_tracepoint (struct bp_location *location) override;
957
958 bool can_download_tracepoint () override;
959
960 void download_trace_state_variable (const trace_state_variable &tsv) override;
961
962 void enable_tracepoint (struct bp_location *location) override;
963
964 void disable_tracepoint (struct bp_location *location) override;
965
966 void trace_set_readonly_regions () override;
967
968 void trace_start () override;
969
970 int get_trace_status (struct trace_status *ts) override;
971
972 void get_tracepoint_status (tracepoint *tp, struct uploaded_tp *utp)
973 override;
974
975 void trace_stop () override;
976
977 int trace_find (enum trace_find_type type, int num,
978 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
979
980 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
981
982 int save_trace_data (const char *filename) override;
983
984 int upload_tracepoints (struct uploaded_tp **utpp) override;
985
986 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
987
988 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
989
990 int get_min_fast_tracepoint_insn_len () override;
991
992 void set_disconnected_tracing (int val) override;
993
994 void set_circular_trace_buffer (int val) override;
995
996 void set_trace_buffer_size (LONGEST val) override;
997
998 bool set_trace_notes (const char *user, const char *notes,
999 const char *stopnotes) override;
1000
1001 int core_of_thread (ptid_t ptid) override;
1002
1003 int verify_memory (const gdb_byte *data,
1004 CORE_ADDR memaddr, ULONGEST size) override;
1005
1006
1007 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
1008
1009 void set_permissions () override;
1010
1011 bool static_tracepoint_marker_at (CORE_ADDR,
1012 struct static_tracepoint_marker *marker)
1013 override;
1014
1015 std::vector<static_tracepoint_marker>
1016 static_tracepoint_markers_by_strid (const char *id) override;
1017
1018 traceframe_info_up traceframe_info () override;
1019
1020 bool use_agent (bool use) override;
1021 bool can_use_agent () override;
1022
1023 struct btrace_target_info *
1024 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
1025
1026 void disable_btrace (struct btrace_target_info *tinfo) override;
1027
1028 void teardown_btrace (struct btrace_target_info *tinfo) override;
1029
1030 enum btrace_error read_btrace (struct btrace_data *data,
1031 struct btrace_target_info *btinfo,
1032 enum btrace_read_type type) override;
1033
1034 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
1035 bool augmented_libraries_svr4_read () override;
1036 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
1037 void follow_clone (ptid_t child_ptid) override;
1038 void follow_exec (inferior *, ptid_t, const char *) override;
1039 int insert_fork_catchpoint (int) override;
1040 int remove_fork_catchpoint (int) override;
1041 int insert_vfork_catchpoint (int) override;
1042 int remove_vfork_catchpoint (int) override;
1043 int insert_exec_catchpoint (int) override;
1044 int remove_exec_catchpoint (int) override;
1045 enum exec_direction_kind execution_direction () override;
1046
1047 bool supports_memory_tagging () override;
1048
1049 bool fetch_memtags (CORE_ADDR address, size_t len,
1050 gdb::byte_vector &tags, int type) override;
1051
1052 bool store_memtags (CORE_ADDR address, size_t len,
1053 const gdb::byte_vector &tags, int type) override;
1054
1055 public: /* Remote specific methods. */
1056
1057 void remote_download_command_source (int num, ULONGEST addr,
1058 struct command_line *cmds);
1059
1060 void remote_file_put (const char *local_file, const char *remote_file,
1061 int from_tty);
1062 void remote_file_get (const char *remote_file, const char *local_file,
1063 int from_tty);
1064 void remote_file_delete (const char *remote_file, int from_tty);
1065
1066 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1067 ULONGEST offset, fileio_error *remote_errno);
1068 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1069 ULONGEST offset, fileio_error *remote_errno);
1070 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1071 ULONGEST offset, fileio_error *remote_errno);
1072
1073 int remote_hostio_send_command (int command_bytes, int which_packet,
1074 fileio_error *remote_errno, const char **attachment,
1075 int *attachment_len);
1076 int remote_hostio_set_filesystem (struct inferior *inf,
1077 fileio_error *remote_errno);
1078 /* We should get rid of this and use fileio_open directly. */
1079 int remote_hostio_open (struct inferior *inf, const char *filename,
1080 int flags, int mode, int warn_if_slow,
1081 fileio_error *remote_errno);
1082 int remote_hostio_close (int fd, fileio_error *remote_errno);
1083
1084 int remote_hostio_unlink (inferior *inf, const char *filename,
1085 fileio_error *remote_errno);
1086
1087 struct remote_state *get_remote_state ();
1088
1089 long get_remote_packet_size (void);
1090 long get_memory_packet_size (struct memory_packet_config *config);
1091
1092 long get_memory_write_packet_size ();
1093 long get_memory_read_packet_size ();
1094
1095 char *append_pending_thread_resumptions (char *p, char *endp,
1096 ptid_t ptid);
1097 static void open_1 (const char *name, int from_tty, int extended_p);
1098 void start_remote (int from_tty, int extended_p);
1099 void remote_detach_1 (struct inferior *inf, int from_tty);
1100
1101 char *append_resumption (char *p, char *endp,
1102 ptid_t ptid, int step, gdb_signal siggnal);
1103 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1104 gdb_signal siggnal);
1105
1106 thread_info *add_current_inferior_and_thread (const char *wait_status);
1107
1108 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1109 target_wait_flags options);
1110 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1111 target_wait_flags options);
1112
1113 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1114 target_waitstatus *status);
1115
1116 ptid_t select_thread_for_ambiguous_stop_reply
1117 (const struct target_waitstatus &status);
1118
1119 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1120
1121 void print_one_stopped_thread (thread_info *thread);
1122 void process_initial_stop_replies (int from_tty);
1123
1124 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1125 bool silent_p);
1126
1127 void btrace_sync_conf (const btrace_config *conf);
1128
1129 void remote_btrace_maybe_reopen ();
1130
1131 void remove_new_children (threads_listing_context *context);
1132 void kill_new_fork_children (inferior *inf);
1133 void discard_pending_stop_replies (struct inferior *inf);
1134 int stop_reply_queue_length ();
1135
1136 void check_pending_events_prevent_wildcard_vcont
1137 (bool *may_global_wildcard_vcont);
1138
1139 void discard_pending_stop_replies_in_queue ();
1140 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1141 struct stop_reply *queued_stop_reply (ptid_t ptid);
1142 int peek_stop_reply (ptid_t ptid);
1143 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1144
1145 void remote_stop_ns (ptid_t ptid);
1146 void remote_interrupt_as ();
1147 void remote_interrupt_ns ();
1148
1149 char *remote_get_noisy_reply ();
1150 int remote_query_attached (int pid);
1151 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1152 int try_open_exec);
1153
1154 ptid_t remote_current_thread (ptid_t oldpid);
1155 ptid_t get_current_thread (const char *wait_status);
1156
1157 void set_thread (ptid_t ptid, int gen);
1158 void set_general_thread (ptid_t ptid);
1159 void set_continue_thread (ptid_t ptid);
1160 void set_general_process ();
1161
1162 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1163
1164 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1165 gdb_ext_thread_info *info);
1166 int remote_get_threadinfo (threadref *threadid, int fieldset,
1167 gdb_ext_thread_info *info);
1168
1169 int parse_threadlist_response (const char *pkt, int result_limit,
1170 threadref *original_echo,
1171 threadref *resultlist,
1172 int *doneflag);
1173 int remote_get_threadlist (int startflag, threadref *nextthread,
1174 int result_limit, int *done, int *result_count,
1175 threadref *threadlist);
1176
1177 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1178 void *context, int looplimit);
1179
1180 int remote_get_threads_with_ql (threads_listing_context *context);
1181 int remote_get_threads_with_qxfer (threads_listing_context *context);
1182 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1183
1184 void extended_remote_restart ();
1185
1186 void get_offsets ();
1187
1188 void remote_check_symbols ();
1189
1190 void remote_supported_packet (const struct protocol_feature *feature,
1191 enum packet_support support,
1192 const char *argument);
1193
1194 void remote_query_supported ();
1195
1196 void remote_packet_size (const protocol_feature *feature,
1197 packet_support support, const char *value);
1198 void remote_supported_thread_options (const protocol_feature *feature,
1199 enum packet_support support,
1200 const char *value);
1201
1202 void remote_serial_quit_handler ();
1203
1204 void remote_detach_pid (int pid);
1205
1206 void remote_vcont_probe ();
1207
1208 void remote_resume_with_hc (ptid_t ptid, int step,
1209 gdb_signal siggnal);
1210
1211 void send_interrupt_sequence ();
1212 void interrupt_query ();
1213
1214 void remote_notif_get_pending_events (const notif_client *nc);
1215
1216 int fetch_register_using_p (struct regcache *regcache,
1217 packet_reg *reg);
1218 int send_g_packet ();
1219 void process_g_packet (struct regcache *regcache);
1220 void fetch_registers_using_g (struct regcache *regcache);
1221 int store_register_using_P (const struct regcache *regcache,
1222 packet_reg *reg);
1223 void store_registers_using_G (const struct regcache *regcache);
1224
1225 void set_remote_traceframe ();
1226
1227 void check_binary_download (CORE_ADDR addr);
1228
1229 target_xfer_status remote_write_bytes_aux (const char *header,
1230 CORE_ADDR memaddr,
1231 const gdb_byte *myaddr,
1232 ULONGEST len_units,
1233 int unit_size,
1234 ULONGEST *xfered_len_units,
1235 char packet_format,
1236 int use_length);
1237
1238 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1239 const gdb_byte *myaddr, ULONGEST len,
1240 int unit_size, ULONGEST *xfered_len);
1241
1242 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1243 ULONGEST len_units,
1244 int unit_size, ULONGEST *xfered_len_units);
1245
1246 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1247 ULONGEST memaddr,
1248 ULONGEST len,
1249 int unit_size,
1250 ULONGEST *xfered_len);
1251
1252 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1253 gdb_byte *myaddr, ULONGEST len,
1254 int unit_size,
1255 ULONGEST *xfered_len);
1256
1257 packet_result remote_send_printf (const char *format, ...)
1258 ATTRIBUTE_PRINTF (2, 3);
1259
1260 target_xfer_status remote_flash_write (ULONGEST address,
1261 ULONGEST length, ULONGEST *xfered_len,
1262 const gdb_byte *data);
1263
1264 int readchar (int timeout);
1265
1266 void remote_serial_write (const char *str, int len);
1267
1268 int putpkt (const char *buf);
1269 int putpkt_binary (const char *buf, int cnt);
1270
1271 int putpkt (const gdb::char_vector &buf)
1272 {
1273 return putpkt (buf.data ());
1274 }
1275
1276 void skip_frame ();
1277 long read_frame (gdb::char_vector *buf_p);
1278 int getpkt (gdb::char_vector *buf, bool forever = false,
1279 bool *is_notif = nullptr);
1280 int remote_vkill (int pid);
1281 void remote_kill_k ();
1282
1283 void extended_remote_disable_randomization (int val);
1284 int extended_remote_run (const std::string &args);
1285
1286 void send_environment_packet (const char *action,
1287 const char *packet,
1288 const char *value);
1289
1290 void extended_remote_environment_support ();
1291 void extended_remote_set_inferior_cwd ();
1292
1293 target_xfer_status remote_write_qxfer (const char *object_name,
1294 const char *annex,
1295 const gdb_byte *writebuf,
1296 ULONGEST offset, LONGEST len,
1297 ULONGEST *xfered_len,
1298 const unsigned int which_packet);
1299
1300 target_xfer_status remote_read_qxfer (const char *object_name,
1301 const char *annex,
1302 gdb_byte *readbuf, ULONGEST offset,
1303 LONGEST len,
1304 ULONGEST *xfered_len,
1305 const unsigned int which_packet);
1306
1307 void push_stop_reply (struct stop_reply *new_event);
1308
1309 bool vcont_r_supported ();
1310
1311 remote_features m_features;
1312
1313 private:
1314
1315 bool start_remote_1 (int from_tty, int extended_p);
1316
1317 /* The remote state. Don't reference this directly. Use the
1318 get_remote_state method instead. */
1319 remote_state m_remote_state;
1320 };
1321
1322 static const target_info extended_remote_target_info = {
1323 "extended-remote",
1324 N_("Extended remote target using gdb-specific protocol"),
1325 remote_doc
1326 };
1327
1328 /* Set up the extended remote target by extending the standard remote
1329 target and adding to it. */
1330
1331 class extended_remote_target final : public remote_target
1332 {
1333 public:
1334 const target_info &info () const override
1335 { return extended_remote_target_info; }
1336
1337 /* Open an extended-remote connection. */
1338 static void open (const char *, int);
1339
1340 bool can_create_inferior () override { return true; }
1341 void create_inferior (const char *, const std::string &,
1342 char **, int) override;
1343
1344 void detach (inferior *, int) override;
1345
1346 bool can_attach () override { return true; }
1347 void attach (const char *, int) override;
1348
1349 void post_attach (int) override;
1350 bool supports_disable_randomization () override;
1351 };
1352
1353 struct stop_reply : public notif_event
1354 {
1355 ~stop_reply ();
1356
1357 /* The identifier of the thread about this event */
1358 ptid_t ptid;
1359
1360 /* The remote state this event is associated with. When the remote
1361 connection, represented by a remote_state object, is closed,
1362 all the associated stop_reply events should be released. */
1363 struct remote_state *rs;
1364
1365 struct target_waitstatus ws;
1366
1367 /* The architecture associated with the expedited registers. */
1368 gdbarch *arch;
1369
1370 /* Expedited registers. This makes remote debugging a bit more
1371 efficient for those targets that provide critical registers as
1372 part of their normal status mechanism (as another roundtrip to
1373 fetch them is avoided). */
1374 std::vector<cached_reg_t> regcache;
1375
1376 enum target_stop_reason stop_reason;
1377
1378 CORE_ADDR watch_data_address;
1379
1380 int core;
1381 };
1382
1383 /* Return TARGET as a remote_target if it is one, else nullptr. */
1384
1385 static remote_target *
1386 as_remote_target (process_stratum_target *target)
1387 {
1388 return dynamic_cast<remote_target *> (target);
1389 }
1390
1391 /* See remote.h. */
1392
1393 bool
1394 is_remote_target (process_stratum_target *target)
1395 {
1396 return as_remote_target (target) != nullptr;
1397 }
1398
1399 /* Per-program-space data key. */
1400 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1401 remote_pspace_data;
1402
1403 /* The variable registered as the control variable used by the
1404 remote exec-file commands. While the remote exec-file setting is
1405 per-program-space, the set/show machinery uses this as the
1406 location of the remote exec-file value. */
1407 static std::string remote_exec_file_var;
1408
1409 /* The size to align memory write packets, when practical. The protocol
1410 does not guarantee any alignment, and gdb will generate short
1411 writes and unaligned writes, but even as a best-effort attempt this
1412 can improve bulk transfers. For instance, if a write is misaligned
1413 relative to the target's data bus, the stub may need to make an extra
1414 round trip fetching data from the target. This doesn't make a
1415 huge difference, but it's easy to do, so we try to be helpful.
1416
1417 The alignment chosen is arbitrary; usually data bus width is
1418 important here, not the possibly larger cache line size. */
1419 enum { REMOTE_ALIGN_WRITES = 16 };
1420
1421 /* Prototypes for local functions. */
1422
1423 static int hexnumlen (ULONGEST num);
1424
1425 static int stubhex (int ch);
1426
1427 static int hexnumstr (char *, ULONGEST);
1428
1429 static int hexnumnstr (char *, ULONGEST, int);
1430
1431 static CORE_ADDR remote_address_masked (CORE_ADDR);
1432
1433 static int stub_unpack_int (const char *buff, int fieldlength);
1434
1435 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1436 cmd_list_element *c);
1437
1438 static void show_packet_config_cmd (ui_file *file,
1439 const unsigned int which_packet,
1440 remote_target *remote);
1441
1442 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1443 int from_tty,
1444 struct cmd_list_element *c,
1445 const char *value);
1446
1447 static ptid_t read_ptid (const char *buf, const char **obuf);
1448
1449 static bool remote_read_description_p (struct target_ops *target);
1450
1451 static void remote_console_output (const char *msg);
1452
1453 static void remote_btrace_reset (remote_state *rs);
1454
1455 static void remote_unpush_and_throw (remote_target *target);
1456
1457 /* For "remote". */
1458
1459 static struct cmd_list_element *remote_cmdlist;
1460
1461 /* For "set remote" and "show remote". */
1462
1463 static struct cmd_list_element *remote_set_cmdlist;
1464 static struct cmd_list_element *remote_show_cmdlist;
1465
1466 /* Controls whether GDB is willing to use range stepping. */
1467
1468 static bool use_range_stepping = true;
1469
1470 /* From the remote target's point of view, each thread is in one of these three
1471 states. */
1472 enum class resume_state
1473 {
1474 /* Not resumed - we haven't been asked to resume this thread. */
1475 NOT_RESUMED,
1476
1477 /* We have been asked to resume this thread, but haven't sent a vCont action
1478 for it yet. We'll need to consider it next time commit_resume is
1479 called. */
1480 RESUMED_PENDING_VCONT,
1481
1482 /* We have been asked to resume this thread, and we have sent a vCont action
1483 for it. */
1484 RESUMED,
1485 };
1486
1487 /* Information about a thread's pending vCont-resume. Used when a thread is in
1488 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1489 stores this information which is then picked up by
1490 remote_target::commit_resume to know which is the proper action for this
1491 thread to include in the vCont packet. */
1492 struct resumed_pending_vcont_info
1493 {
1494 /* True if the last resume call for this thread was a step request, false
1495 if a continue request. */
1496 bool step;
1497
1498 /* The signal specified in the last resume call for this thread. */
1499 gdb_signal sig;
1500 };
1501
1502 /* Private data that we'll store in (struct thread_info)->priv. */
1503 struct remote_thread_info : public private_thread_info
1504 {
1505 std::string extra;
1506 std::string name;
1507 int core = -1;
1508
1509 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1510 sequence of bytes. */
1511 gdb::byte_vector thread_handle;
1512
1513 /* Whether the target stopped for a breakpoint/watchpoint. */
1514 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1515
1516 /* This is set to the data address of the access causing the target
1517 to stop for a watchpoint. */
1518 CORE_ADDR watch_data_address = 0;
1519
1520 /* Get the thread's resume state. */
1521 enum resume_state get_resume_state () const
1522 {
1523 return m_resume_state;
1524 }
1525
1526 /* Put the thread in the NOT_RESUMED state. */
1527 void set_not_resumed ()
1528 {
1529 m_resume_state = resume_state::NOT_RESUMED;
1530 }
1531
1532 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1533 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1534 {
1535 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1536 m_resumed_pending_vcont_info.step = step;
1537 m_resumed_pending_vcont_info.sig = sig;
1538 }
1539
1540 /* Get the information this thread's pending vCont-resumption.
1541
1542 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1543 state. */
1544 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1545 {
1546 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1547
1548 return m_resumed_pending_vcont_info;
1549 }
1550
1551 /* Put the thread in the VCONT_RESUMED state. */
1552 void set_resumed ()
1553 {
1554 m_resume_state = resume_state::RESUMED;
1555 }
1556
1557 private:
1558 /* Resume state for this thread. This is used to implement vCont action
1559 coalescing (only when the target operates in non-stop mode).
1560
1561 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1562 which notes that this thread must be considered in the next commit_resume
1563 call.
1564
1565 remote_target::commit_resume sends a vCont packet with actions for the
1566 threads in the RESUMED_PENDING_VCONT state and moves them to the
1567 VCONT_RESUMED state.
1568
1569 When reporting a stop to the core for a thread, that thread is moved back
1570 to the NOT_RESUMED state. */
1571 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1572
1573 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1574 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1575 };
1576
1577 remote_state::remote_state ()
1578 : buf (400)
1579 {
1580 }
1581
1582 remote_state::~remote_state ()
1583 {
1584 xfree (this->last_pass_packet);
1585 xfree (this->last_program_signals_packet);
1586 xfree (this->finished_object);
1587 xfree (this->finished_annex);
1588 }
1589
1590 /* Utility: generate error from an incoming stub packet. */
1591 static void
1592 trace_error (char *buf)
1593 {
1594 if (*buf++ != 'E')
1595 return; /* not an error msg */
1596 switch (*buf)
1597 {
1598 case '1': /* malformed packet error */
1599 if (*++buf == '0') /* general case: */
1600 error (_("remote.c: error in outgoing packet."));
1601 else
1602 error (_("remote.c: error in outgoing packet at field #%ld."),
1603 strtol (buf, NULL, 16));
1604 default:
1605 error (_("Target returns error code '%s'."), buf);
1606 }
1607 }
1608
1609 /* Utility: wait for reply from stub, while accepting "O" packets. */
1610
1611 char *
1612 remote_target::remote_get_noisy_reply ()
1613 {
1614 struct remote_state *rs = get_remote_state ();
1615
1616 do /* Loop on reply from remote stub. */
1617 {
1618 char *buf;
1619
1620 QUIT; /* Allow user to bail out with ^C. */
1621 getpkt (&rs->buf);
1622 buf = rs->buf.data ();
1623 if (buf[0] == 'E')
1624 trace_error (buf);
1625 else if (startswith (buf, "qRelocInsn:"))
1626 {
1627 ULONGEST ul;
1628 CORE_ADDR from, to, org_to;
1629 const char *p, *pp;
1630 int adjusted_size = 0;
1631 int relocated = 0;
1632
1633 p = buf + strlen ("qRelocInsn:");
1634 pp = unpack_varlen_hex (p, &ul);
1635 if (*pp != ';')
1636 error (_("invalid qRelocInsn packet: %s"), buf);
1637 from = ul;
1638
1639 p = pp + 1;
1640 unpack_varlen_hex (p, &ul);
1641 to = ul;
1642
1643 org_to = to;
1644
1645 try
1646 {
1647 gdbarch_relocate_instruction (current_inferior ()->arch (),
1648 &to, from);
1649 relocated = 1;
1650 }
1651 catch (const gdb_exception &ex)
1652 {
1653 if (ex.error == MEMORY_ERROR)
1654 {
1655 /* Propagate memory errors silently back to the
1656 target. The stub may have limited the range of
1657 addresses we can write to, for example. */
1658 }
1659 else
1660 {
1661 /* Something unexpectedly bad happened. Be verbose
1662 so we can tell what, and propagate the error back
1663 to the stub, so it doesn't get stuck waiting for
1664 a response. */
1665 exception_fprintf (gdb_stderr, ex,
1666 _("warning: relocating instruction: "));
1667 }
1668 putpkt ("E01");
1669 }
1670
1671 if (relocated)
1672 {
1673 adjusted_size = to - org_to;
1674
1675 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1676 putpkt (buf);
1677 }
1678 }
1679 else if (buf[0] == 'O' && buf[1] != 'K')
1680 remote_console_output (buf + 1); /* 'O' message from stub */
1681 else
1682 return buf; /* Here's the actual reply. */
1683 }
1684 while (1);
1685 }
1686
1687 struct remote_arch_state *
1688 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1689 {
1690 remote_arch_state *rsa;
1691
1692 auto it = this->m_arch_states.find (gdbarch);
1693 if (it == this->m_arch_states.end ())
1694 {
1695 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1696 std::forward_as_tuple (gdbarch),
1697 std::forward_as_tuple (gdbarch));
1698 rsa = &p.first->second;
1699
1700 /* Make sure that the packet buffer is plenty big enough for
1701 this architecture. */
1702 if (this->buf.size () < rsa->remote_packet_size)
1703 this->buf.resize (2 * rsa->remote_packet_size);
1704 }
1705 else
1706 rsa = &it->second;
1707
1708 return rsa;
1709 }
1710
1711 /* Fetch the global remote target state. */
1712
1713 remote_state *
1714 remote_target::get_remote_state ()
1715 {
1716 /* Make sure that the remote architecture state has been
1717 initialized, because doing so might reallocate rs->buf. Any
1718 function which calls getpkt also needs to be mindful of changes
1719 to rs->buf, but this call limits the number of places which run
1720 into trouble. */
1721 m_remote_state.get_remote_arch_state (current_inferior ()->arch ());
1722
1723 return &m_remote_state;
1724 }
1725
1726 /* Fetch the remote exec-file from the current program space. */
1727
1728 static const char *
1729 get_remote_exec_file (void)
1730 {
1731 char *remote_exec_file;
1732
1733 remote_exec_file = remote_pspace_data.get (current_program_space);
1734 if (remote_exec_file == NULL)
1735 return "";
1736
1737 return remote_exec_file;
1738 }
1739
1740 /* Set the remote exec file for PSPACE. */
1741
1742 static void
1743 set_pspace_remote_exec_file (struct program_space *pspace,
1744 const char *remote_exec_file)
1745 {
1746 char *old_file = remote_pspace_data.get (pspace);
1747
1748 xfree (old_file);
1749 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1750 }
1751
1752 /* The "set/show remote exec-file" set command hook. */
1753
1754 static void
1755 set_remote_exec_file (const char *ignored, int from_tty,
1756 struct cmd_list_element *c)
1757 {
1758 set_pspace_remote_exec_file (current_program_space,
1759 remote_exec_file_var.c_str ());
1760 }
1761
1762 /* The "set/show remote exec-file" show command hook. */
1763
1764 static void
1765 show_remote_exec_file (struct ui_file *file, int from_tty,
1766 struct cmd_list_element *cmd, const char *value)
1767 {
1768 gdb_printf (file, "%s\n", get_remote_exec_file ());
1769 }
1770
1771 static int
1772 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1773 {
1774 int regnum, num_remote_regs, offset;
1775 struct packet_reg **remote_regs;
1776
1777 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1778 {
1779 struct packet_reg *r = &regs[regnum];
1780
1781 if (register_size (gdbarch, regnum) == 0)
1782 /* Do not try to fetch zero-sized (placeholder) registers. */
1783 r->pnum = -1;
1784 else
1785 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1786
1787 r->regnum = regnum;
1788 }
1789
1790 /* Define the g/G packet format as the contents of each register
1791 with a remote protocol number, in order of ascending protocol
1792 number. */
1793
1794 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1795 for (num_remote_regs = 0, regnum = 0;
1796 regnum < gdbarch_num_regs (gdbarch);
1797 regnum++)
1798 if (regs[regnum].pnum != -1)
1799 remote_regs[num_remote_regs++] = &regs[regnum];
1800
1801 std::sort (remote_regs, remote_regs + num_remote_regs,
1802 [] (const packet_reg *a, const packet_reg *b)
1803 { return a->pnum < b->pnum; });
1804
1805 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1806 {
1807 remote_regs[regnum]->in_g_packet = 1;
1808 remote_regs[regnum]->offset = offset;
1809 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1810 }
1811
1812 return offset;
1813 }
1814
1815 /* Given the architecture described by GDBARCH, return the remote
1816 protocol register's number and the register's offset in the g/G
1817 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1818 If the target does not have a mapping for REGNUM, return false,
1819 otherwise, return true. */
1820
1821 int
1822 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1823 int *pnum, int *poffset)
1824 {
1825 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1826
1827 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1828
1829 map_regcache_remote_table (gdbarch, regs.data ());
1830
1831 *pnum = regs[regnum].pnum;
1832 *poffset = regs[regnum].offset;
1833
1834 return *pnum != -1;
1835 }
1836
1837 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1838 {
1839 /* Use the architecture to build a regnum<->pnum table, which will be
1840 1:1 unless a feature set specifies otherwise. */
1841 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1842
1843 /* Record the maximum possible size of the g packet - it may turn out
1844 to be smaller. */
1845 this->sizeof_g_packet
1846 = map_regcache_remote_table (gdbarch, this->regs.get ());
1847
1848 /* Default maximum number of characters in a packet body. Many
1849 remote stubs have a hardwired buffer size of 400 bytes
1850 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1851 as the maximum packet-size to ensure that the packet and an extra
1852 NUL character can always fit in the buffer. This stops GDB
1853 trashing stubs that try to squeeze an extra NUL into what is
1854 already a full buffer (As of 1999-12-04 that was most stubs). */
1855 this->remote_packet_size = 400 - 1;
1856
1857 /* This one is filled in when a ``g'' packet is received. */
1858 this->actual_register_packet_size = 0;
1859
1860 /* Should rsa->sizeof_g_packet needs more space than the
1861 default, adjust the size accordingly. Remember that each byte is
1862 encoded as two characters. 32 is the overhead for the packet
1863 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1864 (``$NN:G...#NN'') is a better guess, the below has been padded a
1865 little. */
1866 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1867 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1868 }
1869
1870 /* Get a pointer to the current remote target. If not connected to a
1871 remote target, return NULL. */
1872
1873 static remote_target *
1874 get_current_remote_target ()
1875 {
1876 target_ops *proc_target = current_inferior ()->process_target ();
1877 return dynamic_cast<remote_target *> (proc_target);
1878 }
1879
1880 /* Return the current allowed size of a remote packet. This is
1881 inferred from the current architecture, and should be used to
1882 limit the length of outgoing packets. */
1883 long
1884 remote_target::get_remote_packet_size ()
1885 {
1886 struct remote_state *rs = get_remote_state ();
1887 remote_arch_state *rsa
1888 = rs->get_remote_arch_state (current_inferior ()->arch ());
1889
1890 if (rs->explicit_packet_size)
1891 return rs->explicit_packet_size;
1892
1893 return rsa->remote_packet_size;
1894 }
1895
1896 static struct packet_reg *
1897 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1898 long regnum)
1899 {
1900 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1901 return NULL;
1902 else
1903 {
1904 struct packet_reg *r = &rsa->regs[regnum];
1905
1906 gdb_assert (r->regnum == regnum);
1907 return r;
1908 }
1909 }
1910
1911 static struct packet_reg *
1912 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1913 LONGEST pnum)
1914 {
1915 int i;
1916
1917 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1918 {
1919 struct packet_reg *r = &rsa->regs[i];
1920
1921 if (r->pnum == pnum)
1922 return r;
1923 }
1924 return NULL;
1925 }
1926
1927 /* Allow the user to specify what sequence to send to the remote
1928 when he requests a program interruption: Although ^C is usually
1929 what remote systems expect (this is the default, here), it is
1930 sometimes preferable to send a break. On other systems such
1931 as the Linux kernel, a break followed by g, which is Magic SysRq g
1932 is required in order to interrupt the execution. */
1933 const char interrupt_sequence_control_c[] = "Ctrl-C";
1934 const char interrupt_sequence_break[] = "BREAK";
1935 const char interrupt_sequence_break_g[] = "BREAK-g";
1936 static const char *const interrupt_sequence_modes[] =
1937 {
1938 interrupt_sequence_control_c,
1939 interrupt_sequence_break,
1940 interrupt_sequence_break_g,
1941 NULL
1942 };
1943 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1944
1945 static void
1946 show_interrupt_sequence (struct ui_file *file, int from_tty,
1947 struct cmd_list_element *c,
1948 const char *value)
1949 {
1950 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1951 gdb_printf (file,
1952 _("Send the ASCII ETX character (Ctrl-c) "
1953 "to the remote target to interrupt the "
1954 "execution of the program.\n"));
1955 else if (interrupt_sequence_mode == interrupt_sequence_break)
1956 gdb_printf (file,
1957 _("send a break signal to the remote target "
1958 "to interrupt the execution of the program.\n"));
1959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1960 gdb_printf (file,
1961 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1962 "the remote target to interrupt the execution "
1963 "of Linux kernel.\n"));
1964 else
1965 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1966 interrupt_sequence_mode);
1967 }
1968
1969 /* This boolean variable specifies whether interrupt_sequence is sent
1970 to the remote target when gdb connects to it.
1971 This is mostly needed when you debug the Linux kernel: The Linux kernel
1972 expects BREAK g which is Magic SysRq g for connecting gdb. */
1973 static bool interrupt_on_connect = false;
1974
1975 /* This variable is used to implement the "set/show remotebreak" commands.
1976 Since these commands are now deprecated in favor of "set/show remote
1977 interrupt-sequence", it no longer has any effect on the code. */
1978 static bool remote_break;
1979
1980 static void
1981 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1982 {
1983 if (remote_break)
1984 interrupt_sequence_mode = interrupt_sequence_break;
1985 else
1986 interrupt_sequence_mode = interrupt_sequence_control_c;
1987 }
1988
1989 static void
1990 show_remotebreak (struct ui_file *file, int from_tty,
1991 struct cmd_list_element *c,
1992 const char *value)
1993 {
1994 }
1995
1996 /* This variable sets the number of bits in an address that are to be
1997 sent in a memory ("M" or "m") packet. Normally, after stripping
1998 leading zeros, the entire address would be sent. This variable
1999 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
2000 initial implementation of remote.c restricted the address sent in
2001 memory packets to ``host::sizeof long'' bytes - (typically 32
2002 bits). Consequently, for 64 bit targets, the upper 32 bits of an
2003 address was never sent. Since fixing this bug may cause a break in
2004 some remote targets this variable is principally provided to
2005 facilitate backward compatibility. */
2006
2007 static unsigned int remote_address_size;
2008
2009 \f
2010 /* The default max memory-write-packet-size, when the setting is
2011 "fixed". The 16k is historical. (It came from older GDB's using
2012 alloca for buffers and the knowledge (folklore?) that some hosts
2013 don't cope very well with large alloca calls.) */
2014 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
2015
2016 /* The minimum remote packet size for memory transfers. Ensures we
2017 can write at least one byte. */
2018 #define MIN_MEMORY_PACKET_SIZE 20
2019
2020 /* Get the memory packet size, assuming it is fixed. */
2021
2022 static long
2023 get_fixed_memory_packet_size (struct memory_packet_config *config)
2024 {
2025 gdb_assert (config->fixed_p);
2026
2027 if (config->size <= 0)
2028 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
2029 else
2030 return config->size;
2031 }
2032
2033 /* Compute the current size of a read/write packet. Since this makes
2034 use of ``actual_register_packet_size'' the computation is dynamic. */
2035
2036 long
2037 remote_target::get_memory_packet_size (struct memory_packet_config *config)
2038 {
2039 struct remote_state *rs = get_remote_state ();
2040 remote_arch_state *rsa
2041 = rs->get_remote_arch_state (current_inferior ()->arch ());
2042
2043 long what_they_get;
2044 if (config->fixed_p)
2045 what_they_get = get_fixed_memory_packet_size (config);
2046 else
2047 {
2048 what_they_get = get_remote_packet_size ();
2049 /* Limit the packet to the size specified by the user. */
2050 if (config->size > 0
2051 && what_they_get > config->size)
2052 what_they_get = config->size;
2053
2054 /* Limit it to the size of the targets ``g'' response unless we have
2055 permission from the stub to use a larger packet size. */
2056 if (rs->explicit_packet_size == 0
2057 && rsa->actual_register_packet_size > 0
2058 && what_they_get > rsa->actual_register_packet_size)
2059 what_they_get = rsa->actual_register_packet_size;
2060 }
2061 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2062 what_they_get = MIN_MEMORY_PACKET_SIZE;
2063
2064 /* Make sure there is room in the global buffer for this packet
2065 (including its trailing NUL byte). */
2066 if (rs->buf.size () < what_they_get + 1)
2067 rs->buf.resize (2 * what_they_get);
2068
2069 return what_they_get;
2070 }
2071
2072 /* Update the size of a read/write packet. If they user wants
2073 something really big then do a sanity check. */
2074
2075 static void
2076 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2077 bool target_connected)
2078 {
2079 int fixed_p = config->fixed_p;
2080 long size = config->size;
2081
2082 if (args == NULL)
2083 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2084 else if (strcmp (args, "hard") == 0
2085 || strcmp (args, "fixed") == 0)
2086 fixed_p = 1;
2087 else if (strcmp (args, "soft") == 0
2088 || strcmp (args, "limit") == 0)
2089 fixed_p = 0;
2090 else
2091 {
2092 char *end;
2093
2094 size = strtoul (args, &end, 0);
2095 if (args == end)
2096 error (_("Invalid %s (bad syntax)."), config->name);
2097
2098 /* Instead of explicitly capping the size of a packet to or
2099 disallowing it, the user is allowed to set the size to
2100 something arbitrarily large. */
2101 }
2102
2103 /* Extra checks? */
2104 if (fixed_p && !config->fixed_p)
2105 {
2106 /* So that the query shows the correct value. */
2107 long query_size = (size <= 0
2108 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2109 : size);
2110
2111 if (target_connected
2112 && !query (_("The target may not be able to correctly handle a %s\n"
2113 "of %ld bytes. Change the packet size? "),
2114 config->name, query_size))
2115 error (_("Packet size not changed."));
2116 else if (!target_connected
2117 && !query (_("Future remote targets may not be able to "
2118 "correctly handle a %s\nof %ld bytes. Change the "
2119 "packet size for future remote targets? "),
2120 config->name, query_size))
2121 error (_("Packet size not changed."));
2122 }
2123 /* Update the config. */
2124 config->fixed_p = fixed_p;
2125 config->size = size;
2126
2127 const char *target_type = get_target_type_name (target_connected);
2128 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2129 args);
2130
2131 }
2132
2133 /* Show the memory-read or write-packet size configuration CONFIG of the
2134 target REMOTE. If REMOTE is nullptr, the default configuration for future
2135 remote targets should be passed in CONFIG. */
2136
2137 static void
2138 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2139 {
2140 const char *target_type = get_target_type_name (remote != nullptr);
2141
2142 if (config->size == 0)
2143 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2144 else
2145 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2146 config->size);
2147
2148 if (config->fixed_p)
2149 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2150 get_fixed_memory_packet_size (config));
2151 else
2152 {
2153 if (remote != nullptr)
2154 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2155 remote->get_memory_packet_size (config));
2156 else
2157 gdb_puts ("The actual limit will be further reduced "
2158 "dependent on the target.\n");
2159 }
2160 }
2161
2162 /* Configure the memory-write-packet size of the currently selected target. If
2163 no target is available, the default configuration for future remote targets
2164 is configured. */
2165
2166 static void
2167 set_memory_write_packet_size (const char *args, int from_tty)
2168 {
2169 remote_target *remote = get_current_remote_target ();
2170 if (remote != nullptr)
2171 {
2172 set_memory_packet_size
2173 (args, &remote->m_features.m_memory_write_packet_config, true);
2174 }
2175 else
2176 {
2177 memory_packet_config* config = &memory_write_packet_config;
2178 set_memory_packet_size (args, config, false);
2179 }
2180 }
2181
2182 /* Display the memory-write-packet size of the currently selected target. If
2183 no target is available, the default configuration for future remote targets
2184 is shown. */
2185
2186 static void
2187 show_memory_write_packet_size (const char *args, int from_tty)
2188 {
2189 remote_target *remote = get_current_remote_target ();
2190 if (remote != nullptr)
2191 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2192 remote);
2193 else
2194 show_memory_packet_size (&memory_write_packet_config, nullptr);
2195 }
2196
2197 /* Show the number of hardware watchpoints that can be used. */
2198
2199 static void
2200 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2201 struct cmd_list_element *c,
2202 const char *value)
2203 {
2204 gdb_printf (file, _("The maximum number of target hardware "
2205 "watchpoints is %s.\n"), value);
2206 }
2207
2208 /* Show the length limit (in bytes) for hardware watchpoints. */
2209
2210 static void
2211 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2212 struct cmd_list_element *c,
2213 const char *value)
2214 {
2215 gdb_printf (file, _("The maximum length (in bytes) of a target "
2216 "hardware watchpoint is %s.\n"), value);
2217 }
2218
2219 /* Show the number of hardware breakpoints that can be used. */
2220
2221 static void
2222 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2223 struct cmd_list_element *c,
2224 const char *value)
2225 {
2226 gdb_printf (file, _("The maximum number of target hardware "
2227 "breakpoints is %s.\n"), value);
2228 }
2229
2230 /* Controls the maximum number of characters to display in the debug output
2231 for each remote packet. The remaining characters are omitted. */
2232
2233 static int remote_packet_max_chars = 512;
2234
2235 /* Show the maximum number of characters to display for each remote packet
2236 when remote debugging is enabled. */
2237
2238 static void
2239 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2240 struct cmd_list_element *c,
2241 const char *value)
2242 {
2243 gdb_printf (file, _("Number of remote packet characters to "
2244 "display is %s.\n"), value);
2245 }
2246
2247 long
2248 remote_target::get_memory_write_packet_size ()
2249 {
2250 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2251 }
2252
2253 /* Configure the memory-read-packet size of the currently selected target. If
2254 no target is available, the default configuration for future remote targets
2255 is adapted. */
2256
2257 static void
2258 set_memory_read_packet_size (const char *args, int from_tty)
2259 {
2260 remote_target *remote = get_current_remote_target ();
2261 if (remote != nullptr)
2262 set_memory_packet_size
2263 (args, &remote->m_features.m_memory_read_packet_config, true);
2264 else
2265 {
2266 memory_packet_config* config = &memory_read_packet_config;
2267 set_memory_packet_size (args, config, false);
2268 }
2269
2270 }
2271
2272 /* Display the memory-read-packet size of the currently selected target. If
2273 no target is available, the default configuration for future remote targets
2274 is shown. */
2275
2276 static void
2277 show_memory_read_packet_size (const char *args, int from_tty)
2278 {
2279 remote_target *remote = get_current_remote_target ();
2280 if (remote != nullptr)
2281 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2282 remote);
2283 else
2284 show_memory_packet_size (&memory_read_packet_config, nullptr);
2285 }
2286
2287 long
2288 remote_target::get_memory_read_packet_size ()
2289 {
2290 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2291
2292 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2293 extra buffer size argument before the memory read size can be
2294 increased beyond this. */
2295 if (size > get_remote_packet_size ())
2296 size = get_remote_packet_size ();
2297 return size;
2298 }
2299
2300 static enum packet_support packet_config_support (const packet_config *config);
2301
2302
2303 static void
2304 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2305 cmd_list_element *c)
2306 {
2307 remote_target *remote = get_current_remote_target ();
2308 gdb_assert (c->var.has_value ());
2309
2310 auto *default_config = static_cast<packet_config *> (c->context ());
2311 const int packet_idx = std::distance (remote_protocol_packets,
2312 default_config);
2313
2314 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2315 {
2316 const char *name = packets_descriptions[packet_idx].name;
2317 const auto_boolean value = c->var->get<auto_boolean> ();
2318 const char *support = get_packet_support_name (value);
2319 const char *target_type = get_target_type_name (remote != nullptr);
2320
2321 if (remote != nullptr)
2322 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2323 else
2324 remote_protocol_packets[packet_idx].detect = value;
2325
2326 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2327 target_type, support);
2328 return;
2329 }
2330
2331 internal_error (_("Could not find config for %s"), c->name);
2332 }
2333
2334 static void
2335 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2336 remote_target *remote)
2337 {
2338 const char *support = "internal-error";
2339 const char *target_type = get_target_type_name (remote != nullptr);
2340
2341 packet_config *config;
2342 if (remote != nullptr)
2343 config = &remote->m_features.m_protocol_packets[which_packet];
2344 else
2345 config = &remote_protocol_packets[which_packet];
2346
2347 switch (packet_config_support (config))
2348 {
2349 case PACKET_ENABLE:
2350 support = "enabled";
2351 break;
2352 case PACKET_DISABLE:
2353 support = "disabled";
2354 break;
2355 case PACKET_SUPPORT_UNKNOWN:
2356 support = "unknown";
2357 break;
2358 }
2359 switch (config->detect)
2360 {
2361 case AUTO_BOOLEAN_AUTO:
2362 gdb_printf (file,
2363 _("Support for the '%s' packet %s is \"auto\", "
2364 "currently %s.\n"),
2365 packets_descriptions[which_packet].name, target_type,
2366 support);
2367 break;
2368 case AUTO_BOOLEAN_TRUE:
2369 case AUTO_BOOLEAN_FALSE:
2370 gdb_printf (file,
2371 _("Support for the '%s' packet %s is \"%s\".\n"),
2372 packets_descriptions[which_packet].name, target_type,
2373 get_packet_support_name (config->detect));
2374 break;
2375 }
2376 }
2377
2378 static void
2379 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2380 const char *title, int legacy)
2381 {
2382 packets_descriptions[which_packet].name = name;
2383 packets_descriptions[which_packet].title = title;
2384
2385 packet_config *config = &remote_protocol_packets[which_packet];
2386
2387 gdb::unique_xmalloc_ptr<char> set_doc
2388 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2389 name, title);
2390 gdb::unique_xmalloc_ptr<char> show_doc
2391 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2392 name, title);
2393 /* set/show TITLE-packet {auto,on,off} */
2394 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2395 set_show_commands cmds
2396 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2397 &config->detect, set_doc.get (),
2398 show_doc.get (), NULL, /* help_doc */
2399 set_remote_protocol_packet_cmd,
2400 show_remote_protocol_packet_cmd,
2401 &remote_set_cmdlist, &remote_show_cmdlist);
2402 cmds.show->set_context (config);
2403 cmds.set->set_context (config);
2404
2405 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2406 if (legacy)
2407 {
2408 /* It's not clear who should take ownership of the LEGACY_NAME string
2409 created below, so, for now, place the string into a static vector
2410 which ensures the strings is released when GDB exits. */
2411 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2412 gdb::unique_xmalloc_ptr<char> legacy_name
2413 = xstrprintf ("%s-packet", name);
2414 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2415 &remote_set_cmdlist);
2416 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2417 &remote_show_cmdlist);
2418 legacy_names.emplace_back (std::move (legacy_name));
2419 }
2420 }
2421
2422 static enum packet_result
2423 packet_check_result (const char *buf)
2424 {
2425 if (buf[0] != '\0')
2426 {
2427 /* The stub recognized the packet request. Check that the
2428 operation succeeded. */
2429 if (buf[0] == 'E'
2430 && isxdigit (buf[1]) && isxdigit (buf[2])
2431 && buf[3] == '\0')
2432 /* "Enn" - definitely an error. */
2433 return PACKET_ERROR;
2434
2435 /* Always treat "E." as an error. This will be used for
2436 more verbose error messages, such as E.memtypes. */
2437 if (buf[0] == 'E' && buf[1] == '.')
2438 return PACKET_ERROR;
2439
2440 /* The packet may or may not be OK. Just assume it is. */
2441 return PACKET_OK;
2442 }
2443 else
2444 /* The stub does not support the packet. */
2445 return PACKET_UNKNOWN;
2446 }
2447
2448 static enum packet_result
2449 packet_check_result (const gdb::char_vector &buf)
2450 {
2451 return packet_check_result (buf.data ());
2452 }
2453
2454 packet_result
2455 remote_features::packet_ok (const char *buf, const int which_packet)
2456 {
2457 packet_config *config = &m_protocol_packets[which_packet];
2458 packet_description *descr = &packets_descriptions[which_packet];
2459
2460 enum packet_result result;
2461
2462 if (config->detect != AUTO_BOOLEAN_TRUE
2463 && config->support == PACKET_DISABLE)
2464 internal_error (_("packet_ok: attempt to use a disabled packet"));
2465
2466 result = packet_check_result (buf);
2467 switch (result)
2468 {
2469 case PACKET_OK:
2470 case PACKET_ERROR:
2471 /* The stub recognized the packet request. */
2472 if (config->support == PACKET_SUPPORT_UNKNOWN)
2473 {
2474 remote_debug_printf ("Packet %s (%s) is supported",
2475 descr->name, descr->title);
2476 config->support = PACKET_ENABLE;
2477 }
2478 break;
2479 case PACKET_UNKNOWN:
2480 /* The stub does not support the packet. */
2481 if (config->detect == AUTO_BOOLEAN_AUTO
2482 && config->support == PACKET_ENABLE)
2483 {
2484 /* If the stub previously indicated that the packet was
2485 supported then there is a protocol error. */
2486 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2487 descr->name, descr->title);
2488 }
2489 else if (config->detect == AUTO_BOOLEAN_TRUE)
2490 {
2491 /* The user set it wrong. */
2492 error (_("Enabled packet %s (%s) not recognized by stub"),
2493 descr->name, descr->title);
2494 }
2495
2496 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2497 descr->title);
2498 config->support = PACKET_DISABLE;
2499 break;
2500 }
2501
2502 return result;
2503 }
2504
2505 packet_result
2506 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2507 {
2508 return packet_ok (buf.data (), which_packet);
2509 }
2510
2511 /* Returns whether a given packet or feature is supported. This takes
2512 into account the state of the corresponding "set remote foo-packet"
2513 command, which may be used to bypass auto-detection. */
2514
2515 static enum packet_support
2516 packet_config_support (const packet_config *config)
2517 {
2518 switch (config->detect)
2519 {
2520 case AUTO_BOOLEAN_TRUE:
2521 return PACKET_ENABLE;
2522 case AUTO_BOOLEAN_FALSE:
2523 return PACKET_DISABLE;
2524 case AUTO_BOOLEAN_AUTO:
2525 return config->support;
2526 default:
2527 gdb_assert_not_reached ("bad switch");
2528 }
2529 }
2530
2531 packet_support
2532 remote_features::packet_support (int packet) const
2533 {
2534 const packet_config *config = &m_protocol_packets[packet];
2535 return packet_config_support (config);
2536 }
2537
2538 static void
2539 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2540 struct cmd_list_element *c,
2541 const char *value)
2542 {
2543 remote_target *remote = get_current_remote_target ();
2544 gdb_assert (c->var.has_value ());
2545
2546 auto *default_config = static_cast<packet_config *> (c->context ());
2547 const int packet_idx = std::distance (remote_protocol_packets,
2548 default_config);
2549
2550 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2551 {
2552 show_packet_config_cmd (file, packet_idx, remote);
2553 return;
2554 }
2555 internal_error (_("Could not find config for %s"), c->name);
2556 }
2557
2558 /* Should we try one of the 'Z' requests? */
2559
2560 enum Z_packet_type
2561 {
2562 Z_PACKET_SOFTWARE_BP,
2563 Z_PACKET_HARDWARE_BP,
2564 Z_PACKET_WRITE_WP,
2565 Z_PACKET_READ_WP,
2566 Z_PACKET_ACCESS_WP,
2567 NR_Z_PACKET_TYPES
2568 };
2569
2570 /* For compatibility with older distributions. Provide a ``set remote
2571 Z-packet ...'' command that updates all the Z packet types. */
2572
2573 static enum auto_boolean remote_Z_packet_detect;
2574
2575 static void
2576 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2577 struct cmd_list_element *c)
2578 {
2579 remote_target *remote = get_current_remote_target ();
2580 int i;
2581
2582 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2583 {
2584 if (remote != nullptr)
2585 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2586 = remote_Z_packet_detect;
2587 else
2588 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2589 }
2590
2591 const char *support = get_packet_support_name (remote_Z_packet_detect);
2592 const char *target_type = get_target_type_name (remote != nullptr);
2593 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2594 support);
2595
2596 }
2597
2598 static void
2599 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2600 struct cmd_list_element *c,
2601 const char *value)
2602 {
2603 remote_target *remote = get_current_remote_target ();
2604 int i;
2605
2606 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2607 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2608 }
2609
2610 /* Insert fork catchpoint target routine. If fork events are enabled
2611 then return success, nothing more to do. */
2612
2613 int
2614 remote_target::insert_fork_catchpoint (int pid)
2615 {
2616 return !m_features.remote_fork_event_p ();
2617 }
2618
2619 /* Remove fork catchpoint target routine. Nothing to do, just
2620 return success. */
2621
2622 int
2623 remote_target::remove_fork_catchpoint (int pid)
2624 {
2625 return 0;
2626 }
2627
2628 /* Insert vfork catchpoint target routine. If vfork events are enabled
2629 then return success, nothing more to do. */
2630
2631 int
2632 remote_target::insert_vfork_catchpoint (int pid)
2633 {
2634 return !m_features.remote_vfork_event_p ();
2635 }
2636
2637 /* Remove vfork catchpoint target routine. Nothing to do, just
2638 return success. */
2639
2640 int
2641 remote_target::remove_vfork_catchpoint (int pid)
2642 {
2643 return 0;
2644 }
2645
2646 /* Insert exec catchpoint target routine. If exec events are
2647 enabled, just return success. */
2648
2649 int
2650 remote_target::insert_exec_catchpoint (int pid)
2651 {
2652 return !m_features.remote_exec_event_p ();
2653 }
2654
2655 /* Remove exec catchpoint target routine. Nothing to do, just
2656 return success. */
2657
2658 int
2659 remote_target::remove_exec_catchpoint (int pid)
2660 {
2661 return 0;
2662 }
2663
2664 \f
2665
2666 /* Take advantage of the fact that the TID field is not used, to tag
2667 special ptids with it set to != 0. */
2668 static const ptid_t magic_null_ptid (42000, -1, 1);
2669 static const ptid_t not_sent_ptid (42000, -2, 1);
2670 static const ptid_t any_thread_ptid (42000, 0, 1);
2671
2672 /* Find out if the stub attached to PID (and hence GDB should offer to
2673 detach instead of killing it when bailing out). */
2674
2675 int
2676 remote_target::remote_query_attached (int pid)
2677 {
2678 struct remote_state *rs = get_remote_state ();
2679 size_t size = get_remote_packet_size ();
2680
2681 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2682 return 0;
2683
2684 if (m_features.remote_multi_process_p ())
2685 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2686 else
2687 xsnprintf (rs->buf.data (), size, "qAttached");
2688
2689 putpkt (rs->buf);
2690 getpkt (&rs->buf);
2691
2692 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2693 {
2694 case PACKET_OK:
2695 if (strcmp (rs->buf.data (), "1") == 0)
2696 return 1;
2697 break;
2698 case PACKET_ERROR:
2699 warning (_("Remote failure reply: %s"), rs->buf.data ());
2700 break;
2701 case PACKET_UNKNOWN:
2702 break;
2703 }
2704
2705 return 0;
2706 }
2707
2708 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2709 has been invented by GDB, instead of reported by the target. Since
2710 we can be connected to a remote system before before knowing about
2711 any inferior, mark the target with execution when we find the first
2712 inferior. If ATTACHED is 1, then we had just attached to this
2713 inferior. If it is 0, then we just created this inferior. If it
2714 is -1, then try querying the remote stub to find out if it had
2715 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2716 attempt to open this inferior's executable as the main executable
2717 if no main executable is open already. */
2718
2719 inferior *
2720 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2721 int try_open_exec)
2722 {
2723 struct inferior *inf;
2724
2725 /* Check whether this process we're learning about is to be
2726 considered attached, or if is to be considered to have been
2727 spawned by the stub. */
2728 if (attached == -1)
2729 attached = remote_query_attached (pid);
2730
2731 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
2732 {
2733 /* If the target shares code across all inferiors, then every
2734 attach adds a new inferior. */
2735 inf = add_inferior (pid);
2736
2737 /* ... and every inferior is bound to the same program space.
2738 However, each inferior may still have its own address
2739 space. */
2740 inf->aspace = maybe_new_address_space ();
2741 inf->pspace = current_program_space;
2742 }
2743 else
2744 {
2745 /* In the traditional debugging scenario, there's a 1-1 match
2746 between program/address spaces. We simply bind the inferior
2747 to the program space's address space. */
2748 inf = current_inferior ();
2749
2750 /* However, if the current inferior is already bound to a
2751 process, find some other empty inferior. */
2752 if (inf->pid != 0)
2753 {
2754 inf = nullptr;
2755 for (inferior *it : all_inferiors ())
2756 if (it->pid == 0)
2757 {
2758 inf = it;
2759 break;
2760 }
2761 }
2762 if (inf == nullptr)
2763 {
2764 /* Since all inferiors were already bound to a process, add
2765 a new inferior. */
2766 inf = add_inferior_with_spaces ();
2767 }
2768 switch_to_inferior_no_thread (inf);
2769 inf->push_target (this);
2770 inferior_appeared (inf, pid);
2771 }
2772
2773 inf->attach_flag = attached;
2774 inf->fake_pid_p = fake_pid_p;
2775
2776 /* If no main executable is currently open then attempt to
2777 open the file that was executed to create this inferior. */
2778 if (try_open_exec && get_exec_file (0) == NULL)
2779 exec_file_locate_attach (pid, 0, 1);
2780
2781 /* Check for exec file mismatch, and let the user solve it. */
2782 validate_exec_file (1);
2783
2784 return inf;
2785 }
2786
2787 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2788 static remote_thread_info *get_remote_thread_info (remote_target *target,
2789 ptid_t ptid);
2790
2791 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2792 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2793 remote_state::starting_up flag) is true then the new thread is added
2794 silently, otherwise the new thread will be announced to the user. */
2795
2796 thread_info *
2797 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2798 bool silent_p)
2799 {
2800 struct remote_state *rs = get_remote_state ();
2801 struct thread_info *thread;
2802
2803 /* GDB historically didn't pull threads in the initial connection
2804 setup. If the remote target doesn't even have a concept of
2805 threads (e.g., a bare-metal target), even if internally we
2806 consider that a single-threaded target, mentioning a new thread
2807 might be confusing to the user. Be silent then, preserving the
2808 age old behavior. */
2809 if (rs->starting_up || silent_p)
2810 thread = add_thread_silent (this, ptid);
2811 else
2812 thread = add_thread (this, ptid);
2813
2814 if (executing)
2815 get_remote_thread_info (thread)->set_resumed ();
2816 set_executing (this, ptid, executing);
2817 set_running (this, ptid, running);
2818
2819 return thread;
2820 }
2821
2822 /* Come here when we learn about a thread id from the remote target.
2823 It may be the first time we hear about such thread, so take the
2824 opportunity to add it to GDB's thread list. In case this is the
2825 first time we're noticing its corresponding inferior, add it to
2826 GDB's inferior list as well. EXECUTING indicates whether the
2827 thread is (internally) executing or stopped. */
2828
2829 void
2830 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2831 {
2832 /* In non-stop mode, we assume new found threads are (externally)
2833 running until proven otherwise with a stop reply. In all-stop,
2834 we can only get here if all threads are stopped. */
2835 bool running = target_is_non_stop_p ();
2836
2837 /* If this is a new thread, add it to GDB's thread list.
2838 If we leave it up to WFI to do this, bad things will happen. */
2839
2840 thread_info *tp = this->find_thread (currthread);
2841 if (tp != NULL && tp->state == THREAD_EXITED)
2842 {
2843 /* We're seeing an event on a thread id we knew had exited.
2844 This has to be a new thread reusing the old id. Add it. */
2845 remote_add_thread (currthread, running, executing, false);
2846 return;
2847 }
2848
2849 if (!in_thread_list (this, currthread))
2850 {
2851 struct inferior *inf = NULL;
2852 int pid = currthread.pid ();
2853
2854 if (inferior_ptid.is_pid ()
2855 && pid == inferior_ptid.pid ())
2856 {
2857 /* inferior_ptid has no thread member yet. This can happen
2858 with the vAttach -> remote_wait,"TAAthread:" path if the
2859 stub doesn't support qC. This is the first stop reported
2860 after an attach, so this is the main thread. Update the
2861 ptid in the thread list. */
2862 if (in_thread_list (this, ptid_t (pid)))
2863 thread_change_ptid (this, inferior_ptid, currthread);
2864 else
2865 {
2866 thread_info *thr
2867 = remote_add_thread (currthread, running, executing, false);
2868 switch_to_thread (thr);
2869 }
2870 return;
2871 }
2872
2873 if (magic_null_ptid == inferior_ptid)
2874 {
2875 /* inferior_ptid is not set yet. This can happen with the
2876 vRun -> remote_wait,"TAAthread:" path if the stub
2877 doesn't support qC. This is the first stop reported
2878 after an attach, so this is the main thread. Update the
2879 ptid in the thread list. */
2880 thread_change_ptid (this, inferior_ptid, currthread);
2881 return;
2882 }
2883
2884 /* When connecting to a target remote, or to a target
2885 extended-remote which already was debugging an inferior, we
2886 may not know about it yet. Add it before adding its child
2887 thread, so notifications are emitted in a sensible order. */
2888 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2889 {
2890 bool fake_pid_p = !m_features.remote_multi_process_p ();
2891
2892 inf = remote_add_inferior (fake_pid_p,
2893 currthread.pid (), -1, 1);
2894 }
2895
2896 /* This is really a new thread. Add it. */
2897 thread_info *new_thr
2898 = remote_add_thread (currthread, running, executing, false);
2899
2900 /* If we found a new inferior, let the common code do whatever
2901 it needs to with it (e.g., read shared libraries, insert
2902 breakpoints), unless we're just setting up an all-stop
2903 connection. */
2904 if (inf != NULL)
2905 {
2906 struct remote_state *rs = get_remote_state ();
2907
2908 if (!rs->starting_up)
2909 notice_new_inferior (new_thr, executing, 0);
2910 }
2911 }
2912 }
2913
2914 /* Return THREAD's private thread data, creating it if necessary. */
2915
2916 static remote_thread_info *
2917 get_remote_thread_info (thread_info *thread)
2918 {
2919 gdb_assert (thread != NULL);
2920
2921 if (thread->priv == NULL)
2922 thread->priv.reset (new remote_thread_info);
2923
2924 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2925 }
2926
2927 /* Return PTID's private thread data, creating it if necessary. */
2928
2929 static remote_thread_info *
2930 get_remote_thread_info (remote_target *target, ptid_t ptid)
2931 {
2932 thread_info *thr = target->find_thread (ptid);
2933 return get_remote_thread_info (thr);
2934 }
2935
2936 /* Call this function as a result of
2937 1) A halt indication (T packet) containing a thread id
2938 2) A direct query of currthread
2939 3) Successful execution of set thread */
2940
2941 static void
2942 record_currthread (struct remote_state *rs, ptid_t currthread)
2943 {
2944 rs->general_thread = currthread;
2945 }
2946
2947 /* If 'QPassSignals' is supported, tell the remote stub what signals
2948 it can simply pass through to the inferior without reporting. */
2949
2950 void
2951 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2952 {
2953 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2954 {
2955 char *pass_packet, *p;
2956 int count = 0;
2957 struct remote_state *rs = get_remote_state ();
2958
2959 gdb_assert (pass_signals.size () < 256);
2960 for (size_t i = 0; i < pass_signals.size (); i++)
2961 {
2962 if (pass_signals[i])
2963 count++;
2964 }
2965 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2966 strcpy (pass_packet, "QPassSignals:");
2967 p = pass_packet + strlen (pass_packet);
2968 for (size_t i = 0; i < pass_signals.size (); i++)
2969 {
2970 if (pass_signals[i])
2971 {
2972 if (i >= 16)
2973 *p++ = tohex (i >> 4);
2974 *p++ = tohex (i & 15);
2975 if (count)
2976 *p++ = ';';
2977 else
2978 break;
2979 count--;
2980 }
2981 }
2982 *p = 0;
2983 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2984 {
2985 putpkt (pass_packet);
2986 getpkt (&rs->buf);
2987 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2988 xfree (rs->last_pass_packet);
2989 rs->last_pass_packet = pass_packet;
2990 }
2991 else
2992 xfree (pass_packet);
2993 }
2994 }
2995
2996 /* If 'QCatchSyscalls' is supported, tell the remote stub
2997 to report syscalls to GDB. */
2998
2999 int
3000 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
3001 gdb::array_view<const int> syscall_counts)
3002 {
3003 const char *catch_packet;
3004 enum packet_result result;
3005 int n_sysno = 0;
3006
3007 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
3008 {
3009 /* Not supported. */
3010 return 1;
3011 }
3012
3013 if (needed && any_count == 0)
3014 {
3015 /* Count how many syscalls are to be caught. */
3016 for (size_t i = 0; i < syscall_counts.size (); i++)
3017 {
3018 if (syscall_counts[i] != 0)
3019 n_sysno++;
3020 }
3021 }
3022
3023 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
3024 pid, needed, any_count, n_sysno);
3025
3026 std::string built_packet;
3027 if (needed)
3028 {
3029 /* Prepare a packet with the sysno list, assuming max 8+1
3030 characters for a sysno. If the resulting packet size is too
3031 big, fallback on the non-selective packet. */
3032 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
3033 built_packet.reserve (maxpktsz);
3034 built_packet = "QCatchSyscalls:1";
3035 if (any_count == 0)
3036 {
3037 /* Add in each syscall to be caught. */
3038 for (size_t i = 0; i < syscall_counts.size (); i++)
3039 {
3040 if (syscall_counts[i] != 0)
3041 string_appendf (built_packet, ";%zx", i);
3042 }
3043 }
3044 if (built_packet.size () > get_remote_packet_size ())
3045 {
3046 /* catch_packet too big. Fallback to less efficient
3047 non selective mode, with GDB doing the filtering. */
3048 catch_packet = "QCatchSyscalls:1";
3049 }
3050 else
3051 catch_packet = built_packet.c_str ();
3052 }
3053 else
3054 catch_packet = "QCatchSyscalls:0";
3055
3056 struct remote_state *rs = get_remote_state ();
3057
3058 putpkt (catch_packet);
3059 getpkt (&rs->buf);
3060 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3061 if (result == PACKET_OK)
3062 return 0;
3063 else
3064 return -1;
3065 }
3066
3067 /* If 'QProgramSignals' is supported, tell the remote stub what
3068 signals it should pass through to the inferior when detaching. */
3069
3070 void
3071 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3072 {
3073 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3074 {
3075 char *packet, *p;
3076 int count = 0;
3077 struct remote_state *rs = get_remote_state ();
3078
3079 gdb_assert (signals.size () < 256);
3080 for (size_t i = 0; i < signals.size (); i++)
3081 {
3082 if (signals[i])
3083 count++;
3084 }
3085 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3086 strcpy (packet, "QProgramSignals:");
3087 p = packet + strlen (packet);
3088 for (size_t i = 0; i < signals.size (); i++)
3089 {
3090 if (signal_pass_state (i))
3091 {
3092 if (i >= 16)
3093 *p++ = tohex (i >> 4);
3094 *p++ = tohex (i & 15);
3095 if (count)
3096 *p++ = ';';
3097 else
3098 break;
3099 count--;
3100 }
3101 }
3102 *p = 0;
3103 if (!rs->last_program_signals_packet
3104 || strcmp (rs->last_program_signals_packet, packet) != 0)
3105 {
3106 putpkt (packet);
3107 getpkt (&rs->buf);
3108 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3109 xfree (rs->last_program_signals_packet);
3110 rs->last_program_signals_packet = packet;
3111 }
3112 else
3113 xfree (packet);
3114 }
3115 }
3116
3117 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3118 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3119 thread. If GEN is set, set the general thread, if not, then set
3120 the step/continue thread. */
3121 void
3122 remote_target::set_thread (ptid_t ptid, int gen)
3123 {
3124 struct remote_state *rs = get_remote_state ();
3125 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3126 char *buf = rs->buf.data ();
3127 char *endbuf = buf + get_remote_packet_size ();
3128
3129 if (state == ptid)
3130 return;
3131
3132 *buf++ = 'H';
3133 *buf++ = gen ? 'g' : 'c';
3134 if (ptid == magic_null_ptid)
3135 xsnprintf (buf, endbuf - buf, "0");
3136 else if (ptid == any_thread_ptid)
3137 xsnprintf (buf, endbuf - buf, "0");
3138 else if (ptid == minus_one_ptid)
3139 xsnprintf (buf, endbuf - buf, "-1");
3140 else
3141 write_ptid (buf, endbuf, ptid);
3142 putpkt (rs->buf);
3143 getpkt (&rs->buf);
3144 if (gen)
3145 rs->general_thread = ptid;
3146 else
3147 rs->continue_thread = ptid;
3148 }
3149
3150 void
3151 remote_target::set_general_thread (ptid_t ptid)
3152 {
3153 set_thread (ptid, 1);
3154 }
3155
3156 void
3157 remote_target::set_continue_thread (ptid_t ptid)
3158 {
3159 set_thread (ptid, 0);
3160 }
3161
3162 /* Change the remote current process. Which thread within the process
3163 ends up selected isn't important, as long as it is the same process
3164 as what INFERIOR_PTID points to.
3165
3166 This comes from that fact that there is no explicit notion of
3167 "selected process" in the protocol. The selected process for
3168 general operations is the process the selected general thread
3169 belongs to. */
3170
3171 void
3172 remote_target::set_general_process ()
3173 {
3174 /* If the remote can't handle multiple processes, don't bother. */
3175 if (!m_features.remote_multi_process_p ())
3176 return;
3177
3178 remote_state *rs = get_remote_state ();
3179
3180 /* We only need to change the remote current thread if it's pointing
3181 at some other process. */
3182 if (rs->general_thread.pid () != inferior_ptid.pid ())
3183 set_general_thread (inferior_ptid);
3184 }
3185
3186 \f
3187 /* Return nonzero if this is the main thread that we made up ourselves
3188 to model non-threaded targets as single-threaded. */
3189
3190 static int
3191 remote_thread_always_alive (ptid_t ptid)
3192 {
3193 if (ptid == magic_null_ptid)
3194 /* The main thread is always alive. */
3195 return 1;
3196
3197 if (ptid.pid () != 0 && ptid.lwp () == 0)
3198 /* The main thread is always alive. This can happen after a
3199 vAttach, if the remote side doesn't support
3200 multi-threading. */
3201 return 1;
3202
3203 return 0;
3204 }
3205
3206 /* Return nonzero if the thread PTID is still alive on the remote
3207 system. */
3208
3209 bool
3210 remote_target::thread_alive (ptid_t ptid)
3211 {
3212 struct remote_state *rs = get_remote_state ();
3213 char *p, *endp;
3214
3215 /* Check if this is a thread that we made up ourselves to model
3216 non-threaded targets as single-threaded. */
3217 if (remote_thread_always_alive (ptid))
3218 return 1;
3219
3220 p = rs->buf.data ();
3221 endp = p + get_remote_packet_size ();
3222
3223 *p++ = 'T';
3224 write_ptid (p, endp, ptid);
3225
3226 putpkt (rs->buf);
3227 getpkt (&rs->buf);
3228 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3229 }
3230
3231 /* Return a pointer to a thread name if we know it and NULL otherwise.
3232 The thread_info object owns the memory for the name. */
3233
3234 const char *
3235 remote_target::thread_name (struct thread_info *info)
3236 {
3237 if (info->priv != NULL)
3238 {
3239 const std::string &name = get_remote_thread_info (info)->name;
3240 return !name.empty () ? name.c_str () : NULL;
3241 }
3242
3243 return NULL;
3244 }
3245
3246 /* About these extended threadlist and threadinfo packets. They are
3247 variable length packets but, the fields within them are often fixed
3248 length. They are redundant enough to send over UDP as is the
3249 remote protocol in general. There is a matching unit test module
3250 in libstub. */
3251
3252 /* WARNING: This threadref data structure comes from the remote O.S.,
3253 libstub protocol encoding, and remote.c. It is not particularly
3254 changeable. */
3255
3256 /* Right now, the internal structure is int. We want it to be bigger.
3257 Plan to fix this. */
3258
3259 typedef int gdb_threadref; /* Internal GDB thread reference. */
3260
3261 /* gdb_ext_thread_info is an internal GDB data structure which is
3262 equivalent to the reply of the remote threadinfo packet. */
3263
3264 struct gdb_ext_thread_info
3265 {
3266 threadref threadid; /* External form of thread reference. */
3267 int active; /* Has state interesting to GDB?
3268 regs, stack. */
3269 char display[256]; /* Brief state display, name,
3270 blocked/suspended. */
3271 char shortname[32]; /* To be used to name threads. */
3272 char more_display[256]; /* Long info, statistics, queue depth,
3273 whatever. */
3274 };
3275
3276 /* The volume of remote transfers can be limited by submitting
3277 a mask containing bits specifying the desired information.
3278 Use a union of these values as the 'selection' parameter to
3279 get_thread_info. FIXME: Make these TAG names more thread specific. */
3280
3281 #define TAG_THREADID 1
3282 #define TAG_EXISTS 2
3283 #define TAG_DISPLAY 4
3284 #define TAG_THREADNAME 8
3285 #define TAG_MOREDISPLAY 16
3286
3287 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3288
3289 static const char *unpack_nibble (const char *buf, int *val);
3290
3291 static const char *unpack_byte (const char *buf, int *value);
3292
3293 static char *pack_int (char *buf, int value);
3294
3295 static const char *unpack_int (const char *buf, int *value);
3296
3297 static const char *unpack_string (const char *src, char *dest, int length);
3298
3299 static char *pack_threadid (char *pkt, threadref *id);
3300
3301 static const char *unpack_threadid (const char *inbuf, threadref *id);
3302
3303 void int_to_threadref (threadref *id, int value);
3304
3305 static int threadref_to_int (threadref *ref);
3306
3307 static void copy_threadref (threadref *dest, threadref *src);
3308
3309 static int threadmatch (threadref *dest, threadref *src);
3310
3311 static char *pack_threadinfo_request (char *pkt, int mode,
3312 threadref *id);
3313
3314 static char *pack_threadlist_request (char *pkt, int startflag,
3315 int threadcount,
3316 threadref *nextthread);
3317
3318 static int remote_newthread_step (threadref *ref, void *context);
3319
3320
3321 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3322 buffer we're allowed to write to. Returns
3323 BUF+CHARACTERS_WRITTEN. */
3324
3325 char *
3326 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3327 {
3328 int pid, tid;
3329
3330 if (m_features.remote_multi_process_p ())
3331 {
3332 pid = ptid.pid ();
3333 if (pid < 0)
3334 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3335 else
3336 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3337 }
3338 tid = ptid.lwp ();
3339 if (tid < 0)
3340 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3341 else
3342 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3343
3344 return buf;
3345 }
3346
3347 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3348 last parsed char. Returns null_ptid if no thread id is found, and
3349 throws an error if the thread id has an invalid format. */
3350
3351 static ptid_t
3352 read_ptid (const char *buf, const char **obuf)
3353 {
3354 const char *p = buf;
3355 const char *pp;
3356 ULONGEST pid = 0, tid = 0;
3357
3358 if (*p == 'p')
3359 {
3360 /* Multi-process ptid. */
3361 pp = unpack_varlen_hex (p + 1, &pid);
3362 if (*pp != '.')
3363 error (_("invalid remote ptid: %s"), p);
3364
3365 p = pp;
3366 pp = unpack_varlen_hex (p + 1, &tid);
3367 if (obuf)
3368 *obuf = pp;
3369 return ptid_t (pid, tid);
3370 }
3371
3372 /* No multi-process. Just a tid. */
3373 pp = unpack_varlen_hex (p, &tid);
3374
3375 /* Return null_ptid when no thread id is found. */
3376 if (p == pp)
3377 {
3378 if (obuf)
3379 *obuf = pp;
3380 return null_ptid;
3381 }
3382
3383 /* Since the stub is not sending a process id, default to what's
3384 current_inferior, unless it doesn't have a PID yet. If so,
3385 then since there's no way to know the pid of the reported
3386 threads, use the magic number. */
3387 inferior *inf = current_inferior ();
3388 if (inf->pid == 0)
3389 pid = magic_null_ptid.pid ();
3390 else
3391 pid = inf->pid;
3392
3393 if (obuf)
3394 *obuf = pp;
3395 return ptid_t (pid, tid);
3396 }
3397
3398 static int
3399 stubhex (int ch)
3400 {
3401 if (ch >= 'a' && ch <= 'f')
3402 return ch - 'a' + 10;
3403 if (ch >= '0' && ch <= '9')
3404 return ch - '0';
3405 if (ch >= 'A' && ch <= 'F')
3406 return ch - 'A' + 10;
3407 return -1;
3408 }
3409
3410 static int
3411 stub_unpack_int (const char *buff, int fieldlength)
3412 {
3413 int nibble;
3414 int retval = 0;
3415
3416 while (fieldlength)
3417 {
3418 nibble = stubhex (*buff++);
3419 retval |= nibble;
3420 fieldlength--;
3421 if (fieldlength)
3422 retval = retval << 4;
3423 }
3424 return retval;
3425 }
3426
3427 static const char *
3428 unpack_nibble (const char *buf, int *val)
3429 {
3430 *val = fromhex (*buf++);
3431 return buf;
3432 }
3433
3434 static const char *
3435 unpack_byte (const char *buf, int *value)
3436 {
3437 *value = stub_unpack_int (buf, 2);
3438 return buf + 2;
3439 }
3440
3441 static char *
3442 pack_int (char *buf, int value)
3443 {
3444 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3445 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3446 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3447 buf = pack_hex_byte (buf, (value & 0xff));
3448 return buf;
3449 }
3450
3451 static const char *
3452 unpack_int (const char *buf, int *value)
3453 {
3454 *value = stub_unpack_int (buf, 8);
3455 return buf + 8;
3456 }
3457
3458 #if 0 /* Currently unused, uncomment when needed. */
3459 static char *pack_string (char *pkt, char *string);
3460
3461 static char *
3462 pack_string (char *pkt, char *string)
3463 {
3464 char ch;
3465 int len;
3466
3467 len = strlen (string);
3468 if (len > 200)
3469 len = 200; /* Bigger than most GDB packets, junk??? */
3470 pkt = pack_hex_byte (pkt, len);
3471 while (len-- > 0)
3472 {
3473 ch = *string++;
3474 if ((ch == '\0') || (ch == '#'))
3475 ch = '*'; /* Protect encapsulation. */
3476 *pkt++ = ch;
3477 }
3478 return pkt;
3479 }
3480 #endif /* 0 (unused) */
3481
3482 static const char *
3483 unpack_string (const char *src, char *dest, int length)
3484 {
3485 while (length--)
3486 *dest++ = *src++;
3487 *dest = '\0';
3488 return src;
3489 }
3490
3491 static char *
3492 pack_threadid (char *pkt, threadref *id)
3493 {
3494 char *limit;
3495 unsigned char *altid;
3496
3497 altid = (unsigned char *) id;
3498 limit = pkt + BUF_THREAD_ID_SIZE;
3499 while (pkt < limit)
3500 pkt = pack_hex_byte (pkt, *altid++);
3501 return pkt;
3502 }
3503
3504
3505 static const char *
3506 unpack_threadid (const char *inbuf, threadref *id)
3507 {
3508 char *altref;
3509 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3510 int x, y;
3511
3512 altref = (char *) id;
3513
3514 while (inbuf < limit)
3515 {
3516 x = stubhex (*inbuf++);
3517 y = stubhex (*inbuf++);
3518 *altref++ = (x << 4) | y;
3519 }
3520 return inbuf;
3521 }
3522
3523 /* Externally, threadrefs are 64 bits but internally, they are still
3524 ints. This is due to a mismatch of specifications. We would like
3525 to use 64bit thread references internally. This is an adapter
3526 function. */
3527
3528 void
3529 int_to_threadref (threadref *id, int value)
3530 {
3531 unsigned char *scan;
3532
3533 scan = (unsigned char *) id;
3534 {
3535 int i = 4;
3536 while (i--)
3537 *scan++ = 0;
3538 }
3539 *scan++ = (value >> 24) & 0xff;
3540 *scan++ = (value >> 16) & 0xff;
3541 *scan++ = (value >> 8) & 0xff;
3542 *scan++ = (value & 0xff);
3543 }
3544
3545 static int
3546 threadref_to_int (threadref *ref)
3547 {
3548 int i, value = 0;
3549 unsigned char *scan;
3550
3551 scan = *ref;
3552 scan += 4;
3553 i = 4;
3554 while (i-- > 0)
3555 value = (value << 8) | ((*scan++) & 0xff);
3556 return value;
3557 }
3558
3559 static void
3560 copy_threadref (threadref *dest, threadref *src)
3561 {
3562 int i;
3563 unsigned char *csrc, *cdest;
3564
3565 csrc = (unsigned char *) src;
3566 cdest = (unsigned char *) dest;
3567 i = 8;
3568 while (i--)
3569 *cdest++ = *csrc++;
3570 }
3571
3572 static int
3573 threadmatch (threadref *dest, threadref *src)
3574 {
3575 /* Things are broken right now, so just assume we got a match. */
3576 #if 0
3577 unsigned char *srcp, *destp;
3578 int i, result;
3579 srcp = (char *) src;
3580 destp = (char *) dest;
3581
3582 result = 1;
3583 while (i-- > 0)
3584 result &= (*srcp++ == *destp++) ? 1 : 0;
3585 return result;
3586 #endif
3587 return 1;
3588 }
3589
3590 /*
3591 threadid:1, # always request threadid
3592 context_exists:2,
3593 display:4,
3594 unique_name:8,
3595 more_display:16
3596 */
3597
3598 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3599
3600 static char *
3601 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3602 {
3603 *pkt++ = 'q'; /* Info Query */
3604 *pkt++ = 'P'; /* process or thread info */
3605 pkt = pack_int (pkt, mode); /* mode */
3606 pkt = pack_threadid (pkt, id); /* threadid */
3607 *pkt = '\0'; /* terminate */
3608 return pkt;
3609 }
3610
3611 /* These values tag the fields in a thread info response packet. */
3612 /* Tagging the fields allows us to request specific fields and to
3613 add more fields as time goes by. */
3614
3615 #define TAG_THREADID 1 /* Echo the thread identifier. */
3616 #define TAG_EXISTS 2 /* Is this process defined enough to
3617 fetch registers and its stack? */
3618 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3619 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3620 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3621 the process. */
3622
3623 int
3624 remote_target::remote_unpack_thread_info_response (const char *pkt,
3625 threadref *expectedref,
3626 gdb_ext_thread_info *info)
3627 {
3628 struct remote_state *rs = get_remote_state ();
3629 int mask, length;
3630 int tag;
3631 threadref ref;
3632 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3633 int retval = 1;
3634
3635 /* info->threadid = 0; FIXME: implement zero_threadref. */
3636 info->active = 0;
3637 info->display[0] = '\0';
3638 info->shortname[0] = '\0';
3639 info->more_display[0] = '\0';
3640
3641 /* Assume the characters indicating the packet type have been
3642 stripped. */
3643 pkt = unpack_int (pkt, &mask); /* arg mask */
3644 pkt = unpack_threadid (pkt, &ref);
3645
3646 if (mask == 0)
3647 warning (_("Incomplete response to threadinfo request."));
3648 if (!threadmatch (&ref, expectedref))
3649 { /* This is an answer to a different request. */
3650 warning (_("ERROR RMT Thread info mismatch."));
3651 return 0;
3652 }
3653 copy_threadref (&info->threadid, &ref);
3654
3655 /* Loop on tagged fields , try to bail if something goes wrong. */
3656
3657 /* Packets are terminated with nulls. */
3658 while ((pkt < limit) && mask && *pkt)
3659 {
3660 pkt = unpack_int (pkt, &tag); /* tag */
3661 pkt = unpack_byte (pkt, &length); /* length */
3662 if (!(tag & mask)) /* Tags out of synch with mask. */
3663 {
3664 warning (_("ERROR RMT: threadinfo tag mismatch."));
3665 retval = 0;
3666 break;
3667 }
3668 if (tag == TAG_THREADID)
3669 {
3670 if (length != 16)
3671 {
3672 warning (_("ERROR RMT: length of threadid is not 16."));
3673 retval = 0;
3674 break;
3675 }
3676 pkt = unpack_threadid (pkt, &ref);
3677 mask = mask & ~TAG_THREADID;
3678 continue;
3679 }
3680 if (tag == TAG_EXISTS)
3681 {
3682 info->active = stub_unpack_int (pkt, length);
3683 pkt += length;
3684 mask = mask & ~(TAG_EXISTS);
3685 if (length > 8)
3686 {
3687 warning (_("ERROR RMT: 'exists' length too long."));
3688 retval = 0;
3689 break;
3690 }
3691 continue;
3692 }
3693 if (tag == TAG_THREADNAME)
3694 {
3695 pkt = unpack_string (pkt, &info->shortname[0], length);
3696 mask = mask & ~TAG_THREADNAME;
3697 continue;
3698 }
3699 if (tag == TAG_DISPLAY)
3700 {
3701 pkt = unpack_string (pkt, &info->display[0], length);
3702 mask = mask & ~TAG_DISPLAY;
3703 continue;
3704 }
3705 if (tag == TAG_MOREDISPLAY)
3706 {
3707 pkt = unpack_string (pkt, &info->more_display[0], length);
3708 mask = mask & ~TAG_MOREDISPLAY;
3709 continue;
3710 }
3711 warning (_("ERROR RMT: unknown thread info tag."));
3712 break; /* Not a tag we know about. */
3713 }
3714 return retval;
3715 }
3716
3717 int
3718 remote_target::remote_get_threadinfo (threadref *threadid,
3719 int fieldset,
3720 gdb_ext_thread_info *info)
3721 {
3722 struct remote_state *rs = get_remote_state ();
3723 int result;
3724
3725 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3726 putpkt (rs->buf);
3727 getpkt (&rs->buf);
3728
3729 if (rs->buf[0] == '\0')
3730 return 0;
3731
3732 result = remote_unpack_thread_info_response (&rs->buf[2],
3733 threadid, info);
3734 return result;
3735 }
3736
3737 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3738
3739 static char *
3740 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3741 threadref *nextthread)
3742 {
3743 *pkt++ = 'q'; /* info query packet */
3744 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3745 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3746 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3747 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3748 *pkt = '\0';
3749 return pkt;
3750 }
3751
3752 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3753
3754 int
3755 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3756 threadref *original_echo,
3757 threadref *resultlist,
3758 int *doneflag)
3759 {
3760 struct remote_state *rs = get_remote_state ();
3761 int count, resultcount, done;
3762
3763 resultcount = 0;
3764 /* Assume the 'q' and 'M chars have been stripped. */
3765 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3766 /* done parse past here */
3767 pkt = unpack_byte (pkt, &count); /* count field */
3768 pkt = unpack_nibble (pkt, &done);
3769 /* The first threadid is the argument threadid. */
3770 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3771 while ((count-- > 0) && (pkt < limit))
3772 {
3773 pkt = unpack_threadid (pkt, resultlist++);
3774 if (resultcount++ >= result_limit)
3775 break;
3776 }
3777 if (doneflag)
3778 *doneflag = done;
3779 return resultcount;
3780 }
3781
3782 /* Fetch the next batch of threads from the remote. Returns -1 if the
3783 qL packet is not supported, 0 on error and 1 on success. */
3784
3785 int
3786 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3787 int result_limit, int *done, int *result_count,
3788 threadref *threadlist)
3789 {
3790 struct remote_state *rs = get_remote_state ();
3791 int result = 1;
3792
3793 /* Truncate result limit to be smaller than the packet size. */
3794 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3795 >= get_remote_packet_size ())
3796 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3797
3798 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3799 nextthread);
3800 putpkt (rs->buf);
3801 getpkt (&rs->buf);
3802 if (rs->buf[0] == '\0')
3803 {
3804 /* Packet not supported. */
3805 return -1;
3806 }
3807
3808 *result_count =
3809 parse_threadlist_response (&rs->buf[2], result_limit,
3810 &rs->echo_nextthread, threadlist, done);
3811
3812 if (!threadmatch (&rs->echo_nextthread, nextthread))
3813 {
3814 /* FIXME: This is a good reason to drop the packet. */
3815 /* Possibly, there is a duplicate response. */
3816 /* Possibilities :
3817 retransmit immediatly - race conditions
3818 retransmit after timeout - yes
3819 exit
3820 wait for packet, then exit
3821 */
3822 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3823 return 0; /* I choose simply exiting. */
3824 }
3825 if (*result_count <= 0)
3826 {
3827 if (*done != 1)
3828 {
3829 warning (_("RMT ERROR : failed to get remote thread list."));
3830 result = 0;
3831 }
3832 return result; /* break; */
3833 }
3834 if (*result_count > result_limit)
3835 {
3836 *result_count = 0;
3837 warning (_("RMT ERROR: threadlist response longer than requested."));
3838 return 0;
3839 }
3840 return result;
3841 }
3842
3843 /* Fetch the list of remote threads, with the qL packet, and call
3844 STEPFUNCTION for each thread found. Stops iterating and returns 1
3845 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3846 STEPFUNCTION returns false. If the packet is not supported,
3847 returns -1. */
3848
3849 int
3850 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3851 void *context, int looplimit)
3852 {
3853 struct remote_state *rs = get_remote_state ();
3854 int done, i, result_count;
3855 int startflag = 1;
3856 int result = 1;
3857 int loopcount = 0;
3858
3859 done = 0;
3860 while (!done)
3861 {
3862 if (loopcount++ > looplimit)
3863 {
3864 result = 0;
3865 warning (_("Remote fetch threadlist -infinite loop-."));
3866 break;
3867 }
3868 result = remote_get_threadlist (startflag, &rs->nextthread,
3869 MAXTHREADLISTRESULTS,
3870 &done, &result_count,
3871 rs->resultthreadlist);
3872 if (result <= 0)
3873 break;
3874 /* Clear for later iterations. */
3875 startflag = 0;
3876 /* Setup to resume next batch of thread references, set nextthread. */
3877 if (result_count >= 1)
3878 copy_threadref (&rs->nextthread,
3879 &rs->resultthreadlist[result_count - 1]);
3880 i = 0;
3881 while (result_count--)
3882 {
3883 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3884 {
3885 result = 0;
3886 break;
3887 }
3888 }
3889 }
3890 return result;
3891 }
3892
3893 /* A thread found on the remote target. */
3894
3895 struct thread_item
3896 {
3897 explicit thread_item (ptid_t ptid_)
3898 : ptid (ptid_)
3899 {}
3900
3901 thread_item (thread_item &&other) = default;
3902 thread_item &operator= (thread_item &&other) = default;
3903
3904 DISABLE_COPY_AND_ASSIGN (thread_item);
3905
3906 /* The thread's PTID. */
3907 ptid_t ptid;
3908
3909 /* The thread's extra info. */
3910 std::string extra;
3911
3912 /* The thread's name. */
3913 std::string name;
3914
3915 /* The core the thread was running on. -1 if not known. */
3916 int core = -1;
3917
3918 /* The thread handle associated with the thread. */
3919 gdb::byte_vector thread_handle;
3920 };
3921
3922 /* Context passed around to the various methods listing remote
3923 threads. As new threads are found, they're added to the ITEMS
3924 vector. */
3925
3926 struct threads_listing_context
3927 {
3928 /* Return true if this object contains an entry for a thread with ptid
3929 PTID. */
3930
3931 bool contains_thread (ptid_t ptid) const
3932 {
3933 auto match_ptid = [&] (const thread_item &item)
3934 {
3935 return item.ptid == ptid;
3936 };
3937
3938 auto it = std::find_if (this->items.begin (),
3939 this->items.end (),
3940 match_ptid);
3941
3942 return it != this->items.end ();
3943 }
3944
3945 /* Remove the thread with ptid PTID. */
3946
3947 void remove_thread (ptid_t ptid)
3948 {
3949 auto match_ptid = [&] (const thread_item &item)
3950 {
3951 return item.ptid == ptid;
3952 };
3953
3954 auto it = std::remove_if (this->items.begin (),
3955 this->items.end (),
3956 match_ptid);
3957
3958 if (it != this->items.end ())
3959 this->items.erase (it);
3960 }
3961
3962 /* The threads found on the remote target. */
3963 std::vector<thread_item> items;
3964 };
3965
3966 static int
3967 remote_newthread_step (threadref *ref, void *data)
3968 {
3969 struct threads_listing_context *context
3970 = (struct threads_listing_context *) data;
3971 int pid = inferior_ptid.pid ();
3972 int lwp = threadref_to_int (ref);
3973 ptid_t ptid (pid, lwp);
3974
3975 context->items.emplace_back (ptid);
3976
3977 return 1; /* continue iterator */
3978 }
3979
3980 #define CRAZY_MAX_THREADS 1000
3981
3982 ptid_t
3983 remote_target::remote_current_thread (ptid_t oldpid)
3984 {
3985 struct remote_state *rs = get_remote_state ();
3986
3987 putpkt ("qC");
3988 getpkt (&rs->buf);
3989 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3990 {
3991 const char *obuf;
3992 ptid_t result;
3993
3994 result = read_ptid (&rs->buf[2], &obuf);
3995 if (*obuf != '\0')
3996 remote_debug_printf ("warning: garbage in qC reply");
3997
3998 return result;
3999 }
4000 else
4001 return oldpid;
4002 }
4003
4004 /* List remote threads using the deprecated qL packet. */
4005
4006 int
4007 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
4008 {
4009 if (remote_threadlist_iterator (remote_newthread_step, context,
4010 CRAZY_MAX_THREADS) >= 0)
4011 return 1;
4012
4013 return 0;
4014 }
4015
4016 #if defined(HAVE_LIBEXPAT)
4017
4018 static void
4019 start_thread (struct gdb_xml_parser *parser,
4020 const struct gdb_xml_element *element,
4021 void *user_data,
4022 std::vector<gdb_xml_value> &attributes)
4023 {
4024 struct threads_listing_context *data
4025 = (struct threads_listing_context *) user_data;
4026 struct gdb_xml_value *attr;
4027
4028 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
4029 ptid_t ptid = read_ptid (id, NULL);
4030
4031 data->items.emplace_back (ptid);
4032 thread_item &item = data->items.back ();
4033
4034 attr = xml_find_attribute (attributes, "core");
4035 if (attr != NULL)
4036 item.core = *(ULONGEST *) attr->value.get ();
4037
4038 attr = xml_find_attribute (attributes, "name");
4039 if (attr != NULL)
4040 item.name = (const char *) attr->value.get ();
4041
4042 attr = xml_find_attribute (attributes, "handle");
4043 if (attr != NULL)
4044 item.thread_handle = hex2bin ((const char *) attr->value.get ());
4045 }
4046
4047 static void
4048 end_thread (struct gdb_xml_parser *parser,
4049 const struct gdb_xml_element *element,
4050 void *user_data, const char *body_text)
4051 {
4052 struct threads_listing_context *data
4053 = (struct threads_listing_context *) user_data;
4054
4055 if (body_text != NULL && *body_text != '\0')
4056 data->items.back ().extra = body_text;
4057 }
4058
4059 const struct gdb_xml_attribute thread_attributes[] = {
4060 { "id", GDB_XML_AF_NONE, NULL, NULL },
4061 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4062 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4063 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4064 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4065 };
4066
4067 const struct gdb_xml_element thread_children[] = {
4068 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4069 };
4070
4071 const struct gdb_xml_element threads_children[] = {
4072 { "thread", thread_attributes, thread_children,
4073 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4074 start_thread, end_thread },
4075 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4076 };
4077
4078 const struct gdb_xml_element threads_elements[] = {
4079 { "threads", NULL, threads_children,
4080 GDB_XML_EF_NONE, NULL, NULL },
4081 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4082 };
4083
4084 #endif
4085
4086 /* List remote threads using qXfer:threads:read. */
4087
4088 int
4089 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4090 {
4091 #if defined(HAVE_LIBEXPAT)
4092 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4093 {
4094 gdb::optional<gdb::char_vector> xml
4095 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4096
4097 if (xml && (*xml)[0] != '\0')
4098 {
4099 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4100 threads_elements, xml->data (), context);
4101 }
4102
4103 return 1;
4104 }
4105 #endif
4106
4107 return 0;
4108 }
4109
4110 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4111
4112 int
4113 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4114 {
4115 struct remote_state *rs = get_remote_state ();
4116
4117 if (rs->use_threadinfo_query)
4118 {
4119 const char *bufp;
4120
4121 putpkt ("qfThreadInfo");
4122 getpkt (&rs->buf);
4123 bufp = rs->buf.data ();
4124 if (bufp[0] != '\0') /* q packet recognized */
4125 {
4126 while (*bufp++ == 'm') /* reply contains one or more TID */
4127 {
4128 do
4129 {
4130 ptid_t ptid = read_ptid (bufp, &bufp);
4131 context->items.emplace_back (ptid);
4132 }
4133 while (*bufp++ == ','); /* comma-separated list */
4134 putpkt ("qsThreadInfo");
4135 getpkt (&rs->buf);
4136 bufp = rs->buf.data ();
4137 }
4138 return 1;
4139 }
4140 else
4141 {
4142 /* Packet not recognized. */
4143 rs->use_threadinfo_query = 0;
4144 }
4145 }
4146
4147 return 0;
4148 }
4149
4150 /* Return true if INF only has one non-exited thread. */
4151
4152 static bool
4153 has_single_non_exited_thread (inferior *inf)
4154 {
4155 int count = 0;
4156 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4157 if (++count > 1)
4158 break;
4159 return count == 1;
4160 }
4161
4162 /* Implement the to_update_thread_list function for the remote
4163 targets. */
4164
4165 void
4166 remote_target::update_thread_list ()
4167 {
4168 struct threads_listing_context context;
4169 int got_list = 0;
4170
4171 /* We have a few different mechanisms to fetch the thread list. Try
4172 them all, starting with the most preferred one first, falling
4173 back to older methods. */
4174 if (remote_get_threads_with_qxfer (&context)
4175 || remote_get_threads_with_qthreadinfo (&context)
4176 || remote_get_threads_with_ql (&context))
4177 {
4178 got_list = 1;
4179
4180 if (context.items.empty ()
4181 && remote_thread_always_alive (inferior_ptid))
4182 {
4183 /* Some targets don't really support threads, but still
4184 reply an (empty) thread list in response to the thread
4185 listing packets, instead of replying "packet not
4186 supported". Exit early so we don't delete the main
4187 thread. */
4188 return;
4189 }
4190
4191 /* CONTEXT now holds the current thread list on the remote
4192 target end. Delete GDB-side threads no longer found on the
4193 target. */
4194 for (thread_info *tp : all_threads_safe ())
4195 {
4196 if (tp->inf->process_target () != this)
4197 continue;
4198
4199 if (!context.contains_thread (tp->ptid))
4200 {
4201 /* Do not remove the thread if it is the last thread in
4202 the inferior. This situation happens when we have a
4203 pending exit process status to process. Otherwise we
4204 may end up with a seemingly live inferior (i.e. pid
4205 != 0) that has no threads. */
4206 if (has_single_non_exited_thread (tp->inf))
4207 continue;
4208
4209 /* Not found. */
4210 delete_thread (tp);
4211 }
4212 }
4213
4214 /* Remove any unreported fork/vfork/clone child threads from
4215 CONTEXT so that we don't interfere with follow
4216 fork/vfork/clone, which is where creation of such threads is
4217 handled. */
4218 remove_new_children (&context);
4219
4220 /* And now add threads we don't know about yet to our list. */
4221 for (thread_item &item : context.items)
4222 {
4223 if (item.ptid != null_ptid)
4224 {
4225 /* In non-stop mode, we assume new found threads are
4226 executing until proven otherwise with a stop reply.
4227 In all-stop, we can only get here if all threads are
4228 stopped. */
4229 bool executing = target_is_non_stop_p ();
4230
4231 remote_notice_new_inferior (item.ptid, executing);
4232
4233 thread_info *tp = this->find_thread (item.ptid);
4234 remote_thread_info *info = get_remote_thread_info (tp);
4235 info->core = item.core;
4236 info->extra = std::move (item.extra);
4237 info->name = std::move (item.name);
4238 info->thread_handle = std::move (item.thread_handle);
4239 }
4240 }
4241 }
4242
4243 if (!got_list)
4244 {
4245 /* If no thread listing method is supported, then query whether
4246 each known thread is alive, one by one, with the T packet.
4247 If the target doesn't support threads at all, then this is a
4248 no-op. See remote_thread_alive. */
4249 prune_threads ();
4250 }
4251 }
4252
4253 /*
4254 * Collect a descriptive string about the given thread.
4255 * The target may say anything it wants to about the thread
4256 * (typically info about its blocked / runnable state, name, etc.).
4257 * This string will appear in the info threads display.
4258 *
4259 * Optional: targets are not required to implement this function.
4260 */
4261
4262 const char *
4263 remote_target::extra_thread_info (thread_info *tp)
4264 {
4265 struct remote_state *rs = get_remote_state ();
4266 int set;
4267 threadref id;
4268 struct gdb_ext_thread_info threadinfo;
4269
4270 if (rs->remote_desc == 0) /* paranoia */
4271 internal_error (_("remote_threads_extra_info"));
4272
4273 if (tp->ptid == magic_null_ptid
4274 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4275 /* This is the main thread which was added by GDB. The remote
4276 server doesn't know about it. */
4277 return NULL;
4278
4279 std::string &extra = get_remote_thread_info (tp)->extra;
4280
4281 /* If already have cached info, use it. */
4282 if (!extra.empty ())
4283 return extra.c_str ();
4284
4285 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4286 {
4287 /* If we're using qXfer:threads:read, then the extra info is
4288 included in the XML. So if we didn't have anything cached,
4289 it's because there's really no extra info. */
4290 return NULL;
4291 }
4292
4293 if (rs->use_threadextra_query)
4294 {
4295 char *b = rs->buf.data ();
4296 char *endb = b + get_remote_packet_size ();
4297
4298 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4299 b += strlen (b);
4300 write_ptid (b, endb, tp->ptid);
4301
4302 putpkt (rs->buf);
4303 getpkt (&rs->buf);
4304 if (rs->buf[0] != 0)
4305 {
4306 extra.resize (strlen (rs->buf.data ()) / 2);
4307 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4308 return extra.c_str ();
4309 }
4310 }
4311
4312 /* If the above query fails, fall back to the old method. */
4313 rs->use_threadextra_query = 0;
4314 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4315 | TAG_MOREDISPLAY | TAG_DISPLAY;
4316 int_to_threadref (&id, tp->ptid.lwp ());
4317 if (remote_get_threadinfo (&id, set, &threadinfo))
4318 if (threadinfo.active)
4319 {
4320 if (*threadinfo.shortname)
4321 string_appendf (extra, " Name: %s", threadinfo.shortname);
4322 if (*threadinfo.display)
4323 {
4324 if (!extra.empty ())
4325 extra += ',';
4326 string_appendf (extra, " State: %s", threadinfo.display);
4327 }
4328 if (*threadinfo.more_display)
4329 {
4330 if (!extra.empty ())
4331 extra += ',';
4332 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4333 }
4334 return extra.c_str ();
4335 }
4336 return NULL;
4337 }
4338 \f
4339
4340 bool
4341 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4342 struct static_tracepoint_marker *marker)
4343 {
4344 struct remote_state *rs = get_remote_state ();
4345 char *p = rs->buf.data ();
4346
4347 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4348 p += strlen (p);
4349 p += hexnumstr (p, addr);
4350 putpkt (rs->buf);
4351 getpkt (&rs->buf);
4352 p = rs->buf.data ();
4353
4354 if (*p == 'E')
4355 error (_("Remote failure reply: %s"), p);
4356
4357 if (*p++ == 'm')
4358 {
4359 parse_static_tracepoint_marker_definition (p, NULL, marker);
4360 return true;
4361 }
4362
4363 return false;
4364 }
4365
4366 std::vector<static_tracepoint_marker>
4367 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4368 {
4369 struct remote_state *rs = get_remote_state ();
4370 std::vector<static_tracepoint_marker> markers;
4371 const char *p;
4372 static_tracepoint_marker marker;
4373
4374 /* Ask for a first packet of static tracepoint marker
4375 definition. */
4376 putpkt ("qTfSTM");
4377 getpkt (&rs->buf);
4378 p = rs->buf.data ();
4379 if (*p == 'E')
4380 error (_("Remote failure reply: %s"), p);
4381
4382 while (*p++ == 'm')
4383 {
4384 do
4385 {
4386 parse_static_tracepoint_marker_definition (p, &p, &marker);
4387
4388 if (strid == NULL || marker.str_id == strid)
4389 markers.push_back (std::move (marker));
4390 }
4391 while (*p++ == ','); /* comma-separated list */
4392 /* Ask for another packet of static tracepoint definition. */
4393 putpkt ("qTsSTM");
4394 getpkt (&rs->buf);
4395 p = rs->buf.data ();
4396 }
4397
4398 return markers;
4399 }
4400
4401 \f
4402 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4403
4404 ptid_t
4405 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4406 {
4407 return ptid_t (inferior_ptid.pid (), lwp);
4408 }
4409 \f
4410
4411 /* Restart the remote side; this is an extended protocol operation. */
4412
4413 void
4414 remote_target::extended_remote_restart ()
4415 {
4416 struct remote_state *rs = get_remote_state ();
4417
4418 /* Send the restart command; for reasons I don't understand the
4419 remote side really expects a number after the "R". */
4420 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4421 putpkt (rs->buf);
4422
4423 remote_fileio_reset ();
4424 }
4425 \f
4426 /* Clean up connection to a remote debugger. */
4427
4428 void
4429 remote_target::close ()
4430 {
4431 /* Make sure we leave stdin registered in the event loop. */
4432 terminal_ours ();
4433
4434 trace_reset_local_state ();
4435
4436 delete this;
4437 }
4438
4439 remote_target::~remote_target ()
4440 {
4441 struct remote_state *rs = get_remote_state ();
4442
4443 /* Check for NULL because we may get here with a partially
4444 constructed target/connection. */
4445 if (rs->remote_desc == nullptr)
4446 return;
4447
4448 serial_close (rs->remote_desc);
4449
4450 /* We are destroying the remote target, so we should discard
4451 everything of this target. */
4452 discard_pending_stop_replies_in_queue ();
4453
4454 rs->delete_async_event_handler ();
4455
4456 delete rs->notif_state;
4457 }
4458
4459 /* Query the remote side for the text, data and bss offsets. */
4460
4461 void
4462 remote_target::get_offsets ()
4463 {
4464 struct remote_state *rs = get_remote_state ();
4465 char *buf;
4466 char *ptr;
4467 int lose, num_segments = 0, do_sections, do_segments;
4468 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4469
4470 if (current_program_space->symfile_object_file == NULL)
4471 return;
4472
4473 putpkt ("qOffsets");
4474 getpkt (&rs->buf);
4475 buf = rs->buf.data ();
4476
4477 if (buf[0] == '\000')
4478 return; /* Return silently. Stub doesn't support
4479 this command. */
4480 if (buf[0] == 'E')
4481 {
4482 warning (_("Remote failure reply: %s"), buf);
4483 return;
4484 }
4485
4486 /* Pick up each field in turn. This used to be done with scanf, but
4487 scanf will make trouble if CORE_ADDR size doesn't match
4488 conversion directives correctly. The following code will work
4489 with any size of CORE_ADDR. */
4490 text_addr = data_addr = bss_addr = 0;
4491 ptr = buf;
4492 lose = 0;
4493
4494 if (startswith (ptr, "Text="))
4495 {
4496 ptr += 5;
4497 /* Don't use strtol, could lose on big values. */
4498 while (*ptr && *ptr != ';')
4499 text_addr = (text_addr << 4) + fromhex (*ptr++);
4500
4501 if (startswith (ptr, ";Data="))
4502 {
4503 ptr += 6;
4504 while (*ptr && *ptr != ';')
4505 data_addr = (data_addr << 4) + fromhex (*ptr++);
4506 }
4507 else
4508 lose = 1;
4509
4510 if (!lose && startswith (ptr, ";Bss="))
4511 {
4512 ptr += 5;
4513 while (*ptr && *ptr != ';')
4514 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4515
4516 if (bss_addr != data_addr)
4517 warning (_("Target reported unsupported offsets: %s"), buf);
4518 }
4519 else
4520 lose = 1;
4521 }
4522 else if (startswith (ptr, "TextSeg="))
4523 {
4524 ptr += 8;
4525 /* Don't use strtol, could lose on big values. */
4526 while (*ptr && *ptr != ';')
4527 text_addr = (text_addr << 4) + fromhex (*ptr++);
4528 num_segments = 1;
4529
4530 if (startswith (ptr, ";DataSeg="))
4531 {
4532 ptr += 9;
4533 while (*ptr && *ptr != ';')
4534 data_addr = (data_addr << 4) + fromhex (*ptr++);
4535 num_segments++;
4536 }
4537 }
4538 else
4539 lose = 1;
4540
4541 if (lose)
4542 error (_("Malformed response to offset query, %s"), buf);
4543 else if (*ptr != '\0')
4544 warning (_("Target reported unsupported offsets: %s"), buf);
4545
4546 objfile *objf = current_program_space->symfile_object_file;
4547 section_offsets offs = objf->section_offsets;
4548
4549 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4550 do_segments = (data != NULL);
4551 do_sections = num_segments == 0;
4552
4553 if (num_segments > 0)
4554 {
4555 segments[0] = text_addr;
4556 segments[1] = data_addr;
4557 }
4558 /* If we have two segments, we can still try to relocate everything
4559 by assuming that the .text and .data offsets apply to the whole
4560 text and data segments. Convert the offsets given in the packet
4561 to base addresses for symfile_map_offsets_to_segments. */
4562 else if (data != nullptr && data->segments.size () == 2)
4563 {
4564 segments[0] = data->segments[0].base + text_addr;
4565 segments[1] = data->segments[1].base + data_addr;
4566 num_segments = 2;
4567 }
4568 /* If the object file has only one segment, assume that it is text
4569 rather than data; main programs with no writable data are rare,
4570 but programs with no code are useless. Of course the code might
4571 have ended up in the data segment... to detect that we would need
4572 the permissions here. */
4573 else if (data && data->segments.size () == 1)
4574 {
4575 segments[0] = data->segments[0].base + text_addr;
4576 num_segments = 1;
4577 }
4578 /* There's no way to relocate by segment. */
4579 else
4580 do_segments = 0;
4581
4582 if (do_segments)
4583 {
4584 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4585 data.get (), offs,
4586 num_segments, segments);
4587
4588 if (ret == 0 && !do_sections)
4589 error (_("Can not handle qOffsets TextSeg "
4590 "response with this symbol file"));
4591
4592 if (ret > 0)
4593 do_sections = 0;
4594 }
4595
4596 if (do_sections)
4597 {
4598 offs[SECT_OFF_TEXT (objf)] = text_addr;
4599
4600 /* This is a temporary kludge to force data and bss to use the
4601 same offsets because that's what nlmconv does now. The real
4602 solution requires changes to the stub and remote.c that I
4603 don't have time to do right now. */
4604
4605 offs[SECT_OFF_DATA (objf)] = data_addr;
4606 offs[SECT_OFF_BSS (objf)] = data_addr;
4607 }
4608
4609 objfile_relocate (objf, offs);
4610 }
4611
4612 /* Send interrupt_sequence to remote target. */
4613
4614 void
4615 remote_target::send_interrupt_sequence ()
4616 {
4617 struct remote_state *rs = get_remote_state ();
4618
4619 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4620 remote_serial_write ("\x03", 1);
4621 else if (interrupt_sequence_mode == interrupt_sequence_break)
4622 serial_send_break (rs->remote_desc);
4623 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4624 {
4625 serial_send_break (rs->remote_desc);
4626 remote_serial_write ("g", 1);
4627 }
4628 else
4629 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4630 interrupt_sequence_mode);
4631 }
4632
4633
4634 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4635 and extract the PTID. Returns NULL_PTID if not found. */
4636
4637 static ptid_t
4638 stop_reply_extract_thread (const char *stop_reply)
4639 {
4640 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4641 {
4642 const char *p;
4643
4644 /* Txx r:val ; r:val (...) */
4645 p = &stop_reply[3];
4646
4647 /* Look for "register" named "thread". */
4648 while (*p != '\0')
4649 {
4650 const char *p1;
4651
4652 p1 = strchr (p, ':');
4653 if (p1 == NULL)
4654 return null_ptid;
4655
4656 if (strncmp (p, "thread", p1 - p) == 0)
4657 return read_ptid (++p1, &p);
4658
4659 p1 = strchr (p, ';');
4660 if (p1 == NULL)
4661 return null_ptid;
4662 p1++;
4663
4664 p = p1;
4665 }
4666 }
4667
4668 return null_ptid;
4669 }
4670
4671 /* Determine the remote side's current thread. If we have a stop
4672 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4673 "thread" register we can extract the current thread from. If not,
4674 ask the remote which is the current thread with qC. The former
4675 method avoids a roundtrip. */
4676
4677 ptid_t
4678 remote_target::get_current_thread (const char *wait_status)
4679 {
4680 ptid_t ptid = null_ptid;
4681
4682 /* Note we don't use remote_parse_stop_reply as that makes use of
4683 the target architecture, which we haven't yet fully determined at
4684 this point. */
4685 if (wait_status != NULL)
4686 ptid = stop_reply_extract_thread (wait_status);
4687 if (ptid == null_ptid)
4688 ptid = remote_current_thread (inferior_ptid);
4689
4690 return ptid;
4691 }
4692
4693 /* Query the remote target for which is the current thread/process,
4694 add it to our tables, and update INFERIOR_PTID. The caller is
4695 responsible for setting the state such that the remote end is ready
4696 to return the current thread.
4697
4698 This function is called after handling the '?' or 'vRun' packets,
4699 whose response is a stop reply from which we can also try
4700 extracting the thread. If the target doesn't support the explicit
4701 qC query, we infer the current thread from that stop reply, passed
4702 in in WAIT_STATUS, which may be NULL.
4703
4704 The function returns pointer to the main thread of the inferior. */
4705
4706 thread_info *
4707 remote_target::add_current_inferior_and_thread (const char *wait_status)
4708 {
4709 bool fake_pid_p = false;
4710
4711 switch_to_no_thread ();
4712
4713 /* Now, if we have thread information, update the current thread's
4714 ptid. */
4715 ptid_t curr_ptid = get_current_thread (wait_status);
4716
4717 if (curr_ptid != null_ptid)
4718 {
4719 if (!m_features.remote_multi_process_p ())
4720 fake_pid_p = true;
4721 }
4722 else
4723 {
4724 /* Without this, some commands which require an active target
4725 (such as kill) won't work. This variable serves (at least)
4726 double duty as both the pid of the target process (if it has
4727 such), and as a flag indicating that a target is active. */
4728 curr_ptid = magic_null_ptid;
4729 fake_pid_p = true;
4730 }
4731
4732 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4733
4734 /* Add the main thread and switch to it. Don't try reading
4735 registers yet, since we haven't fetched the target description
4736 yet. */
4737 thread_info *tp = add_thread_silent (this, curr_ptid);
4738 switch_to_thread_no_regs (tp);
4739
4740 return tp;
4741 }
4742
4743 /* Print info about a thread that was found already stopped on
4744 connection. */
4745
4746 void
4747 remote_target::print_one_stopped_thread (thread_info *thread)
4748 {
4749 target_waitstatus ws;
4750
4751 /* If there is a pending waitstatus, use it. If there isn't it's because
4752 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4753 and process_initial_stop_replies decided it wasn't interesting to save
4754 and report to the core. */
4755 if (thread->has_pending_waitstatus ())
4756 {
4757 ws = thread->pending_waitstatus ();
4758 thread->clear_pending_waitstatus ();
4759 }
4760 else
4761 {
4762 ws.set_stopped (GDB_SIGNAL_0);
4763 }
4764
4765 switch_to_thread (thread);
4766 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4767 set_current_sal_from_frame (get_current_frame ());
4768
4769 /* For "info program". */
4770 set_last_target_status (this, thread->ptid, ws);
4771
4772 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4773 {
4774 enum gdb_signal sig = ws.sig ();
4775
4776 if (signal_print_state (sig))
4777 notify_signal_received (sig);
4778 }
4779
4780 notify_normal_stop (nullptr, 1);
4781 }
4782
4783 /* Process all initial stop replies the remote side sent in response
4784 to the ? packet. These indicate threads that were already stopped
4785 on initial connection. We mark these threads as stopped and print
4786 their current frame before giving the user the prompt. */
4787
4788 void
4789 remote_target::process_initial_stop_replies (int from_tty)
4790 {
4791 int pending_stop_replies = stop_reply_queue_length ();
4792 struct thread_info *selected = NULL;
4793 struct thread_info *lowest_stopped = NULL;
4794 struct thread_info *first = NULL;
4795
4796 /* This is only used when the target is non-stop. */
4797 gdb_assert (target_is_non_stop_p ());
4798
4799 /* Consume the initial pending events. */
4800 while (pending_stop_replies-- > 0)
4801 {
4802 ptid_t waiton_ptid = minus_one_ptid;
4803 ptid_t event_ptid;
4804 struct target_waitstatus ws;
4805 int ignore_event = 0;
4806
4807 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4808 if (remote_debug)
4809 print_target_wait_results (waiton_ptid, event_ptid, ws);
4810
4811 switch (ws.kind ())
4812 {
4813 case TARGET_WAITKIND_IGNORE:
4814 case TARGET_WAITKIND_NO_RESUMED:
4815 case TARGET_WAITKIND_SIGNALLED:
4816 case TARGET_WAITKIND_EXITED:
4817 /* We shouldn't see these, but if we do, just ignore. */
4818 remote_debug_printf ("event ignored");
4819 ignore_event = 1;
4820 break;
4821
4822 default:
4823 break;
4824 }
4825
4826 if (ignore_event)
4827 continue;
4828
4829 thread_info *evthread = this->find_thread (event_ptid);
4830
4831 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4832 {
4833 enum gdb_signal sig = ws.sig ();
4834
4835 /* Stubs traditionally report SIGTRAP as initial signal,
4836 instead of signal 0. Suppress it. */
4837 if (sig == GDB_SIGNAL_TRAP)
4838 sig = GDB_SIGNAL_0;
4839 evthread->set_stop_signal (sig);
4840 ws.set_stopped (sig);
4841 }
4842
4843 if (ws.kind () != TARGET_WAITKIND_STOPPED
4844 || ws.sig () != GDB_SIGNAL_0)
4845 evthread->set_pending_waitstatus (ws);
4846
4847 set_executing (this, event_ptid, false);
4848 set_running (this, event_ptid, false);
4849 get_remote_thread_info (evthread)->set_not_resumed ();
4850 }
4851
4852 /* "Notice" the new inferiors before anything related to
4853 registers/memory. */
4854 for (inferior *inf : all_non_exited_inferiors (this))
4855 {
4856 inf->needs_setup = true;
4857
4858 if (non_stop)
4859 {
4860 thread_info *thread = any_live_thread_of_inferior (inf);
4861 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4862 from_tty);
4863 }
4864 }
4865
4866 /* If all-stop on top of non-stop, pause all threads. Note this
4867 records the threads' stop pc, so must be done after "noticing"
4868 the inferiors. */
4869 if (!non_stop)
4870 {
4871 {
4872 /* At this point, the remote target is not async. It needs to be for
4873 the poll in stop_all_threads to consider events from it, so enable
4874 it temporarily. */
4875 gdb_assert (!this->is_async_p ());
4876 SCOPE_EXIT { target_async (false); };
4877 target_async (true);
4878 stop_all_threads ("remote connect in all-stop");
4879 }
4880
4881 /* If all threads of an inferior were already stopped, we
4882 haven't setup the inferior yet. */
4883 for (inferior *inf : all_non_exited_inferiors (this))
4884 {
4885 if (inf->needs_setup)
4886 {
4887 thread_info *thread = any_live_thread_of_inferior (inf);
4888 switch_to_thread_no_regs (thread);
4889 setup_inferior (0);
4890 }
4891 }
4892 }
4893
4894 /* Now go over all threads that are stopped, and print their current
4895 frame. If all-stop, then if there's a signalled thread, pick
4896 that as current. */
4897 for (thread_info *thread : all_non_exited_threads (this))
4898 {
4899 if (first == NULL)
4900 first = thread;
4901
4902 if (!non_stop)
4903 thread->set_running (false);
4904 else if (thread->state != THREAD_STOPPED)
4905 continue;
4906
4907 if (selected == nullptr && thread->has_pending_waitstatus ())
4908 selected = thread;
4909
4910 if (lowest_stopped == NULL
4911 || thread->inf->num < lowest_stopped->inf->num
4912 || thread->per_inf_num < lowest_stopped->per_inf_num)
4913 lowest_stopped = thread;
4914
4915 if (non_stop)
4916 print_one_stopped_thread (thread);
4917 }
4918
4919 /* In all-stop, we only print the status of one thread, and leave
4920 others with their status pending. */
4921 if (!non_stop)
4922 {
4923 thread_info *thread = selected;
4924 if (thread == NULL)
4925 thread = lowest_stopped;
4926 if (thread == NULL)
4927 thread = first;
4928
4929 print_one_stopped_thread (thread);
4930 }
4931 }
4932
4933 /* Mark a remote_target as starting (by setting the starting_up flag within
4934 its remote_state) for the lifetime of this object. The reference count
4935 on the remote target is temporarily incremented, to prevent the target
4936 being deleted under our feet. */
4937
4938 struct scoped_mark_target_starting
4939 {
4940 /* Constructor, TARGET is the target to be marked as starting, its
4941 reference count will be incremented. */
4942 scoped_mark_target_starting (remote_target *target)
4943 : m_remote_target (remote_target_ref::new_reference (target)),
4944 m_restore_starting_up (set_starting_up_flag (target))
4945 { /* Nothing. */ }
4946
4947 private:
4948
4949 /* Helper function, set the starting_up flag on TARGET and return an
4950 object which, when it goes out of scope, will restore the previous
4951 value of the starting_up flag. */
4952 static scoped_restore_tmpl<bool>
4953 set_starting_up_flag (remote_target *target)
4954 {
4955 remote_state *rs = target->get_remote_state ();
4956 gdb_assert (!rs->starting_up);
4957 return make_scoped_restore (&rs->starting_up, true);
4958 }
4959
4960 /* A gdb::ref_ptr pointer to a remote_target. */
4961 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4962
4963 /* A reference to the target on which we are operating. */
4964 remote_target_ref m_remote_target;
4965
4966 /* An object which restores the previous value of the starting_up flag
4967 when it goes out of scope. */
4968 scoped_restore_tmpl<bool> m_restore_starting_up;
4969 };
4970
4971 /* Helper for remote_target::start_remote, start the remote connection and
4972 sync state. Return true if everything goes OK, otherwise, return false.
4973 This function exists so that the scoped_restore created within it will
4974 expire before we return to remote_target::start_remote. */
4975
4976 bool
4977 remote_target::start_remote_1 (int from_tty, int extended_p)
4978 {
4979 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4980
4981 struct remote_state *rs = get_remote_state ();
4982
4983 /* Signal other parts that we're going through the initial setup,
4984 and so things may not be stable yet. E.g., we don't try to
4985 install tracepoints until we've relocated symbols. Also, a
4986 Ctrl-C before we're connected and synced up can't interrupt the
4987 target. Instead, it offers to drop the (potentially wedged)
4988 connection. */
4989 scoped_mark_target_starting target_is_starting (this);
4990
4991 QUIT;
4992
4993 if (interrupt_on_connect)
4994 send_interrupt_sequence ();
4995
4996 /* Ack any packet which the remote side has already sent. */
4997 remote_serial_write ("+", 1);
4998
4999 /* The first packet we send to the target is the optional "supported
5000 packets" request. If the target can answer this, it will tell us
5001 which later probes to skip. */
5002 remote_query_supported ();
5003
5004 /* Check vCont support and set the remote state's vCont_action_support
5005 attribute. */
5006 remote_vcont_probe ();
5007
5008 /* If the stub wants to get a QAllow, compose one and send it. */
5009 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
5010 set_permissions ();
5011
5012 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
5013 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
5014 as a reply to known packet. For packet "vFile:setfs:" it is an
5015 invalid reply and GDB would return error in
5016 remote_hostio_set_filesystem, making remote files access impossible.
5017 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
5018 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
5019 {
5020 const char v_mustreplyempty[] = "vMustReplyEmpty";
5021
5022 putpkt (v_mustreplyempty);
5023 getpkt (&rs->buf);
5024 if (strcmp (rs->buf.data (), "OK") == 0)
5025 {
5026 m_features.m_protocol_packets[PACKET_vFile_setfs].support
5027 = PACKET_DISABLE;
5028 }
5029 else if (strcmp (rs->buf.data (), "") != 0)
5030 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
5031 rs->buf.data ());
5032 }
5033
5034 /* Next, we possibly activate noack mode.
5035
5036 If the QStartNoAckMode packet configuration is set to AUTO,
5037 enable noack mode if the stub reported a wish for it with
5038 qSupported.
5039
5040 If set to TRUE, then enable noack mode even if the stub didn't
5041 report it in qSupported. If the stub doesn't reply OK, the
5042 session ends with an error.
5043
5044 If FALSE, then don't activate noack mode, regardless of what the
5045 stub claimed should be the default with qSupported. */
5046
5047 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
5048 {
5049 putpkt ("QStartNoAckMode");
5050 getpkt (&rs->buf);
5051 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
5052 rs->noack_mode = 1;
5053 }
5054
5055 if (extended_p)
5056 {
5057 /* Tell the remote that we are using the extended protocol. */
5058 putpkt ("!");
5059 getpkt (&rs->buf);
5060 }
5061
5062 /* Let the target know which signals it is allowed to pass down to
5063 the program. */
5064 update_signals_program_target ();
5065
5066 /* Next, if the target can specify a description, read it. We do
5067 this before anything involving memory or registers. */
5068 target_find_description ();
5069
5070 /* Next, now that we know something about the target, update the
5071 address spaces in the program spaces. */
5072 update_address_spaces ();
5073
5074 /* On OSs where the list of libraries is global to all
5075 processes, we fetch them early. */
5076 if (gdbarch_has_global_solist (current_inferior ()->arch ()))
5077 solib_add (NULL, from_tty, auto_solib_add);
5078
5079 if (target_is_non_stop_p ())
5080 {
5081 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5082 error (_("Non-stop mode requested, but remote "
5083 "does not support non-stop"));
5084
5085 putpkt ("QNonStop:1");
5086 getpkt (&rs->buf);
5087
5088 if (strcmp (rs->buf.data (), "OK") != 0)
5089 error (_("Remote refused setting non-stop mode with: %s"),
5090 rs->buf.data ());
5091
5092 /* Find about threads and processes the stub is already
5093 controlling. We default to adding them in the running state.
5094 The '?' query below will then tell us about which threads are
5095 stopped. */
5096 this->update_thread_list ();
5097 }
5098 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5099 {
5100 /* Don't assume that the stub can operate in all-stop mode.
5101 Request it explicitly. */
5102 putpkt ("QNonStop:0");
5103 getpkt (&rs->buf);
5104
5105 if (strcmp (rs->buf.data (), "OK") != 0)
5106 error (_("Remote refused setting all-stop mode with: %s"),
5107 rs->buf.data ());
5108 }
5109
5110 /* Upload TSVs regardless of whether the target is running or not. The
5111 remote stub, such as GDBserver, may have some predefined or builtin
5112 TSVs, even if the target is not running. */
5113 if (get_trace_status (current_trace_status ()) != -1)
5114 {
5115 struct uploaded_tsv *uploaded_tsvs = NULL;
5116
5117 upload_trace_state_variables (&uploaded_tsvs);
5118 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5119 }
5120
5121 /* Check whether the target is running now. */
5122 putpkt ("?");
5123 getpkt (&rs->buf);
5124
5125 if (!target_is_non_stop_p ())
5126 {
5127 char *wait_status = NULL;
5128
5129 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5130 {
5131 if (!extended_p)
5132 error (_("The target is not running (try extended-remote?)"));
5133 return false;
5134 }
5135 else
5136 {
5137 /* Save the reply for later. */
5138 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5139 strcpy (wait_status, rs->buf.data ());
5140 }
5141
5142 /* Fetch thread list. */
5143 target_update_thread_list ();
5144
5145 /* Let the stub know that we want it to return the thread. */
5146 set_continue_thread (minus_one_ptid);
5147
5148 if (thread_count (this) == 0)
5149 {
5150 /* Target has no concept of threads at all. GDB treats
5151 non-threaded target as single-threaded; add a main
5152 thread. */
5153 thread_info *tp = add_current_inferior_and_thread (wait_status);
5154 get_remote_thread_info (tp)->set_resumed ();
5155 }
5156 else
5157 {
5158 /* We have thread information; select the thread the target
5159 says should be current. If we're reconnecting to a
5160 multi-threaded program, this will ideally be the thread
5161 that last reported an event before GDB disconnected. */
5162 ptid_t curr_thread = get_current_thread (wait_status);
5163 if (curr_thread == null_ptid)
5164 {
5165 /* Odd... The target was able to list threads, but not
5166 tell us which thread was current (no "thread"
5167 register in T stop reply?). Just pick the first
5168 thread in the thread list then. */
5169
5170 remote_debug_printf ("warning: couldn't determine remote "
5171 "current thread; picking first in list.");
5172
5173 for (thread_info *tp : all_non_exited_threads (this,
5174 minus_one_ptid))
5175 {
5176 switch_to_thread (tp);
5177 break;
5178 }
5179 }
5180 else
5181 switch_to_thread (this->find_thread (curr_thread));
5182
5183 get_remote_thread_info (inferior_thread ())->set_resumed ();
5184 }
5185
5186 /* init_wait_for_inferior should be called before get_offsets in order
5187 to manage `inserted' flag in bp loc in a correct state.
5188 breakpoint_init_inferior, called from init_wait_for_inferior, set
5189 `inserted' flag to 0, while before breakpoint_re_set, called from
5190 start_remote, set `inserted' flag to 1. In the initialization of
5191 inferior, breakpoint_init_inferior should be called first, and then
5192 breakpoint_re_set can be called. If this order is broken, state of
5193 `inserted' flag is wrong, and cause some problems on breakpoint
5194 manipulation. */
5195 init_wait_for_inferior ();
5196
5197 get_offsets (); /* Get text, data & bss offsets. */
5198
5199 /* If we could not find a description using qXfer, and we know
5200 how to do it some other way, try again. This is not
5201 supported for non-stop; it could be, but it is tricky if
5202 there are no stopped threads when we connect. */
5203 if (remote_read_description_p (this)
5204 && gdbarch_target_desc (current_inferior ()->arch ()) == NULL)
5205 {
5206 target_clear_description ();
5207 target_find_description ();
5208 }
5209
5210 /* Use the previously fetched status. */
5211 gdb_assert (wait_status != NULL);
5212 struct notif_event *reply
5213 = remote_notif_parse (this, &notif_client_stop, wait_status);
5214 push_stop_reply ((struct stop_reply *) reply);
5215
5216 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5217 }
5218 else
5219 {
5220 /* Clear WFI global state. Do this before finding about new
5221 threads and inferiors, and setting the current inferior.
5222 Otherwise we would clear the proceed status of the current
5223 inferior when we want its stop_soon state to be preserved
5224 (see notice_new_inferior). */
5225 init_wait_for_inferior ();
5226
5227 /* In non-stop, we will either get an "OK", meaning that there
5228 are no stopped threads at this time; or, a regular stop
5229 reply. In the latter case, there may be more than one thread
5230 stopped --- we pull them all out using the vStopped
5231 mechanism. */
5232 if (strcmp (rs->buf.data (), "OK") != 0)
5233 {
5234 const notif_client *notif = &notif_client_stop;
5235
5236 /* remote_notif_get_pending_replies acks this one, and gets
5237 the rest out. */
5238 rs->notif_state->pending_event[notif_client_stop.id]
5239 = remote_notif_parse (this, notif, rs->buf.data ());
5240 remote_notif_get_pending_events (notif);
5241 }
5242
5243 if (thread_count (this) == 0)
5244 {
5245 if (!extended_p)
5246 error (_("The target is not running (try extended-remote?)"));
5247 return false;
5248 }
5249
5250 /* Report all signals during attach/startup. */
5251 pass_signals ({});
5252
5253 /* If there are already stopped threads, mark them stopped and
5254 report their stops before giving the prompt to the user. */
5255 process_initial_stop_replies (from_tty);
5256
5257 if (target_can_async_p ())
5258 target_async (true);
5259 }
5260
5261 /* Give the target a chance to look up symbols. */
5262 for (inferior *inf : all_inferiors (this))
5263 {
5264 /* The inferiors that exist at this point were created from what
5265 was found already running on the remote side, so we know they
5266 have execution. */
5267 gdb_assert (this->has_execution (inf));
5268
5269 /* No use without a symbol-file. */
5270 if (inf->pspace->symfile_object_file == nullptr)
5271 continue;
5272
5273 /* Need to switch to a specific thread, because remote_check_symbols
5274 uses INFERIOR_PTID to set the general thread. */
5275 scoped_restore_current_thread restore_thread;
5276 thread_info *thread = any_thread_of_inferior (inf);
5277 switch_to_thread (thread);
5278 this->remote_check_symbols ();
5279 }
5280
5281 /* Possibly the target has been engaged in a trace run started
5282 previously; find out where things are at. */
5283 if (get_trace_status (current_trace_status ()) != -1)
5284 {
5285 struct uploaded_tp *uploaded_tps = NULL;
5286
5287 if (current_trace_status ()->running)
5288 gdb_printf (_("Trace is already running on the target.\n"));
5289
5290 upload_tracepoints (&uploaded_tps);
5291
5292 merge_uploaded_tracepoints (&uploaded_tps);
5293 }
5294
5295 /* Possibly the target has been engaged in a btrace record started
5296 previously; find out where things are at. */
5297 remote_btrace_maybe_reopen ();
5298
5299 return true;
5300 }
5301
5302 /* Start the remote connection and sync state. */
5303
5304 void
5305 remote_target::start_remote (int from_tty, int extended_p)
5306 {
5307 if (start_remote_1 (from_tty, extended_p)
5308 && breakpoints_should_be_inserted_now ())
5309 insert_breakpoints ();
5310 }
5311
5312 const char *
5313 remote_target::connection_string ()
5314 {
5315 remote_state *rs = get_remote_state ();
5316
5317 if (rs->remote_desc->name != NULL)
5318 return rs->remote_desc->name;
5319 else
5320 return NULL;
5321 }
5322
5323 /* Open a connection to a remote debugger.
5324 NAME is the filename used for communication. */
5325
5326 void
5327 remote_target::open (const char *name, int from_tty)
5328 {
5329 open_1 (name, from_tty, 0);
5330 }
5331
5332 /* Open a connection to a remote debugger using the extended
5333 remote gdb protocol. NAME is the filename used for communication. */
5334
5335 void
5336 extended_remote_target::open (const char *name, int from_tty)
5337 {
5338 open_1 (name, from_tty, 1 /*extended_p */);
5339 }
5340
5341 void
5342 remote_features::reset_all_packet_configs_support ()
5343 {
5344 int i;
5345
5346 for (i = 0; i < PACKET_MAX; i++)
5347 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5348 }
5349
5350 /* Initialize all packet configs. */
5351
5352 static void
5353 init_all_packet_configs (void)
5354 {
5355 int i;
5356
5357 for (i = 0; i < PACKET_MAX; i++)
5358 {
5359 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5360 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5361 }
5362 }
5363
5364 /* Symbol look-up. */
5365
5366 void
5367 remote_target::remote_check_symbols ()
5368 {
5369 char *tmp;
5370 int end;
5371
5372 /* It doesn't make sense to send a qSymbol packet for an inferior that
5373 doesn't have execution, because the remote side doesn't know about
5374 inferiors without execution. */
5375 gdb_assert (target_has_execution ());
5376
5377 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5378 return;
5379
5380 /* Make sure the remote is pointing at the right process. Note
5381 there's no way to select "no process". */
5382 set_general_process ();
5383
5384 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5385 because we need both at the same time. */
5386 gdb::char_vector msg (get_remote_packet_size ());
5387 gdb::char_vector reply (get_remote_packet_size ());
5388
5389 /* Invite target to request symbol lookups. */
5390
5391 putpkt ("qSymbol::");
5392 getpkt (&reply);
5393 m_features.packet_ok (reply, PACKET_qSymbol);
5394
5395 while (startswith (reply.data (), "qSymbol:"))
5396 {
5397 struct bound_minimal_symbol sym;
5398
5399 tmp = &reply[8];
5400 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5401 strlen (tmp) / 2);
5402 msg[end] = '\0';
5403 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5404 if (sym.minsym == NULL)
5405 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5406 &reply[8]);
5407 else
5408 {
5409 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
5410 CORE_ADDR sym_addr = sym.value_address ();
5411
5412 /* If this is a function address, return the start of code
5413 instead of any data function descriptor. */
5414 sym_addr = gdbarch_convert_from_func_ptr_addr
5415 (current_inferior ()->arch (), sym_addr,
5416 current_inferior ()->top_target ());
5417
5418 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5419 phex_nz (sym_addr, addr_size), &reply[8]);
5420 }
5421
5422 putpkt (msg.data ());
5423 getpkt (&reply);
5424 }
5425 }
5426
5427 static struct serial *
5428 remote_serial_open (const char *name)
5429 {
5430 static int udp_warning = 0;
5431
5432 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5433 of in ser-tcp.c, because it is the remote protocol assuming that the
5434 serial connection is reliable and not the serial connection promising
5435 to be. */
5436 if (!udp_warning && startswith (name, "udp:"))
5437 {
5438 warning (_("The remote protocol may be unreliable over UDP.\n"
5439 "Some events may be lost, rendering further debugging "
5440 "impossible."));
5441 udp_warning = 1;
5442 }
5443
5444 return serial_open (name);
5445 }
5446
5447 /* Inform the target of our permission settings. The permission flags
5448 work without this, but if the target knows the settings, it can do
5449 a couple things. First, it can add its own check, to catch cases
5450 that somehow manage to get by the permissions checks in target
5451 methods. Second, if the target is wired to disallow particular
5452 settings (for instance, a system in the field that is not set up to
5453 be able to stop at a breakpoint), it can object to any unavailable
5454 permissions. */
5455
5456 void
5457 remote_target::set_permissions ()
5458 {
5459 struct remote_state *rs = get_remote_state ();
5460
5461 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5462 "WriteReg:%x;WriteMem:%x;"
5463 "InsertBreak:%x;InsertTrace:%x;"
5464 "InsertFastTrace:%x;Stop:%x",
5465 may_write_registers, may_write_memory,
5466 may_insert_breakpoints, may_insert_tracepoints,
5467 may_insert_fast_tracepoints, may_stop);
5468 putpkt (rs->buf);
5469 getpkt (&rs->buf);
5470
5471 /* If the target didn't like the packet, warn the user. Do not try
5472 to undo the user's settings, that would just be maddening. */
5473 if (strcmp (rs->buf.data (), "OK") != 0)
5474 warning (_("Remote refused setting permissions with: %s"),
5475 rs->buf.data ());
5476 }
5477
5478 /* This type describes each known response to the qSupported
5479 packet. */
5480 struct protocol_feature
5481 {
5482 /* The name of this protocol feature. */
5483 const char *name;
5484
5485 /* The default for this protocol feature. */
5486 enum packet_support default_support;
5487
5488 /* The function to call when this feature is reported, or after
5489 qSupported processing if the feature is not supported.
5490 The first argument points to this structure. The second
5491 argument indicates whether the packet requested support be
5492 enabled, disabled, or probed (or the default, if this function
5493 is being called at the end of processing and this feature was
5494 not reported). The third argument may be NULL; if not NULL, it
5495 is a NUL-terminated string taken from the packet following
5496 this feature's name and an equals sign. */
5497 void (*func) (remote_target *remote, const struct protocol_feature *,
5498 enum packet_support, const char *);
5499
5500 /* The corresponding packet for this feature. Only used if
5501 FUNC is remote_supported_packet. */
5502 int packet;
5503 };
5504
5505 static void
5506 remote_supported_packet (remote_target *remote,
5507 const struct protocol_feature *feature,
5508 enum packet_support support,
5509 const char *argument)
5510 {
5511 if (argument)
5512 {
5513 warning (_("Remote qSupported response supplied an unexpected value for"
5514 " \"%s\"."), feature->name);
5515 return;
5516 }
5517
5518 remote->m_features.m_protocol_packets[feature->packet].support = support;
5519 }
5520
5521 void
5522 remote_target::remote_packet_size (const protocol_feature *feature,
5523 enum packet_support support,
5524 const char *value)
5525 {
5526 struct remote_state *rs = get_remote_state ();
5527
5528 int packet_size;
5529 char *value_end;
5530
5531 if (support != PACKET_ENABLE)
5532 return;
5533
5534 if (value == NULL || *value == '\0')
5535 {
5536 warning (_("Remote target reported \"%s\" without a size."),
5537 feature->name);
5538 return;
5539 }
5540
5541 errno = 0;
5542 packet_size = strtol (value, &value_end, 16);
5543 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5544 {
5545 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5546 feature->name, value);
5547 return;
5548 }
5549
5550 /* Record the new maximum packet size. */
5551 rs->explicit_packet_size = packet_size;
5552 }
5553
5554 static void
5555 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5556 enum packet_support support, const char *value)
5557 {
5558 remote->remote_packet_size (feature, support, value);
5559 }
5560
5561 void
5562 remote_target::remote_supported_thread_options (const protocol_feature *feature,
5563 enum packet_support support,
5564 const char *value)
5565 {
5566 struct remote_state *rs = get_remote_state ();
5567
5568 m_features.m_protocol_packets[feature->packet].support = support;
5569
5570 if (support != PACKET_ENABLE)
5571 return;
5572
5573 if (value == nullptr || *value == '\0')
5574 {
5575 warning (_("Remote target reported \"%s\" without supported options."),
5576 feature->name);
5577 return;
5578 }
5579
5580 ULONGEST options = 0;
5581 const char *p = unpack_varlen_hex (value, &options);
5582
5583 if (*p != '\0')
5584 {
5585 warning (_("Remote target reported \"%s\" with "
5586 "bad thread options: \"%s\"."),
5587 feature->name, value);
5588 return;
5589 }
5590
5591 /* Record the set of supported options. */
5592 rs->supported_thread_options = (gdb_thread_option) options;
5593 }
5594
5595 static void
5596 remote_supported_thread_options (remote_target *remote,
5597 const protocol_feature *feature,
5598 enum packet_support support,
5599 const char *value)
5600 {
5601 remote->remote_supported_thread_options (feature, support, value);
5602 }
5603
5604 static const struct protocol_feature remote_protocol_features[] = {
5605 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5606 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5607 PACKET_qXfer_auxv },
5608 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5609 PACKET_qXfer_exec_file },
5610 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5611 PACKET_qXfer_features },
5612 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5613 PACKET_qXfer_libraries },
5614 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5615 PACKET_qXfer_libraries_svr4 },
5616 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5617 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5618 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5619 PACKET_qXfer_memory_map },
5620 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5621 PACKET_qXfer_osdata },
5622 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5623 PACKET_qXfer_threads },
5624 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5625 PACKET_qXfer_traceframe_info },
5626 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5627 PACKET_QPassSignals },
5628 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5629 PACKET_QCatchSyscalls },
5630 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5631 PACKET_QProgramSignals },
5632 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5633 PACKET_QSetWorkingDir },
5634 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5635 PACKET_QStartupWithShell },
5636 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5637 PACKET_QEnvironmentHexEncoded },
5638 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5639 PACKET_QEnvironmentReset },
5640 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5641 PACKET_QEnvironmentUnset },
5642 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5643 PACKET_QStartNoAckMode },
5644 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5645 PACKET_multiprocess_feature },
5646 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5647 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5648 PACKET_qXfer_siginfo_read },
5649 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5650 PACKET_qXfer_siginfo_write },
5651 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5652 PACKET_ConditionalTracepoints },
5653 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5654 PACKET_ConditionalBreakpoints },
5655 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5656 PACKET_BreakpointCommands },
5657 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5658 PACKET_FastTracepoints },
5659 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5660 PACKET_StaticTracepoints },
5661 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5662 PACKET_InstallInTrace},
5663 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5664 PACKET_DisconnectedTracing_feature },
5665 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5666 PACKET_bc },
5667 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5668 PACKET_bs },
5669 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5670 PACKET_TracepointSource },
5671 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5672 PACKET_QAllow },
5673 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5674 PACKET_EnableDisableTracepoints_feature },
5675 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5676 PACKET_qXfer_fdpic },
5677 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5678 PACKET_qXfer_uib },
5679 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5680 PACKET_QDisableRandomization },
5681 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5682 { "QTBuffer:size", PACKET_DISABLE,
5683 remote_supported_packet, PACKET_QTBuffer_size},
5684 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5685 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5686 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5687 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5688 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5689 PACKET_qXfer_btrace },
5690 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5691 PACKET_qXfer_btrace_conf },
5692 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5693 PACKET_Qbtrace_conf_bts_size },
5694 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5695 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5696 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5697 PACKET_fork_event_feature },
5698 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5699 PACKET_vfork_event_feature },
5700 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5701 PACKET_exec_event_feature },
5702 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5703 PACKET_Qbtrace_conf_pt_size },
5704 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5705 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5706 { "QThreadOptions", PACKET_DISABLE, remote_supported_thread_options,
5707 PACKET_QThreadOptions },
5708 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5709 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5710 PACKET_memory_tagging_feature },
5711 };
5712
5713 static char *remote_support_xml;
5714
5715 /* Register string appended to "xmlRegisters=" in qSupported query. */
5716
5717 void
5718 register_remote_support_xml (const char *xml)
5719 {
5720 #if defined(HAVE_LIBEXPAT)
5721 if (remote_support_xml == NULL)
5722 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5723 else
5724 {
5725 char *copy = xstrdup (remote_support_xml + 13);
5726 char *saveptr;
5727 char *p = strtok_r (copy, ",", &saveptr);
5728
5729 do
5730 {
5731 if (strcmp (p, xml) == 0)
5732 {
5733 /* already there */
5734 xfree (copy);
5735 return;
5736 }
5737 }
5738 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5739 xfree (copy);
5740
5741 remote_support_xml = reconcat (remote_support_xml,
5742 remote_support_xml, ",", xml,
5743 (char *) NULL);
5744 }
5745 #endif
5746 }
5747
5748 static void
5749 remote_query_supported_append (std::string *msg, const char *append)
5750 {
5751 if (!msg->empty ())
5752 msg->append (";");
5753 msg->append (append);
5754 }
5755
5756 void
5757 remote_target::remote_query_supported ()
5758 {
5759 struct remote_state *rs = get_remote_state ();
5760 char *next;
5761 int i;
5762 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5763
5764 /* The packet support flags are handled differently for this packet
5765 than for most others. We treat an error, a disabled packet, and
5766 an empty response identically: any features which must be reported
5767 to be used will be automatically disabled. An empty buffer
5768 accomplishes this, since that is also the representation for a list
5769 containing no features. */
5770
5771 rs->buf[0] = 0;
5772 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5773 {
5774 std::string q;
5775
5776 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5777 != AUTO_BOOLEAN_FALSE)
5778 remote_query_supported_append (&q, "multiprocess+");
5779
5780 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5781 != AUTO_BOOLEAN_FALSE)
5782 remote_query_supported_append (&q, "swbreak+");
5783
5784 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5785 != AUTO_BOOLEAN_FALSE)
5786 remote_query_supported_append (&q, "hwbreak+");
5787
5788 remote_query_supported_append (&q, "qRelocInsn+");
5789
5790 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5791 != AUTO_BOOLEAN_FALSE)
5792 remote_query_supported_append (&q, "fork-events+");
5793
5794 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5795 != AUTO_BOOLEAN_FALSE)
5796 remote_query_supported_append (&q, "vfork-events+");
5797
5798 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5799 != AUTO_BOOLEAN_FALSE)
5800 remote_query_supported_append (&q, "exec-events+");
5801
5802 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5803 != AUTO_BOOLEAN_FALSE)
5804 remote_query_supported_append (&q, "vContSupported+");
5805
5806 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5807 != AUTO_BOOLEAN_FALSE)
5808 remote_query_supported_append (&q, "QThreadEvents+");
5809
5810 if (m_features.packet_set_cmd_state (PACKET_QThreadOptions)
5811 != AUTO_BOOLEAN_FALSE)
5812 remote_query_supported_append (&q, "QThreadOptions+");
5813
5814 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5815 != AUTO_BOOLEAN_FALSE)
5816 remote_query_supported_append (&q, "no-resumed+");
5817
5818 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5819 != AUTO_BOOLEAN_FALSE)
5820 remote_query_supported_append (&q, "memory-tagging+");
5821
5822 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5823 the qSupported:xmlRegisters=i386 handling. */
5824 if (remote_support_xml != NULL
5825 && (m_features.packet_support (PACKET_qXfer_features)
5826 != PACKET_DISABLE))
5827 remote_query_supported_append (&q, remote_support_xml);
5828
5829 q = "qSupported:" + q;
5830 putpkt (q.c_str ());
5831
5832 getpkt (&rs->buf);
5833
5834 /* If an error occurred, warn, but do not return - just reset the
5835 buffer to empty and go on to disable features. */
5836 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5837 {
5838 warning (_("Remote failure reply: %s"), rs->buf.data ());
5839 rs->buf[0] = 0;
5840 }
5841 }
5842
5843 memset (seen, 0, sizeof (seen));
5844
5845 next = rs->buf.data ();
5846 while (*next)
5847 {
5848 enum packet_support is_supported;
5849 char *p, *end, *name_end, *value;
5850
5851 /* First separate out this item from the rest of the packet. If
5852 there's another item after this, we overwrite the separator
5853 (terminated strings are much easier to work with). */
5854 p = next;
5855 end = strchr (p, ';');
5856 if (end == NULL)
5857 {
5858 end = p + strlen (p);
5859 next = end;
5860 }
5861 else
5862 {
5863 *end = '\0';
5864 next = end + 1;
5865
5866 if (end == p)
5867 {
5868 warning (_("empty item in \"qSupported\" response"));
5869 continue;
5870 }
5871 }
5872
5873 name_end = strchr (p, '=');
5874 if (name_end)
5875 {
5876 /* This is a name=value entry. */
5877 is_supported = PACKET_ENABLE;
5878 value = name_end + 1;
5879 *name_end = '\0';
5880 }
5881 else
5882 {
5883 value = NULL;
5884 switch (end[-1])
5885 {
5886 case '+':
5887 is_supported = PACKET_ENABLE;
5888 break;
5889
5890 case '-':
5891 is_supported = PACKET_DISABLE;
5892 break;
5893
5894 case '?':
5895 is_supported = PACKET_SUPPORT_UNKNOWN;
5896 break;
5897
5898 default:
5899 warning (_("unrecognized item \"%s\" "
5900 "in \"qSupported\" response"), p);
5901 continue;
5902 }
5903 end[-1] = '\0';
5904 }
5905
5906 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5907 if (strcmp (remote_protocol_features[i].name, p) == 0)
5908 {
5909 const struct protocol_feature *feature;
5910
5911 seen[i] = 1;
5912 feature = &remote_protocol_features[i];
5913 feature->func (this, feature, is_supported, value);
5914 break;
5915 }
5916 }
5917
5918 /* If we increased the packet size, make sure to increase the global
5919 buffer size also. We delay this until after parsing the entire
5920 qSupported packet, because this is the same buffer we were
5921 parsing. */
5922 if (rs->buf.size () < rs->explicit_packet_size)
5923 rs->buf.resize (rs->explicit_packet_size);
5924
5925 /* Handle the defaults for unmentioned features. */
5926 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5927 if (!seen[i])
5928 {
5929 const struct protocol_feature *feature;
5930
5931 feature = &remote_protocol_features[i];
5932 feature->func (this, feature, feature->default_support, NULL);
5933 }
5934 }
5935
5936 /* Serial QUIT handler for the remote serial descriptor.
5937
5938 Defers handling a Ctrl-C until we're done with the current
5939 command/response packet sequence, unless:
5940
5941 - We're setting up the connection. Don't send a remote interrupt
5942 request, as we're not fully synced yet. Quit immediately
5943 instead.
5944
5945 - The target has been resumed in the foreground
5946 (target_terminal::is_ours is false) with a synchronous resume
5947 packet, and we're blocked waiting for the stop reply, thus a
5948 Ctrl-C should be immediately sent to the target.
5949
5950 - We get a second Ctrl-C while still within the same serial read or
5951 write. In that case the serial is seemingly wedged --- offer to
5952 quit/disconnect.
5953
5954 - We see a second Ctrl-C without target response, after having
5955 previously interrupted the target. In that case the target/stub
5956 is probably wedged --- offer to quit/disconnect.
5957 */
5958
5959 void
5960 remote_target::remote_serial_quit_handler ()
5961 {
5962 struct remote_state *rs = get_remote_state ();
5963
5964 if (check_quit_flag ())
5965 {
5966 /* If we're starting up, we're not fully synced yet. Quit
5967 immediately. */
5968 if (rs->starting_up)
5969 quit ();
5970 else if (rs->got_ctrlc_during_io)
5971 {
5972 if (query (_("The target is not responding to GDB commands.\n"
5973 "Stop debugging it? ")))
5974 remote_unpush_and_throw (this);
5975 }
5976 /* If ^C has already been sent once, offer to disconnect. */
5977 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5978 interrupt_query ();
5979 /* All-stop protocol, and blocked waiting for stop reply. Send
5980 an interrupt request. */
5981 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5982 target_interrupt ();
5983 else
5984 rs->got_ctrlc_during_io = 1;
5985 }
5986 }
5987
5988 /* The remote_target that is current while the quit handler is
5989 overridden with remote_serial_quit_handler. */
5990 static remote_target *curr_quit_handler_target;
5991
5992 static void
5993 remote_serial_quit_handler ()
5994 {
5995 curr_quit_handler_target->remote_serial_quit_handler ();
5996 }
5997
5998 /* Remove the remote target from the target stack of each inferior
5999 that is using it. Upper targets depend on it so remove them
6000 first. */
6001
6002 static void
6003 remote_unpush_target (remote_target *target)
6004 {
6005 /* We have to unpush the target from all inferiors, even those that
6006 aren't running. */
6007 scoped_restore_current_inferior restore_current_inferior;
6008
6009 for (inferior *inf : all_inferiors (target))
6010 {
6011 switch_to_inferior_no_thread (inf);
6012 inf->pop_all_targets_at_and_above (process_stratum);
6013 generic_mourn_inferior ();
6014 }
6015
6016 /* Don't rely on target_close doing this when the target is popped
6017 from the last remote inferior above, because something may be
6018 holding a reference to the target higher up on the stack, meaning
6019 target_close won't be called yet. We lost the connection to the
6020 target, so clear these now, otherwise we may later throw
6021 TARGET_CLOSE_ERROR while trying to tell the remote target to
6022 close the file. */
6023 fileio_handles_invalidate_target (target);
6024 }
6025
6026 static void
6027 remote_unpush_and_throw (remote_target *target)
6028 {
6029 remote_unpush_target (target);
6030 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6031 }
6032
6033 void
6034 remote_target::open_1 (const char *name, int from_tty, int extended_p)
6035 {
6036 remote_target *curr_remote = get_current_remote_target ();
6037
6038 if (name == 0)
6039 error (_("To open a remote debug connection, you need to specify what\n"
6040 "serial device is attached to the remote system\n"
6041 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
6042
6043 /* If we're connected to a running target, target_preopen will kill it.
6044 Ask this question first, before target_preopen has a chance to kill
6045 anything. */
6046 if (curr_remote != NULL && !target_has_execution ())
6047 {
6048 if (from_tty
6049 && !query (_("Already connected to a remote target. Disconnect? ")))
6050 error (_("Still connected."));
6051 }
6052
6053 /* Here the possibly existing remote target gets unpushed. */
6054 target_preopen (from_tty);
6055
6056 remote_fileio_reset ();
6057 reopen_exec_file ();
6058 reread_symbols (from_tty);
6059
6060 remote_target *remote
6061 = (extended_p ? new extended_remote_target () : new remote_target ());
6062 target_ops_up target_holder (remote);
6063
6064 remote_state *rs = remote->get_remote_state ();
6065
6066 /* See FIXME above. */
6067 if (!target_async_permitted)
6068 rs->wait_forever_enabled_p = true;
6069
6070 rs->remote_desc = remote_serial_open (name);
6071 if (!rs->remote_desc)
6072 perror_with_name (name);
6073
6074 if (baud_rate != -1)
6075 {
6076 if (serial_setbaudrate (rs->remote_desc, baud_rate))
6077 {
6078 /* The requested speed could not be set. Error out to
6079 top level after closing remote_desc. Take care to
6080 set remote_desc to NULL to avoid closing remote_desc
6081 more than once. */
6082 serial_close (rs->remote_desc);
6083 rs->remote_desc = NULL;
6084 perror_with_name (name);
6085 }
6086 }
6087
6088 serial_setparity (rs->remote_desc, serial_parity);
6089 serial_raw (rs->remote_desc);
6090
6091 /* If there is something sitting in the buffer we might take it as a
6092 response to a command, which would be bad. */
6093 serial_flush_input (rs->remote_desc);
6094
6095 if (from_tty)
6096 {
6097 gdb_puts ("Remote debugging using ");
6098 gdb_puts (name);
6099 gdb_puts ("\n");
6100 }
6101
6102 /* Switch to using the remote target now. */
6103 current_inferior ()->push_target (std::move (target_holder));
6104
6105 /* Register extra event sources in the event loop. */
6106 rs->create_async_event_handler ();
6107
6108 rs->notif_state = remote_notif_state_allocate (remote);
6109
6110 /* Reset the target state; these things will be queried either by
6111 remote_query_supported or as they are needed. */
6112 remote->m_features.reset_all_packet_configs_support ();
6113 rs->explicit_packet_size = 0;
6114 rs->noack_mode = 0;
6115 rs->extended = extended_p;
6116 rs->waiting_for_stop_reply = 0;
6117 rs->ctrlc_pending_p = 0;
6118 rs->got_ctrlc_during_io = 0;
6119
6120 rs->general_thread = not_sent_ptid;
6121 rs->continue_thread = not_sent_ptid;
6122 rs->remote_traceframe_number = -1;
6123
6124 rs->last_resume_exec_dir = EXEC_FORWARD;
6125
6126 /* Probe for ability to use "ThreadInfo" query, as required. */
6127 rs->use_threadinfo_query = 1;
6128 rs->use_threadextra_query = 1;
6129
6130 rs->readahead_cache.invalidate ();
6131
6132 if (target_async_permitted)
6133 {
6134 /* FIXME: cagney/1999-09-23: During the initial connection it is
6135 assumed that the target is already ready and able to respond to
6136 requests. Unfortunately remote_start_remote() eventually calls
6137 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6138 around this. Eventually a mechanism that allows
6139 wait_for_inferior() to expect/get timeouts will be
6140 implemented. */
6141 rs->wait_forever_enabled_p = false;
6142 }
6143
6144 /* First delete any symbols previously loaded from shared libraries. */
6145 no_shared_libraries (NULL, 0);
6146
6147 /* Start the remote connection. If error() or QUIT, discard this
6148 target (we'd otherwise be in an inconsistent state) and then
6149 propogate the error on up the exception chain. This ensures that
6150 the caller doesn't stumble along blindly assuming that the
6151 function succeeded. The CLI doesn't have this problem but other
6152 UI's, such as MI do.
6153
6154 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6155 this function should return an error indication letting the
6156 caller restore the previous state. Unfortunately the command
6157 ``target remote'' is directly wired to this function making that
6158 impossible. On a positive note, the CLI side of this problem has
6159 been fixed - the function set_cmd_context() makes it possible for
6160 all the ``target ....'' commands to share a common callback
6161 function. See cli-dump.c. */
6162 {
6163
6164 try
6165 {
6166 remote->start_remote (from_tty, extended_p);
6167 }
6168 catch (const gdb_exception &ex)
6169 {
6170 /* Pop the partially set up target - unless something else did
6171 already before throwing the exception. */
6172 if (ex.error != TARGET_CLOSE_ERROR)
6173 remote_unpush_target (remote);
6174 throw;
6175 }
6176 }
6177
6178 remote_btrace_reset (rs);
6179
6180 if (target_async_permitted)
6181 rs->wait_forever_enabled_p = true;
6182 }
6183
6184 /* Determine if WS represents a fork status. */
6185
6186 static bool
6187 is_fork_status (target_waitkind kind)
6188 {
6189 return (kind == TARGET_WAITKIND_FORKED
6190 || kind == TARGET_WAITKIND_VFORKED);
6191 }
6192
6193 /* Return a reference to the field where a pending child status, if
6194 there's one, is recorded. If there's no child event pending, the
6195 returned waitstatus has TARGET_WAITKIND_IGNORE kind. */
6196
6197 static const target_waitstatus &
6198 thread_pending_status (struct thread_info *thread)
6199 {
6200 return (thread->has_pending_waitstatus ()
6201 ? thread->pending_waitstatus ()
6202 : thread->pending_follow);
6203 }
6204
6205 /* Return THREAD's pending status if it is a pending fork/vfork (but
6206 not clone) parent, else return nullptr. */
6207
6208 static const target_waitstatus *
6209 thread_pending_fork_status (struct thread_info *thread)
6210 {
6211 const target_waitstatus &ws = thread_pending_status (thread);
6212
6213 if (!is_fork_status (ws.kind ()))
6214 return nullptr;
6215
6216 return &ws;
6217 }
6218
6219 /* Return THREAD's pending status if is is a pending fork/vfork/clone
6220 event, else return nullptr. */
6221
6222 static const target_waitstatus *
6223 thread_pending_child_status (thread_info *thread)
6224 {
6225 const target_waitstatus &ws = thread_pending_status (thread);
6226
6227 if (!is_new_child_status (ws.kind ()))
6228 return nullptr;
6229
6230 return &ws;
6231 }
6232
6233 /* Detach the specified process. */
6234
6235 void
6236 remote_target::remote_detach_pid (int pid)
6237 {
6238 struct remote_state *rs = get_remote_state ();
6239
6240 /* This should not be necessary, but the handling for D;PID in
6241 GDBserver versions prior to 8.2 incorrectly assumes that the
6242 selected process points to the same process we're detaching,
6243 leading to misbehavior (and possibly GDBserver crashing) when it
6244 does not. Since it's easy and cheap, work around it by forcing
6245 GDBserver to select GDB's current process. */
6246 set_general_process ();
6247
6248 if (m_features.remote_multi_process_p ())
6249 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6250 else
6251 strcpy (rs->buf.data (), "D");
6252
6253 putpkt (rs->buf);
6254 getpkt (&rs->buf);
6255
6256 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6257 ;
6258 else if (rs->buf[0] == '\0')
6259 error (_("Remote doesn't know how to detach"));
6260 else
6261 {
6262 /* It is possible that we have an unprocessed exit event for this
6263 pid. If this is the case then we can ignore the failure to detach
6264 and just pretend that the detach worked, as far as the user is
6265 concerned, the process exited immediately after the detach. */
6266 bool process_has_already_exited = false;
6267 remote_notif_get_pending_events (&notif_client_stop);
6268 for (stop_reply_up &reply : rs->stop_reply_queue)
6269 {
6270 if (reply->ptid.pid () != pid)
6271 continue;
6272
6273 enum target_waitkind kind = reply->ws.kind ();
6274 if (kind == TARGET_WAITKIND_EXITED
6275 || kind == TARGET_WAITKIND_SIGNALLED)
6276 {
6277 process_has_already_exited = true;
6278 remote_debug_printf
6279 ("detach failed, but process already exited");
6280 break;
6281 }
6282 }
6283
6284 if (!process_has_already_exited)
6285 error (_("can't detach process: %s"), (char *) rs->buf.data ());
6286 }
6287 }
6288
6289 /* This detaches a program to which we previously attached, using
6290 inferior_ptid to identify the process. After this is done, GDB
6291 can be used to debug some other program. We better not have left
6292 any breakpoints in the target program or it'll die when it hits
6293 one. */
6294
6295 void
6296 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6297 {
6298 int pid = inferior_ptid.pid ();
6299 struct remote_state *rs = get_remote_state ();
6300 int is_fork_parent;
6301
6302 if (!target_has_execution ())
6303 error (_("No process to detach from."));
6304
6305 target_announce_detach (from_tty);
6306
6307 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
6308 {
6309 /* If we're in breakpoints-always-inserted mode, or the inferior
6310 is running, we have to remove breakpoints before detaching.
6311 We don't do this in common code instead because not all
6312 targets support removing breakpoints while the target is
6313 running. The remote target / gdbserver does, though. */
6314 remove_breakpoints_inf (current_inferior ());
6315 }
6316
6317 /* Tell the remote target to detach. */
6318 remote_detach_pid (pid);
6319
6320 /* Exit only if this is the only active inferior. */
6321 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6322 gdb_puts (_("Ending remote debugging.\n"));
6323
6324 /* See if any thread of the inferior we are detaching has a pending fork
6325 status. In that case, we must detach from the child resulting from
6326 that fork. */
6327 for (thread_info *thread : inf->non_exited_threads ())
6328 {
6329 const target_waitstatus *ws = thread_pending_fork_status (thread);
6330
6331 if (ws == nullptr)
6332 continue;
6333
6334 remote_detach_pid (ws->child_ptid ().pid ());
6335 }
6336
6337 /* Check also for any pending fork events in the stop reply queue. */
6338 remote_notif_get_pending_events (&notif_client_stop);
6339 for (stop_reply_up &reply : rs->stop_reply_queue)
6340 {
6341 if (reply->ptid.pid () != pid)
6342 continue;
6343
6344 if (!is_fork_status (reply->ws.kind ()))
6345 continue;
6346
6347 remote_detach_pid (reply->ws.child_ptid ().pid ());
6348 }
6349
6350 thread_info *tp = this->find_thread (inferior_ptid);
6351
6352 /* Check to see if we are detaching a fork parent. Note that if we
6353 are detaching a fork child, tp == NULL. */
6354 is_fork_parent = (tp != NULL
6355 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6356
6357 /* If doing detach-on-fork, we don't mourn, because that will delete
6358 breakpoints that should be available for the followed inferior. */
6359 if (!is_fork_parent)
6360 {
6361 /* Save the pid as a string before mourning, since that will
6362 unpush the remote target, and we need the string after. */
6363 std::string infpid = target_pid_to_str (ptid_t (pid));
6364
6365 target_mourn_inferior (inferior_ptid);
6366 if (print_inferior_events)
6367 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6368 inf->num, infpid.c_str ());
6369 }
6370 else
6371 {
6372 switch_to_no_thread ();
6373 detach_inferior (current_inferior ());
6374 }
6375 }
6376
6377 void
6378 remote_target::detach (inferior *inf, int from_tty)
6379 {
6380 remote_detach_1 (inf, from_tty);
6381 }
6382
6383 void
6384 extended_remote_target::detach (inferior *inf, int from_tty)
6385 {
6386 remote_detach_1 (inf, from_tty);
6387 }
6388
6389 /* Target follow-fork function for remote targets. On entry, and
6390 at return, the current inferior is the fork parent.
6391
6392 Note that although this is currently only used for extended-remote,
6393 it is named remote_follow_fork in anticipation of using it for the
6394 remote target as well. */
6395
6396 void
6397 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6398 target_waitkind fork_kind, bool follow_child,
6399 bool detach_fork)
6400 {
6401 process_stratum_target::follow_fork (child_inf, child_ptid,
6402 fork_kind, follow_child, detach_fork);
6403
6404 if ((fork_kind == TARGET_WAITKIND_FORKED
6405 && m_features.remote_fork_event_p ())
6406 || (fork_kind == TARGET_WAITKIND_VFORKED
6407 && m_features.remote_vfork_event_p ()))
6408 {
6409 /* When following the parent and detaching the child, we detach
6410 the child here. For the case of following the child and
6411 detaching the parent, the detach is done in the target-
6412 independent follow fork code in infrun.c. We can't use
6413 target_detach when detaching an unfollowed child because
6414 the client side doesn't know anything about the child. */
6415 if (detach_fork && !follow_child)
6416 {
6417 /* Detach the fork child. */
6418 remote_detach_pid (child_ptid.pid ());
6419 }
6420 }
6421 }
6422
6423 void
6424 remote_target::follow_clone (ptid_t child_ptid)
6425 {
6426 remote_add_thread (child_ptid, false, false, false);
6427 }
6428
6429 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6430 in the program space of the new inferior. */
6431
6432 void
6433 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6434 const char *execd_pathname)
6435 {
6436 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6437
6438 /* We know that this is a target file name, so if it has the "target:"
6439 prefix we strip it off before saving it in the program space. */
6440 if (is_target_filename (execd_pathname))
6441 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6442
6443 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6444 }
6445
6446 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6447
6448 void
6449 remote_target::disconnect (const char *args, int from_tty)
6450 {
6451 if (args)
6452 error (_("Argument given to \"disconnect\" when remotely debugging."));
6453
6454 /* Make sure we unpush even the extended remote targets. Calling
6455 target_mourn_inferior won't unpush, and
6456 remote_target::mourn_inferior won't unpush if there is more than
6457 one inferior left. */
6458 remote_unpush_target (this);
6459
6460 if (from_tty)
6461 gdb_puts ("Ending remote debugging.\n");
6462 }
6463
6464 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6465 be chatty about it. */
6466
6467 void
6468 extended_remote_target::attach (const char *args, int from_tty)
6469 {
6470 struct remote_state *rs = get_remote_state ();
6471 int pid;
6472 char *wait_status = NULL;
6473
6474 pid = parse_pid_to_attach (args);
6475
6476 /* Remote PID can be freely equal to getpid, do not check it here the same
6477 way as in other targets. */
6478
6479 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6480 error (_("This target does not support attaching to a process"));
6481
6482 target_announce_attach (from_tty, pid);
6483
6484 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6485 putpkt (rs->buf);
6486 getpkt (&rs->buf);
6487
6488 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6489 {
6490 case PACKET_OK:
6491 if (!target_is_non_stop_p ())
6492 {
6493 /* Save the reply for later. */
6494 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6495 strcpy (wait_status, rs->buf.data ());
6496 }
6497 else if (strcmp (rs->buf.data (), "OK") != 0)
6498 error (_("Attaching to %s failed with: %s"),
6499 target_pid_to_str (ptid_t (pid)).c_str (),
6500 rs->buf.data ());
6501 break;
6502 case PACKET_UNKNOWN:
6503 error (_("This target does not support attaching to a process"));
6504 default:
6505 error (_("Attaching to %s failed"),
6506 target_pid_to_str (ptid_t (pid)).c_str ());
6507 }
6508
6509 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6510
6511 inferior_ptid = ptid_t (pid);
6512
6513 if (target_is_non_stop_p ())
6514 {
6515 /* Get list of threads. */
6516 update_thread_list ();
6517
6518 thread_info *thread = first_thread_of_inferior (current_inferior ());
6519 if (thread != nullptr)
6520 switch_to_thread (thread);
6521
6522 /* Invalidate our notion of the remote current thread. */
6523 record_currthread (rs, minus_one_ptid);
6524 }
6525 else
6526 {
6527 /* Now, if we have thread information, update the main thread's
6528 ptid. */
6529 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6530
6531 /* Add the main thread to the thread list. We add the thread
6532 silently in this case (the final true parameter). */
6533 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6534
6535 switch_to_thread (thr);
6536 }
6537
6538 /* Next, if the target can specify a description, read it. We do
6539 this before anything involving memory or registers. */
6540 target_find_description ();
6541
6542 if (!target_is_non_stop_p ())
6543 {
6544 /* Use the previously fetched status. */
6545 gdb_assert (wait_status != NULL);
6546
6547 struct notif_event *reply
6548 = remote_notif_parse (this, &notif_client_stop, wait_status);
6549
6550 push_stop_reply ((struct stop_reply *) reply);
6551 }
6552 else
6553 {
6554 gdb_assert (wait_status == NULL);
6555
6556 gdb_assert (target_can_async_p ());
6557 }
6558 }
6559
6560 /* Implementation of the to_post_attach method. */
6561
6562 void
6563 extended_remote_target::post_attach (int pid)
6564 {
6565 /* Get text, data & bss offsets. */
6566 get_offsets ();
6567
6568 /* In certain cases GDB might not have had the chance to start
6569 symbol lookup up until now. This could happen if the debugged
6570 binary is not using shared libraries, the vsyscall page is not
6571 present (on Linux) and the binary itself hadn't changed since the
6572 debugging process was started. */
6573 if (current_program_space->symfile_object_file != NULL)
6574 remote_check_symbols();
6575 }
6576
6577 \f
6578 /* Check for the availability of vCont. This function should also check
6579 the response. */
6580
6581 void
6582 remote_target::remote_vcont_probe ()
6583 {
6584 remote_state *rs = get_remote_state ();
6585 char *buf;
6586
6587 strcpy (rs->buf.data (), "vCont?");
6588 putpkt (rs->buf);
6589 getpkt (&rs->buf);
6590 buf = rs->buf.data ();
6591
6592 /* Make sure that the features we assume are supported. */
6593 if (startswith (buf, "vCont"))
6594 {
6595 char *p = &buf[5];
6596 int support_c, support_C;
6597
6598 rs->supports_vCont.s = 0;
6599 rs->supports_vCont.S = 0;
6600 support_c = 0;
6601 support_C = 0;
6602 rs->supports_vCont.t = 0;
6603 rs->supports_vCont.r = 0;
6604 while (p && *p == ';')
6605 {
6606 p++;
6607 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6608 rs->supports_vCont.s = 1;
6609 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6610 rs->supports_vCont.S = 1;
6611 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6612 support_c = 1;
6613 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6614 support_C = 1;
6615 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6616 rs->supports_vCont.t = 1;
6617 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6618 rs->supports_vCont.r = 1;
6619
6620 p = strchr (p, ';');
6621 }
6622
6623 /* If c, and C are not all supported, we can't use vCont. Clearing
6624 BUF will make packet_ok disable the packet. */
6625 if (!support_c || !support_C)
6626 buf[0] = 0;
6627 }
6628
6629 m_features.packet_ok (rs->buf, PACKET_vCont);
6630 }
6631
6632 /* Helper function for building "vCont" resumptions. Write a
6633 resumption to P. ENDP points to one-passed-the-end of the buffer
6634 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6635 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6636 resumed thread should be single-stepped and/or signalled. If PTID
6637 equals minus_one_ptid, then all threads are resumed; if PTID
6638 represents a process, then all threads of the process are
6639 resumed. */
6640
6641 char *
6642 remote_target::append_resumption (char *p, char *endp,
6643 ptid_t ptid, int step, gdb_signal siggnal)
6644 {
6645 struct remote_state *rs = get_remote_state ();
6646
6647 if (step && siggnal != GDB_SIGNAL_0)
6648 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6649 else if (step
6650 /* GDB is willing to range step. */
6651 && use_range_stepping
6652 /* Target supports range stepping. */
6653 && rs->supports_vCont.r
6654 /* We don't currently support range stepping multiple
6655 threads with a wildcard (though the protocol allows it,
6656 so stubs shouldn't make an active effort to forbid
6657 it). */
6658 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6659 {
6660 struct thread_info *tp;
6661
6662 if (ptid == minus_one_ptid)
6663 {
6664 /* If we don't know about the target thread's tid, then
6665 we're resuming magic_null_ptid (see caller). */
6666 tp = this->find_thread (magic_null_ptid);
6667 }
6668 else
6669 tp = this->find_thread (ptid);
6670 gdb_assert (tp != NULL);
6671
6672 if (tp->control.may_range_step)
6673 {
6674 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
6675
6676 p += xsnprintf (p, endp - p, ";r%s,%s",
6677 phex_nz (tp->control.step_range_start,
6678 addr_size),
6679 phex_nz (tp->control.step_range_end,
6680 addr_size));
6681 }
6682 else
6683 p += xsnprintf (p, endp - p, ";s");
6684 }
6685 else if (step)
6686 p += xsnprintf (p, endp - p, ";s");
6687 else if (siggnal != GDB_SIGNAL_0)
6688 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6689 else
6690 p += xsnprintf (p, endp - p, ";c");
6691
6692 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6693 {
6694 ptid_t nptid;
6695
6696 /* All (-1) threads of process. */
6697 nptid = ptid_t (ptid.pid (), -1);
6698
6699 p += xsnprintf (p, endp - p, ":");
6700 p = write_ptid (p, endp, nptid);
6701 }
6702 else if (ptid != minus_one_ptid)
6703 {
6704 p += xsnprintf (p, endp - p, ":");
6705 p = write_ptid (p, endp, ptid);
6706 }
6707
6708 return p;
6709 }
6710
6711 /* Clear the thread's private info on resume. */
6712
6713 static void
6714 resume_clear_thread_private_info (struct thread_info *thread)
6715 {
6716 if (thread->priv != NULL)
6717 {
6718 remote_thread_info *priv = get_remote_thread_info (thread);
6719
6720 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6721 priv->watch_data_address = 0;
6722 }
6723 }
6724
6725 /* Append a vCont continue-with-signal action for threads that have a
6726 non-zero stop signal. */
6727
6728 char *
6729 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6730 ptid_t ptid)
6731 {
6732 for (thread_info *thread : all_non_exited_threads (this, ptid))
6733 if (inferior_ptid != thread->ptid
6734 && thread->stop_signal () != GDB_SIGNAL_0)
6735 {
6736 p = append_resumption (p, endp, thread->ptid,
6737 0, thread->stop_signal ());
6738 thread->set_stop_signal (GDB_SIGNAL_0);
6739 resume_clear_thread_private_info (thread);
6740 }
6741
6742 return p;
6743 }
6744
6745 /* Set the target running, using the packets that use Hc
6746 (c/s/C/S). */
6747
6748 void
6749 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6750 gdb_signal siggnal)
6751 {
6752 struct remote_state *rs = get_remote_state ();
6753 char *buf;
6754
6755 rs->last_sent_signal = siggnal;
6756 rs->last_sent_step = step;
6757
6758 /* The c/s/C/S resume packets use Hc, so set the continue
6759 thread. */
6760 if (ptid == minus_one_ptid)
6761 set_continue_thread (any_thread_ptid);
6762 else
6763 set_continue_thread (ptid);
6764
6765 for (thread_info *thread : all_non_exited_threads (this))
6766 resume_clear_thread_private_info (thread);
6767
6768 buf = rs->buf.data ();
6769 if (::execution_direction == EXEC_REVERSE)
6770 {
6771 /* We don't pass signals to the target in reverse exec mode. */
6772 if (info_verbose && siggnal != GDB_SIGNAL_0)
6773 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6774 siggnal);
6775
6776 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6777 error (_("Remote reverse-step not supported."));
6778 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6779 error (_("Remote reverse-continue not supported."));
6780
6781 strcpy (buf, step ? "bs" : "bc");
6782 }
6783 else if (siggnal != GDB_SIGNAL_0)
6784 {
6785 buf[0] = step ? 'S' : 'C';
6786 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6787 buf[2] = tohex (((int) siggnal) & 0xf);
6788 buf[3] = '\0';
6789 }
6790 else
6791 strcpy (buf, step ? "s" : "c");
6792
6793 putpkt (buf);
6794 }
6795
6796 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6797 STEP, and SIGGNAL have the same meaning as in target_resume. This
6798 function returns non-zero iff it resumes the inferior.
6799
6800 This function issues a strict subset of all possible vCont commands
6801 at the moment. */
6802
6803 int
6804 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6805 enum gdb_signal siggnal)
6806 {
6807 struct remote_state *rs = get_remote_state ();
6808 char *p;
6809 char *endp;
6810
6811 /* No reverse execution actions defined for vCont. */
6812 if (::execution_direction == EXEC_REVERSE)
6813 return 0;
6814
6815 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6816 return 0;
6817
6818 p = rs->buf.data ();
6819 endp = p + get_remote_packet_size ();
6820
6821 /* If we could generate a wider range of packets, we'd have to worry
6822 about overflowing BUF. Should there be a generic
6823 "multi-part-packet" packet? */
6824
6825 p += xsnprintf (p, endp - p, "vCont");
6826
6827 if (scope_ptid == magic_null_ptid)
6828 {
6829 /* MAGIC_NULL_PTID means that we don't have any active threads,
6830 so we don't have any TID numbers the inferior will
6831 understand. Make sure to only send forms that do not specify
6832 a TID. */
6833 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6834 }
6835 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6836 {
6837 /* Resume all threads (of all processes, or of a single
6838 process), with preference for INFERIOR_PTID. This assumes
6839 inferior_ptid belongs to the set of all threads we are about
6840 to resume. */
6841 if (step || siggnal != GDB_SIGNAL_0)
6842 {
6843 /* Step inferior_ptid, with or without signal. */
6844 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6845 }
6846
6847 /* Also pass down any pending signaled resumption for other
6848 threads not the current. */
6849 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6850
6851 /* And continue others without a signal. */
6852 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6853 }
6854 else
6855 {
6856 /* Scheduler locking; resume only SCOPE_PTID. */
6857 append_resumption (p, endp, scope_ptid, step, siggnal);
6858 }
6859
6860 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6861 putpkt (rs->buf);
6862
6863 if (target_is_non_stop_p ())
6864 {
6865 /* In non-stop, the stub replies to vCont with "OK". The stop
6866 reply will be reported asynchronously by means of a `%Stop'
6867 notification. */
6868 getpkt (&rs->buf);
6869 if (strcmp (rs->buf.data (), "OK") != 0)
6870 error (_("Unexpected vCont reply in non-stop mode: %s"),
6871 rs->buf.data ());
6872 }
6873
6874 return 1;
6875 }
6876
6877 /* Tell the remote machine to resume. */
6878
6879 void
6880 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6881 {
6882 struct remote_state *rs = get_remote_state ();
6883
6884 /* When connected in non-stop mode, the core resumes threads
6885 individually. Resuming remote threads directly in target_resume
6886 would thus result in sending one packet per thread. Instead, to
6887 minimize roundtrip latency, here we just store the resume
6888 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6889 resumption will be done in remote_target::commit_resume, where we'll be
6890 able to do vCont action coalescing. */
6891 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6892 {
6893 remote_thread_info *remote_thr
6894 = get_remote_thread_info (inferior_thread ());
6895
6896 /* We don't expect the core to ask to resume an already resumed (from
6897 its point of view) thread. */
6898 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6899
6900 remote_thr->set_resumed_pending_vcont (step, siggnal);
6901
6902 /* There's actually nothing that says that the core can't
6903 request a wildcard resume in non-stop mode, though. It's
6904 just that we know it doesn't currently, so we don't bother
6905 with it. */
6906 gdb_assert (scope_ptid == inferior_ptid);
6907 return;
6908 }
6909
6910 commit_requested_thread_options ();
6911
6912 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6913 (explained in remote-notif.c:handle_notification) so
6914 remote_notif_process is not called. We need find a place where
6915 it is safe to start a 'vNotif' sequence. It is good to do it
6916 before resuming inferior, because inferior was stopped and no RSP
6917 traffic at that moment. */
6918 if (!target_is_non_stop_p ())
6919 remote_notif_process (rs->notif_state, &notif_client_stop);
6920
6921 rs->last_resume_exec_dir = ::execution_direction;
6922
6923 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6924 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6925 remote_resume_with_hc (scope_ptid, step, siggnal);
6926
6927 /* Update resumed state tracked by the remote target. */
6928 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6929 get_remote_thread_info (tp)->set_resumed ();
6930
6931 /* We've just told the target to resume. The remote server will
6932 wait for the inferior to stop, and then send a stop reply. In
6933 the mean time, we can't start another command/query ourselves
6934 because the stub wouldn't be ready to process it. This applies
6935 only to the base all-stop protocol, however. In non-stop (which
6936 only supports vCont), the stub replies with an "OK", and is
6937 immediate able to process further serial input. */
6938 if (!target_is_non_stop_p ())
6939 rs->waiting_for_stop_reply = 1;
6940 }
6941
6942 /* Private per-inferior info for target remote processes. */
6943
6944 struct remote_inferior : public private_inferior
6945 {
6946 /* Whether we can send a wildcard vCont for this process. */
6947 bool may_wildcard_vcont = true;
6948 };
6949
6950 /* Get the remote private inferior data associated to INF. */
6951
6952 static remote_inferior *
6953 get_remote_inferior (inferior *inf)
6954 {
6955 if (inf->priv == NULL)
6956 inf->priv.reset (new remote_inferior);
6957
6958 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6959 }
6960
6961 /* Class used to track the construction of a vCont packet in the
6962 outgoing packet buffer. This is used to send multiple vCont
6963 packets if we have more actions than would fit a single packet. */
6964
6965 class vcont_builder
6966 {
6967 public:
6968 explicit vcont_builder (remote_target *remote)
6969 : m_remote (remote)
6970 {
6971 restart ();
6972 }
6973
6974 void flush ();
6975 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6976
6977 private:
6978 void restart ();
6979
6980 /* The remote target. */
6981 remote_target *m_remote;
6982
6983 /* Pointer to the first action. P points here if no action has been
6984 appended yet. */
6985 char *m_first_action;
6986
6987 /* Where the next action will be appended. */
6988 char *m_p;
6989
6990 /* The end of the buffer. Must never write past this. */
6991 char *m_endp;
6992 };
6993
6994 /* Prepare the outgoing buffer for a new vCont packet. */
6995
6996 void
6997 vcont_builder::restart ()
6998 {
6999 struct remote_state *rs = m_remote->get_remote_state ();
7000
7001 m_p = rs->buf.data ();
7002 m_endp = m_p + m_remote->get_remote_packet_size ();
7003 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
7004 m_first_action = m_p;
7005 }
7006
7007 /* If the vCont packet being built has any action, send it to the
7008 remote end. */
7009
7010 void
7011 vcont_builder::flush ()
7012 {
7013 struct remote_state *rs;
7014
7015 if (m_p == m_first_action)
7016 return;
7017
7018 rs = m_remote->get_remote_state ();
7019 m_remote->putpkt (rs->buf);
7020 m_remote->getpkt (&rs->buf);
7021 if (strcmp (rs->buf.data (), "OK") != 0)
7022 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
7023 }
7024
7025 /* The largest action is range-stepping, with its two addresses. This
7026 is more than sufficient. If a new, bigger action is created, it'll
7027 quickly trigger a failed assertion in append_resumption (and we'll
7028 just bump this). */
7029 #define MAX_ACTION_SIZE 200
7030
7031 /* Append a new vCont action in the outgoing packet being built. If
7032 the action doesn't fit the packet along with previous actions, push
7033 what we've got so far to the remote end and start over a new vCont
7034 packet (with the new action). */
7035
7036 void
7037 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
7038 {
7039 char buf[MAX_ACTION_SIZE + 1];
7040
7041 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
7042 ptid, step, siggnal);
7043
7044 /* Check whether this new action would fit in the vCont packet along
7045 with previous actions. If not, send what we've got so far and
7046 start a new vCont packet. */
7047 size_t rsize = endp - buf;
7048 if (rsize > m_endp - m_p)
7049 {
7050 flush ();
7051 restart ();
7052
7053 /* Should now fit. */
7054 gdb_assert (rsize <= m_endp - m_p);
7055 }
7056
7057 memcpy (m_p, buf, rsize);
7058 m_p += rsize;
7059 *m_p = '\0';
7060 }
7061
7062 /* to_commit_resume implementation. */
7063
7064 void
7065 remote_target::commit_resumed ()
7066 {
7067 /* If connected in all-stop mode, we'd send the remote resume
7068 request directly from remote_resume. Likewise if
7069 reverse-debugging, as there are no defined vCont actions for
7070 reverse execution. */
7071 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
7072 return;
7073
7074 commit_requested_thread_options ();
7075
7076 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
7077 instead of resuming all threads of each process individually.
7078 However, if any thread of a process must remain halted, we can't
7079 send wildcard resumes and must send one action per thread.
7080
7081 Care must be taken to not resume threads/processes the server
7082 side already told us are stopped, but the core doesn't know about
7083 yet, because the events are still in the vStopped notification
7084 queue. For example:
7085
7086 #1 => vCont s:p1.1;c
7087 #2 <= OK
7088 #3 <= %Stopped T05 p1.1
7089 #4 => vStopped
7090 #5 <= T05 p1.2
7091 #6 => vStopped
7092 #7 <= OK
7093 #8 (infrun handles the stop for p1.1 and continues stepping)
7094 #9 => vCont s:p1.1;c
7095
7096 The last vCont above would resume thread p1.2 by mistake, because
7097 the server has no idea that the event for p1.2 had not been
7098 handled yet.
7099
7100 The server side must similarly ignore resume actions for the
7101 thread that has a pending %Stopped notification (and any other
7102 threads with events pending), until GDB acks the notification
7103 with vStopped. Otherwise, e.g., the following case is
7104 mishandled:
7105
7106 #1 => g (or any other packet)
7107 #2 <= [registers]
7108 #3 <= %Stopped T05 p1.2
7109 #4 => vCont s:p1.1;c
7110 #5 <= OK
7111
7112 Above, the server must not resume thread p1.2. GDB can't know
7113 that p1.2 stopped until it acks the %Stopped notification, and
7114 since from GDB's perspective all threads should be running, it
7115 sends a "c" action.
7116
7117 Finally, special care must also be given to handling fork/vfork
7118 events. A (v)fork event actually tells us that two processes
7119 stopped -- the parent and the child. Until we follow the fork,
7120 we must not resume the child. Therefore, if we have a pending
7121 fork follow, we must not send a global wildcard resume action
7122 (vCont;c). We can still send process-wide wildcards though. */
7123
7124 /* Start by assuming a global wildcard (vCont;c) is possible. */
7125 bool may_global_wildcard_vcont = true;
7126
7127 /* And assume every process is individually wildcard-able too. */
7128 for (inferior *inf : all_non_exited_inferiors (this))
7129 {
7130 remote_inferior *priv = get_remote_inferior (inf);
7131
7132 priv->may_wildcard_vcont = true;
7133 }
7134
7135 /* Check for any pending events (not reported or processed yet) and
7136 disable process and global wildcard resumes appropriately. */
7137 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
7138
7139 bool any_pending_vcont_resume = false;
7140
7141 for (thread_info *tp : all_non_exited_threads (this))
7142 {
7143 remote_thread_info *priv = get_remote_thread_info (tp);
7144
7145 /* If a thread of a process is not meant to be resumed, then we
7146 can't wildcard that process. */
7147 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
7148 {
7149 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
7150
7151 /* And if we can't wildcard a process, we can't wildcard
7152 everything either. */
7153 may_global_wildcard_vcont = false;
7154 continue;
7155 }
7156
7157 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
7158 any_pending_vcont_resume = true;
7159
7160 /* If a thread is the parent of an unfollowed fork/vfork/clone,
7161 then we can't do a global wildcard, as that would resume the
7162 pending child. */
7163 if (thread_pending_child_status (tp) != nullptr)
7164 may_global_wildcard_vcont = false;
7165 }
7166
7167 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7168 do. */
7169 if (!any_pending_vcont_resume)
7170 return;
7171
7172 /* Now let's build the vCont packet(s). Actions must be appended
7173 from narrower to wider scopes (thread -> process -> global). If
7174 we end up with too many actions for a single packet vcont_builder
7175 flushes the current vCont packet to the remote side and starts a
7176 new one. */
7177 struct vcont_builder vcont_builder (this);
7178
7179 /* Threads first. */
7180 for (thread_info *tp : all_non_exited_threads (this))
7181 {
7182 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7183
7184 /* If the thread was previously vCont-resumed, no need to send a specific
7185 action for it. If we didn't receive a resume request for it, don't
7186 send an action for it either. */
7187 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7188 continue;
7189
7190 gdb_assert (!thread_is_in_step_over_chain (tp));
7191
7192 /* We should never be commit-resuming a thread that has a stop reply.
7193 Otherwise, we would end up reporting a stop event for a thread while
7194 it is running on the remote target. */
7195 remote_state *rs = get_remote_state ();
7196 for (const auto &stop_reply : rs->stop_reply_queue)
7197 gdb_assert (stop_reply->ptid != tp->ptid);
7198
7199 const resumed_pending_vcont_info &info
7200 = remote_thr->resumed_pending_vcont_info ();
7201
7202 /* Check if we need to send a specific action for this thread. If not,
7203 it will be included in a wildcard resume instead. */
7204 if (info.step || info.sig != GDB_SIGNAL_0
7205 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7206 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7207
7208 remote_thr->set_resumed ();
7209 }
7210
7211 /* Now check whether we can send any process-wide wildcard. This is
7212 to avoid sending a global wildcard in the case nothing is
7213 supposed to be resumed. */
7214 bool any_process_wildcard = false;
7215
7216 for (inferior *inf : all_non_exited_inferiors (this))
7217 {
7218 if (get_remote_inferior (inf)->may_wildcard_vcont)
7219 {
7220 any_process_wildcard = true;
7221 break;
7222 }
7223 }
7224
7225 if (any_process_wildcard)
7226 {
7227 /* If all processes are wildcard-able, then send a single "c"
7228 action, otherwise, send an "all (-1) threads of process"
7229 continue action for each running process, if any. */
7230 if (may_global_wildcard_vcont)
7231 {
7232 vcont_builder.push_action (minus_one_ptid,
7233 false, GDB_SIGNAL_0);
7234 }
7235 else
7236 {
7237 for (inferior *inf : all_non_exited_inferiors (this))
7238 {
7239 if (get_remote_inferior (inf)->may_wildcard_vcont)
7240 {
7241 vcont_builder.push_action (ptid_t (inf->pid),
7242 false, GDB_SIGNAL_0);
7243 }
7244 }
7245 }
7246 }
7247
7248 vcont_builder.flush ();
7249 }
7250
7251 /* Implementation of target_has_pending_events. */
7252
7253 bool
7254 remote_target::has_pending_events ()
7255 {
7256 if (target_can_async_p ())
7257 {
7258 remote_state *rs = get_remote_state ();
7259
7260 if (rs->async_event_handler_marked ())
7261 return true;
7262
7263 /* Note that BUFCNT can be negative, indicating sticky
7264 error. */
7265 if (rs->remote_desc->bufcnt != 0)
7266 return true;
7267 }
7268 return false;
7269 }
7270
7271 \f
7272
7273 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7274 thread, all threads of a remote process, or all threads of all
7275 processes. */
7276
7277 void
7278 remote_target::remote_stop_ns (ptid_t ptid)
7279 {
7280 struct remote_state *rs = get_remote_state ();
7281 char *p = rs->buf.data ();
7282 char *endp = p + get_remote_packet_size ();
7283
7284 /* If any thread that needs to stop was resumed but pending a vCont
7285 resume, generate a phony stop_reply. However, first check
7286 whether the thread wasn't resumed with a signal. Generating a
7287 phony stop in that case would result in losing the signal. */
7288 bool needs_commit = false;
7289 for (thread_info *tp : all_non_exited_threads (this, ptid))
7290 {
7291 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7292
7293 if (remote_thr->get_resume_state ()
7294 == resume_state::RESUMED_PENDING_VCONT)
7295 {
7296 const resumed_pending_vcont_info &info
7297 = remote_thr->resumed_pending_vcont_info ();
7298 if (info.sig != GDB_SIGNAL_0)
7299 {
7300 /* This signal must be forwarded to the inferior. We
7301 could commit-resume just this thread, but its simpler
7302 to just commit-resume everything. */
7303 needs_commit = true;
7304 break;
7305 }
7306 }
7307 }
7308
7309 if (needs_commit)
7310 commit_resumed ();
7311 else
7312 for (thread_info *tp : all_non_exited_threads (this, ptid))
7313 {
7314 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7315
7316 if (remote_thr->get_resume_state ()
7317 == resume_state::RESUMED_PENDING_VCONT)
7318 {
7319 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7320 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7321 tp->ptid.lwp (),
7322 pulongest (tp->ptid.tid ()));
7323
7324 /* Check that the thread wasn't resumed with a signal.
7325 Generating a phony stop would result in losing the
7326 signal. */
7327 const resumed_pending_vcont_info &info
7328 = remote_thr->resumed_pending_vcont_info ();
7329 gdb_assert (info.sig == GDB_SIGNAL_0);
7330
7331 stop_reply *sr = new stop_reply ();
7332 sr->ptid = tp->ptid;
7333 sr->rs = rs;
7334 sr->ws.set_stopped (GDB_SIGNAL_0);
7335 sr->arch = tp->inf->arch ();
7336 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7337 sr->watch_data_address = 0;
7338 sr->core = 0;
7339 this->push_stop_reply (sr);
7340
7341 /* Pretend that this thread was actually resumed on the
7342 remote target, then stopped. If we leave it in the
7343 RESUMED_PENDING_VCONT state and the commit_resumed
7344 method is called while the stop reply is still in the
7345 queue, we'll end up reporting a stop event to the core
7346 for that thread while it is running on the remote
7347 target... that would be bad. */
7348 remote_thr->set_resumed ();
7349 }
7350 }
7351
7352 if (!rs->supports_vCont.t)
7353 error (_("Remote server does not support stopping threads"));
7354
7355 if (ptid == minus_one_ptid
7356 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7357 p += xsnprintf (p, endp - p, "vCont;t");
7358 else
7359 {
7360 ptid_t nptid;
7361
7362 p += xsnprintf (p, endp - p, "vCont;t:");
7363
7364 if (ptid.is_pid ())
7365 /* All (-1) threads of process. */
7366 nptid = ptid_t (ptid.pid (), -1);
7367 else
7368 {
7369 /* Small optimization: if we already have a stop reply for
7370 this thread, no use in telling the stub we want this
7371 stopped. */
7372 if (peek_stop_reply (ptid))
7373 return;
7374
7375 nptid = ptid;
7376 }
7377
7378 write_ptid (p, endp, nptid);
7379 }
7380
7381 /* In non-stop, we get an immediate OK reply. The stop reply will
7382 come in asynchronously by notification. */
7383 putpkt (rs->buf);
7384 getpkt (&rs->buf);
7385 if (strcmp (rs->buf.data (), "OK") != 0)
7386 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7387 rs->buf.data ());
7388 }
7389
7390 /* All-stop version of target_interrupt. Sends a break or a ^C to
7391 interrupt the remote target. It is undefined which thread of which
7392 process reports the interrupt. */
7393
7394 void
7395 remote_target::remote_interrupt_as ()
7396 {
7397 struct remote_state *rs = get_remote_state ();
7398
7399 rs->ctrlc_pending_p = 1;
7400
7401 /* If the inferior is stopped already, but the core didn't know
7402 about it yet, just ignore the request. The pending stop events
7403 will be collected in remote_wait. */
7404 if (stop_reply_queue_length () > 0)
7405 return;
7406
7407 /* Send interrupt_sequence to remote target. */
7408 send_interrupt_sequence ();
7409 }
7410
7411 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7412 the remote target. It is undefined which thread of which process
7413 reports the interrupt. Throws an error if the packet is not
7414 supported by the server. */
7415
7416 void
7417 remote_target::remote_interrupt_ns ()
7418 {
7419 struct remote_state *rs = get_remote_state ();
7420 char *p = rs->buf.data ();
7421 char *endp = p + get_remote_packet_size ();
7422
7423 xsnprintf (p, endp - p, "vCtrlC");
7424
7425 /* In non-stop, we get an immediate OK reply. The stop reply will
7426 come in asynchronously by notification. */
7427 putpkt (rs->buf);
7428 getpkt (&rs->buf);
7429
7430 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7431 {
7432 case PACKET_OK:
7433 break;
7434 case PACKET_UNKNOWN:
7435 error (_("No support for interrupting the remote target."));
7436 case PACKET_ERROR:
7437 error (_("Interrupting target failed: %s"), rs->buf.data ());
7438 }
7439 }
7440
7441 /* Implement the to_stop function for the remote targets. */
7442
7443 void
7444 remote_target::stop (ptid_t ptid)
7445 {
7446 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7447
7448 if (target_is_non_stop_p ())
7449 remote_stop_ns (ptid);
7450 else
7451 {
7452 /* We don't currently have a way to transparently pause the
7453 remote target in all-stop mode. Interrupt it instead. */
7454 remote_interrupt_as ();
7455 }
7456 }
7457
7458 /* Implement the to_interrupt function for the remote targets. */
7459
7460 void
7461 remote_target::interrupt ()
7462 {
7463 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7464
7465 if (target_is_non_stop_p ())
7466 remote_interrupt_ns ();
7467 else
7468 remote_interrupt_as ();
7469 }
7470
7471 /* Implement the to_pass_ctrlc function for the remote targets. */
7472
7473 void
7474 remote_target::pass_ctrlc ()
7475 {
7476 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7477
7478 struct remote_state *rs = get_remote_state ();
7479
7480 /* If we're starting up, we're not fully synced yet. Quit
7481 immediately. */
7482 if (rs->starting_up)
7483 quit ();
7484 /* If ^C has already been sent once, offer to disconnect. */
7485 else if (rs->ctrlc_pending_p)
7486 interrupt_query ();
7487 else
7488 target_interrupt ();
7489 }
7490
7491 /* Ask the user what to do when an interrupt is received. */
7492
7493 void
7494 remote_target::interrupt_query ()
7495 {
7496 struct remote_state *rs = get_remote_state ();
7497
7498 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7499 {
7500 if (query (_("The target is not responding to interrupt requests.\n"
7501 "Stop debugging it? ")))
7502 {
7503 remote_unpush_target (this);
7504 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7505 }
7506 }
7507 else
7508 {
7509 if (query (_("Interrupted while waiting for the program.\n"
7510 "Give up waiting? ")))
7511 quit ();
7512 }
7513 }
7514
7515 /* Enable/disable target terminal ownership. Most targets can use
7516 terminal groups to control terminal ownership. Remote targets are
7517 different in that explicit transfer of ownership to/from GDB/target
7518 is required. */
7519
7520 void
7521 remote_target::terminal_inferior ()
7522 {
7523 /* NOTE: At this point we could also register our selves as the
7524 recipient of all input. Any characters typed could then be
7525 passed on down to the target. */
7526 }
7527
7528 void
7529 remote_target::terminal_ours ()
7530 {
7531 }
7532
7533 static void
7534 remote_console_output (const char *msg)
7535 {
7536 const char *p;
7537
7538 for (p = msg; p[0] && p[1]; p += 2)
7539 {
7540 char tb[2];
7541 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7542
7543 tb[0] = c;
7544 tb[1] = 0;
7545 gdb_stdtarg->puts (tb);
7546 }
7547 gdb_stdtarg->flush ();
7548 }
7549
7550 /* Return the length of the stop reply queue. */
7551
7552 int
7553 remote_target::stop_reply_queue_length ()
7554 {
7555 remote_state *rs = get_remote_state ();
7556 return rs->stop_reply_queue.size ();
7557 }
7558
7559 static void
7560 remote_notif_stop_parse (remote_target *remote,
7561 const notif_client *self, const char *buf,
7562 struct notif_event *event)
7563 {
7564 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7565 }
7566
7567 static void
7568 remote_notif_stop_ack (remote_target *remote,
7569 const notif_client *self, const char *buf,
7570 struct notif_event *event)
7571 {
7572 struct stop_reply *stop_reply = (struct stop_reply *) event;
7573
7574 /* acknowledge */
7575 putpkt (remote, self->ack_command);
7576
7577 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7578 the notification. It was left in the queue because we need to
7579 acknowledge it and pull the rest of the notifications out. */
7580 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7581 remote->push_stop_reply (stop_reply);
7582 }
7583
7584 static int
7585 remote_notif_stop_can_get_pending_events (remote_target *remote,
7586 const notif_client *self)
7587 {
7588 /* We can't get pending events in remote_notif_process for
7589 notification stop, and we have to do this in remote_wait_ns
7590 instead. If we fetch all queued events from stub, remote stub
7591 may exit and we have no chance to process them back in
7592 remote_wait_ns. */
7593 remote_state *rs = remote->get_remote_state ();
7594 rs->mark_async_event_handler ();
7595 return 0;
7596 }
7597
7598 stop_reply::~stop_reply ()
7599 {
7600 for (cached_reg_t &reg : regcache)
7601 xfree (reg.data);
7602 }
7603
7604 static notif_event_up
7605 remote_notif_stop_alloc_reply ()
7606 {
7607 return notif_event_up (new struct stop_reply ());
7608 }
7609
7610 /* A client of notification Stop. */
7611
7612 const notif_client notif_client_stop =
7613 {
7614 "Stop",
7615 "vStopped",
7616 remote_notif_stop_parse,
7617 remote_notif_stop_ack,
7618 remote_notif_stop_can_get_pending_events,
7619 remote_notif_stop_alloc_reply,
7620 REMOTE_NOTIF_STOP,
7621 };
7622
7623 /* If CONTEXT contains any fork/vfork/clone child threads that have
7624 not been reported yet, remove them from the CONTEXT list. If such
7625 a thread exists it is because we are stopped at a fork/vfork/clone
7626 catchpoint and have not yet called follow_fork/follow_clone, which
7627 will set up the host-side data structures for the new child. */
7628
7629 void
7630 remote_target::remove_new_children (threads_listing_context *context)
7631 {
7632 const notif_client *notif = &notif_client_stop;
7633
7634 /* For any threads stopped at a (v)fork/clone event, remove the
7635 corresponding child threads from the CONTEXT list. */
7636 for (thread_info *thread : all_non_exited_threads (this))
7637 {
7638 const target_waitstatus *ws = thread_pending_child_status (thread);
7639
7640 if (ws == nullptr)
7641 continue;
7642
7643 context->remove_thread (ws->child_ptid ());
7644 }
7645
7646 /* Check for any pending (v)fork/clone events (not reported or
7647 processed yet) in process PID and remove those child threads from
7648 the CONTEXT list as well. */
7649 remote_notif_get_pending_events (notif);
7650 for (auto &event : get_remote_state ()->stop_reply_queue)
7651 if (is_new_child_status (event->ws.kind ()))
7652 context->remove_thread (event->ws.child_ptid ());
7653 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7654 context->remove_thread (event->ptid);
7655 }
7656
7657 /* Check whether any event pending in the vStopped queue would prevent a
7658 global or process wildcard vCont action. Set *may_global_wildcard to
7659 false if we can't do a global wildcard (vCont;c), and clear the event
7660 inferior's may_wildcard_vcont flag if we can't do a process-wide
7661 wildcard resume (vCont;c:pPID.-1). */
7662
7663 void
7664 remote_target::check_pending_events_prevent_wildcard_vcont
7665 (bool *may_global_wildcard)
7666 {
7667 const notif_client *notif = &notif_client_stop;
7668
7669 remote_notif_get_pending_events (notif);
7670 for (auto &event : get_remote_state ()->stop_reply_queue)
7671 {
7672 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7673 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7674 continue;
7675
7676 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7677 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7678 *may_global_wildcard = false;
7679
7680 /* This may be the first time we heard about this process.
7681 Regardless, we must not do a global wildcard resume, otherwise
7682 we'd resume this process too. */
7683 *may_global_wildcard = false;
7684 if (event->ptid != null_ptid)
7685 {
7686 inferior *inf = find_inferior_ptid (this, event->ptid);
7687 if (inf != NULL)
7688 get_remote_inferior (inf)->may_wildcard_vcont = false;
7689 }
7690 }
7691 }
7692
7693 /* Discard all pending stop replies of inferior INF. */
7694
7695 void
7696 remote_target::discard_pending_stop_replies (struct inferior *inf)
7697 {
7698 struct stop_reply *reply;
7699 struct remote_state *rs = get_remote_state ();
7700 struct remote_notif_state *rns = rs->notif_state;
7701
7702 /* This function can be notified when an inferior exists. When the
7703 target is not remote, the notification state is NULL. */
7704 if (rs->remote_desc == NULL)
7705 return;
7706
7707 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7708
7709 /* Discard the in-flight notification. */
7710 if (reply != NULL && reply->ptid.pid () == inf->pid)
7711 {
7712 /* Leave the notification pending, since the server expects that
7713 we acknowledge it with vStopped. But clear its contents, so
7714 that later on when we acknowledge it, we also discard it. */
7715 remote_debug_printf
7716 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7717 reply->ptid.to_string().c_str(),
7718 reply->ws.to_string ().c_str ());
7719 reply->ws.set_ignore ();
7720 }
7721
7722 /* Discard the stop replies we have already pulled with
7723 vStopped. */
7724 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7725 rs->stop_reply_queue.end (),
7726 [=] (const stop_reply_up &event)
7727 {
7728 return event->ptid.pid () == inf->pid;
7729 });
7730 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7731 remote_debug_printf
7732 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7733 (*it)->ptid.to_string().c_str(),
7734 (*it)->ws.to_string ().c_str ());
7735 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7736 }
7737
7738 /* Discard the stop replies for RS in stop_reply_queue. */
7739
7740 void
7741 remote_target::discard_pending_stop_replies_in_queue ()
7742 {
7743 remote_state *rs = get_remote_state ();
7744
7745 /* Discard the stop replies we have already pulled with
7746 vStopped. */
7747 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7748 rs->stop_reply_queue.end (),
7749 [=] (const stop_reply_up &event)
7750 {
7751 return event->rs == rs;
7752 });
7753 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7754 }
7755
7756 /* Remove the first reply in 'stop_reply_queue' which matches
7757 PTID. */
7758
7759 struct stop_reply *
7760 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7761 {
7762 remote_state *rs = get_remote_state ();
7763
7764 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7765 rs->stop_reply_queue.end (),
7766 [=] (const stop_reply_up &event)
7767 {
7768 return event->ptid.matches (ptid);
7769 });
7770 struct stop_reply *result;
7771 if (iter == rs->stop_reply_queue.end ())
7772 result = nullptr;
7773 else
7774 {
7775 result = iter->release ();
7776 rs->stop_reply_queue.erase (iter);
7777 }
7778
7779 if (notif_debug)
7780 gdb_printf (gdb_stdlog,
7781 "notif: discard queued event: 'Stop' in %s\n",
7782 ptid.to_string ().c_str ());
7783
7784 return result;
7785 }
7786
7787 /* Look for a queued stop reply belonging to PTID. If one is found,
7788 remove it from the queue, and return it. Returns NULL if none is
7789 found. If there are still queued events left to process, tell the
7790 event loop to get back to target_wait soon. */
7791
7792 struct stop_reply *
7793 remote_target::queued_stop_reply (ptid_t ptid)
7794 {
7795 remote_state *rs = get_remote_state ();
7796 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7797
7798 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7799 {
7800 /* There's still at least an event left. */
7801 rs->mark_async_event_handler ();
7802 }
7803
7804 return r;
7805 }
7806
7807 /* Push a fully parsed stop reply in the stop reply queue. Since we
7808 know that we now have at least one queued event left to pass to the
7809 core side, tell the event loop to get back to target_wait soon. */
7810
7811 void
7812 remote_target::push_stop_reply (struct stop_reply *new_event)
7813 {
7814 remote_state *rs = get_remote_state ();
7815 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7816
7817 if (notif_debug)
7818 gdb_printf (gdb_stdlog,
7819 "notif: push 'Stop' %s to queue %d\n",
7820 new_event->ptid.to_string ().c_str (),
7821 int (rs->stop_reply_queue.size ()));
7822
7823 /* Mark the pending event queue only if async mode is currently enabled.
7824 If async mode is not currently enabled, then, if it later becomes
7825 enabled, and there are events in this queue, we will mark the event
7826 token at that point, see remote_target::async. */
7827 if (target_is_async_p ())
7828 rs->mark_async_event_handler ();
7829 }
7830
7831 /* Returns true if we have a stop reply for PTID. */
7832
7833 int
7834 remote_target::peek_stop_reply (ptid_t ptid)
7835 {
7836 remote_state *rs = get_remote_state ();
7837 for (auto &event : rs->stop_reply_queue)
7838 if (ptid == event->ptid
7839 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7840 return 1;
7841 return 0;
7842 }
7843
7844 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7845 starting with P and ending with PEND matches PREFIX. */
7846
7847 static int
7848 strprefix (const char *p, const char *pend, const char *prefix)
7849 {
7850 for ( ; p < pend; p++, prefix++)
7851 if (*p != *prefix)
7852 return 0;
7853 return *prefix == '\0';
7854 }
7855
7856 /* Parse the stop reply in BUF. Either the function succeeds, and the
7857 result is stored in EVENT, or throws an error. */
7858
7859 void
7860 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7861 {
7862 remote_arch_state *rsa = NULL;
7863 ULONGEST addr;
7864 const char *p;
7865 int skipregs = 0;
7866
7867 event->ptid = null_ptid;
7868 event->rs = get_remote_state ();
7869 event->ws.set_ignore ();
7870 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7871 event->regcache.clear ();
7872 event->core = -1;
7873
7874 switch (buf[0])
7875 {
7876 case 'T': /* Status with PC, SP, FP, ... */
7877 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7878 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7879 ss = signal number
7880 n... = register number
7881 r... = register contents
7882 */
7883
7884 p = &buf[3]; /* after Txx */
7885 while (*p)
7886 {
7887 const char *p1;
7888 int fieldsize;
7889
7890 p1 = strchr (p, ':');
7891 if (p1 == NULL)
7892 error (_("Malformed packet(a) (missing colon): %s\n\
7893 Packet: '%s'\n"),
7894 p, buf);
7895 if (p == p1)
7896 error (_("Malformed packet(a) (missing register number): %s\n\
7897 Packet: '%s'\n"),
7898 p, buf);
7899
7900 /* Some "registers" are actually extended stop information.
7901 Note if you're adding a new entry here: GDB 7.9 and
7902 earlier assume that all register "numbers" that start
7903 with an hex digit are real register numbers. Make sure
7904 the server only sends such a packet if it knows the
7905 client understands it. */
7906
7907 if (strprefix (p, p1, "thread"))
7908 event->ptid = read_ptid (++p1, &p);
7909 else if (strprefix (p, p1, "syscall_entry"))
7910 {
7911 ULONGEST sysno;
7912
7913 p = unpack_varlen_hex (++p1, &sysno);
7914 event->ws.set_syscall_entry ((int) sysno);
7915 }
7916 else if (strprefix (p, p1, "syscall_return"))
7917 {
7918 ULONGEST sysno;
7919
7920 p = unpack_varlen_hex (++p1, &sysno);
7921 event->ws.set_syscall_return ((int) sysno);
7922 }
7923 else if (strprefix (p, p1, "watch")
7924 || strprefix (p, p1, "rwatch")
7925 || strprefix (p, p1, "awatch"))
7926 {
7927 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7928 p = unpack_varlen_hex (++p1, &addr);
7929 event->watch_data_address = (CORE_ADDR) addr;
7930 }
7931 else if (strprefix (p, p1, "swbreak"))
7932 {
7933 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7934
7935 /* Make sure the stub doesn't forget to indicate support
7936 with qSupported. */
7937 if (m_features.packet_support (PACKET_swbreak_feature)
7938 != PACKET_ENABLE)
7939 error (_("Unexpected swbreak stop reason"));
7940
7941 /* The value part is documented as "must be empty",
7942 though we ignore it, in case we ever decide to make
7943 use of it in a backward compatible way. */
7944 p = strchrnul (p1 + 1, ';');
7945 }
7946 else if (strprefix (p, p1, "hwbreak"))
7947 {
7948 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7949
7950 /* Make sure the stub doesn't forget to indicate support
7951 with qSupported. */
7952 if (m_features.packet_support (PACKET_hwbreak_feature)
7953 != PACKET_ENABLE)
7954 error (_("Unexpected hwbreak stop reason"));
7955
7956 /* See above. */
7957 p = strchrnul (p1 + 1, ';');
7958 }
7959 else if (strprefix (p, p1, "library"))
7960 {
7961 event->ws.set_loaded ();
7962 p = strchrnul (p1 + 1, ';');
7963 }
7964 else if (strprefix (p, p1, "replaylog"))
7965 {
7966 event->ws.set_no_history ();
7967 /* p1 will indicate "begin" or "end", but it makes
7968 no difference for now, so ignore it. */
7969 p = strchrnul (p1 + 1, ';');
7970 }
7971 else if (strprefix (p, p1, "core"))
7972 {
7973 ULONGEST c;
7974
7975 p = unpack_varlen_hex (++p1, &c);
7976 event->core = c;
7977 }
7978 else if (strprefix (p, p1, "fork"))
7979 event->ws.set_forked (read_ptid (++p1, &p));
7980 else if (strprefix (p, p1, "vfork"))
7981 event->ws.set_vforked (read_ptid (++p1, &p));
7982 else if (strprefix (p, p1, "clone"))
7983 event->ws.set_thread_cloned (read_ptid (++p1, &p));
7984 else if (strprefix (p, p1, "vforkdone"))
7985 {
7986 event->ws.set_vfork_done ();
7987 p = strchrnul (p1 + 1, ';');
7988 }
7989 else if (strprefix (p, p1, "exec"))
7990 {
7991 ULONGEST ignored;
7992 int pathlen;
7993
7994 /* Determine the length of the execd pathname. */
7995 p = unpack_varlen_hex (++p1, &ignored);
7996 pathlen = (p - p1) / 2;
7997
7998 /* Save the pathname for event reporting and for
7999 the next run command. */
8000 gdb::unique_xmalloc_ptr<char> pathname
8001 ((char *) xmalloc (pathlen + 1));
8002 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
8003 pathname.get ()[pathlen] = '\0';
8004
8005 /* This is freed during event handling. */
8006 event->ws.set_execd (std::move (pathname));
8007
8008 /* Skip the registers included in this packet, since
8009 they may be for an architecture different from the
8010 one used by the original program. */
8011 skipregs = 1;
8012 }
8013 else if (strprefix (p, p1, "create"))
8014 {
8015 event->ws.set_thread_created ();
8016 p = strchrnul (p1 + 1, ';');
8017 }
8018 else
8019 {
8020 ULONGEST pnum;
8021 const char *p_temp;
8022
8023 if (skipregs)
8024 {
8025 p = strchrnul (p1 + 1, ';');
8026 p++;
8027 continue;
8028 }
8029
8030 /* Maybe a real ``P'' register number. */
8031 p_temp = unpack_varlen_hex (p, &pnum);
8032 /* If the first invalid character is the colon, we got a
8033 register number. Otherwise, it's an unknown stop
8034 reason. */
8035 if (p_temp == p1)
8036 {
8037 /* If we haven't parsed the event's thread yet, find
8038 it now, in order to find the architecture of the
8039 reported expedited registers. */
8040 if (event->ptid == null_ptid)
8041 {
8042 /* If there is no thread-id information then leave
8043 the event->ptid as null_ptid. Later in
8044 process_stop_reply we will pick a suitable
8045 thread. */
8046 const char *thr = strstr (p1 + 1, ";thread:");
8047 if (thr != NULL)
8048 event->ptid = read_ptid (thr + strlen (";thread:"),
8049 NULL);
8050 }
8051
8052 if (rsa == NULL)
8053 {
8054 inferior *inf
8055 = (event->ptid == null_ptid
8056 ? NULL
8057 : find_inferior_ptid (this, event->ptid));
8058 /* If this is the first time we learn anything
8059 about this process, skip the registers
8060 included in this packet, since we don't yet
8061 know which architecture to use to parse them.
8062 We'll determine the architecture later when
8063 we process the stop reply and retrieve the
8064 target description, via
8065 remote_notice_new_inferior ->
8066 post_create_inferior. */
8067 if (inf == NULL)
8068 {
8069 p = strchrnul (p1 + 1, ';');
8070 p++;
8071 continue;
8072 }
8073
8074 event->arch = inf->arch ();
8075 rsa = event->rs->get_remote_arch_state (event->arch);
8076 }
8077
8078 packet_reg *reg
8079 = packet_reg_from_pnum (event->arch, rsa, pnum);
8080 cached_reg_t cached_reg;
8081
8082 if (reg == NULL)
8083 error (_("Remote sent bad register number %s: %s\n\
8084 Packet: '%s'\n"),
8085 hex_string (pnum), p, buf);
8086
8087 cached_reg.num = reg->regnum;
8088 cached_reg.data = (gdb_byte *)
8089 xmalloc (register_size (event->arch, reg->regnum));
8090
8091 p = p1 + 1;
8092 fieldsize = hex2bin (p, cached_reg.data,
8093 register_size (event->arch, reg->regnum));
8094 p += 2 * fieldsize;
8095 if (fieldsize < register_size (event->arch, reg->regnum))
8096 warning (_("Remote reply is too short: %s"), buf);
8097
8098 event->regcache.push_back (cached_reg);
8099 }
8100 else
8101 {
8102 /* Not a number. Silently skip unknown optional
8103 info. */
8104 p = strchrnul (p1 + 1, ';');
8105 }
8106 }
8107
8108 if (*p != ';')
8109 error (_("Remote register badly formatted: %s\nhere: %s"),
8110 buf, p);
8111 ++p;
8112 }
8113
8114 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
8115 break;
8116
8117 /* fall through */
8118 case 'S': /* Old style status, just signal only. */
8119 {
8120 int sig;
8121
8122 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
8123 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
8124 event->ws.set_stopped ((enum gdb_signal) sig);
8125 else
8126 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
8127 }
8128 break;
8129 case 'w': /* Thread exited. */
8130 {
8131 ULONGEST value;
8132
8133 p = unpack_varlen_hex (&buf[1], &value);
8134 event->ws.set_thread_exited (value);
8135 if (*p != ';')
8136 error (_("stop reply packet badly formatted: %s"), buf);
8137 event->ptid = read_ptid (++p, NULL);
8138 break;
8139 }
8140 case 'W': /* Target exited. */
8141 case 'X':
8142 {
8143 ULONGEST value;
8144
8145 /* GDB used to accept only 2 hex chars here. Stubs should
8146 only send more if they detect GDB supports multi-process
8147 support. */
8148 p = unpack_varlen_hex (&buf[1], &value);
8149
8150 if (buf[0] == 'W')
8151 {
8152 /* The remote process exited. */
8153 event->ws.set_exited (value);
8154 }
8155 else
8156 {
8157 /* The remote process exited with a signal. */
8158 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
8159 event->ws.set_signalled ((enum gdb_signal) value);
8160 else
8161 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
8162 }
8163
8164 /* If no process is specified, return null_ptid, and let the
8165 caller figure out the right process to use. */
8166 int pid = 0;
8167 if (*p == '\0')
8168 ;
8169 else if (*p == ';')
8170 {
8171 p++;
8172
8173 if (*p == '\0')
8174 ;
8175 else if (startswith (p, "process:"))
8176 {
8177 ULONGEST upid;
8178
8179 p += sizeof ("process:") - 1;
8180 unpack_varlen_hex (p, &upid);
8181 pid = upid;
8182 }
8183 else
8184 error (_("unknown stop reply packet: %s"), buf);
8185 }
8186 else
8187 error (_("unknown stop reply packet: %s"), buf);
8188 event->ptid = ptid_t (pid);
8189 }
8190 break;
8191 case 'N':
8192 event->ws.set_no_resumed ();
8193 event->ptid = minus_one_ptid;
8194 break;
8195 }
8196 }
8197
8198 /* When the stub wants to tell GDB about a new notification reply, it
8199 sends a notification (%Stop, for example). Those can come it at
8200 any time, hence, we have to make sure that any pending
8201 putpkt/getpkt sequence we're making is finished, before querying
8202 the stub for more events with the corresponding ack command
8203 (vStopped, for example). E.g., if we started a vStopped sequence
8204 immediately upon receiving the notification, something like this
8205 could happen:
8206
8207 1.1) --> Hg 1
8208 1.2) <-- OK
8209 1.3) --> g
8210 1.4) <-- %Stop
8211 1.5) --> vStopped
8212 1.6) <-- (registers reply to step #1.3)
8213
8214 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8215 query.
8216
8217 To solve this, whenever we parse a %Stop notification successfully,
8218 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8219 doing whatever we were doing:
8220
8221 2.1) --> Hg 1
8222 2.2) <-- OK
8223 2.3) --> g
8224 2.4) <-- %Stop
8225 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8226 2.5) <-- (registers reply to step #2.3)
8227
8228 Eventually after step #2.5, we return to the event loop, which
8229 notices there's an event on the
8230 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8231 associated callback --- the function below. At this point, we're
8232 always safe to start a vStopped sequence. :
8233
8234 2.6) --> vStopped
8235 2.7) <-- T05 thread:2
8236 2.8) --> vStopped
8237 2.9) --> OK
8238 */
8239
8240 void
8241 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8242 {
8243 struct remote_state *rs = get_remote_state ();
8244
8245 if (rs->notif_state->pending_event[nc->id] != NULL)
8246 {
8247 if (notif_debug)
8248 gdb_printf (gdb_stdlog,
8249 "notif: process: '%s' ack pending event\n",
8250 nc->name);
8251
8252 /* acknowledge */
8253 nc->ack (this, nc, rs->buf.data (),
8254 rs->notif_state->pending_event[nc->id]);
8255 rs->notif_state->pending_event[nc->id] = NULL;
8256
8257 while (1)
8258 {
8259 getpkt (&rs->buf);
8260 if (strcmp (rs->buf.data (), "OK") == 0)
8261 break;
8262 else
8263 remote_notif_ack (this, nc, rs->buf.data ());
8264 }
8265 }
8266 else
8267 {
8268 if (notif_debug)
8269 gdb_printf (gdb_stdlog,
8270 "notif: process: '%s' no pending reply\n",
8271 nc->name);
8272 }
8273 }
8274
8275 /* Wrapper around remote_target::remote_notif_get_pending_events to
8276 avoid having to export the whole remote_target class. */
8277
8278 void
8279 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8280 {
8281 remote->remote_notif_get_pending_events (nc);
8282 }
8283
8284 /* Called from process_stop_reply when the stop packet we are responding
8285 to didn't include a process-id or thread-id. STATUS is the stop event
8286 we are responding to.
8287
8288 It is the task of this function to select a suitable thread (or process)
8289 and return its ptid, this is the thread (or process) we will assume the
8290 stop event came from.
8291
8292 In some cases there isn't really any choice about which thread (or
8293 process) is selected, a basic remote with a single process containing a
8294 single thread might choose not to send any process-id or thread-id in
8295 its stop packets, this function will select and return the one and only
8296 thread.
8297
8298 However, if a target supports multiple threads (or processes) and still
8299 doesn't include a thread-id (or process-id) in its stop packet then
8300 first, this is a badly behaving target, and second, we're going to have
8301 to select a thread (or process) at random and use that. This function
8302 will print a warning to the user if it detects that there is the
8303 possibility that GDB is guessing which thread (or process) to
8304 report.
8305
8306 Note that this is called before GDB fetches the updated thread list from the
8307 target. So it's possible for the stop reply to be ambiguous and for GDB to
8308 not realize it. For example, if there's initially one thread, the target
8309 spawns a second thread, and then sends a stop reply without an id that
8310 concerns the first thread. GDB will assume the stop reply is about the
8311 first thread - the only thread it knows about - without printing a warning.
8312 Anyway, if the remote meant for the stop reply to be about the second thread,
8313 then it would be really broken, because GDB doesn't know about that thread
8314 yet. */
8315
8316 ptid_t
8317 remote_target::select_thread_for_ambiguous_stop_reply
8318 (const target_waitstatus &status)
8319 {
8320 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8321
8322 /* Some stop events apply to all threads in an inferior, while others
8323 only apply to a single thread. */
8324 bool process_wide_stop
8325 = (status.kind () == TARGET_WAITKIND_EXITED
8326 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8327
8328 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8329
8330 thread_info *first_resumed_thread = nullptr;
8331 bool ambiguous = false;
8332
8333 /* Consider all non-exited threads of the target, find the first resumed
8334 one. */
8335 for (thread_info *thr : all_non_exited_threads (this))
8336 {
8337 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8338
8339 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8340 continue;
8341
8342 if (first_resumed_thread == nullptr)
8343 first_resumed_thread = thr;
8344 else if (!process_wide_stop
8345 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8346 ambiguous = true;
8347 }
8348
8349 gdb_assert (first_resumed_thread != nullptr);
8350
8351 remote_debug_printf ("first resumed thread is %s",
8352 pid_to_str (first_resumed_thread->ptid).c_str ());
8353 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8354
8355 /* Warn if the remote target is sending ambiguous stop replies. */
8356 if (ambiguous)
8357 {
8358 static bool warned = false;
8359
8360 if (!warned)
8361 {
8362 /* If you are seeing this warning then the remote target has
8363 stopped without specifying a thread-id, but the target
8364 does have multiple threads (or inferiors), and so GDB is
8365 having to guess which thread stopped.
8366
8367 Examples of what might cause this are the target sending
8368 and 'S' stop packet, or a 'T' stop packet and not
8369 including a thread-id.
8370
8371 Additionally, the target might send a 'W' or 'X packet
8372 without including a process-id, when the target has
8373 multiple running inferiors. */
8374 if (process_wide_stop)
8375 warning (_("multi-inferior target stopped without "
8376 "sending a process-id, using first "
8377 "non-exited inferior"));
8378 else
8379 warning (_("multi-threaded target stopped without "
8380 "sending a thread-id, using first "
8381 "non-exited thread"));
8382 warned = true;
8383 }
8384 }
8385
8386 /* If this is a stop for all threads then don't use a particular threads
8387 ptid, instead create a new ptid where only the pid field is set. */
8388 if (process_wide_stop)
8389 return ptid_t (first_resumed_thread->ptid.pid ());
8390 else
8391 return first_resumed_thread->ptid;
8392 }
8393
8394 /* Called when it is decided that STOP_REPLY holds the info of the
8395 event that is to be returned to the core. This function always
8396 destroys STOP_REPLY. */
8397
8398 ptid_t
8399 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8400 struct target_waitstatus *status)
8401 {
8402 *status = stop_reply->ws;
8403 ptid_t ptid = stop_reply->ptid;
8404
8405 /* If no thread/process was reported by the stub then select a suitable
8406 thread/process. */
8407 if (ptid == null_ptid)
8408 ptid = select_thread_for_ambiguous_stop_reply (*status);
8409 gdb_assert (ptid != null_ptid);
8410
8411 if (status->kind () != TARGET_WAITKIND_EXITED
8412 && status->kind () != TARGET_WAITKIND_SIGNALLED
8413 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8414 {
8415 /* Expedited registers. */
8416 if (!stop_reply->regcache.empty ())
8417 {
8418 /* 'w' stop replies don't cary expedited registers (which
8419 wouldn't make any sense for a thread that is gone
8420 already). */
8421 gdb_assert (status->kind () != TARGET_WAITKIND_THREAD_EXITED);
8422
8423 struct regcache *regcache
8424 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8425
8426 for (cached_reg_t &reg : stop_reply->regcache)
8427 {
8428 regcache->raw_supply (reg.num, reg.data);
8429 xfree (reg.data);
8430 }
8431
8432 stop_reply->regcache.clear ();
8433 }
8434
8435 remote_notice_new_inferior (ptid, false);
8436 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8437 remote_thr->core = stop_reply->core;
8438 remote_thr->stop_reason = stop_reply->stop_reason;
8439 remote_thr->watch_data_address = stop_reply->watch_data_address;
8440
8441 if (target_is_non_stop_p ())
8442 {
8443 /* If the target works in non-stop mode, a stop-reply indicates that
8444 only this thread stopped. */
8445 remote_thr->set_not_resumed ();
8446 }
8447 else
8448 {
8449 /* If the target works in all-stop mode, a stop-reply indicates that
8450 all the target's threads stopped. */
8451 for (thread_info *tp : all_non_exited_threads (this))
8452 get_remote_thread_info (tp)->set_not_resumed ();
8453 }
8454 }
8455
8456 delete stop_reply;
8457 return ptid;
8458 }
8459
8460 /* The non-stop mode version of target_wait. */
8461
8462 ptid_t
8463 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8464 target_wait_flags options)
8465 {
8466 struct remote_state *rs = get_remote_state ();
8467 struct stop_reply *stop_reply;
8468 int ret;
8469 bool is_notif = false;
8470
8471 /* If in non-stop mode, get out of getpkt even if a
8472 notification is received. */
8473
8474 ret = getpkt (&rs->buf, false /* forever */, &is_notif);
8475 while (1)
8476 {
8477 if (ret != -1 && !is_notif)
8478 switch (rs->buf[0])
8479 {
8480 case 'E': /* Error of some sort. */
8481 /* We're out of sync with the target now. Did it continue
8482 or not? We can't tell which thread it was in non-stop,
8483 so just ignore this. */
8484 warning (_("Remote failure reply: %s"), rs->buf.data ());
8485 break;
8486 case 'O': /* Console output. */
8487 remote_console_output (&rs->buf[1]);
8488 break;
8489 default:
8490 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8491 break;
8492 }
8493
8494 /* Acknowledge a pending stop reply that may have arrived in the
8495 mean time. */
8496 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8497 remote_notif_get_pending_events (&notif_client_stop);
8498
8499 /* If indeed we noticed a stop reply, we're done. */
8500 stop_reply = queued_stop_reply (ptid);
8501 if (stop_reply != NULL)
8502 return process_stop_reply (stop_reply, status);
8503
8504 /* Still no event. If we're just polling for an event, then
8505 return to the event loop. */
8506 if (options & TARGET_WNOHANG)
8507 {
8508 status->set_ignore ();
8509 return minus_one_ptid;
8510 }
8511
8512 /* Otherwise do a blocking wait. */
8513 ret = getpkt (&rs->buf, true /* forever */, &is_notif);
8514 }
8515 }
8516
8517 /* Return the first resumed thread. */
8518
8519 static ptid_t
8520 first_remote_resumed_thread (remote_target *target)
8521 {
8522 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8523 if (tp->resumed ())
8524 return tp->ptid;
8525 return null_ptid;
8526 }
8527
8528 /* Wait until the remote machine stops, then return, storing status in
8529 STATUS just as `wait' would. */
8530
8531 ptid_t
8532 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8533 target_wait_flags options)
8534 {
8535 struct remote_state *rs = get_remote_state ();
8536 ptid_t event_ptid = null_ptid;
8537 char *buf;
8538 struct stop_reply *stop_reply;
8539
8540 again:
8541
8542 status->set_ignore ();
8543
8544 stop_reply = queued_stop_reply (ptid);
8545 if (stop_reply != NULL)
8546 {
8547 /* None of the paths that push a stop reply onto the queue should
8548 have set the waiting_for_stop_reply flag. */
8549 gdb_assert (!rs->waiting_for_stop_reply);
8550 event_ptid = process_stop_reply (stop_reply, status);
8551 }
8552 else
8553 {
8554 bool forever = ((options & TARGET_WNOHANG) == 0
8555 && rs->wait_forever_enabled_p);
8556
8557 if (!rs->waiting_for_stop_reply)
8558 {
8559 status->set_no_resumed ();
8560 return minus_one_ptid;
8561 }
8562
8563 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8564 _never_ wait for ever -> test on target_is_async_p().
8565 However, before we do that we need to ensure that the caller
8566 knows how to take the target into/out of async mode. */
8567 bool is_notif;
8568 int ret = getpkt (&rs->buf, forever, &is_notif);
8569
8570 /* GDB gets a notification. Return to core as this event is
8571 not interesting. */
8572 if (ret != -1 && is_notif)
8573 return minus_one_ptid;
8574
8575 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8576 return minus_one_ptid;
8577
8578 buf = rs->buf.data ();
8579
8580 /* Assume that the target has acknowledged Ctrl-C unless we receive
8581 an 'F' or 'O' packet. */
8582 if (buf[0] != 'F' && buf[0] != 'O')
8583 rs->ctrlc_pending_p = 0;
8584
8585 switch (buf[0])
8586 {
8587 case 'E': /* Error of some sort. */
8588 /* We're out of sync with the target now. Did it continue or
8589 not? Not is more likely, so report a stop. */
8590 rs->waiting_for_stop_reply = 0;
8591
8592 warning (_("Remote failure reply: %s"), buf);
8593 status->set_stopped (GDB_SIGNAL_0);
8594 break;
8595 case 'F': /* File-I/O request. */
8596 /* GDB may access the inferior memory while handling the File-I/O
8597 request, but we don't want GDB accessing memory while waiting
8598 for a stop reply. See the comments in putpkt_binary. Set
8599 waiting_for_stop_reply to 0 temporarily. */
8600 rs->waiting_for_stop_reply = 0;
8601 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8602 rs->ctrlc_pending_p = 0;
8603 /* GDB handled the File-I/O request, and the target is running
8604 again. Keep waiting for events. */
8605 rs->waiting_for_stop_reply = 1;
8606 break;
8607 case 'N': case 'T': case 'S': case 'X': case 'W': case 'w':
8608 {
8609 /* There is a stop reply to handle. */
8610 rs->waiting_for_stop_reply = 0;
8611
8612 stop_reply
8613 = (struct stop_reply *) remote_notif_parse (this,
8614 &notif_client_stop,
8615 rs->buf.data ());
8616
8617 event_ptid = process_stop_reply (stop_reply, status);
8618 break;
8619 }
8620 case 'O': /* Console output. */
8621 remote_console_output (buf + 1);
8622 break;
8623 case '\0':
8624 if (rs->last_sent_signal != GDB_SIGNAL_0)
8625 {
8626 /* Zero length reply means that we tried 'S' or 'C' and the
8627 remote system doesn't support it. */
8628 target_terminal::ours_for_output ();
8629 gdb_printf
8630 ("Can't send signals to this remote system. %s not sent.\n",
8631 gdb_signal_to_name (rs->last_sent_signal));
8632 rs->last_sent_signal = GDB_SIGNAL_0;
8633 target_terminal::inferior ();
8634
8635 strcpy (buf, rs->last_sent_step ? "s" : "c");
8636 putpkt (buf);
8637 break;
8638 }
8639 /* fallthrough */
8640 default:
8641 warning (_("Invalid remote reply: %s"), buf);
8642 break;
8643 }
8644 }
8645
8646 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8647 return minus_one_ptid;
8648 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8649 {
8650 /* Nothing interesting happened. If we're doing a non-blocking
8651 poll, we're done. Otherwise, go back to waiting. */
8652 if (options & TARGET_WNOHANG)
8653 return minus_one_ptid;
8654 else
8655 goto again;
8656 }
8657 else if (status->kind () != TARGET_WAITKIND_EXITED
8658 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8659 {
8660 if (event_ptid != null_ptid)
8661 record_currthread (rs, event_ptid);
8662 else
8663 event_ptid = first_remote_resumed_thread (this);
8664 }
8665 else
8666 {
8667 /* A process exit. Invalidate our notion of current thread. */
8668 record_currthread (rs, minus_one_ptid);
8669 /* It's possible that the packet did not include a pid. */
8670 if (event_ptid == null_ptid)
8671 event_ptid = first_remote_resumed_thread (this);
8672 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8673 if (event_ptid == null_ptid)
8674 event_ptid = magic_null_ptid;
8675 }
8676
8677 return event_ptid;
8678 }
8679
8680 /* Wait until the remote machine stops, then return, storing status in
8681 STATUS just as `wait' would. */
8682
8683 ptid_t
8684 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8685 target_wait_flags options)
8686 {
8687 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8688
8689 remote_state *rs = get_remote_state ();
8690
8691 /* Start by clearing the flag that asks for our wait method to be called,
8692 we'll mark it again at the end if needed. If the target is not in
8693 async mode then the async token should not be marked. */
8694 if (target_is_async_p ())
8695 rs->clear_async_event_handler ();
8696 else
8697 gdb_assert (!rs->async_event_handler_marked ());
8698
8699 ptid_t event_ptid;
8700
8701 if (target_is_non_stop_p ())
8702 event_ptid = wait_ns (ptid, status, options);
8703 else
8704 event_ptid = wait_as (ptid, status, options);
8705
8706 if (target_is_async_p ())
8707 {
8708 /* If there are events left in the queue, or unacknowledged
8709 notifications, then tell the event loop to call us again. */
8710 if (!rs->stop_reply_queue.empty ()
8711 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8712 rs->mark_async_event_handler ();
8713 }
8714
8715 return event_ptid;
8716 }
8717
8718 /* Fetch a single register using a 'p' packet. */
8719
8720 int
8721 remote_target::fetch_register_using_p (struct regcache *regcache,
8722 packet_reg *reg)
8723 {
8724 struct gdbarch *gdbarch = regcache->arch ();
8725 struct remote_state *rs = get_remote_state ();
8726 char *buf, *p;
8727 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8728 int i;
8729
8730 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8731 return 0;
8732
8733 if (reg->pnum == -1)
8734 return 0;
8735
8736 p = rs->buf.data ();
8737 *p++ = 'p';
8738 p += hexnumstr (p, reg->pnum);
8739 *p++ = '\0';
8740 putpkt (rs->buf);
8741 getpkt (&rs->buf);
8742
8743 buf = rs->buf.data ();
8744
8745 switch (m_features.packet_ok (rs->buf, PACKET_p))
8746 {
8747 case PACKET_OK:
8748 break;
8749 case PACKET_UNKNOWN:
8750 return 0;
8751 case PACKET_ERROR:
8752 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8753 gdbarch_register_name (regcache->arch (), reg->regnum),
8754 buf);
8755 }
8756
8757 /* If this register is unfetchable, tell the regcache. */
8758 if (buf[0] == 'x')
8759 {
8760 regcache->raw_supply (reg->regnum, NULL);
8761 return 1;
8762 }
8763
8764 /* Otherwise, parse and supply the value. */
8765 p = buf;
8766 i = 0;
8767 while (p[0] != 0)
8768 {
8769 if (p[1] == 0)
8770 error (_("fetch_register_using_p: early buf termination"));
8771
8772 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8773 p += 2;
8774 }
8775 regcache->raw_supply (reg->regnum, regp);
8776 return 1;
8777 }
8778
8779 /* Fetch the registers included in the target's 'g' packet. */
8780
8781 int
8782 remote_target::send_g_packet ()
8783 {
8784 struct remote_state *rs = get_remote_state ();
8785 int buf_len;
8786
8787 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8788 putpkt (rs->buf);
8789 getpkt (&rs->buf);
8790 if (packet_check_result (rs->buf) == PACKET_ERROR)
8791 error (_("Could not read registers; remote failure reply '%s'"),
8792 rs->buf.data ());
8793
8794 /* We can get out of synch in various cases. If the first character
8795 in the buffer is not a hex character, assume that has happened
8796 and try to fetch another packet to read. */
8797 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8798 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8799 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8800 && rs->buf[0] != 'x') /* New: unavailable register value. */
8801 {
8802 remote_debug_printf ("Bad register packet; fetching a new packet");
8803 getpkt (&rs->buf);
8804 }
8805
8806 buf_len = strlen (rs->buf.data ());
8807
8808 /* Sanity check the received packet. */
8809 if (buf_len % 2 != 0)
8810 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8811
8812 return buf_len / 2;
8813 }
8814
8815 void
8816 remote_target::process_g_packet (struct regcache *regcache)
8817 {
8818 struct gdbarch *gdbarch = regcache->arch ();
8819 struct remote_state *rs = get_remote_state ();
8820 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8821 int i, buf_len;
8822 char *p;
8823 char *regs;
8824
8825 buf_len = strlen (rs->buf.data ());
8826
8827 /* Further sanity checks, with knowledge of the architecture. */
8828 if (buf_len > 2 * rsa->sizeof_g_packet)
8829 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8830 "bytes): %s"),
8831 rsa->sizeof_g_packet, buf_len / 2,
8832 rs->buf.data ());
8833
8834 /* Save the size of the packet sent to us by the target. It is used
8835 as a heuristic when determining the max size of packets that the
8836 target can safely receive. */
8837 if (rsa->actual_register_packet_size == 0)
8838 rsa->actual_register_packet_size = buf_len;
8839
8840 /* If this is smaller than we guessed the 'g' packet would be,
8841 update our records. A 'g' reply that doesn't include a register's
8842 value implies either that the register is not available, or that
8843 the 'p' packet must be used. */
8844 if (buf_len < 2 * rsa->sizeof_g_packet)
8845 {
8846 long sizeof_g_packet = buf_len / 2;
8847
8848 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8849 {
8850 long offset = rsa->regs[i].offset;
8851 long reg_size = register_size (gdbarch, i);
8852
8853 if (rsa->regs[i].pnum == -1)
8854 continue;
8855
8856 if (offset >= sizeof_g_packet)
8857 rsa->regs[i].in_g_packet = 0;
8858 else if (offset + reg_size > sizeof_g_packet)
8859 error (_("Truncated register %d in remote 'g' packet"), i);
8860 else
8861 rsa->regs[i].in_g_packet = 1;
8862 }
8863
8864 /* Looks valid enough, we can assume this is the correct length
8865 for a 'g' packet. It's important not to adjust
8866 rsa->sizeof_g_packet if we have truncated registers otherwise
8867 this "if" won't be run the next time the method is called
8868 with a packet of the same size and one of the internal errors
8869 below will trigger instead. */
8870 rsa->sizeof_g_packet = sizeof_g_packet;
8871 }
8872
8873 regs = (char *) alloca (rsa->sizeof_g_packet);
8874
8875 /* Unimplemented registers read as all bits zero. */
8876 memset (regs, 0, rsa->sizeof_g_packet);
8877
8878 /* Reply describes registers byte by byte, each byte encoded as two
8879 hex characters. Suck them all up, then supply them to the
8880 register cacheing/storage mechanism. */
8881
8882 p = rs->buf.data ();
8883 for (i = 0; i < rsa->sizeof_g_packet; i++)
8884 {
8885 if (p[0] == 0 || p[1] == 0)
8886 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8887 internal_error (_("unexpected end of 'g' packet reply"));
8888
8889 if (p[0] == 'x' && p[1] == 'x')
8890 regs[i] = 0; /* 'x' */
8891 else
8892 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8893 p += 2;
8894 }
8895
8896 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8897 {
8898 struct packet_reg *r = &rsa->regs[i];
8899 long reg_size = register_size (gdbarch, i);
8900
8901 if (r->in_g_packet)
8902 {
8903 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8904 /* This shouldn't happen - we adjusted in_g_packet above. */
8905 internal_error (_("unexpected end of 'g' packet reply"));
8906 else if (rs->buf[r->offset * 2] == 'x')
8907 {
8908 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8909 /* The register isn't available, mark it as such (at
8910 the same time setting the value to zero). */
8911 regcache->raw_supply (r->regnum, NULL);
8912 }
8913 else
8914 regcache->raw_supply (r->regnum, regs + r->offset);
8915 }
8916 }
8917 }
8918
8919 void
8920 remote_target::fetch_registers_using_g (struct regcache *regcache)
8921 {
8922 send_g_packet ();
8923 process_g_packet (regcache);
8924 }
8925
8926 /* Make the remote selected traceframe match GDB's selected
8927 traceframe. */
8928
8929 void
8930 remote_target::set_remote_traceframe ()
8931 {
8932 int newnum;
8933 struct remote_state *rs = get_remote_state ();
8934
8935 if (rs->remote_traceframe_number == get_traceframe_number ())
8936 return;
8937
8938 /* Avoid recursion, remote_trace_find calls us again. */
8939 rs->remote_traceframe_number = get_traceframe_number ();
8940
8941 newnum = target_trace_find (tfind_number,
8942 get_traceframe_number (), 0, 0, NULL);
8943
8944 /* Should not happen. If it does, all bets are off. */
8945 if (newnum != get_traceframe_number ())
8946 warning (_("could not set remote traceframe"));
8947 }
8948
8949 void
8950 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8951 {
8952 struct gdbarch *gdbarch = regcache->arch ();
8953 struct remote_state *rs = get_remote_state ();
8954 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8955 int i;
8956
8957 set_remote_traceframe ();
8958 set_general_thread (regcache->ptid ());
8959
8960 if (regnum >= 0)
8961 {
8962 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8963
8964 gdb_assert (reg != NULL);
8965
8966 /* If this register might be in the 'g' packet, try that first -
8967 we are likely to read more than one register. If this is the
8968 first 'g' packet, we might be overly optimistic about its
8969 contents, so fall back to 'p'. */
8970 if (reg->in_g_packet)
8971 {
8972 fetch_registers_using_g (regcache);
8973 if (reg->in_g_packet)
8974 return;
8975 }
8976
8977 if (fetch_register_using_p (regcache, reg))
8978 return;
8979
8980 /* This register is not available. */
8981 regcache->raw_supply (reg->regnum, NULL);
8982
8983 return;
8984 }
8985
8986 fetch_registers_using_g (regcache);
8987
8988 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8989 if (!rsa->regs[i].in_g_packet)
8990 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8991 {
8992 /* This register is not available. */
8993 regcache->raw_supply (i, NULL);
8994 }
8995 }
8996
8997 /* Prepare to store registers. Since we may send them all (using a
8998 'G' request), we have to read out the ones we don't want to change
8999 first. */
9000
9001 void
9002 remote_target::prepare_to_store (struct regcache *regcache)
9003 {
9004 struct remote_state *rs = get_remote_state ();
9005 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9006 int i;
9007
9008 /* Make sure the entire registers array is valid. */
9009 switch (m_features.packet_support (PACKET_P))
9010 {
9011 case PACKET_DISABLE:
9012 case PACKET_SUPPORT_UNKNOWN:
9013 /* Make sure all the necessary registers are cached. */
9014 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9015 if (rsa->regs[i].in_g_packet)
9016 regcache->raw_update (rsa->regs[i].regnum);
9017 break;
9018 case PACKET_ENABLE:
9019 break;
9020 }
9021 }
9022
9023 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
9024 packet was not recognized. */
9025
9026 int
9027 remote_target::store_register_using_P (const struct regcache *regcache,
9028 packet_reg *reg)
9029 {
9030 struct gdbarch *gdbarch = regcache->arch ();
9031 struct remote_state *rs = get_remote_state ();
9032 /* Try storing a single register. */
9033 char *buf = rs->buf.data ();
9034 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
9035 char *p;
9036
9037 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
9038 return 0;
9039
9040 if (reg->pnum == -1)
9041 return 0;
9042
9043 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
9044 p = buf + strlen (buf);
9045 regcache->raw_collect (reg->regnum, regp);
9046 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
9047 putpkt (rs->buf);
9048 getpkt (&rs->buf);
9049
9050 switch (m_features.packet_ok (rs->buf, PACKET_P))
9051 {
9052 case PACKET_OK:
9053 return 1;
9054 case PACKET_ERROR:
9055 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
9056 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
9057 case PACKET_UNKNOWN:
9058 return 0;
9059 default:
9060 internal_error (_("Bad result from packet_ok"));
9061 }
9062 }
9063
9064 /* Store register REGNUM, or all registers if REGNUM == -1, from the
9065 contents of the register cache buffer. FIXME: ignores errors. */
9066
9067 void
9068 remote_target::store_registers_using_G (const struct regcache *regcache)
9069 {
9070 struct remote_state *rs = get_remote_state ();
9071 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
9072 gdb_byte *regs;
9073 char *p;
9074
9075 /* Extract all the registers in the regcache copying them into a
9076 local buffer. */
9077 {
9078 int i;
9079
9080 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
9081 memset (regs, 0, rsa->sizeof_g_packet);
9082 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
9083 {
9084 struct packet_reg *r = &rsa->regs[i];
9085
9086 if (r->in_g_packet)
9087 regcache->raw_collect (r->regnum, regs + r->offset);
9088 }
9089 }
9090
9091 /* Command describes registers byte by byte,
9092 each byte encoded as two hex characters. */
9093 p = rs->buf.data ();
9094 *p++ = 'G';
9095 bin2hex (regs, p, rsa->sizeof_g_packet);
9096 putpkt (rs->buf);
9097 getpkt (&rs->buf);
9098 if (packet_check_result (rs->buf) == PACKET_ERROR)
9099 error (_("Could not write registers; remote failure reply '%s'"),
9100 rs->buf.data ());
9101 }
9102
9103 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
9104 of the register cache buffer. FIXME: ignores errors. */
9105
9106 void
9107 remote_target::store_registers (struct regcache *regcache, int regnum)
9108 {
9109 struct gdbarch *gdbarch = regcache->arch ();
9110 struct remote_state *rs = get_remote_state ();
9111 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
9112 int i;
9113
9114 set_remote_traceframe ();
9115 set_general_thread (regcache->ptid ());
9116
9117 if (regnum >= 0)
9118 {
9119 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
9120
9121 gdb_assert (reg != NULL);
9122
9123 /* Always prefer to store registers using the 'P' packet if
9124 possible; we often change only a small number of registers.
9125 Sometimes we change a larger number; we'd need help from a
9126 higher layer to know to use 'G'. */
9127 if (store_register_using_P (regcache, reg))
9128 return;
9129
9130 /* For now, don't complain if we have no way to write the
9131 register. GDB loses track of unavailable registers too
9132 easily. Some day, this may be an error. We don't have
9133 any way to read the register, either... */
9134 if (!reg->in_g_packet)
9135 return;
9136
9137 store_registers_using_G (regcache);
9138 return;
9139 }
9140
9141 store_registers_using_G (regcache);
9142
9143 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
9144 if (!rsa->regs[i].in_g_packet)
9145 if (!store_register_using_P (regcache, &rsa->regs[i]))
9146 /* See above for why we do not issue an error here. */
9147 continue;
9148 }
9149 \f
9150
9151 /* Return the number of hex digits in num. */
9152
9153 static int
9154 hexnumlen (ULONGEST num)
9155 {
9156 int i;
9157
9158 for (i = 0; num != 0; i++)
9159 num >>= 4;
9160
9161 return std::max (i, 1);
9162 }
9163
9164 /* Set BUF to the minimum number of hex digits representing NUM. */
9165
9166 static int
9167 hexnumstr (char *buf, ULONGEST num)
9168 {
9169 int len = hexnumlen (num);
9170
9171 return hexnumnstr (buf, num, len);
9172 }
9173
9174
9175 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9176
9177 static int
9178 hexnumnstr (char *buf, ULONGEST num, int width)
9179 {
9180 int i;
9181
9182 buf[width] = '\0';
9183
9184 for (i = width - 1; i >= 0; i--)
9185 {
9186 buf[i] = "0123456789abcdef"[(num & 0xf)];
9187 num >>= 4;
9188 }
9189
9190 return width;
9191 }
9192
9193 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9194
9195 static CORE_ADDR
9196 remote_address_masked (CORE_ADDR addr)
9197 {
9198 unsigned int address_size = remote_address_size;
9199
9200 /* If "remoteaddresssize" was not set, default to target address size. */
9201 if (!address_size)
9202 address_size = gdbarch_addr_bit (current_inferior ()->arch ());
9203
9204 if (address_size > 0
9205 && address_size < (sizeof (ULONGEST) * 8))
9206 {
9207 /* Only create a mask when that mask can safely be constructed
9208 in a ULONGEST variable. */
9209 ULONGEST mask = 1;
9210
9211 mask = (mask << address_size) - 1;
9212 addr &= mask;
9213 }
9214 return addr;
9215 }
9216
9217 /* Determine whether the remote target supports binary downloading.
9218 This is accomplished by sending a no-op memory write of zero length
9219 to the target at the specified address. It does not suffice to send
9220 the whole packet, since many stubs strip the eighth bit and
9221 subsequently compute a wrong checksum, which causes real havoc with
9222 remote_write_bytes.
9223
9224 NOTE: This can still lose if the serial line is not eight-bit
9225 clean. In cases like this, the user should clear "remote
9226 X-packet". */
9227
9228 void
9229 remote_target::check_binary_download (CORE_ADDR addr)
9230 {
9231 struct remote_state *rs = get_remote_state ();
9232
9233 switch (m_features.packet_support (PACKET_X))
9234 {
9235 case PACKET_DISABLE:
9236 break;
9237 case PACKET_ENABLE:
9238 break;
9239 case PACKET_SUPPORT_UNKNOWN:
9240 {
9241 char *p;
9242
9243 p = rs->buf.data ();
9244 *p++ = 'X';
9245 p += hexnumstr (p, (ULONGEST) addr);
9246 *p++ = ',';
9247 p += hexnumstr (p, (ULONGEST) 0);
9248 *p++ = ':';
9249 *p = '\0';
9250
9251 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9252 getpkt (&rs->buf);
9253
9254 if (rs->buf[0] == '\0')
9255 {
9256 remote_debug_printf ("binary downloading NOT supported by target");
9257 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9258 }
9259 else
9260 {
9261 remote_debug_printf ("binary downloading supported by target");
9262 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9263 }
9264 break;
9265 }
9266 }
9267 }
9268
9269 /* Helper function to resize the payload in order to try to get a good
9270 alignment. We try to write an amount of data such that the next write will
9271 start on an address aligned on REMOTE_ALIGN_WRITES. */
9272
9273 static int
9274 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9275 {
9276 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9277 }
9278
9279 /* Write memory data directly to the remote machine.
9280 This does not inform the data cache; the data cache uses this.
9281 HEADER is the starting part of the packet.
9282 MEMADDR is the address in the remote memory space.
9283 MYADDR is the address of the buffer in our space.
9284 LEN_UNITS is the number of addressable units to write.
9285 UNIT_SIZE is the length in bytes of an addressable unit.
9286 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9287 should send data as binary ('X'), or hex-encoded ('M').
9288
9289 The function creates packet of the form
9290 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9291
9292 where encoding of <DATA> is terminated by PACKET_FORMAT.
9293
9294 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9295 are omitted.
9296
9297 Return the transferred status, error or OK (an
9298 'enum target_xfer_status' value). Save the number of addressable units
9299 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9300
9301 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9302 exchange between gdb and the stub could look like (?? in place of the
9303 checksum):
9304
9305 -> $m1000,4#??
9306 <- aaaabbbbccccdddd
9307
9308 -> $M1000,3:eeeeffffeeee#??
9309 <- OK
9310
9311 -> $m1000,4#??
9312 <- eeeeffffeeeedddd */
9313
9314 target_xfer_status
9315 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9316 const gdb_byte *myaddr,
9317 ULONGEST len_units,
9318 int unit_size,
9319 ULONGEST *xfered_len_units,
9320 char packet_format, int use_length)
9321 {
9322 struct remote_state *rs = get_remote_state ();
9323 char *p;
9324 char *plen = NULL;
9325 int plenlen = 0;
9326 int todo_units;
9327 int units_written;
9328 int payload_capacity_bytes;
9329 int payload_length_bytes;
9330
9331 if (packet_format != 'X' && packet_format != 'M')
9332 internal_error (_("remote_write_bytes_aux: bad packet format"));
9333
9334 if (len_units == 0)
9335 return TARGET_XFER_EOF;
9336
9337 payload_capacity_bytes = get_memory_write_packet_size ();
9338
9339 /* The packet buffer will be large enough for the payload;
9340 get_memory_packet_size ensures this. */
9341 rs->buf[0] = '\0';
9342
9343 /* Compute the size of the actual payload by subtracting out the
9344 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9345
9346 payload_capacity_bytes -= strlen ("$,:#NN");
9347 if (!use_length)
9348 /* The comma won't be used. */
9349 payload_capacity_bytes += 1;
9350 payload_capacity_bytes -= strlen (header);
9351 payload_capacity_bytes -= hexnumlen (memaddr);
9352
9353 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9354
9355 strcat (rs->buf.data (), header);
9356 p = rs->buf.data () + strlen (header);
9357
9358 /* Compute a best guess of the number of bytes actually transfered. */
9359 if (packet_format == 'X')
9360 {
9361 /* Best guess at number of bytes that will fit. */
9362 todo_units = std::min (len_units,
9363 (ULONGEST) payload_capacity_bytes / unit_size);
9364 if (use_length)
9365 payload_capacity_bytes -= hexnumlen (todo_units);
9366 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9367 }
9368 else
9369 {
9370 /* Number of bytes that will fit. */
9371 todo_units
9372 = std::min (len_units,
9373 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9374 if (use_length)
9375 payload_capacity_bytes -= hexnumlen (todo_units);
9376 todo_units = std::min (todo_units,
9377 (payload_capacity_bytes / unit_size) / 2);
9378 }
9379
9380 if (todo_units <= 0)
9381 internal_error (_("minimum packet size too small to write data"));
9382
9383 /* If we already need another packet, then try to align the end
9384 of this packet to a useful boundary. */
9385 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9386 todo_units = align_for_efficient_write (todo_units, memaddr);
9387
9388 /* Append "<memaddr>". */
9389 memaddr = remote_address_masked (memaddr);
9390 p += hexnumstr (p, (ULONGEST) memaddr);
9391
9392 if (use_length)
9393 {
9394 /* Append ",". */
9395 *p++ = ',';
9396
9397 /* Append the length and retain its location and size. It may need to be
9398 adjusted once the packet body has been created. */
9399 plen = p;
9400 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9401 p += plenlen;
9402 }
9403
9404 /* Append ":". */
9405 *p++ = ':';
9406 *p = '\0';
9407
9408 /* Append the packet body. */
9409 if (packet_format == 'X')
9410 {
9411 /* Binary mode. Send target system values byte by byte, in
9412 increasing byte addresses. Only escape certain critical
9413 characters. */
9414 payload_length_bytes =
9415 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9416 &units_written, payload_capacity_bytes);
9417
9418 /* If not all TODO units fit, then we'll need another packet. Make
9419 a second try to keep the end of the packet aligned. Don't do
9420 this if the packet is tiny. */
9421 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9422 {
9423 int new_todo_units;
9424
9425 new_todo_units = align_for_efficient_write (units_written, memaddr);
9426
9427 if (new_todo_units != units_written)
9428 payload_length_bytes =
9429 remote_escape_output (myaddr, new_todo_units, unit_size,
9430 (gdb_byte *) p, &units_written,
9431 payload_capacity_bytes);
9432 }
9433
9434 p += payload_length_bytes;
9435 if (use_length && units_written < todo_units)
9436 {
9437 /* Escape chars have filled up the buffer prematurely,
9438 and we have actually sent fewer units than planned.
9439 Fix-up the length field of the packet. Use the same
9440 number of characters as before. */
9441 plen += hexnumnstr (plen, (ULONGEST) units_written,
9442 plenlen);
9443 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9444 }
9445 }
9446 else
9447 {
9448 /* Normal mode: Send target system values byte by byte, in
9449 increasing byte addresses. Each byte is encoded as a two hex
9450 value. */
9451 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9452 units_written = todo_units;
9453 }
9454
9455 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9456 getpkt (&rs->buf);
9457
9458 if (rs->buf[0] == 'E')
9459 return TARGET_XFER_E_IO;
9460
9461 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9462 send fewer units than we'd planned. */
9463 *xfered_len_units = (ULONGEST) units_written;
9464 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9465 }
9466
9467 /* Write memory data directly to the remote machine.
9468 This does not inform the data cache; the data cache uses this.
9469 MEMADDR is the address in the remote memory space.
9470 MYADDR is the address of the buffer in our space.
9471 LEN is the number of bytes.
9472
9473 Return the transferred status, error or OK (an
9474 'enum target_xfer_status' value). Save the number of bytes
9475 transferred in *XFERED_LEN. Only transfer a single packet. */
9476
9477 target_xfer_status
9478 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9479 ULONGEST len, int unit_size,
9480 ULONGEST *xfered_len)
9481 {
9482 const char *packet_format = NULL;
9483
9484 /* Check whether the target supports binary download. */
9485 check_binary_download (memaddr);
9486
9487 switch (m_features.packet_support (PACKET_X))
9488 {
9489 case PACKET_ENABLE:
9490 packet_format = "X";
9491 break;
9492 case PACKET_DISABLE:
9493 packet_format = "M";
9494 break;
9495 case PACKET_SUPPORT_UNKNOWN:
9496 internal_error (_("remote_write_bytes: bad internal state"));
9497 default:
9498 internal_error (_("bad switch"));
9499 }
9500
9501 return remote_write_bytes_aux (packet_format,
9502 memaddr, myaddr, len, unit_size, xfered_len,
9503 packet_format[0], 1);
9504 }
9505
9506 /* Read memory data directly from the remote machine.
9507 This does not use the data cache; the data cache uses this.
9508 MEMADDR is the address in the remote memory space.
9509 MYADDR is the address of the buffer in our space.
9510 LEN_UNITS is the number of addressable memory units to read..
9511 UNIT_SIZE is the length in bytes of an addressable unit.
9512
9513 Return the transferred status, error or OK (an
9514 'enum target_xfer_status' value). Save the number of bytes
9515 transferred in *XFERED_LEN_UNITS.
9516
9517 See the comment of remote_write_bytes_aux for an example of
9518 memory read/write exchange between gdb and the stub. */
9519
9520 target_xfer_status
9521 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9522 ULONGEST len_units,
9523 int unit_size, ULONGEST *xfered_len_units)
9524 {
9525 struct remote_state *rs = get_remote_state ();
9526 int buf_size_bytes; /* Max size of packet output buffer. */
9527 char *p;
9528 int todo_units;
9529 int decoded_bytes;
9530
9531 buf_size_bytes = get_memory_read_packet_size ();
9532 /* The packet buffer will be large enough for the payload;
9533 get_memory_packet_size ensures this. */
9534
9535 /* Number of units that will fit. */
9536 todo_units = std::min (len_units,
9537 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9538
9539 /* Construct "m"<memaddr>","<len>". */
9540 memaddr = remote_address_masked (memaddr);
9541 p = rs->buf.data ();
9542 *p++ = 'm';
9543 p += hexnumstr (p, (ULONGEST) memaddr);
9544 *p++ = ',';
9545 p += hexnumstr (p, (ULONGEST) todo_units);
9546 *p = '\0';
9547 putpkt (rs->buf);
9548 getpkt (&rs->buf);
9549 if (rs->buf[0] == 'E'
9550 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9551 && rs->buf[3] == '\0')
9552 return TARGET_XFER_E_IO;
9553 /* Reply describes memory byte by byte, each byte encoded as two hex
9554 characters. */
9555 p = rs->buf.data ();
9556 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9557 /* Return what we have. Let higher layers handle partial reads. */
9558 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9559 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9560 }
9561
9562 /* Using the set of read-only target sections of remote, read live
9563 read-only memory.
9564
9565 For interface/parameters/return description see target.h,
9566 to_xfer_partial. */
9567
9568 target_xfer_status
9569 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9570 ULONGEST memaddr,
9571 ULONGEST len,
9572 int unit_size,
9573 ULONGEST *xfered_len)
9574 {
9575 const struct target_section *secp;
9576
9577 secp = target_section_by_addr (this, memaddr);
9578 if (secp != NULL
9579 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9580 {
9581 ULONGEST memend = memaddr + len;
9582
9583 const std::vector<target_section> *table
9584 = target_get_section_table (this);
9585 for (const target_section &p : *table)
9586 {
9587 if (memaddr >= p.addr)
9588 {
9589 if (memend <= p.endaddr)
9590 {
9591 /* Entire transfer is within this section. */
9592 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9593 xfered_len);
9594 }
9595 else if (memaddr >= p.endaddr)
9596 {
9597 /* This section ends before the transfer starts. */
9598 continue;
9599 }
9600 else
9601 {
9602 /* This section overlaps the transfer. Just do half. */
9603 len = p.endaddr - memaddr;
9604 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9605 xfered_len);
9606 }
9607 }
9608 }
9609 }
9610
9611 return TARGET_XFER_EOF;
9612 }
9613
9614 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9615 first if the requested memory is unavailable in traceframe.
9616 Otherwise, fall back to remote_read_bytes_1. */
9617
9618 target_xfer_status
9619 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9620 gdb_byte *myaddr, ULONGEST len, int unit_size,
9621 ULONGEST *xfered_len)
9622 {
9623 if (len == 0)
9624 return TARGET_XFER_EOF;
9625
9626 if (get_traceframe_number () != -1)
9627 {
9628 std::vector<mem_range> available;
9629
9630 /* If we fail to get the set of available memory, then the
9631 target does not support querying traceframe info, and so we
9632 attempt reading from the traceframe anyway (assuming the
9633 target implements the old QTro packet then). */
9634 if (traceframe_available_memory (&available, memaddr, len))
9635 {
9636 if (available.empty () || available[0].start != memaddr)
9637 {
9638 enum target_xfer_status res;
9639
9640 /* Don't read into the traceframe's available
9641 memory. */
9642 if (!available.empty ())
9643 {
9644 LONGEST oldlen = len;
9645
9646 len = available[0].start - memaddr;
9647 gdb_assert (len <= oldlen);
9648 }
9649
9650 /* This goes through the topmost target again. */
9651 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9652 len, unit_size, xfered_len);
9653 if (res == TARGET_XFER_OK)
9654 return TARGET_XFER_OK;
9655 else
9656 {
9657 /* No use trying further, we know some memory starting
9658 at MEMADDR isn't available. */
9659 *xfered_len = len;
9660 return (*xfered_len != 0) ?
9661 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9662 }
9663 }
9664
9665 /* Don't try to read more than how much is available, in
9666 case the target implements the deprecated QTro packet to
9667 cater for older GDBs (the target's knowledge of read-only
9668 sections may be outdated by now). */
9669 len = available[0].length;
9670 }
9671 }
9672
9673 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9674 }
9675
9676 \f
9677
9678 /* Sends a packet with content determined by the printf format string
9679 FORMAT and the remaining arguments, then gets the reply. Returns
9680 whether the packet was a success, a failure, or unknown. */
9681
9682 packet_result
9683 remote_target::remote_send_printf (const char *format, ...)
9684 {
9685 struct remote_state *rs = get_remote_state ();
9686 int max_size = get_remote_packet_size ();
9687 va_list ap;
9688
9689 va_start (ap, format);
9690
9691 rs->buf[0] = '\0';
9692 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9693
9694 va_end (ap);
9695
9696 if (size >= max_size)
9697 internal_error (_("Too long remote packet."));
9698
9699 if (putpkt (rs->buf) < 0)
9700 error (_("Communication problem with target."));
9701
9702 rs->buf[0] = '\0';
9703 getpkt (&rs->buf);
9704
9705 return packet_check_result (rs->buf);
9706 }
9707
9708 /* Flash writing can take quite some time. We'll set
9709 effectively infinite timeout for flash operations.
9710 In future, we'll need to decide on a better approach. */
9711 static const int remote_flash_timeout = 1000;
9712
9713 void
9714 remote_target::flash_erase (ULONGEST address, LONGEST length)
9715 {
9716 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
9717 enum packet_result ret;
9718 scoped_restore restore_timeout
9719 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9720
9721 ret = remote_send_printf ("vFlashErase:%s,%s",
9722 phex (address, addr_size),
9723 phex (length, 4));
9724 switch (ret)
9725 {
9726 case PACKET_UNKNOWN:
9727 error (_("Remote target does not support flash erase"));
9728 case PACKET_ERROR:
9729 error (_("Error erasing flash with vFlashErase packet"));
9730 default:
9731 break;
9732 }
9733 }
9734
9735 target_xfer_status
9736 remote_target::remote_flash_write (ULONGEST address,
9737 ULONGEST length, ULONGEST *xfered_len,
9738 const gdb_byte *data)
9739 {
9740 scoped_restore restore_timeout
9741 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9742 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9743 xfered_len,'X', 0);
9744 }
9745
9746 void
9747 remote_target::flash_done ()
9748 {
9749 int ret;
9750
9751 scoped_restore restore_timeout
9752 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9753
9754 ret = remote_send_printf ("vFlashDone");
9755
9756 switch (ret)
9757 {
9758 case PACKET_UNKNOWN:
9759 error (_("Remote target does not support vFlashDone"));
9760 case PACKET_ERROR:
9761 error (_("Error finishing flash operation"));
9762 default:
9763 break;
9764 }
9765 }
9766
9767 \f
9768 /* Stuff for dealing with the packets which are part of this protocol.
9769 See comment at top of file for details. */
9770
9771 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9772 error to higher layers. Called when a serial error is detected.
9773 The exception message is STRING, followed by a colon and a blank,
9774 the system error message for errno at function entry and final dot
9775 for output compatibility with throw_perror_with_name. */
9776
9777 static void
9778 unpush_and_perror (remote_target *target, const char *string)
9779 {
9780 int saved_errno = errno;
9781
9782 remote_unpush_target (target);
9783 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9784 safe_strerror (saved_errno));
9785 }
9786
9787 /* Read a single character from the remote end. The current quit
9788 handler is overridden to avoid quitting in the middle of packet
9789 sequence, as that would break communication with the remote server.
9790 See remote_serial_quit_handler for more detail. */
9791
9792 int
9793 remote_target::readchar (int timeout)
9794 {
9795 int ch;
9796 struct remote_state *rs = get_remote_state ();
9797
9798 {
9799 scoped_restore restore_quit_target
9800 = make_scoped_restore (&curr_quit_handler_target, this);
9801 scoped_restore restore_quit
9802 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9803
9804 rs->got_ctrlc_during_io = 0;
9805
9806 ch = serial_readchar (rs->remote_desc, timeout);
9807
9808 if (rs->got_ctrlc_during_io)
9809 set_quit_flag ();
9810 }
9811
9812 if (ch >= 0)
9813 return ch;
9814
9815 switch ((enum serial_rc) ch)
9816 {
9817 case SERIAL_EOF:
9818 remote_unpush_target (this);
9819 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9820 /* no return */
9821 case SERIAL_ERROR:
9822 unpush_and_perror (this, _("Remote communication error. "
9823 "Target disconnected"));
9824 /* no return */
9825 case SERIAL_TIMEOUT:
9826 break;
9827 }
9828 return ch;
9829 }
9830
9831 /* Wrapper for serial_write that closes the target and throws if
9832 writing fails. The current quit handler is overridden to avoid
9833 quitting in the middle of packet sequence, as that would break
9834 communication with the remote server. See
9835 remote_serial_quit_handler for more detail. */
9836
9837 void
9838 remote_target::remote_serial_write (const char *str, int len)
9839 {
9840 struct remote_state *rs = get_remote_state ();
9841
9842 scoped_restore restore_quit_target
9843 = make_scoped_restore (&curr_quit_handler_target, this);
9844 scoped_restore restore_quit
9845 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9846
9847 rs->got_ctrlc_during_io = 0;
9848
9849 if (serial_write (rs->remote_desc, str, len))
9850 {
9851 unpush_and_perror (this, _("Remote communication error. "
9852 "Target disconnected"));
9853 }
9854
9855 if (rs->got_ctrlc_during_io)
9856 set_quit_flag ();
9857 }
9858
9859 /* Return a string representing an escaped version of BUF, of len N.
9860 E.g. \n is converted to \\n, \t to \\t, etc. */
9861
9862 static std::string
9863 escape_buffer (const char *buf, int n)
9864 {
9865 string_file stb;
9866
9867 stb.putstrn (buf, n, '\\');
9868 return stb.release ();
9869 }
9870
9871 int
9872 remote_target::putpkt (const char *buf)
9873 {
9874 return putpkt_binary (buf, strlen (buf));
9875 }
9876
9877 /* Wrapper around remote_target::putpkt to avoid exporting
9878 remote_target. */
9879
9880 int
9881 putpkt (remote_target *remote, const char *buf)
9882 {
9883 return remote->putpkt (buf);
9884 }
9885
9886 /* Send a packet to the remote machine, with error checking. The data
9887 of the packet is in BUF. The string in BUF can be at most
9888 get_remote_packet_size () - 5 to account for the $, # and checksum,
9889 and for a possible /0 if we are debugging (remote_debug) and want
9890 to print the sent packet as a string. */
9891
9892 int
9893 remote_target::putpkt_binary (const char *buf, int cnt)
9894 {
9895 struct remote_state *rs = get_remote_state ();
9896 int i;
9897 unsigned char csum = 0;
9898 gdb::def_vector<char> data (cnt + 6);
9899 char *buf2 = data.data ();
9900
9901 int ch;
9902 int tcount = 0;
9903 char *p;
9904
9905 /* Catch cases like trying to read memory or listing threads while
9906 we're waiting for a stop reply. The remote server wouldn't be
9907 ready to handle this request, so we'd hang and timeout. We don't
9908 have to worry about this in synchronous mode, because in that
9909 case it's not possible to issue a command while the target is
9910 running. This is not a problem in non-stop mode, because in that
9911 case, the stub is always ready to process serial input. */
9912 if (!target_is_non_stop_p ()
9913 && target_is_async_p ()
9914 && rs->waiting_for_stop_reply)
9915 {
9916 error (_("Cannot execute this command while the target is running.\n"
9917 "Use the \"interrupt\" command to stop the target\n"
9918 "and then try again."));
9919 }
9920
9921 /* Copy the packet into buffer BUF2, encapsulating it
9922 and giving it a checksum. */
9923
9924 p = buf2;
9925 *p++ = '$';
9926
9927 for (i = 0; i < cnt; i++)
9928 {
9929 csum += buf[i];
9930 *p++ = buf[i];
9931 }
9932 *p++ = '#';
9933 *p++ = tohex ((csum >> 4) & 0xf);
9934 *p++ = tohex (csum & 0xf);
9935
9936 /* Send it over and over until we get a positive ack. */
9937
9938 while (1)
9939 {
9940 if (remote_debug)
9941 {
9942 *p = '\0';
9943
9944 int len = (int) (p - buf2);
9945 int max_chars;
9946
9947 if (remote_packet_max_chars < 0)
9948 max_chars = len;
9949 else
9950 max_chars = remote_packet_max_chars;
9951
9952 std::string str
9953 = escape_buffer (buf2, std::min (len, max_chars));
9954
9955 if (len > max_chars)
9956 remote_debug_printf_nofunc
9957 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9958 len - max_chars);
9959 else
9960 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9961 }
9962 remote_serial_write (buf2, p - buf2);
9963
9964 /* If this is a no acks version of the remote protocol, send the
9965 packet and move on. */
9966 if (rs->noack_mode)
9967 break;
9968
9969 /* Read until either a timeout occurs (-2) or '+' is read.
9970 Handle any notification that arrives in the mean time. */
9971 while (1)
9972 {
9973 ch = readchar (remote_timeout);
9974
9975 switch (ch)
9976 {
9977 case '+':
9978 remote_debug_printf_nofunc ("Received Ack");
9979 return 1;
9980 case '-':
9981 remote_debug_printf_nofunc ("Received Nak");
9982 /* FALLTHROUGH */
9983 case SERIAL_TIMEOUT:
9984 tcount++;
9985 if (tcount > 3)
9986 return 0;
9987 break; /* Retransmit buffer. */
9988 case '$':
9989 {
9990 remote_debug_printf ("Packet instead of Ack, ignoring it");
9991 /* It's probably an old response sent because an ACK
9992 was lost. Gobble up the packet and ack it so it
9993 doesn't get retransmitted when we resend this
9994 packet. */
9995 skip_frame ();
9996 remote_serial_write ("+", 1);
9997 continue; /* Now, go look for +. */
9998 }
9999
10000 case '%':
10001 {
10002 int val;
10003
10004 /* If we got a notification, handle it, and go back to looking
10005 for an ack. */
10006 /* We've found the start of a notification. Now
10007 collect the data. */
10008 val = read_frame (&rs->buf);
10009 if (val >= 0)
10010 {
10011 remote_debug_printf_nofunc
10012 (" Notification received: %s",
10013 escape_buffer (rs->buf.data (), val).c_str ());
10014
10015 handle_notification (rs->notif_state, rs->buf.data ());
10016 /* We're in sync now, rewait for the ack. */
10017 tcount = 0;
10018 }
10019 else
10020 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10021 rs->buf.data ());
10022 continue;
10023 }
10024 /* fall-through */
10025 default:
10026 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
10027 rs->buf.data ());
10028 continue;
10029 }
10030 break; /* Here to retransmit. */
10031 }
10032
10033 #if 0
10034 /* This is wrong. If doing a long backtrace, the user should be
10035 able to get out next time we call QUIT, without anything as
10036 violent as interrupt_query. If we want to provide a way out of
10037 here without getting to the next QUIT, it should be based on
10038 hitting ^C twice as in remote_wait. */
10039 if (quit_flag)
10040 {
10041 quit_flag = 0;
10042 interrupt_query ();
10043 }
10044 #endif
10045 }
10046
10047 return 0;
10048 }
10049
10050 /* Come here after finding the start of a frame when we expected an
10051 ack. Do our best to discard the rest of this packet. */
10052
10053 void
10054 remote_target::skip_frame ()
10055 {
10056 int c;
10057
10058 while (1)
10059 {
10060 c = readchar (remote_timeout);
10061 switch (c)
10062 {
10063 case SERIAL_TIMEOUT:
10064 /* Nothing we can do. */
10065 return;
10066 case '#':
10067 /* Discard the two bytes of checksum and stop. */
10068 c = readchar (remote_timeout);
10069 if (c >= 0)
10070 c = readchar (remote_timeout);
10071
10072 return;
10073 case '*': /* Run length encoding. */
10074 /* Discard the repeat count. */
10075 c = readchar (remote_timeout);
10076 if (c < 0)
10077 return;
10078 break;
10079 default:
10080 /* A regular character. */
10081 break;
10082 }
10083 }
10084 }
10085
10086 /* Come here after finding the start of the frame. Collect the rest
10087 into *BUF, verifying the checksum, length, and handling run-length
10088 compression. NUL terminate the buffer. If there is not enough room,
10089 expand *BUF.
10090
10091 Returns -1 on error, number of characters in buffer (ignoring the
10092 trailing NULL) on success. (could be extended to return one of the
10093 SERIAL status indications). */
10094
10095 long
10096 remote_target::read_frame (gdb::char_vector *buf_p)
10097 {
10098 unsigned char csum;
10099 long bc;
10100 int c;
10101 char *buf = buf_p->data ();
10102 struct remote_state *rs = get_remote_state ();
10103
10104 csum = 0;
10105 bc = 0;
10106
10107 while (1)
10108 {
10109 c = readchar (remote_timeout);
10110 switch (c)
10111 {
10112 case SERIAL_TIMEOUT:
10113 remote_debug_printf ("Timeout in mid-packet, retrying");
10114 return -1;
10115
10116 case '$':
10117 remote_debug_printf ("Saw new packet start in middle of old one");
10118 return -1; /* Start a new packet, count retries. */
10119
10120 case '#':
10121 {
10122 unsigned char pktcsum;
10123 int check_0 = 0;
10124 int check_1 = 0;
10125
10126 buf[bc] = '\0';
10127
10128 check_0 = readchar (remote_timeout);
10129 if (check_0 >= 0)
10130 check_1 = readchar (remote_timeout);
10131
10132 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
10133 {
10134 remote_debug_printf ("Timeout in checksum, retrying");
10135 return -1;
10136 }
10137 else if (check_0 < 0 || check_1 < 0)
10138 {
10139 remote_debug_printf ("Communication error in checksum");
10140 return -1;
10141 }
10142
10143 /* Don't recompute the checksum; with no ack packets we
10144 don't have any way to indicate a packet retransmission
10145 is necessary. */
10146 if (rs->noack_mode)
10147 return bc;
10148
10149 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
10150 if (csum == pktcsum)
10151 return bc;
10152
10153 remote_debug_printf
10154 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
10155 pktcsum, csum, escape_buffer (buf, bc).c_str ());
10156
10157 /* Number of characters in buffer ignoring trailing
10158 NULL. */
10159 return -1;
10160 }
10161 case '*': /* Run length encoding. */
10162 {
10163 int repeat;
10164
10165 csum += c;
10166 c = readchar (remote_timeout);
10167 csum += c;
10168 repeat = c - ' ' + 3; /* Compute repeat count. */
10169
10170 /* The character before ``*'' is repeated. */
10171
10172 if (repeat > 0 && repeat <= 255 && bc > 0)
10173 {
10174 if (bc + repeat - 1 >= buf_p->size () - 1)
10175 {
10176 /* Make some more room in the buffer. */
10177 buf_p->resize (buf_p->size () + repeat);
10178 buf = buf_p->data ();
10179 }
10180
10181 memset (&buf[bc], buf[bc - 1], repeat);
10182 bc += repeat;
10183 continue;
10184 }
10185
10186 buf[bc] = '\0';
10187 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10188 return -1;
10189 }
10190 default:
10191 if (bc >= buf_p->size () - 1)
10192 {
10193 /* Make some more room in the buffer. */
10194 buf_p->resize (buf_p->size () * 2);
10195 buf = buf_p->data ();
10196 }
10197
10198 buf[bc++] = c;
10199 csum += c;
10200 continue;
10201 }
10202 }
10203 }
10204
10205 /* Set this to the maximum number of seconds to wait instead of waiting forever
10206 in target_wait(). If this timer times out, then it generates an error and
10207 the command is aborted. This replaces most of the need for timeouts in the
10208 GDB test suite, and makes it possible to distinguish between a hung target
10209 and one with slow communications. */
10210
10211 static int watchdog = 0;
10212 static void
10213 show_watchdog (struct ui_file *file, int from_tty,
10214 struct cmd_list_element *c, const char *value)
10215 {
10216 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10217 }
10218
10219 /* Read a packet from the remote machine, with error checking, and
10220 store it in *BUF. Resize *BUF if necessary to hold the result. If
10221 FOREVER, wait forever rather than timing out; this is used (in
10222 synchronous mode) to wait for a target that is is executing user
10223 code to stop. If FOREVER == false, this function is allowed to time
10224 out gracefully and return an indication of this to the caller.
10225 Otherwise return the number of bytes read. If IS_NOTIF is not
10226 NULL, then consider receiving a notification enough reason to
10227 return to the caller. In this case, *IS_NOTIF is an output boolean
10228 that indicates whether *BUF holds a notification or not (a regular
10229 packet). */
10230
10231 int
10232 remote_target::getpkt (gdb::char_vector *buf, bool forever, bool *is_notif)
10233 {
10234 struct remote_state *rs = get_remote_state ();
10235 int c;
10236 int tries;
10237 int timeout;
10238 int val = -1;
10239
10240 strcpy (buf->data (), "timeout");
10241
10242 if (forever)
10243 timeout = watchdog > 0 ? watchdog : -1;
10244 else if (is_notif != nullptr)
10245 timeout = 0; /* There should already be a char in the buffer. If
10246 not, bail out. */
10247 else
10248 timeout = remote_timeout;
10249
10250 #define MAX_TRIES 3
10251
10252 /* Process any number of notifications, and then return when
10253 we get a packet. */
10254 for (;;)
10255 {
10256 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10257 times. */
10258 for (tries = 1; tries <= MAX_TRIES; tries++)
10259 {
10260 /* This can loop forever if the remote side sends us
10261 characters continuously, but if it pauses, we'll get
10262 SERIAL_TIMEOUT from readchar because of timeout. Then
10263 we'll count that as a retry.
10264
10265 Note that even when forever is set, we will only wait
10266 forever prior to the start of a packet. After that, we
10267 expect characters to arrive at a brisk pace. They should
10268 show up within remote_timeout intervals. */
10269 do
10270 c = readchar (timeout);
10271 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10272
10273 if (c == SERIAL_TIMEOUT)
10274 {
10275 if (is_notif != nullptr)
10276 return -1; /* Don't complain, it's normal to not get
10277 anything in this case. */
10278
10279 if (forever) /* Watchdog went off? Kill the target. */
10280 {
10281 remote_unpush_target (this);
10282 throw_error (TARGET_CLOSE_ERROR,
10283 _("Watchdog timeout has expired. "
10284 "Target detached."));
10285 }
10286
10287 remote_debug_printf ("Timed out.");
10288 }
10289 else
10290 {
10291 /* We've found the start of a packet or notification.
10292 Now collect the data. */
10293 val = read_frame (buf);
10294 if (val >= 0)
10295 break;
10296 }
10297
10298 remote_serial_write ("-", 1);
10299 }
10300
10301 if (tries > MAX_TRIES)
10302 {
10303 /* We have tried hard enough, and just can't receive the
10304 packet/notification. Give up. */
10305 gdb_printf (_("Ignoring packet error, continuing...\n"));
10306
10307 /* Skip the ack char if we're in no-ack mode. */
10308 if (!rs->noack_mode)
10309 remote_serial_write ("+", 1);
10310 return -1;
10311 }
10312
10313 /* If we got an ordinary packet, return that to our caller. */
10314 if (c == '$')
10315 {
10316 if (remote_debug)
10317 {
10318 int max_chars;
10319
10320 if (remote_packet_max_chars < 0)
10321 max_chars = val;
10322 else
10323 max_chars = remote_packet_max_chars;
10324
10325 std::string str
10326 = escape_buffer (buf->data (),
10327 std::min (val, max_chars));
10328
10329 if (val > max_chars)
10330 remote_debug_printf_nofunc
10331 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10332 val - max_chars);
10333 else
10334 remote_debug_printf_nofunc ("Packet received: %s",
10335 str.c_str ());
10336 }
10337
10338 /* Skip the ack char if we're in no-ack mode. */
10339 if (!rs->noack_mode)
10340 remote_serial_write ("+", 1);
10341 if (is_notif != NULL)
10342 *is_notif = false;
10343 return val;
10344 }
10345
10346 /* If we got a notification, handle it, and go back to looking
10347 for a packet. */
10348 else
10349 {
10350 gdb_assert (c == '%');
10351
10352 remote_debug_printf_nofunc
10353 (" Notification received: %s",
10354 escape_buffer (buf->data (), val).c_str ());
10355
10356 if (is_notif != NULL)
10357 *is_notif = true;
10358
10359 handle_notification (rs->notif_state, buf->data ());
10360
10361 /* Notifications require no acknowledgement. */
10362
10363 if (is_notif != nullptr)
10364 return val;
10365 }
10366 }
10367 }
10368
10369 /* Kill any new fork children of inferior INF that haven't been
10370 processed by follow_fork. */
10371
10372 void
10373 remote_target::kill_new_fork_children (inferior *inf)
10374 {
10375 remote_state *rs = get_remote_state ();
10376 const notif_client *notif = &notif_client_stop;
10377
10378 /* Kill the fork child threads of any threads in inferior INF that are stopped
10379 at a fork event. */
10380 for (thread_info *thread : inf->non_exited_threads ())
10381 {
10382 const target_waitstatus *ws = thread_pending_fork_status (thread);
10383
10384 if (ws == nullptr)
10385 continue;
10386
10387 int child_pid = ws->child_ptid ().pid ();
10388 int res = remote_vkill (child_pid);
10389
10390 if (res != 0)
10391 error (_("Can't kill fork child process %d"), child_pid);
10392 }
10393
10394 /* Check for any pending fork events (not reported or processed yet)
10395 in inferior INF and kill those fork child threads as well. */
10396 remote_notif_get_pending_events (notif);
10397 for (auto &event : rs->stop_reply_queue)
10398 {
10399 if (event->ptid.pid () != inf->pid)
10400 continue;
10401
10402 if (!is_fork_status (event->ws.kind ()))
10403 continue;
10404
10405 int child_pid = event->ws.child_ptid ().pid ();
10406 int res = remote_vkill (child_pid);
10407
10408 if (res != 0)
10409 error (_("Can't kill fork child process %d"), child_pid);
10410 }
10411 }
10412
10413 \f
10414 /* Target hook to kill the current inferior. */
10415
10416 void
10417 remote_target::kill ()
10418 {
10419 int res = -1;
10420 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10421
10422 gdb_assert (inf != nullptr);
10423
10424 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10425 {
10426 /* If we're stopped while forking and we haven't followed yet,
10427 kill the child task. We need to do this before killing the
10428 parent task because if this is a vfork then the parent will
10429 be sleeping. */
10430 kill_new_fork_children (inf);
10431
10432 res = remote_vkill (inf->pid);
10433 if (res == 0)
10434 {
10435 target_mourn_inferior (inferior_ptid);
10436 return;
10437 }
10438 }
10439
10440 /* If we are in 'target remote' mode and we are killing the only
10441 inferior, then we will tell gdbserver to exit and unpush the
10442 target. */
10443 if (res == -1 && !m_features.remote_multi_process_p ()
10444 && number_of_live_inferiors (this) == 1)
10445 {
10446 remote_kill_k ();
10447
10448 /* We've killed the remote end, we get to mourn it. If we are
10449 not in extended mode, mourning the inferior also unpushes
10450 remote_ops from the target stack, which closes the remote
10451 connection. */
10452 target_mourn_inferior (inferior_ptid);
10453
10454 return;
10455 }
10456
10457 error (_("Can't kill process"));
10458 }
10459
10460 /* Send a kill request to the target using the 'vKill' packet. */
10461
10462 int
10463 remote_target::remote_vkill (int pid)
10464 {
10465 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10466 return -1;
10467
10468 remote_state *rs = get_remote_state ();
10469
10470 /* Tell the remote target to detach. */
10471 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10472 putpkt (rs->buf);
10473 getpkt (&rs->buf);
10474
10475 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10476 {
10477 case PACKET_OK:
10478 return 0;
10479 case PACKET_ERROR:
10480 return 1;
10481 case PACKET_UNKNOWN:
10482 return -1;
10483 default:
10484 internal_error (_("Bad result from packet_ok"));
10485 }
10486 }
10487
10488 /* Send a kill request to the target using the 'k' packet. */
10489
10490 void
10491 remote_target::remote_kill_k ()
10492 {
10493 /* Catch errors so the user can quit from gdb even when we
10494 aren't on speaking terms with the remote system. */
10495 try
10496 {
10497 putpkt ("k");
10498 }
10499 catch (const gdb_exception_error &ex)
10500 {
10501 if (ex.error == TARGET_CLOSE_ERROR)
10502 {
10503 /* If we got an (EOF) error that caused the target
10504 to go away, then we're done, that's what we wanted.
10505 "k" is susceptible to cause a premature EOF, given
10506 that the remote server isn't actually required to
10507 reply to "k", and it can happen that it doesn't
10508 even get to reply ACK to the "k". */
10509 return;
10510 }
10511
10512 /* Otherwise, something went wrong. We didn't actually kill
10513 the target. Just propagate the exception, and let the
10514 user or higher layers decide what to do. */
10515 throw;
10516 }
10517 }
10518
10519 void
10520 remote_target::mourn_inferior ()
10521 {
10522 struct remote_state *rs = get_remote_state ();
10523
10524 /* We're no longer interested in notification events of an inferior
10525 that exited or was killed/detached. */
10526 discard_pending_stop_replies (current_inferior ());
10527
10528 /* In 'target remote' mode with one inferior, we close the connection. */
10529 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10530 {
10531 remote_unpush_target (this);
10532 return;
10533 }
10534
10535 /* In case we got here due to an error, but we're going to stay
10536 connected. */
10537 rs->waiting_for_stop_reply = 0;
10538
10539 /* If the current general thread belonged to the process we just
10540 detached from or has exited, the remote side current general
10541 thread becomes undefined. Considering a case like this:
10542
10543 - We just got here due to a detach.
10544 - The process that we're detaching from happens to immediately
10545 report a global breakpoint being hit in non-stop mode, in the
10546 same thread we had selected before.
10547 - GDB attaches to this process again.
10548 - This event happens to be the next event we handle.
10549
10550 GDB would consider that the current general thread didn't need to
10551 be set on the stub side (with Hg), since for all it knew,
10552 GENERAL_THREAD hadn't changed.
10553
10554 Notice that although in all-stop mode, the remote server always
10555 sets the current thread to the thread reporting the stop event,
10556 that doesn't happen in non-stop mode; in non-stop, the stub *must
10557 not* change the current thread when reporting a breakpoint hit,
10558 due to the decoupling of event reporting and event handling.
10559
10560 To keep things simple, we always invalidate our notion of the
10561 current thread. */
10562 record_currthread (rs, minus_one_ptid);
10563
10564 /* Call common code to mark the inferior as not running. */
10565 generic_mourn_inferior ();
10566 }
10567
10568 bool
10569 extended_remote_target::supports_disable_randomization ()
10570 {
10571 return (m_features.packet_support (PACKET_QDisableRandomization)
10572 == PACKET_ENABLE);
10573 }
10574
10575 void
10576 remote_target::extended_remote_disable_randomization (int val)
10577 {
10578 struct remote_state *rs = get_remote_state ();
10579 char *reply;
10580
10581 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10582 "QDisableRandomization:%x", val);
10583 putpkt (rs->buf);
10584 reply = remote_get_noisy_reply ();
10585 if (*reply == '\0')
10586 error (_("Target does not support QDisableRandomization."));
10587 if (strcmp (reply, "OK") != 0)
10588 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10589 }
10590
10591 int
10592 remote_target::extended_remote_run (const std::string &args)
10593 {
10594 struct remote_state *rs = get_remote_state ();
10595 int len;
10596 const char *remote_exec_file = get_remote_exec_file ();
10597
10598 /* If the user has disabled vRun support, or we have detected that
10599 support is not available, do not try it. */
10600 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10601 return -1;
10602
10603 strcpy (rs->buf.data (), "vRun;");
10604 len = strlen (rs->buf.data ());
10605
10606 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10607 error (_("Remote file name too long for run packet"));
10608 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10609 strlen (remote_exec_file));
10610
10611 if (!args.empty ())
10612 {
10613 int i;
10614
10615 gdb_argv argv (args.c_str ());
10616 for (i = 0; argv[i] != NULL; i++)
10617 {
10618 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10619 error (_("Argument list too long for run packet"));
10620 rs->buf[len++] = ';';
10621 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10622 strlen (argv[i]));
10623 }
10624 }
10625
10626 rs->buf[len++] = '\0';
10627
10628 putpkt (rs->buf);
10629 getpkt (&rs->buf);
10630
10631 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10632 {
10633 case PACKET_OK:
10634 /* We have a wait response. All is well. */
10635 return 0;
10636 case PACKET_UNKNOWN:
10637 return -1;
10638 case PACKET_ERROR:
10639 if (remote_exec_file[0] == '\0')
10640 error (_("Running the default executable on the remote target failed; "
10641 "try \"set remote exec-file\"?"));
10642 else
10643 error (_("Running \"%s\" on the remote target failed"),
10644 remote_exec_file);
10645 default:
10646 gdb_assert_not_reached ("bad switch");
10647 }
10648 }
10649
10650 /* Helper function to send set/unset environment packets. ACTION is
10651 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10652 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10653 sent. */
10654
10655 void
10656 remote_target::send_environment_packet (const char *action,
10657 const char *packet,
10658 const char *value)
10659 {
10660 remote_state *rs = get_remote_state ();
10661
10662 /* Convert the environment variable to an hex string, which
10663 is the best format to be transmitted over the wire. */
10664 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10665 strlen (value));
10666
10667 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10668 "%s:%s", packet, encoded_value.c_str ());
10669
10670 putpkt (rs->buf);
10671 getpkt (&rs->buf);
10672 if (strcmp (rs->buf.data (), "OK") != 0)
10673 warning (_("Unable to %s environment variable '%s' on remote."),
10674 action, value);
10675 }
10676
10677 /* Helper function to handle the QEnvironment* packets. */
10678
10679 void
10680 remote_target::extended_remote_environment_support ()
10681 {
10682 remote_state *rs = get_remote_state ();
10683
10684 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10685 {
10686 putpkt ("QEnvironmentReset");
10687 getpkt (&rs->buf);
10688 if (strcmp (rs->buf.data (), "OK") != 0)
10689 warning (_("Unable to reset environment on remote."));
10690 }
10691
10692 gdb_environ *e = &current_inferior ()->environment;
10693
10694 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10695 != PACKET_DISABLE)
10696 {
10697 for (const std::string &el : e->user_set_env ())
10698 send_environment_packet ("set", "QEnvironmentHexEncoded",
10699 el.c_str ());
10700 }
10701
10702
10703 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10704 for (const std::string &el : e->user_unset_env ())
10705 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10706 }
10707
10708 /* Helper function to set the current working directory for the
10709 inferior in the remote target. */
10710
10711 void
10712 remote_target::extended_remote_set_inferior_cwd ()
10713 {
10714 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10715 {
10716 const std::string &inferior_cwd = current_inferior ()->cwd ();
10717 remote_state *rs = get_remote_state ();
10718
10719 if (!inferior_cwd.empty ())
10720 {
10721 std::string hexpath
10722 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10723 inferior_cwd.size ());
10724
10725 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10726 "QSetWorkingDir:%s", hexpath.c_str ());
10727 }
10728 else
10729 {
10730 /* An empty inferior_cwd means that the user wants us to
10731 reset the remote server's inferior's cwd. */
10732 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10733 "QSetWorkingDir:");
10734 }
10735
10736 putpkt (rs->buf);
10737 getpkt (&rs->buf);
10738 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10739 error (_("\
10740 Remote replied unexpectedly while setting the inferior's working\n\
10741 directory: %s"),
10742 rs->buf.data ());
10743
10744 }
10745 }
10746
10747 /* In the extended protocol we want to be able to do things like
10748 "run" and have them basically work as expected. So we need
10749 a special create_inferior function. We support changing the
10750 executable file and the command line arguments, but not the
10751 environment. */
10752
10753 void
10754 extended_remote_target::create_inferior (const char *exec_file,
10755 const std::string &args,
10756 char **env, int from_tty)
10757 {
10758 int run_worked;
10759 char *stop_reply;
10760 struct remote_state *rs = get_remote_state ();
10761 const char *remote_exec_file = get_remote_exec_file ();
10762
10763 /* If running asynchronously, register the target file descriptor
10764 with the event loop. */
10765 if (target_can_async_p ())
10766 target_async (true);
10767
10768 /* Disable address space randomization if requested (and supported). */
10769 if (supports_disable_randomization ())
10770 extended_remote_disable_randomization (disable_randomization);
10771
10772 /* If startup-with-shell is on, we inform gdbserver to start the
10773 remote inferior using a shell. */
10774 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10775 {
10776 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10777 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10778 putpkt (rs->buf);
10779 getpkt (&rs->buf);
10780 if (strcmp (rs->buf.data (), "OK") != 0)
10781 error (_("\
10782 Remote replied unexpectedly while setting startup-with-shell: %s"),
10783 rs->buf.data ());
10784 }
10785
10786 extended_remote_environment_support ();
10787
10788 extended_remote_set_inferior_cwd ();
10789
10790 /* Now restart the remote server. */
10791 run_worked = extended_remote_run (args) != -1;
10792 if (!run_worked)
10793 {
10794 /* vRun was not supported. Fail if we need it to do what the
10795 user requested. */
10796 if (remote_exec_file[0])
10797 error (_("Remote target does not support \"set remote exec-file\""));
10798 if (!args.empty ())
10799 error (_("Remote target does not support \"set args\" or run ARGS"));
10800
10801 /* Fall back to "R". */
10802 extended_remote_restart ();
10803 }
10804
10805 /* vRun's success return is a stop reply. */
10806 stop_reply = run_worked ? rs->buf.data () : NULL;
10807 add_current_inferior_and_thread (stop_reply);
10808
10809 /* Get updated offsets, if the stub uses qOffsets. */
10810 get_offsets ();
10811 }
10812 \f
10813
10814 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10815 the list of conditions (in agent expression bytecode format), if any, the
10816 target needs to evaluate. The output is placed into the packet buffer
10817 started from BUF and ended at BUF_END. */
10818
10819 static int
10820 remote_add_target_side_condition (struct gdbarch *gdbarch,
10821 struct bp_target_info *bp_tgt, char *buf,
10822 char *buf_end)
10823 {
10824 if (bp_tgt->conditions.empty ())
10825 return 0;
10826
10827 buf += strlen (buf);
10828 xsnprintf (buf, buf_end - buf, "%s", ";");
10829 buf++;
10830
10831 /* Send conditions to the target. */
10832 for (agent_expr *aexpr : bp_tgt->conditions)
10833 {
10834 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10835 buf += strlen (buf);
10836 for (int i = 0; i < aexpr->buf.size (); ++i)
10837 buf = pack_hex_byte (buf, aexpr->buf[i]);
10838 *buf = '\0';
10839 }
10840 return 0;
10841 }
10842
10843 static void
10844 remote_add_target_side_commands (struct gdbarch *gdbarch,
10845 struct bp_target_info *bp_tgt, char *buf)
10846 {
10847 if (bp_tgt->tcommands.empty ())
10848 return;
10849
10850 buf += strlen (buf);
10851
10852 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10853 buf += strlen (buf);
10854
10855 /* Concatenate all the agent expressions that are commands into the
10856 cmds parameter. */
10857 for (agent_expr *aexpr : bp_tgt->tcommands)
10858 {
10859 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10860 buf += strlen (buf);
10861 for (int i = 0; i < aexpr->buf.size (); ++i)
10862 buf = pack_hex_byte (buf, aexpr->buf[i]);
10863 *buf = '\0';
10864 }
10865 }
10866
10867 /* Insert a breakpoint. On targets that have software breakpoint
10868 support, we ask the remote target to do the work; on targets
10869 which don't, we insert a traditional memory breakpoint. */
10870
10871 int
10872 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10873 struct bp_target_info *bp_tgt)
10874 {
10875 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10876 If it succeeds, then set the support to PACKET_ENABLE. If it
10877 fails, and the user has explicitly requested the Z support then
10878 report an error, otherwise, mark it disabled and go on. */
10879
10880 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10881 {
10882 CORE_ADDR addr = bp_tgt->reqstd_address;
10883 struct remote_state *rs;
10884 char *p, *endbuf;
10885
10886 /* Make sure the remote is pointing at the right process, if
10887 necessary. */
10888 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10889 set_general_process ();
10890
10891 rs = get_remote_state ();
10892 p = rs->buf.data ();
10893 endbuf = p + get_remote_packet_size ();
10894
10895 *(p++) = 'Z';
10896 *(p++) = '0';
10897 *(p++) = ',';
10898 addr = (ULONGEST) remote_address_masked (addr);
10899 p += hexnumstr (p, addr);
10900 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10901
10902 if (supports_evaluation_of_breakpoint_conditions ())
10903 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10904
10905 if (can_run_breakpoint_commands ())
10906 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10907
10908 putpkt (rs->buf);
10909 getpkt (&rs->buf);
10910
10911 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10912 {
10913 case PACKET_ERROR:
10914 return -1;
10915 case PACKET_OK:
10916 return 0;
10917 case PACKET_UNKNOWN:
10918 break;
10919 }
10920 }
10921
10922 /* If this breakpoint has target-side commands but this stub doesn't
10923 support Z0 packets, throw error. */
10924 if (!bp_tgt->tcommands.empty ())
10925 throw_error (NOT_SUPPORTED_ERROR, _("\
10926 Target doesn't support breakpoints that have target side commands."));
10927
10928 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10929 }
10930
10931 int
10932 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10933 struct bp_target_info *bp_tgt,
10934 enum remove_bp_reason reason)
10935 {
10936 CORE_ADDR addr = bp_tgt->placed_address;
10937 struct remote_state *rs = get_remote_state ();
10938
10939 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10940 {
10941 char *p = rs->buf.data ();
10942 char *endbuf = p + get_remote_packet_size ();
10943
10944 /* Make sure the remote is pointing at the right process, if
10945 necessary. */
10946 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
10947 set_general_process ();
10948
10949 *(p++) = 'z';
10950 *(p++) = '0';
10951 *(p++) = ',';
10952
10953 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10954 p += hexnumstr (p, addr);
10955 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10956
10957 putpkt (rs->buf);
10958 getpkt (&rs->buf);
10959
10960 return (rs->buf[0] == 'E');
10961 }
10962
10963 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10964 }
10965
10966 static enum Z_packet_type
10967 watchpoint_to_Z_packet (int type)
10968 {
10969 switch (type)
10970 {
10971 case hw_write:
10972 return Z_PACKET_WRITE_WP;
10973 break;
10974 case hw_read:
10975 return Z_PACKET_READ_WP;
10976 break;
10977 case hw_access:
10978 return Z_PACKET_ACCESS_WP;
10979 break;
10980 default:
10981 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10982 }
10983 }
10984
10985 int
10986 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10987 enum target_hw_bp_type type, struct expression *cond)
10988 {
10989 struct remote_state *rs = get_remote_state ();
10990 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10991 char *p;
10992 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10993
10994 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10995 + to_underlying (packet))) == PACKET_DISABLE)
10996 return 1;
10997
10998 /* Make sure the remote is pointing at the right process, if
10999 necessary. */
11000 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11001 set_general_process ();
11002
11003 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
11004 p = strchr (rs->buf.data (), '\0');
11005 addr = remote_address_masked (addr);
11006 p += hexnumstr (p, (ULONGEST) addr);
11007 xsnprintf (p, endbuf - p, ",%x", len);
11008
11009 putpkt (rs->buf);
11010 getpkt (&rs->buf);
11011
11012 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11013 + to_underlying (packet))))
11014 {
11015 case PACKET_ERROR:
11016 return -1;
11017 case PACKET_UNKNOWN:
11018 return 1;
11019 case PACKET_OK:
11020 return 0;
11021 }
11022 internal_error (_("remote_insert_watchpoint: reached end of function"));
11023 }
11024
11025 bool
11026 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
11027 CORE_ADDR start, int length)
11028 {
11029 CORE_ADDR diff = remote_address_masked (addr - start);
11030
11031 return diff < length;
11032 }
11033
11034
11035 int
11036 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
11037 enum target_hw_bp_type type, struct expression *cond)
11038 {
11039 struct remote_state *rs = get_remote_state ();
11040 char *endbuf = rs->buf.data () + get_remote_packet_size ();
11041 char *p;
11042 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
11043
11044 if (m_features.packet_support ((to_underlying (PACKET_Z0)
11045 + to_underlying (packet))) == PACKET_DISABLE)
11046 return -1;
11047
11048 /* Make sure the remote is pointing at the right process, if
11049 necessary. */
11050 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11051 set_general_process ();
11052
11053 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
11054 p = strchr (rs->buf.data (), '\0');
11055 addr = remote_address_masked (addr);
11056 p += hexnumstr (p, (ULONGEST) addr);
11057 xsnprintf (p, endbuf - p, ",%x", len);
11058 putpkt (rs->buf);
11059 getpkt (&rs->buf);
11060
11061 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
11062 + to_underlying (packet))))
11063 {
11064 case PACKET_ERROR:
11065 case PACKET_UNKNOWN:
11066 return -1;
11067 case PACKET_OK:
11068 return 0;
11069 }
11070 internal_error (_("remote_remove_watchpoint: reached end of function"));
11071 }
11072
11073
11074 static int remote_hw_watchpoint_limit = -1;
11075 static int remote_hw_watchpoint_length_limit = -1;
11076 static int remote_hw_breakpoint_limit = -1;
11077
11078 int
11079 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
11080 {
11081 if (remote_hw_watchpoint_length_limit == 0)
11082 return 0;
11083 else if (remote_hw_watchpoint_length_limit < 0)
11084 return 1;
11085 else if (len <= remote_hw_watchpoint_length_limit)
11086 return 1;
11087 else
11088 return 0;
11089 }
11090
11091 int
11092 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
11093 {
11094 if (type == bp_hardware_breakpoint)
11095 {
11096 if (remote_hw_breakpoint_limit == 0)
11097 return 0;
11098 else if (remote_hw_breakpoint_limit < 0)
11099 return 1;
11100 else if (cnt <= remote_hw_breakpoint_limit)
11101 return 1;
11102 }
11103 else
11104 {
11105 if (remote_hw_watchpoint_limit == 0)
11106 return 0;
11107 else if (remote_hw_watchpoint_limit < 0)
11108 return 1;
11109 else if (ot)
11110 return -1;
11111 else if (cnt <= remote_hw_watchpoint_limit)
11112 return 1;
11113 }
11114 return -1;
11115 }
11116
11117 /* The to_stopped_by_sw_breakpoint method of target remote. */
11118
11119 bool
11120 remote_target::stopped_by_sw_breakpoint ()
11121 {
11122 struct thread_info *thread = inferior_thread ();
11123
11124 return (thread->priv != NULL
11125 && (get_remote_thread_info (thread)->stop_reason
11126 == TARGET_STOPPED_BY_SW_BREAKPOINT));
11127 }
11128
11129 /* The to_supports_stopped_by_sw_breakpoint method of target
11130 remote. */
11131
11132 bool
11133 remote_target::supports_stopped_by_sw_breakpoint ()
11134 {
11135 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
11136 }
11137
11138 /* The to_stopped_by_hw_breakpoint method of target remote. */
11139
11140 bool
11141 remote_target::stopped_by_hw_breakpoint ()
11142 {
11143 struct thread_info *thread = inferior_thread ();
11144
11145 return (thread->priv != NULL
11146 && (get_remote_thread_info (thread)->stop_reason
11147 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11148 }
11149
11150 /* The to_supports_stopped_by_hw_breakpoint method of target
11151 remote. */
11152
11153 bool
11154 remote_target::supports_stopped_by_hw_breakpoint ()
11155 {
11156 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11157 }
11158
11159 bool
11160 remote_target::stopped_by_watchpoint ()
11161 {
11162 struct thread_info *thread = inferior_thread ();
11163
11164 return (thread->priv != NULL
11165 && (get_remote_thread_info (thread)->stop_reason
11166 == TARGET_STOPPED_BY_WATCHPOINT));
11167 }
11168
11169 bool
11170 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11171 {
11172 struct thread_info *thread = inferior_thread ();
11173
11174 if (thread->priv != NULL
11175 && (get_remote_thread_info (thread)->stop_reason
11176 == TARGET_STOPPED_BY_WATCHPOINT))
11177 {
11178 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11179 return true;
11180 }
11181
11182 return false;
11183 }
11184
11185
11186 int
11187 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11188 struct bp_target_info *bp_tgt)
11189 {
11190 CORE_ADDR addr = bp_tgt->reqstd_address;
11191 struct remote_state *rs;
11192 char *p, *endbuf;
11193 char *message;
11194
11195 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11196 return -1;
11197
11198 /* Make sure the remote is pointing at the right process, if
11199 necessary. */
11200 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11201 set_general_process ();
11202
11203 rs = get_remote_state ();
11204 p = rs->buf.data ();
11205 endbuf = p + get_remote_packet_size ();
11206
11207 *(p++) = 'Z';
11208 *(p++) = '1';
11209 *(p++) = ',';
11210
11211 addr = remote_address_masked (addr);
11212 p += hexnumstr (p, (ULONGEST) addr);
11213 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11214
11215 if (supports_evaluation_of_breakpoint_conditions ())
11216 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11217
11218 if (can_run_breakpoint_commands ())
11219 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11220
11221 putpkt (rs->buf);
11222 getpkt (&rs->buf);
11223
11224 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11225 {
11226 case PACKET_ERROR:
11227 if (rs->buf[1] == '.')
11228 {
11229 message = strchr (&rs->buf[2], '.');
11230 if (message)
11231 error (_("Remote failure reply: %s"), message + 1);
11232 }
11233 return -1;
11234 case PACKET_UNKNOWN:
11235 return -1;
11236 case PACKET_OK:
11237 return 0;
11238 }
11239 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11240 }
11241
11242
11243 int
11244 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11245 struct bp_target_info *bp_tgt)
11246 {
11247 CORE_ADDR addr;
11248 struct remote_state *rs = get_remote_state ();
11249 char *p = rs->buf.data ();
11250 char *endbuf = p + get_remote_packet_size ();
11251
11252 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11253 return -1;
11254
11255 /* Make sure the remote is pointing at the right process, if
11256 necessary. */
11257 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
11258 set_general_process ();
11259
11260 *(p++) = 'z';
11261 *(p++) = '1';
11262 *(p++) = ',';
11263
11264 addr = remote_address_masked (bp_tgt->placed_address);
11265 p += hexnumstr (p, (ULONGEST) addr);
11266 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11267
11268 putpkt (rs->buf);
11269 getpkt (&rs->buf);
11270
11271 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11272 {
11273 case PACKET_ERROR:
11274 case PACKET_UNKNOWN:
11275 return -1;
11276 case PACKET_OK:
11277 return 0;
11278 }
11279 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11280 }
11281
11282 /* Verify memory using the "qCRC:" request. */
11283
11284 int
11285 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11286 {
11287 struct remote_state *rs = get_remote_state ();
11288 unsigned long host_crc, target_crc;
11289 char *tmp;
11290
11291 /* It doesn't make sense to use qCRC if the remote target is
11292 connected but not running. */
11293 if (target_has_execution ()
11294 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11295 {
11296 enum packet_result result;
11297
11298 /* Make sure the remote is pointing at the right process. */
11299 set_general_process ();
11300
11301 /* FIXME: assumes lma can fit into long. */
11302 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11303 (long) lma, (long) size);
11304 putpkt (rs->buf);
11305
11306 /* Be clever; compute the host_crc before waiting for target
11307 reply. */
11308 host_crc = xcrc32 (data, size, 0xffffffff);
11309
11310 getpkt (&rs->buf);
11311
11312 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11313 if (result == PACKET_ERROR)
11314 return -1;
11315 else if (result == PACKET_OK)
11316 {
11317 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11318 target_crc = target_crc * 16 + fromhex (*tmp);
11319
11320 return (host_crc == target_crc);
11321 }
11322 }
11323
11324 return simple_verify_memory (this, data, lma, size);
11325 }
11326
11327 /* compare-sections command
11328
11329 With no arguments, compares each loadable section in the exec bfd
11330 with the same memory range on the target, and reports mismatches.
11331 Useful for verifying the image on the target against the exec file. */
11332
11333 static void
11334 compare_sections_command (const char *args, int from_tty)
11335 {
11336 asection *s;
11337 const char *sectname;
11338 bfd_size_type size;
11339 bfd_vma lma;
11340 int matched = 0;
11341 int mismatched = 0;
11342 int res;
11343 int read_only = 0;
11344
11345 if (!current_program_space->exec_bfd ())
11346 error (_("command cannot be used without an exec file"));
11347
11348 if (args != NULL && strcmp (args, "-r") == 0)
11349 {
11350 read_only = 1;
11351 args = NULL;
11352 }
11353
11354 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11355 {
11356 if (!(s->flags & SEC_LOAD))
11357 continue; /* Skip non-loadable section. */
11358
11359 if (read_only && (s->flags & SEC_READONLY) == 0)
11360 continue; /* Skip writeable sections */
11361
11362 size = bfd_section_size (s);
11363 if (size == 0)
11364 continue; /* Skip zero-length section. */
11365
11366 sectname = bfd_section_name (s);
11367 if (args && strcmp (args, sectname) != 0)
11368 continue; /* Not the section selected by user. */
11369
11370 matched = 1; /* Do this section. */
11371 lma = s->lma;
11372
11373 gdb::byte_vector sectdata (size);
11374 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11375 sectdata.data (), 0, size);
11376
11377 res = target_verify_memory (sectdata.data (), lma, size);
11378
11379 if (res == -1)
11380 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11381 paddress (current_inferior ()->arch (), lma),
11382 paddress (current_inferior ()->arch (), lma + size));
11383
11384 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11385 paddress (current_inferior ()->arch (), lma),
11386 paddress (current_inferior ()->arch (), lma + size));
11387 if (res)
11388 gdb_printf ("matched.\n");
11389 else
11390 {
11391 gdb_printf ("MIS-MATCHED!\n");
11392 mismatched++;
11393 }
11394 }
11395 if (mismatched > 0)
11396 warning (_("One or more sections of the target image does "
11397 "not match the loaded file"));
11398 if (args && !matched)
11399 gdb_printf (_("No loaded section named '%s'.\n"), args);
11400 }
11401
11402 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11403 into remote target. The number of bytes written to the remote
11404 target is returned, or -1 for error. */
11405
11406 target_xfer_status
11407 remote_target::remote_write_qxfer (const char *object_name,
11408 const char *annex, const gdb_byte *writebuf,
11409 ULONGEST offset, LONGEST len,
11410 ULONGEST *xfered_len,
11411 const unsigned int which_packet)
11412 {
11413 int i, buf_len;
11414 ULONGEST n;
11415 struct remote_state *rs = get_remote_state ();
11416 int max_size = get_memory_write_packet_size ();
11417
11418 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11419 return TARGET_XFER_E_IO;
11420
11421 /* Insert header. */
11422 i = snprintf (rs->buf.data (), max_size,
11423 "qXfer:%s:write:%s:%s:",
11424 object_name, annex ? annex : "",
11425 phex_nz (offset, sizeof offset));
11426 max_size -= (i + 1);
11427
11428 /* Escape as much data as fits into rs->buf. */
11429 buf_len = remote_escape_output
11430 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11431
11432 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11433 || getpkt (&rs->buf) < 0
11434 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11435 return TARGET_XFER_E_IO;
11436
11437 unpack_varlen_hex (rs->buf.data (), &n);
11438
11439 *xfered_len = n;
11440 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11441 }
11442
11443 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11444 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11445 number of bytes read is returned, or 0 for EOF, or -1 for error.
11446 The number of bytes read may be less than LEN without indicating an
11447 EOF. PACKET is checked and updated to indicate whether the remote
11448 target supports this object. */
11449
11450 target_xfer_status
11451 remote_target::remote_read_qxfer (const char *object_name,
11452 const char *annex,
11453 gdb_byte *readbuf, ULONGEST offset,
11454 LONGEST len,
11455 ULONGEST *xfered_len,
11456 const unsigned int which_packet)
11457 {
11458 struct remote_state *rs = get_remote_state ();
11459 LONGEST i, n, packet_len;
11460
11461 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11462 return TARGET_XFER_E_IO;
11463
11464 /* Check whether we've cached an end-of-object packet that matches
11465 this request. */
11466 if (rs->finished_object)
11467 {
11468 if (strcmp (object_name, rs->finished_object) == 0
11469 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11470 && offset == rs->finished_offset)
11471 return TARGET_XFER_EOF;
11472
11473
11474 /* Otherwise, we're now reading something different. Discard
11475 the cache. */
11476 xfree (rs->finished_object);
11477 xfree (rs->finished_annex);
11478 rs->finished_object = NULL;
11479 rs->finished_annex = NULL;
11480 }
11481
11482 /* Request only enough to fit in a single packet. The actual data
11483 may not, since we don't know how much of it will need to be escaped;
11484 the target is free to respond with slightly less data. We subtract
11485 five to account for the response type and the protocol frame. */
11486 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11487 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11488 "qXfer:%s:read:%s:%s,%s",
11489 object_name, annex ? annex : "",
11490 phex_nz (offset, sizeof offset),
11491 phex_nz (n, sizeof n));
11492 i = putpkt (rs->buf);
11493 if (i < 0)
11494 return TARGET_XFER_E_IO;
11495
11496 rs->buf[0] = '\0';
11497 packet_len = getpkt (&rs->buf);
11498 if (packet_len < 0
11499 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11500 return TARGET_XFER_E_IO;
11501
11502 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11503 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11504
11505 /* 'm' means there is (or at least might be) more data after this
11506 batch. That does not make sense unless there's at least one byte
11507 of data in this reply. */
11508 if (rs->buf[0] == 'm' && packet_len == 1)
11509 error (_("Remote qXfer reply contained no data."));
11510
11511 /* Got some data. */
11512 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11513 packet_len - 1, readbuf, n);
11514
11515 /* 'l' is an EOF marker, possibly including a final block of data,
11516 or possibly empty. If we have the final block of a non-empty
11517 object, record this fact to bypass a subsequent partial read. */
11518 if (rs->buf[0] == 'l' && offset + i > 0)
11519 {
11520 rs->finished_object = xstrdup (object_name);
11521 rs->finished_annex = xstrdup (annex ? annex : "");
11522 rs->finished_offset = offset + i;
11523 }
11524
11525 if (i == 0)
11526 return TARGET_XFER_EOF;
11527 else
11528 {
11529 *xfered_len = i;
11530 return TARGET_XFER_OK;
11531 }
11532 }
11533
11534 enum target_xfer_status
11535 remote_target::xfer_partial (enum target_object object,
11536 const char *annex, gdb_byte *readbuf,
11537 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11538 ULONGEST *xfered_len)
11539 {
11540 struct remote_state *rs;
11541 int i;
11542 char *p2;
11543 char query_type;
11544 int unit_size
11545 = gdbarch_addressable_memory_unit_size (current_inferior ()->arch ());
11546
11547 set_remote_traceframe ();
11548 set_general_thread (inferior_ptid);
11549
11550 rs = get_remote_state ();
11551
11552 /* Handle memory using the standard memory routines. */
11553 if (object == TARGET_OBJECT_MEMORY)
11554 {
11555 /* If the remote target is connected but not running, we should
11556 pass this request down to a lower stratum (e.g. the executable
11557 file). */
11558 if (!target_has_execution ())
11559 return TARGET_XFER_EOF;
11560
11561 if (writebuf != NULL)
11562 return remote_write_bytes (offset, writebuf, len, unit_size,
11563 xfered_len);
11564 else
11565 return remote_read_bytes (offset, readbuf, len, unit_size,
11566 xfered_len);
11567 }
11568
11569 /* Handle extra signal info using qxfer packets. */
11570 if (object == TARGET_OBJECT_SIGNAL_INFO)
11571 {
11572 if (readbuf)
11573 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11574 xfered_len, PACKET_qXfer_siginfo_read);
11575 else
11576 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11577 xfered_len, PACKET_qXfer_siginfo_write);
11578 }
11579
11580 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11581 {
11582 if (readbuf)
11583 return remote_read_qxfer ("statictrace", annex,
11584 readbuf, offset, len, xfered_len,
11585 PACKET_qXfer_statictrace_read);
11586 else
11587 return TARGET_XFER_E_IO;
11588 }
11589
11590 /* Only handle flash writes. */
11591 if (writebuf != NULL)
11592 {
11593 switch (object)
11594 {
11595 case TARGET_OBJECT_FLASH:
11596 return remote_flash_write (offset, len, xfered_len,
11597 writebuf);
11598
11599 default:
11600 return TARGET_XFER_E_IO;
11601 }
11602 }
11603
11604 /* Map pre-existing objects onto letters. DO NOT do this for new
11605 objects!!! Instead specify new query packets. */
11606 switch (object)
11607 {
11608 case TARGET_OBJECT_AVR:
11609 query_type = 'R';
11610 break;
11611
11612 case TARGET_OBJECT_AUXV:
11613 gdb_assert (annex == NULL);
11614 return remote_read_qxfer
11615 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11616
11617 case TARGET_OBJECT_AVAILABLE_FEATURES:
11618 return remote_read_qxfer
11619 ("features", annex, readbuf, offset, len, xfered_len,
11620 PACKET_qXfer_features);
11621
11622 case TARGET_OBJECT_LIBRARIES:
11623 return remote_read_qxfer
11624 ("libraries", annex, readbuf, offset, len, xfered_len,
11625 PACKET_qXfer_libraries);
11626
11627 case TARGET_OBJECT_LIBRARIES_SVR4:
11628 return remote_read_qxfer
11629 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11630 PACKET_qXfer_libraries_svr4);
11631
11632 case TARGET_OBJECT_MEMORY_MAP:
11633 gdb_assert (annex == NULL);
11634 return remote_read_qxfer
11635 ("memory-map", annex, readbuf, offset, len, xfered_len,
11636 PACKET_qXfer_memory_map);
11637
11638 case TARGET_OBJECT_OSDATA:
11639 /* Should only get here if we're connected. */
11640 gdb_assert (rs->remote_desc);
11641 return remote_read_qxfer
11642 ("osdata", annex, readbuf, offset, len, xfered_len,
11643 PACKET_qXfer_osdata);
11644
11645 case TARGET_OBJECT_THREADS:
11646 gdb_assert (annex == NULL);
11647 return remote_read_qxfer
11648 ("threads", annex, readbuf, offset, len, xfered_len,
11649 PACKET_qXfer_threads);
11650
11651 case TARGET_OBJECT_TRACEFRAME_INFO:
11652 gdb_assert (annex == NULL);
11653 return remote_read_qxfer
11654 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11655 PACKET_qXfer_traceframe_info);
11656
11657 case TARGET_OBJECT_FDPIC:
11658 return remote_read_qxfer
11659 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11660
11661 case TARGET_OBJECT_OPENVMS_UIB:
11662 return remote_read_qxfer
11663 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11664
11665 case TARGET_OBJECT_BTRACE:
11666 return remote_read_qxfer
11667 ("btrace", annex, readbuf, offset, len, xfered_len,
11668 PACKET_qXfer_btrace);
11669
11670 case TARGET_OBJECT_BTRACE_CONF:
11671 return remote_read_qxfer
11672 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11673 PACKET_qXfer_btrace_conf);
11674
11675 case TARGET_OBJECT_EXEC_FILE:
11676 return remote_read_qxfer
11677 ("exec-file", annex, readbuf, offset, len, xfered_len,
11678 PACKET_qXfer_exec_file);
11679
11680 default:
11681 return TARGET_XFER_E_IO;
11682 }
11683
11684 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11685 large enough let the caller deal with it. */
11686 if (len < get_remote_packet_size ())
11687 return TARGET_XFER_E_IO;
11688 len = get_remote_packet_size ();
11689
11690 /* Except for querying the minimum buffer size, target must be open. */
11691 if (!rs->remote_desc)
11692 error (_("remote query is only available after target open"));
11693
11694 gdb_assert (annex != NULL);
11695 gdb_assert (readbuf != NULL);
11696
11697 p2 = rs->buf.data ();
11698 *p2++ = 'q';
11699 *p2++ = query_type;
11700
11701 /* We used one buffer char for the remote protocol q command and
11702 another for the query type. As the remote protocol encapsulation
11703 uses 4 chars plus one extra in case we are debugging
11704 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11705 string. */
11706 i = 0;
11707 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11708 {
11709 /* Bad caller may have sent forbidden characters. */
11710 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11711 *p2++ = annex[i];
11712 i++;
11713 }
11714 *p2 = '\0';
11715 gdb_assert (annex[i] == '\0');
11716
11717 i = putpkt (rs->buf);
11718 if (i < 0)
11719 return TARGET_XFER_E_IO;
11720
11721 getpkt (&rs->buf);
11722 strcpy ((char *) readbuf, rs->buf.data ());
11723
11724 *xfered_len = strlen ((char *) readbuf);
11725 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11726 }
11727
11728 /* Implementation of to_get_memory_xfer_limit. */
11729
11730 ULONGEST
11731 remote_target::get_memory_xfer_limit ()
11732 {
11733 return get_memory_write_packet_size ();
11734 }
11735
11736 int
11737 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11738 const gdb_byte *pattern, ULONGEST pattern_len,
11739 CORE_ADDR *found_addrp)
11740 {
11741 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
11742 struct remote_state *rs = get_remote_state ();
11743 int max_size = get_memory_write_packet_size ();
11744
11745 /* Number of packet bytes used to encode the pattern;
11746 this could be more than PATTERN_LEN due to escape characters. */
11747 int escaped_pattern_len;
11748 /* Amount of pattern that was encodable in the packet. */
11749 int used_pattern_len;
11750 int i;
11751 int found;
11752 ULONGEST found_addr;
11753
11754 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11755 {
11756 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11757 == len);
11758 };
11759
11760 /* Don't go to the target if we don't have to. This is done before
11761 checking packet_support to avoid the possibility that a success for this
11762 edge case means the facility works in general. */
11763 if (pattern_len > search_space_len)
11764 return 0;
11765 if (pattern_len == 0)
11766 {
11767 *found_addrp = start_addr;
11768 return 1;
11769 }
11770
11771 /* If we already know the packet isn't supported, fall back to the simple
11772 way of searching memory. */
11773
11774 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11775 {
11776 /* Target doesn't provided special support, fall back and use the
11777 standard support (copy memory and do the search here). */
11778 return simple_search_memory (read_memory, start_addr, search_space_len,
11779 pattern, pattern_len, found_addrp);
11780 }
11781
11782 /* Make sure the remote is pointing at the right process. */
11783 set_general_process ();
11784
11785 /* Insert header. */
11786 i = snprintf (rs->buf.data (), max_size,
11787 "qSearch:memory:%s;%s;",
11788 phex_nz (start_addr, addr_size),
11789 phex_nz (search_space_len, sizeof (search_space_len)));
11790 max_size -= (i + 1);
11791
11792 /* Escape as much data as fits into rs->buf. */
11793 escaped_pattern_len =
11794 remote_escape_output (pattern, pattern_len, 1,
11795 (gdb_byte *) rs->buf.data () + i,
11796 &used_pattern_len, max_size);
11797
11798 /* Bail if the pattern is too large. */
11799 if (used_pattern_len != pattern_len)
11800 error (_("Pattern is too large to transmit to remote target."));
11801
11802 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11803 || getpkt (&rs->buf) < 0
11804 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11805 {
11806 /* The request may not have worked because the command is not
11807 supported. If so, fall back to the simple way. */
11808 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11809 {
11810 return simple_search_memory (read_memory, start_addr, search_space_len,
11811 pattern, pattern_len, found_addrp);
11812 }
11813 return -1;
11814 }
11815
11816 if (rs->buf[0] == '0')
11817 found = 0;
11818 else if (rs->buf[0] == '1')
11819 {
11820 found = 1;
11821 if (rs->buf[1] != ',')
11822 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11823 unpack_varlen_hex (&rs->buf[2], &found_addr);
11824 *found_addrp = found_addr;
11825 }
11826 else
11827 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11828
11829 return found;
11830 }
11831
11832 void
11833 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11834 {
11835 struct remote_state *rs = get_remote_state ();
11836 char *p = rs->buf.data ();
11837
11838 if (!rs->remote_desc)
11839 error (_("remote rcmd is only available after target open"));
11840
11841 /* Send a NULL command across as an empty command. */
11842 if (command == NULL)
11843 command = "";
11844
11845 /* The query prefix. */
11846 strcpy (rs->buf.data (), "qRcmd,");
11847 p = strchr (rs->buf.data (), '\0');
11848
11849 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11850 > get_remote_packet_size ())
11851 error (_("\"monitor\" command ``%s'' is too long."), command);
11852
11853 /* Encode the actual command. */
11854 bin2hex ((const gdb_byte *) command, p, strlen (command));
11855
11856 if (putpkt (rs->buf) < 0)
11857 error (_("Communication problem with target."));
11858
11859 /* get/display the response */
11860 while (1)
11861 {
11862 char *buf;
11863
11864 /* XXX - see also remote_get_noisy_reply(). */
11865 QUIT; /* Allow user to bail out with ^C. */
11866 rs->buf[0] = '\0';
11867 if (getpkt (&rs->buf) == -1)
11868 {
11869 /* Timeout. Continue to (try to) read responses.
11870 This is better than stopping with an error, assuming the stub
11871 is still executing the (long) monitor command.
11872 If needed, the user can interrupt gdb using C-c, obtaining
11873 an effect similar to stop on timeout. */
11874 continue;
11875 }
11876 buf = rs->buf.data ();
11877 if (buf[0] == '\0')
11878 error (_("Target does not support this command."));
11879 if (buf[0] == 'O' && buf[1] != 'K')
11880 {
11881 remote_console_output (buf + 1); /* 'O' message from stub. */
11882 continue;
11883 }
11884 if (strcmp (buf, "OK") == 0)
11885 break;
11886 if (strlen (buf) == 3 && buf[0] == 'E'
11887 && isxdigit (buf[1]) && isxdigit (buf[2]))
11888 {
11889 error (_("Protocol error with Rcmd"));
11890 }
11891 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11892 {
11893 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11894
11895 gdb_putc (c, outbuf);
11896 }
11897 break;
11898 }
11899 }
11900
11901 std::vector<mem_region>
11902 remote_target::memory_map ()
11903 {
11904 std::vector<mem_region> result;
11905 gdb::optional<gdb::char_vector> text
11906 = target_read_stralloc (current_inferior ()->top_target (),
11907 TARGET_OBJECT_MEMORY_MAP, NULL);
11908
11909 if (text)
11910 result = parse_memory_map (text->data ());
11911
11912 return result;
11913 }
11914
11915 /* Set of callbacks used to implement the 'maint packet' command. */
11916
11917 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11918 {
11919 /* Called before the packet is sent. BUF is the packet content before
11920 the protocol specific prefix, suffix, and escaping is added. */
11921
11922 void sending (gdb::array_view<const char> &buf) override
11923 {
11924 gdb_puts ("sending: ");
11925 print_packet (buf);
11926 gdb_puts ("\n");
11927 }
11928
11929 /* Called with BUF, the reply from the remote target. */
11930
11931 void received (gdb::array_view<const char> &buf) override
11932 {
11933 gdb_puts ("received: \"");
11934 print_packet (buf);
11935 gdb_puts ("\"\n");
11936 }
11937
11938 private:
11939
11940 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11941 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11942
11943 static void
11944 print_packet (gdb::array_view<const char> &buf)
11945 {
11946 string_file stb;
11947
11948 for (int i = 0; i < buf.size (); ++i)
11949 {
11950 gdb_byte c = buf[i];
11951 if (isprint (c))
11952 gdb_putc (c, &stb);
11953 else
11954 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11955 }
11956
11957 gdb_puts (stb.string ().c_str ());
11958 }
11959 };
11960
11961 /* See remote.h. */
11962
11963 void
11964 send_remote_packet (gdb::array_view<const char> &buf,
11965 send_remote_packet_callbacks *callbacks)
11966 {
11967 if (buf.size () == 0 || buf.data ()[0] == '\0')
11968 error (_("a remote packet must not be empty"));
11969
11970 remote_target *remote = get_current_remote_target ();
11971 if (remote == nullptr)
11972 error (_("packets can only be sent to a remote target"));
11973
11974 callbacks->sending (buf);
11975
11976 remote->putpkt_binary (buf.data (), buf.size ());
11977 remote_state *rs = remote->get_remote_state ();
11978 int bytes = remote->getpkt (&rs->buf);
11979
11980 if (bytes < 0)
11981 error (_("error while fetching packet from remote target"));
11982
11983 gdb::array_view<const char> view (&rs->buf[0], bytes);
11984 callbacks->received (view);
11985 }
11986
11987 /* Entry point for the 'maint packet' command. */
11988
11989 static void
11990 cli_packet_command (const char *args, int from_tty)
11991 {
11992 cli_packet_command_callbacks cb;
11993 gdb::array_view<const char> view
11994 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11995 send_remote_packet (view, &cb);
11996 }
11997
11998 #if 0
11999 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
12000
12001 static void display_thread_info (struct gdb_ext_thread_info *info);
12002
12003 static void threadset_test_cmd (char *cmd, int tty);
12004
12005 static void threadalive_test (char *cmd, int tty);
12006
12007 static void threadlist_test_cmd (char *cmd, int tty);
12008
12009 int get_and_display_threadinfo (threadref *ref);
12010
12011 static void threadinfo_test_cmd (char *cmd, int tty);
12012
12013 static int thread_display_step (threadref *ref, void *context);
12014
12015 static void threadlist_update_test_cmd (char *cmd, int tty);
12016
12017 static void init_remote_threadtests (void);
12018
12019 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
12020
12021 static void
12022 threadset_test_cmd (const char *cmd, int tty)
12023 {
12024 int sample_thread = SAMPLE_THREAD;
12025
12026 gdb_printf (_("Remote threadset test\n"));
12027 set_general_thread (sample_thread);
12028 }
12029
12030
12031 static void
12032 threadalive_test (const char *cmd, int tty)
12033 {
12034 int sample_thread = SAMPLE_THREAD;
12035 int pid = inferior_ptid.pid ();
12036 ptid_t ptid = ptid_t (pid, sample_thread, 0);
12037
12038 if (remote_thread_alive (ptid))
12039 gdb_printf ("PASS: Thread alive test\n");
12040 else
12041 gdb_printf ("FAIL: Thread alive test\n");
12042 }
12043
12044 void output_threadid (char *title, threadref *ref);
12045
12046 void
12047 output_threadid (char *title, threadref *ref)
12048 {
12049 char hexid[20];
12050
12051 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
12052 hexid[16] = 0;
12053 gdb_printf ("%s %s\n", title, (&hexid[0]));
12054 }
12055
12056 static void
12057 threadlist_test_cmd (const char *cmd, int tty)
12058 {
12059 int startflag = 1;
12060 threadref nextthread;
12061 int done, result_count;
12062 threadref threadlist[3];
12063
12064 gdb_printf ("Remote Threadlist test\n");
12065 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
12066 &result_count, &threadlist[0]))
12067 gdb_printf ("FAIL: threadlist test\n");
12068 else
12069 {
12070 threadref *scan = threadlist;
12071 threadref *limit = scan + result_count;
12072
12073 while (scan < limit)
12074 output_threadid (" thread ", scan++);
12075 }
12076 }
12077
12078 void
12079 display_thread_info (struct gdb_ext_thread_info *info)
12080 {
12081 output_threadid ("Threadid: ", &info->threadid);
12082 gdb_printf ("Name: %s\n ", info->shortname);
12083 gdb_printf ("State: %s\n", info->display);
12084 gdb_printf ("other: %s\n\n", info->more_display);
12085 }
12086
12087 int
12088 get_and_display_threadinfo (threadref *ref)
12089 {
12090 int result;
12091 int set;
12092 struct gdb_ext_thread_info threadinfo;
12093
12094 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
12095 | TAG_MOREDISPLAY | TAG_DISPLAY;
12096 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
12097 display_thread_info (&threadinfo);
12098 return result;
12099 }
12100
12101 static void
12102 threadinfo_test_cmd (const char *cmd, int tty)
12103 {
12104 int athread = SAMPLE_THREAD;
12105 threadref thread;
12106 int set;
12107
12108 int_to_threadref (&thread, athread);
12109 gdb_printf ("Remote Threadinfo test\n");
12110 if (!get_and_display_threadinfo (&thread))
12111 gdb_printf ("FAIL cannot get thread info\n");
12112 }
12113
12114 static int
12115 thread_display_step (threadref *ref, void *context)
12116 {
12117 /* output_threadid(" threadstep ",ref); *//* simple test */
12118 return get_and_display_threadinfo (ref);
12119 }
12120
12121 static void
12122 threadlist_update_test_cmd (const char *cmd, int tty)
12123 {
12124 gdb_printf ("Remote Threadlist update test\n");
12125 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
12126 }
12127
12128 static void
12129 init_remote_threadtests (void)
12130 {
12131 add_com ("tlist", class_obscure, threadlist_test_cmd,
12132 _("Fetch and print the remote list of "
12133 "thread identifiers, one pkt only."));
12134 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
12135 _("Fetch and display info about one thread."));
12136 add_com ("tset", class_obscure, threadset_test_cmd,
12137 _("Test setting to a different thread."));
12138 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
12139 _("Iterate through updating all remote thread info."));
12140 add_com ("talive", class_obscure, threadalive_test,
12141 _("Remote thread alive test."));
12142 }
12143
12144 #endif /* 0 */
12145
12146 /* Convert a thread ID to a string. */
12147
12148 std::string
12149 remote_target::pid_to_str (ptid_t ptid)
12150 {
12151 if (ptid == null_ptid)
12152 return normal_pid_to_str (ptid);
12153 else if (ptid.is_pid ())
12154 {
12155 /* Printing an inferior target id. */
12156
12157 /* When multi-process extensions are off, there's no way in the
12158 remote protocol to know the remote process id, if there's any
12159 at all. There's one exception --- when we're connected with
12160 target extended-remote, and we manually attached to a process
12161 with "attach PID". We don't record anywhere a flag that
12162 allows us to distinguish that case from the case of
12163 connecting with extended-remote and the stub already being
12164 attached to a process, and reporting yes to qAttached, hence
12165 no smart special casing here. */
12166 if (!m_features.remote_multi_process_p ())
12167 return "Remote target";
12168
12169 return normal_pid_to_str (ptid);
12170 }
12171 else
12172 {
12173 if (magic_null_ptid == ptid)
12174 return "Thread <main>";
12175 else if (m_features.remote_multi_process_p ())
12176 if (ptid.lwp () == 0)
12177 return normal_pid_to_str (ptid);
12178 else
12179 return string_printf ("Thread %d.%ld",
12180 ptid.pid (), ptid.lwp ());
12181 else
12182 return string_printf ("Thread %ld", ptid.lwp ());
12183 }
12184 }
12185
12186 /* Get the address of the thread local variable in OBJFILE which is
12187 stored at OFFSET within the thread local storage for thread PTID. */
12188
12189 CORE_ADDR
12190 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12191 CORE_ADDR offset)
12192 {
12193 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12194 {
12195 struct remote_state *rs = get_remote_state ();
12196 char *p = rs->buf.data ();
12197 char *endp = p + get_remote_packet_size ();
12198 enum packet_result result;
12199
12200 strcpy (p, "qGetTLSAddr:");
12201 p += strlen (p);
12202 p = write_ptid (p, endp, ptid);
12203 *p++ = ',';
12204 p += hexnumstr (p, offset);
12205 *p++ = ',';
12206 p += hexnumstr (p, lm);
12207 *p++ = '\0';
12208
12209 putpkt (rs->buf);
12210 getpkt (&rs->buf);
12211 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12212 if (result == PACKET_OK)
12213 {
12214 ULONGEST addr;
12215
12216 unpack_varlen_hex (rs->buf.data (), &addr);
12217 return addr;
12218 }
12219 else if (result == PACKET_UNKNOWN)
12220 throw_error (TLS_GENERIC_ERROR,
12221 _("Remote target doesn't support qGetTLSAddr packet"));
12222 else
12223 throw_error (TLS_GENERIC_ERROR,
12224 _("Remote target failed to process qGetTLSAddr request"));
12225 }
12226 else
12227 throw_error (TLS_GENERIC_ERROR,
12228 _("TLS not supported or disabled on this target"));
12229 /* Not reached. */
12230 return 0;
12231 }
12232
12233 /* Provide thread local base, i.e. Thread Information Block address.
12234 Returns 1 if ptid is found and thread_local_base is non zero. */
12235
12236 bool
12237 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12238 {
12239 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12240 {
12241 struct remote_state *rs = get_remote_state ();
12242 char *p = rs->buf.data ();
12243 char *endp = p + get_remote_packet_size ();
12244 enum packet_result result;
12245
12246 strcpy (p, "qGetTIBAddr:");
12247 p += strlen (p);
12248 p = write_ptid (p, endp, ptid);
12249 *p++ = '\0';
12250
12251 putpkt (rs->buf);
12252 getpkt (&rs->buf);
12253 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12254 if (result == PACKET_OK)
12255 {
12256 ULONGEST val;
12257 unpack_varlen_hex (rs->buf.data (), &val);
12258 if (addr)
12259 *addr = (CORE_ADDR) val;
12260 return true;
12261 }
12262 else if (result == PACKET_UNKNOWN)
12263 error (_("Remote target doesn't support qGetTIBAddr packet"));
12264 else
12265 error (_("Remote target failed to process qGetTIBAddr request"));
12266 }
12267 else
12268 error (_("qGetTIBAddr not supported or disabled on this target"));
12269 /* Not reached. */
12270 return false;
12271 }
12272
12273 /* Support for inferring a target description based on the current
12274 architecture and the size of a 'g' packet. While the 'g' packet
12275 can have any size (since optional registers can be left off the
12276 end), some sizes are easily recognizable given knowledge of the
12277 approximate architecture. */
12278
12279 struct remote_g_packet_guess
12280 {
12281 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12282 : bytes (bytes_),
12283 tdesc (tdesc_)
12284 {
12285 }
12286
12287 int bytes;
12288 const struct target_desc *tdesc;
12289 };
12290
12291 struct remote_g_packet_data
12292 {
12293 std::vector<remote_g_packet_guess> guesses;
12294 };
12295
12296 static const registry<gdbarch>::key<struct remote_g_packet_data>
12297 remote_g_packet_data_handle;
12298
12299 static struct remote_g_packet_data *
12300 get_g_packet_data (struct gdbarch *gdbarch)
12301 {
12302 struct remote_g_packet_data *data
12303 = remote_g_packet_data_handle.get (gdbarch);
12304 if (data == nullptr)
12305 data = remote_g_packet_data_handle.emplace (gdbarch);
12306 return data;
12307 }
12308
12309 void
12310 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12311 const struct target_desc *tdesc)
12312 {
12313 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12314
12315 gdb_assert (tdesc != NULL);
12316
12317 for (const remote_g_packet_guess &guess : data->guesses)
12318 if (guess.bytes == bytes)
12319 internal_error (_("Duplicate g packet description added for size %d"),
12320 bytes);
12321
12322 data->guesses.emplace_back (bytes, tdesc);
12323 }
12324
12325 /* Return true if remote_read_description would do anything on this target
12326 and architecture, false otherwise. */
12327
12328 static bool
12329 remote_read_description_p (struct target_ops *target)
12330 {
12331 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12332
12333 return !data->guesses.empty ();
12334 }
12335
12336 const struct target_desc *
12337 remote_target::read_description ()
12338 {
12339 remote_g_packet_data *data = get_g_packet_data (current_inferior ()->arch ());
12340
12341 /* Do not try this during initial connection, when we do not know
12342 whether there is a running but stopped thread. */
12343 if (!target_has_execution () || inferior_ptid == null_ptid)
12344 return beneath ()->read_description ();
12345
12346 if (!data->guesses.empty ())
12347 {
12348 int bytes = send_g_packet ();
12349
12350 for (const remote_g_packet_guess &guess : data->guesses)
12351 if (guess.bytes == bytes)
12352 return guess.tdesc;
12353
12354 /* We discard the g packet. A minor optimization would be to
12355 hold on to it, and fill the register cache once we have selected
12356 an architecture, but it's too tricky to do safely. */
12357 }
12358
12359 return beneath ()->read_description ();
12360 }
12361
12362 /* Remote file transfer support. This is host-initiated I/O, not
12363 target-initiated; for target-initiated, see remote-fileio.c. */
12364
12365 /* If *LEFT is at least the length of STRING, copy STRING to
12366 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12367 decrease *LEFT. Otherwise raise an error. */
12368
12369 static void
12370 remote_buffer_add_string (char **buffer, int *left, const char *string)
12371 {
12372 int len = strlen (string);
12373
12374 if (len > *left)
12375 error (_("Packet too long for target."));
12376
12377 memcpy (*buffer, string, len);
12378 *buffer += len;
12379 *left -= len;
12380
12381 /* NUL-terminate the buffer as a convenience, if there is
12382 room. */
12383 if (*left)
12384 **buffer = '\0';
12385 }
12386
12387 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12388 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12389 decrease *LEFT. Otherwise raise an error. */
12390
12391 static void
12392 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12393 int len)
12394 {
12395 if (2 * len > *left)
12396 error (_("Packet too long for target."));
12397
12398 bin2hex (bytes, *buffer, len);
12399 *buffer += 2 * len;
12400 *left -= 2 * len;
12401
12402 /* NUL-terminate the buffer as a convenience, if there is
12403 room. */
12404 if (*left)
12405 **buffer = '\0';
12406 }
12407
12408 /* If *LEFT is large enough, convert VALUE to hex and add it to
12409 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12410 decrease *LEFT. Otherwise raise an error. */
12411
12412 static void
12413 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12414 {
12415 int len = hexnumlen (value);
12416
12417 if (len > *left)
12418 error (_("Packet too long for target."));
12419
12420 hexnumstr (*buffer, value);
12421 *buffer += len;
12422 *left -= len;
12423
12424 /* NUL-terminate the buffer as a convenience, if there is
12425 room. */
12426 if (*left)
12427 **buffer = '\0';
12428 }
12429
12430 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12431 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12432 was included, and *ATTACHMENT to point to the start of the annex
12433 if any. The length of the packet isn't needed here; there may
12434 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12435
12436 Return 0 if the packet could be parsed, -1 if it could not. If
12437 -1 is returned, the other variables may not be initialized. */
12438
12439 static int
12440 remote_hostio_parse_result (const char *buffer, int *retcode,
12441 fileio_error *remote_errno, const char **attachment)
12442 {
12443 char *p, *p2;
12444
12445 *remote_errno = FILEIO_SUCCESS;
12446 *attachment = NULL;
12447
12448 if (buffer[0] != 'F')
12449 return -1;
12450
12451 errno = 0;
12452 *retcode = strtol (&buffer[1], &p, 16);
12453 if (errno != 0 || p == &buffer[1])
12454 return -1;
12455
12456 /* Check for ",errno". */
12457 if (*p == ',')
12458 {
12459 errno = 0;
12460 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12461 if (errno != 0 || p + 1 == p2)
12462 return -1;
12463 p = p2;
12464 }
12465
12466 /* Check for ";attachment". If there is no attachment, the
12467 packet should end here. */
12468 if (*p == ';')
12469 {
12470 *attachment = p + 1;
12471 return 0;
12472 }
12473 else if (*p == '\0')
12474 return 0;
12475 else
12476 return -1;
12477 }
12478
12479 /* Send a prepared I/O packet to the target and read its response.
12480 The prepared packet is in the global RS->BUF before this function
12481 is called, and the answer is there when we return.
12482
12483 COMMAND_BYTES is the length of the request to send, which may include
12484 binary data. WHICH_PACKET is the packet configuration to check
12485 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12486 is set to the error number and -1 is returned. Otherwise the value
12487 returned by the function is returned.
12488
12489 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12490 attachment is expected; an error will be reported if there's a
12491 mismatch. If one is found, *ATTACHMENT will be set to point into
12492 the packet buffer and *ATTACHMENT_LEN will be set to the
12493 attachment's length. */
12494
12495 int
12496 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12497 fileio_error *remote_errno, const char **attachment,
12498 int *attachment_len)
12499 {
12500 struct remote_state *rs = get_remote_state ();
12501 int ret, bytes_read;
12502 const char *attachment_tmp;
12503
12504 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12505 {
12506 *remote_errno = FILEIO_ENOSYS;
12507 return -1;
12508 }
12509
12510 putpkt_binary (rs->buf.data (), command_bytes);
12511 bytes_read = getpkt (&rs->buf);
12512
12513 /* If it timed out, something is wrong. Don't try to parse the
12514 buffer. */
12515 if (bytes_read < 0)
12516 {
12517 *remote_errno = FILEIO_EINVAL;
12518 return -1;
12519 }
12520
12521 switch (m_features.packet_ok (rs->buf, which_packet))
12522 {
12523 case PACKET_ERROR:
12524 *remote_errno = FILEIO_EINVAL;
12525 return -1;
12526 case PACKET_UNKNOWN:
12527 *remote_errno = FILEIO_ENOSYS;
12528 return -1;
12529 case PACKET_OK:
12530 break;
12531 }
12532
12533 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12534 &attachment_tmp))
12535 {
12536 *remote_errno = FILEIO_EINVAL;
12537 return -1;
12538 }
12539
12540 /* Make sure we saw an attachment if and only if we expected one. */
12541 if ((attachment_tmp == NULL && attachment != NULL)
12542 || (attachment_tmp != NULL && attachment == NULL))
12543 {
12544 *remote_errno = FILEIO_EINVAL;
12545 return -1;
12546 }
12547
12548 /* If an attachment was found, it must point into the packet buffer;
12549 work out how many bytes there were. */
12550 if (attachment_tmp != NULL)
12551 {
12552 *attachment = attachment_tmp;
12553 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12554 }
12555
12556 return ret;
12557 }
12558
12559 /* See declaration.h. */
12560
12561 void
12562 readahead_cache::invalidate ()
12563 {
12564 this->fd = -1;
12565 }
12566
12567 /* See declaration.h. */
12568
12569 void
12570 readahead_cache::invalidate_fd (int fd)
12571 {
12572 if (this->fd == fd)
12573 this->fd = -1;
12574 }
12575
12576 /* Set the filesystem remote_hostio functions that take FILENAME
12577 arguments will use. Return 0 on success, or -1 if an error
12578 occurs (and set *REMOTE_ERRNO). */
12579
12580 int
12581 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12582 fileio_error *remote_errno)
12583 {
12584 struct remote_state *rs = get_remote_state ();
12585 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12586 char *p = rs->buf.data ();
12587 int left = get_remote_packet_size () - 1;
12588 char arg[9];
12589 int ret;
12590
12591 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12592 return 0;
12593
12594 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12595 return 0;
12596
12597 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12598
12599 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12600 remote_buffer_add_string (&p, &left, arg);
12601
12602 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12603 remote_errno, NULL, NULL);
12604
12605 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12606 return 0;
12607
12608 if (ret == 0)
12609 rs->fs_pid = required_pid;
12610
12611 return ret;
12612 }
12613
12614 /* Implementation of to_fileio_open. */
12615
12616 int
12617 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12618 int flags, int mode, int warn_if_slow,
12619 fileio_error *remote_errno)
12620 {
12621 struct remote_state *rs = get_remote_state ();
12622 char *p = rs->buf.data ();
12623 int left = get_remote_packet_size () - 1;
12624
12625 if (warn_if_slow)
12626 {
12627 static int warning_issued = 0;
12628
12629 gdb_printf (_("Reading %s from remote target...\n"),
12630 filename);
12631
12632 if (!warning_issued)
12633 {
12634 warning (_("File transfers from remote targets can be slow."
12635 " Use \"set sysroot\" to access files locally"
12636 " instead."));
12637 warning_issued = 1;
12638 }
12639 }
12640
12641 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12642 return -1;
12643
12644 remote_buffer_add_string (&p, &left, "vFile:open:");
12645
12646 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12647 strlen (filename));
12648 remote_buffer_add_string (&p, &left, ",");
12649
12650 remote_buffer_add_int (&p, &left, flags);
12651 remote_buffer_add_string (&p, &left, ",");
12652
12653 remote_buffer_add_int (&p, &left, mode);
12654
12655 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12656 remote_errno, NULL, NULL);
12657 }
12658
12659 int
12660 remote_target::fileio_open (struct inferior *inf, const char *filename,
12661 int flags, int mode, int warn_if_slow,
12662 fileio_error *remote_errno)
12663 {
12664 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12665 remote_errno);
12666 }
12667
12668 /* Implementation of to_fileio_pwrite. */
12669
12670 int
12671 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12672 ULONGEST offset, fileio_error *remote_errno)
12673 {
12674 struct remote_state *rs = get_remote_state ();
12675 char *p = rs->buf.data ();
12676 int left = get_remote_packet_size ();
12677 int out_len;
12678
12679 rs->readahead_cache.invalidate_fd (fd);
12680
12681 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12682
12683 remote_buffer_add_int (&p, &left, fd);
12684 remote_buffer_add_string (&p, &left, ",");
12685
12686 remote_buffer_add_int (&p, &left, offset);
12687 remote_buffer_add_string (&p, &left, ",");
12688
12689 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12690 (get_remote_packet_size ()
12691 - (p - rs->buf.data ())));
12692
12693 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12694 remote_errno, NULL, NULL);
12695 }
12696
12697 int
12698 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12699 ULONGEST offset, fileio_error *remote_errno)
12700 {
12701 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12702 }
12703
12704 /* Helper for the implementation of to_fileio_pread. Read the file
12705 from the remote side with vFile:pread. */
12706
12707 int
12708 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12709 ULONGEST offset, fileio_error *remote_errno)
12710 {
12711 struct remote_state *rs = get_remote_state ();
12712 char *p = rs->buf.data ();
12713 const char *attachment;
12714 int left = get_remote_packet_size ();
12715 int ret, attachment_len;
12716 int read_len;
12717
12718 remote_buffer_add_string (&p, &left, "vFile:pread:");
12719
12720 remote_buffer_add_int (&p, &left, fd);
12721 remote_buffer_add_string (&p, &left, ",");
12722
12723 remote_buffer_add_int (&p, &left, len);
12724 remote_buffer_add_string (&p, &left, ",");
12725
12726 remote_buffer_add_int (&p, &left, offset);
12727
12728 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12729 remote_errno, &attachment,
12730 &attachment_len);
12731
12732 if (ret < 0)
12733 return ret;
12734
12735 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12736 read_buf, len);
12737 if (read_len != ret)
12738 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12739
12740 return ret;
12741 }
12742
12743 /* See declaration.h. */
12744
12745 int
12746 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12747 ULONGEST offset)
12748 {
12749 if (this->fd == fd
12750 && this->offset <= offset
12751 && offset < this->offset + this->buf.size ())
12752 {
12753 ULONGEST max = this->offset + this->buf.size ();
12754
12755 if (offset + len > max)
12756 len = max - offset;
12757
12758 memcpy (read_buf, &this->buf[offset - this->offset], len);
12759 return len;
12760 }
12761
12762 return 0;
12763 }
12764
12765 /* Implementation of to_fileio_pread. */
12766
12767 int
12768 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12769 ULONGEST offset, fileio_error *remote_errno)
12770 {
12771 int ret;
12772 struct remote_state *rs = get_remote_state ();
12773 readahead_cache *cache = &rs->readahead_cache;
12774
12775 ret = cache->pread (fd, read_buf, len, offset);
12776 if (ret > 0)
12777 {
12778 cache->hit_count++;
12779
12780 remote_debug_printf ("readahead cache hit %s",
12781 pulongest (cache->hit_count));
12782 return ret;
12783 }
12784
12785 cache->miss_count++;
12786
12787 remote_debug_printf ("readahead cache miss %s",
12788 pulongest (cache->miss_count));
12789
12790 cache->fd = fd;
12791 cache->offset = offset;
12792 cache->buf.resize (get_remote_packet_size ());
12793
12794 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12795 cache->buf.size (),
12796 cache->offset, remote_errno);
12797 if (ret <= 0)
12798 {
12799 cache->invalidate_fd (fd);
12800 return ret;
12801 }
12802
12803 cache->buf.resize (ret);
12804 return cache->pread (fd, read_buf, len, offset);
12805 }
12806
12807 int
12808 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12809 ULONGEST offset, fileio_error *remote_errno)
12810 {
12811 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12812 }
12813
12814 /* Implementation of to_fileio_close. */
12815
12816 int
12817 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12818 {
12819 struct remote_state *rs = get_remote_state ();
12820 char *p = rs->buf.data ();
12821 int left = get_remote_packet_size () - 1;
12822
12823 rs->readahead_cache.invalidate_fd (fd);
12824
12825 remote_buffer_add_string (&p, &left, "vFile:close:");
12826
12827 remote_buffer_add_int (&p, &left, fd);
12828
12829 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12830 remote_errno, NULL, NULL);
12831 }
12832
12833 int
12834 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12835 {
12836 return remote_hostio_close (fd, remote_errno);
12837 }
12838
12839 /* Implementation of to_fileio_unlink. */
12840
12841 int
12842 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12843 fileio_error *remote_errno)
12844 {
12845 struct remote_state *rs = get_remote_state ();
12846 char *p = rs->buf.data ();
12847 int left = get_remote_packet_size () - 1;
12848
12849 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12850 return -1;
12851
12852 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12853
12854 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12855 strlen (filename));
12856
12857 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12858 remote_errno, NULL, NULL);
12859 }
12860
12861 int
12862 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12863 fileio_error *remote_errno)
12864 {
12865 return remote_hostio_unlink (inf, filename, remote_errno);
12866 }
12867
12868 /* Implementation of to_fileio_readlink. */
12869
12870 gdb::optional<std::string>
12871 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12872 fileio_error *remote_errno)
12873 {
12874 struct remote_state *rs = get_remote_state ();
12875 char *p = rs->buf.data ();
12876 const char *attachment;
12877 int left = get_remote_packet_size ();
12878 int len, attachment_len;
12879 int read_len;
12880
12881 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12882 return {};
12883
12884 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12885
12886 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12887 strlen (filename));
12888
12889 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12890 remote_errno, &attachment,
12891 &attachment_len);
12892
12893 if (len < 0)
12894 return {};
12895
12896 std::string ret (len, '\0');
12897
12898 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12899 (gdb_byte *) &ret[0], len);
12900 if (read_len != len)
12901 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12902
12903 return ret;
12904 }
12905
12906 /* Implementation of to_fileio_fstat. */
12907
12908 int
12909 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12910 {
12911 struct remote_state *rs = get_remote_state ();
12912 char *p = rs->buf.data ();
12913 int left = get_remote_packet_size ();
12914 int attachment_len, ret;
12915 const char *attachment;
12916 struct fio_stat fst;
12917 int read_len;
12918
12919 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12920
12921 remote_buffer_add_int (&p, &left, fd);
12922
12923 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12924 remote_errno, &attachment,
12925 &attachment_len);
12926 if (ret < 0)
12927 {
12928 if (*remote_errno != FILEIO_ENOSYS)
12929 return ret;
12930
12931 /* Strictly we should return -1, ENOSYS here, but when
12932 "set sysroot remote:" was implemented in August 2008
12933 BFD's need for a stat function was sidestepped with
12934 this hack. This was not remedied until March 2015
12935 so we retain the previous behavior to avoid breaking
12936 compatibility.
12937
12938 Note that the memset is a March 2015 addition; older
12939 GDBs set st_size *and nothing else* so the structure
12940 would have garbage in all other fields. This might
12941 break something but retaining the previous behavior
12942 here would be just too wrong. */
12943
12944 memset (st, 0, sizeof (struct stat));
12945 st->st_size = INT_MAX;
12946 return 0;
12947 }
12948
12949 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12950 (gdb_byte *) &fst, sizeof (fst));
12951
12952 if (read_len != ret)
12953 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12954
12955 if (read_len != sizeof (fst))
12956 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12957 read_len, (int) sizeof (fst));
12958
12959 remote_fileio_to_host_stat (&fst, st);
12960
12961 return 0;
12962 }
12963
12964 /* Implementation of to_filesystem_is_local. */
12965
12966 bool
12967 remote_target::filesystem_is_local ()
12968 {
12969 /* Valgrind GDB presents itself as a remote target but works
12970 on the local filesystem: it does not implement remote get
12971 and users are not expected to set a sysroot. To handle
12972 this case we treat the remote filesystem as local if the
12973 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12974 does not support vFile:open. */
12975 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12976 {
12977 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12978
12979 if (ps == PACKET_SUPPORT_UNKNOWN)
12980 {
12981 int fd;
12982 fileio_error remote_errno;
12983
12984 /* Try opening a file to probe support. The supplied
12985 filename is irrelevant, we only care about whether
12986 the stub recognizes the packet or not. */
12987 fd = remote_hostio_open (NULL, "just probing",
12988 FILEIO_O_RDONLY, 0700, 0,
12989 &remote_errno);
12990
12991 if (fd >= 0)
12992 remote_hostio_close (fd, &remote_errno);
12993
12994 ps = m_features.packet_support (PACKET_vFile_open);
12995 }
12996
12997 if (ps == PACKET_DISABLE)
12998 {
12999 static int warning_issued = 0;
13000
13001 if (!warning_issued)
13002 {
13003 warning (_("remote target does not support file"
13004 " transfer, attempting to access files"
13005 " from local filesystem."));
13006 warning_issued = 1;
13007 }
13008
13009 return true;
13010 }
13011 }
13012
13013 return false;
13014 }
13015
13016 static char *
13017 remote_hostio_error (fileio_error errnum)
13018 {
13019 int host_error = fileio_error_to_host (errnum);
13020
13021 if (host_error == -1)
13022 error (_("Unknown remote I/O error %d"), errnum);
13023 else
13024 error (_("Remote I/O error: %s"), safe_strerror (host_error));
13025 }
13026
13027 /* A RAII wrapper around a remote file descriptor. */
13028
13029 class scoped_remote_fd
13030 {
13031 public:
13032 scoped_remote_fd (remote_target *remote, int fd)
13033 : m_remote (remote), m_fd (fd)
13034 {
13035 }
13036
13037 ~scoped_remote_fd ()
13038 {
13039 if (m_fd != -1)
13040 {
13041 try
13042 {
13043 fileio_error remote_errno;
13044 m_remote->remote_hostio_close (m_fd, &remote_errno);
13045 }
13046 catch (...)
13047 {
13048 /* Swallow exception before it escapes the dtor. If
13049 something goes wrong, likely the connection is gone,
13050 and there's nothing else that can be done. */
13051 }
13052 }
13053 }
13054
13055 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
13056
13057 /* Release ownership of the file descriptor, and return it. */
13058 ATTRIBUTE_UNUSED_RESULT int release () noexcept
13059 {
13060 int fd = m_fd;
13061 m_fd = -1;
13062 return fd;
13063 }
13064
13065 /* Return the owned file descriptor. */
13066 int get () const noexcept
13067 {
13068 return m_fd;
13069 }
13070
13071 private:
13072 /* The remote target. */
13073 remote_target *m_remote;
13074
13075 /* The owned remote I/O file descriptor. */
13076 int m_fd;
13077 };
13078
13079 void
13080 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
13081 {
13082 remote_target *remote = get_current_remote_target ();
13083
13084 if (remote == nullptr)
13085 error (_("command can only be used with remote target"));
13086
13087 remote->remote_file_put (local_file, remote_file, from_tty);
13088 }
13089
13090 void
13091 remote_target::remote_file_put (const char *local_file, const char *remote_file,
13092 int from_tty)
13093 {
13094 int retcode, bytes, io_size;
13095 fileio_error remote_errno;
13096 int bytes_in_buffer;
13097 int saw_eof;
13098 ULONGEST offset;
13099
13100 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
13101 if (file == NULL)
13102 perror_with_name (local_file);
13103
13104 scoped_remote_fd fd
13105 (this, remote_hostio_open (NULL,
13106 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
13107 | FILEIO_O_TRUNC),
13108 0700, 0, &remote_errno));
13109 if (fd.get () == -1)
13110 remote_hostio_error (remote_errno);
13111
13112 /* Send up to this many bytes at once. They won't all fit in the
13113 remote packet limit, so we'll transfer slightly fewer. */
13114 io_size = get_remote_packet_size ();
13115 gdb::byte_vector buffer (io_size);
13116
13117 bytes_in_buffer = 0;
13118 saw_eof = 0;
13119 offset = 0;
13120 while (bytes_in_buffer || !saw_eof)
13121 {
13122 if (!saw_eof)
13123 {
13124 bytes = fread (buffer.data () + bytes_in_buffer, 1,
13125 io_size - bytes_in_buffer,
13126 file.get ());
13127 if (bytes == 0)
13128 {
13129 if (ferror (file.get ()))
13130 error (_("Error reading %s."), local_file);
13131 else
13132 {
13133 /* EOF. Unless there is something still in the
13134 buffer from the last iteration, we are done. */
13135 saw_eof = 1;
13136 if (bytes_in_buffer == 0)
13137 break;
13138 }
13139 }
13140 }
13141 else
13142 bytes = 0;
13143
13144 bytes += bytes_in_buffer;
13145 bytes_in_buffer = 0;
13146
13147 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13148 offset, &remote_errno);
13149
13150 if (retcode < 0)
13151 remote_hostio_error (remote_errno);
13152 else if (retcode == 0)
13153 error (_("Remote write of %d bytes returned 0!"), bytes);
13154 else if (retcode < bytes)
13155 {
13156 /* Short write. Save the rest of the read data for the next
13157 write. */
13158 bytes_in_buffer = bytes - retcode;
13159 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13160 }
13161
13162 offset += retcode;
13163 }
13164
13165 if (remote_hostio_close (fd.release (), &remote_errno))
13166 remote_hostio_error (remote_errno);
13167
13168 if (from_tty)
13169 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13170 }
13171
13172 void
13173 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13174 {
13175 remote_target *remote = get_current_remote_target ();
13176
13177 if (remote == nullptr)
13178 error (_("command can only be used with remote target"));
13179
13180 remote->remote_file_get (remote_file, local_file, from_tty);
13181 }
13182
13183 void
13184 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13185 int from_tty)
13186 {
13187 fileio_error remote_errno;
13188 int bytes, io_size;
13189 ULONGEST offset;
13190
13191 scoped_remote_fd fd
13192 (this, remote_hostio_open (NULL,
13193 remote_file, FILEIO_O_RDONLY, 0, 0,
13194 &remote_errno));
13195 if (fd.get () == -1)
13196 remote_hostio_error (remote_errno);
13197
13198 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13199 if (file == NULL)
13200 perror_with_name (local_file);
13201
13202 /* Send up to this many bytes at once. They won't all fit in the
13203 remote packet limit, so we'll transfer slightly fewer. */
13204 io_size = get_remote_packet_size ();
13205 gdb::byte_vector buffer (io_size);
13206
13207 offset = 0;
13208 while (1)
13209 {
13210 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13211 &remote_errno);
13212 if (bytes == 0)
13213 /* Success, but no bytes, means end-of-file. */
13214 break;
13215 if (bytes == -1)
13216 remote_hostio_error (remote_errno);
13217
13218 offset += bytes;
13219
13220 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13221 if (bytes == 0)
13222 perror_with_name (local_file);
13223 }
13224
13225 if (remote_hostio_close (fd.release (), &remote_errno))
13226 remote_hostio_error (remote_errno);
13227
13228 if (from_tty)
13229 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13230 }
13231
13232 void
13233 remote_file_delete (const char *remote_file, int from_tty)
13234 {
13235 remote_target *remote = get_current_remote_target ();
13236
13237 if (remote == nullptr)
13238 error (_("command can only be used with remote target"));
13239
13240 remote->remote_file_delete (remote_file, from_tty);
13241 }
13242
13243 void
13244 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13245 {
13246 int retcode;
13247 fileio_error remote_errno;
13248
13249 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13250 if (retcode == -1)
13251 remote_hostio_error (remote_errno);
13252
13253 if (from_tty)
13254 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13255 }
13256
13257 static void
13258 remote_put_command (const char *args, int from_tty)
13259 {
13260 if (args == NULL)
13261 error_no_arg (_("file to put"));
13262
13263 gdb_argv argv (args);
13264 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13265 error (_("Invalid parameters to remote put"));
13266
13267 remote_file_put (argv[0], argv[1], from_tty);
13268 }
13269
13270 static void
13271 remote_get_command (const char *args, int from_tty)
13272 {
13273 if (args == NULL)
13274 error_no_arg (_("file to get"));
13275
13276 gdb_argv argv (args);
13277 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13278 error (_("Invalid parameters to remote get"));
13279
13280 remote_file_get (argv[0], argv[1], from_tty);
13281 }
13282
13283 static void
13284 remote_delete_command (const char *args, int from_tty)
13285 {
13286 if (args == NULL)
13287 error_no_arg (_("file to delete"));
13288
13289 gdb_argv argv (args);
13290 if (argv[0] == NULL || argv[1] != NULL)
13291 error (_("Invalid parameters to remote delete"));
13292
13293 remote_file_delete (argv[0], from_tty);
13294 }
13295
13296 bool
13297 remote_target::can_execute_reverse ()
13298 {
13299 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13300 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13301 return true;
13302 else
13303 return false;
13304 }
13305
13306 bool
13307 remote_target::supports_non_stop ()
13308 {
13309 return true;
13310 }
13311
13312 bool
13313 remote_target::supports_disable_randomization ()
13314 {
13315 /* Only supported in extended mode. */
13316 return false;
13317 }
13318
13319 bool
13320 remote_target::supports_multi_process ()
13321 {
13322 return m_features.remote_multi_process_p ();
13323 }
13324
13325 int
13326 remote_target::remote_supports_cond_tracepoints ()
13327 {
13328 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13329 == PACKET_ENABLE);
13330 }
13331
13332 bool
13333 remote_target::supports_evaluation_of_breakpoint_conditions ()
13334 {
13335 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13336 == PACKET_ENABLE);
13337 }
13338
13339 int
13340 remote_target::remote_supports_fast_tracepoints ()
13341 {
13342 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13343 }
13344
13345 int
13346 remote_target::remote_supports_static_tracepoints ()
13347 {
13348 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13349 }
13350
13351 int
13352 remote_target::remote_supports_install_in_trace ()
13353 {
13354 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13355 }
13356
13357 bool
13358 remote_target::supports_enable_disable_tracepoint ()
13359 {
13360 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13361 == PACKET_ENABLE);
13362 }
13363
13364 bool
13365 remote_target::supports_string_tracing ()
13366 {
13367 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13368 }
13369
13370 bool
13371 remote_target::can_run_breakpoint_commands ()
13372 {
13373 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13374 }
13375
13376 void
13377 remote_target::trace_init ()
13378 {
13379 struct remote_state *rs = get_remote_state ();
13380
13381 putpkt ("QTinit");
13382 remote_get_noisy_reply ();
13383 if (strcmp (rs->buf.data (), "OK") != 0)
13384 error (_("Target does not support this command."));
13385 }
13386
13387 /* Recursive routine to walk through command list including loops, and
13388 download packets for each command. */
13389
13390 void
13391 remote_target::remote_download_command_source (int num, ULONGEST addr,
13392 struct command_line *cmds)
13393 {
13394 struct remote_state *rs = get_remote_state ();
13395 struct command_line *cmd;
13396
13397 for (cmd = cmds; cmd; cmd = cmd->next)
13398 {
13399 QUIT; /* Allow user to bail out with ^C. */
13400 strcpy (rs->buf.data (), "QTDPsrc:");
13401 encode_source_string (num, addr, "cmd", cmd->line,
13402 rs->buf.data () + strlen (rs->buf.data ()),
13403 rs->buf.size () - strlen (rs->buf.data ()));
13404 putpkt (rs->buf);
13405 remote_get_noisy_reply ();
13406 if (strcmp (rs->buf.data (), "OK"))
13407 warning (_("Target does not support source download."));
13408
13409 if (cmd->control_type == while_control
13410 || cmd->control_type == while_stepping_control)
13411 {
13412 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13413
13414 QUIT; /* Allow user to bail out with ^C. */
13415 strcpy (rs->buf.data (), "QTDPsrc:");
13416 encode_source_string (num, addr, "cmd", "end",
13417 rs->buf.data () + strlen (rs->buf.data ()),
13418 rs->buf.size () - strlen (rs->buf.data ()));
13419 putpkt (rs->buf);
13420 remote_get_noisy_reply ();
13421 if (strcmp (rs->buf.data (), "OK"))
13422 warning (_("Target does not support source download."));
13423 }
13424 }
13425 }
13426
13427 void
13428 remote_target::download_tracepoint (struct bp_location *loc)
13429 {
13430 CORE_ADDR tpaddr;
13431 char addrbuf[40];
13432 std::vector<std::string> tdp_actions;
13433 std::vector<std::string> stepping_actions;
13434 char *pkt;
13435 struct breakpoint *b = loc->owner;
13436 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
13437 struct remote_state *rs = get_remote_state ();
13438 int ret;
13439 const char *err_msg = _("Tracepoint packet too large for target.");
13440 size_t size_left;
13441
13442 /* We use a buffer other than rs->buf because we'll build strings
13443 across multiple statements, and other statements in between could
13444 modify rs->buf. */
13445 gdb::char_vector buf (get_remote_packet_size ());
13446
13447 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13448
13449 tpaddr = loc->address;
13450 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13451 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13452 b->number, addrbuf, /* address */
13453 (b->enable_state == bp_enabled ? 'E' : 'D'),
13454 t->step_count, t->pass_count);
13455
13456 if (ret < 0 || ret >= buf.size ())
13457 error ("%s", err_msg);
13458
13459 /* Fast tracepoints are mostly handled by the target, but we can
13460 tell the target how big of an instruction block should be moved
13461 around. */
13462 if (b->type == bp_fast_tracepoint)
13463 {
13464 /* Only test for support at download time; we may not know
13465 target capabilities at definition time. */
13466 if (remote_supports_fast_tracepoints ())
13467 {
13468 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13469 NULL))
13470 {
13471 size_left = buf.size () - strlen (buf.data ());
13472 ret = snprintf (buf.data () + strlen (buf.data ()),
13473 size_left, ":F%x",
13474 gdb_insn_length (loc->gdbarch, tpaddr));
13475
13476 if (ret < 0 || ret >= size_left)
13477 error ("%s", err_msg);
13478 }
13479 else
13480 /* If it passed validation at definition but fails now,
13481 something is very wrong. */
13482 internal_error (_("Fast tracepoint not valid during download"));
13483 }
13484 else
13485 /* Fast tracepoints are functionally identical to regular
13486 tracepoints, so don't take lack of support as a reason to
13487 give up on the trace run. */
13488 warning (_("Target does not support fast tracepoints, "
13489 "downloading %d as regular tracepoint"), b->number);
13490 }
13491 else if (b->type == bp_static_tracepoint
13492 || b->type == bp_static_marker_tracepoint)
13493 {
13494 /* Only test for support at download time; we may not know
13495 target capabilities at definition time. */
13496 if (remote_supports_static_tracepoints ())
13497 {
13498 struct static_tracepoint_marker marker;
13499
13500 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13501 {
13502 size_left = buf.size () - strlen (buf.data ());
13503 ret = snprintf (buf.data () + strlen (buf.data ()),
13504 size_left, ":S");
13505
13506 if (ret < 0 || ret >= size_left)
13507 error ("%s", err_msg);
13508 }
13509 else
13510 error (_("Static tracepoint not valid during download"));
13511 }
13512 else
13513 /* Fast tracepoints are functionally identical to regular
13514 tracepoints, so don't take lack of support as a reason
13515 to give up on the trace run. */
13516 error (_("Target does not support static tracepoints"));
13517 }
13518 /* If the tracepoint has a conditional, make it into an agent
13519 expression and append to the definition. */
13520 if (loc->cond)
13521 {
13522 /* Only test support at download time, we may not know target
13523 capabilities at definition time. */
13524 if (remote_supports_cond_tracepoints ())
13525 {
13526 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13527 loc->cond.get ());
13528
13529 size_left = buf.size () - strlen (buf.data ());
13530
13531 ret = snprintf (buf.data () + strlen (buf.data ()),
13532 size_left, ":X%x,", (int) aexpr->buf.size ());
13533
13534 if (ret < 0 || ret >= size_left)
13535 error ("%s", err_msg);
13536
13537 size_left = buf.size () - strlen (buf.data ());
13538
13539 /* Two bytes to encode each aexpr byte, plus the terminating
13540 null byte. */
13541 if (aexpr->buf.size () * 2 + 1 > size_left)
13542 error ("%s", err_msg);
13543
13544 pkt = buf.data () + strlen (buf.data ());
13545
13546 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13547 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13548 *pkt = '\0';
13549 }
13550 else
13551 warning (_("Target does not support conditional tracepoints, "
13552 "ignoring tp %d cond"), b->number);
13553 }
13554
13555 if (b->commands || !default_collect.empty ())
13556 {
13557 size_left = buf.size () - strlen (buf.data ());
13558
13559 ret = snprintf (buf.data () + strlen (buf.data ()),
13560 size_left, "-");
13561
13562 if (ret < 0 || ret >= size_left)
13563 error ("%s", err_msg);
13564 }
13565
13566 putpkt (buf.data ());
13567 remote_get_noisy_reply ();
13568 if (strcmp (rs->buf.data (), "OK"))
13569 error (_("Target does not support tracepoints."));
13570
13571 /* do_single_steps (t); */
13572 for (auto action_it = tdp_actions.begin ();
13573 action_it != tdp_actions.end (); action_it++)
13574 {
13575 QUIT; /* Allow user to bail out with ^C. */
13576
13577 bool has_more = ((action_it + 1) != tdp_actions.end ()
13578 || !stepping_actions.empty ());
13579
13580 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13581 b->number, addrbuf, /* address */
13582 action_it->c_str (),
13583 has_more ? '-' : 0);
13584
13585 if (ret < 0 || ret >= buf.size ())
13586 error ("%s", err_msg);
13587
13588 putpkt (buf.data ());
13589 remote_get_noisy_reply ();
13590 if (strcmp (rs->buf.data (), "OK"))
13591 error (_("Error on target while setting tracepoints."));
13592 }
13593
13594 for (auto action_it = stepping_actions.begin ();
13595 action_it != stepping_actions.end (); action_it++)
13596 {
13597 QUIT; /* Allow user to bail out with ^C. */
13598
13599 bool is_first = action_it == stepping_actions.begin ();
13600 bool has_more = (action_it + 1) != stepping_actions.end ();
13601
13602 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13603 b->number, addrbuf, /* address */
13604 is_first ? "S" : "",
13605 action_it->c_str (),
13606 has_more ? "-" : "");
13607
13608 if (ret < 0 || ret >= buf.size ())
13609 error ("%s", err_msg);
13610
13611 putpkt (buf.data ());
13612 remote_get_noisy_reply ();
13613 if (strcmp (rs->buf.data (), "OK"))
13614 error (_("Error on target while setting tracepoints."));
13615 }
13616
13617 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13618 {
13619 if (b->locspec != nullptr)
13620 {
13621 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13622
13623 if (ret < 0 || ret >= buf.size ())
13624 error ("%s", err_msg);
13625
13626 const char *str = b->locspec->to_string ();
13627 encode_source_string (b->number, loc->address, "at", str,
13628 buf.data () + strlen (buf.data ()),
13629 buf.size () - strlen (buf.data ()));
13630 putpkt (buf.data ());
13631 remote_get_noisy_reply ();
13632 if (strcmp (rs->buf.data (), "OK"))
13633 warning (_("Target does not support source download."));
13634 }
13635 if (b->cond_string)
13636 {
13637 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13638
13639 if (ret < 0 || ret >= buf.size ())
13640 error ("%s", err_msg);
13641
13642 encode_source_string (b->number, loc->address,
13643 "cond", b->cond_string.get (),
13644 buf.data () + strlen (buf.data ()),
13645 buf.size () - strlen (buf.data ()));
13646 putpkt (buf.data ());
13647 remote_get_noisy_reply ();
13648 if (strcmp (rs->buf.data (), "OK"))
13649 warning (_("Target does not support source download."));
13650 }
13651 remote_download_command_source (b->number, loc->address,
13652 breakpoint_commands (b));
13653 }
13654 }
13655
13656 bool
13657 remote_target::can_download_tracepoint ()
13658 {
13659 struct remote_state *rs = get_remote_state ();
13660 struct trace_status *ts;
13661 int status;
13662
13663 /* Don't try to install tracepoints until we've relocated our
13664 symbols, and fetched and merged the target's tracepoint list with
13665 ours. */
13666 if (rs->starting_up)
13667 return false;
13668
13669 ts = current_trace_status ();
13670 status = get_trace_status (ts);
13671
13672 if (status == -1 || !ts->running_known || !ts->running)
13673 return false;
13674
13675 /* If we are in a tracing experiment, but remote stub doesn't support
13676 installing tracepoint in trace, we have to return. */
13677 if (!remote_supports_install_in_trace ())
13678 return false;
13679
13680 return true;
13681 }
13682
13683
13684 void
13685 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13686 {
13687 struct remote_state *rs = get_remote_state ();
13688 char *p;
13689
13690 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13691 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13692 tsv.builtin);
13693 p = rs->buf.data () + strlen (rs->buf.data ());
13694 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13695 >= get_remote_packet_size ())
13696 error (_("Trace state variable name too long for tsv definition packet"));
13697 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13698 *p++ = '\0';
13699 putpkt (rs->buf);
13700 remote_get_noisy_reply ();
13701 if (rs->buf[0] == '\0')
13702 error (_("Target does not support this command."));
13703 if (strcmp (rs->buf.data (), "OK") != 0)
13704 error (_("Error on target while downloading trace state variable."));
13705 }
13706
13707 void
13708 remote_target::enable_tracepoint (struct bp_location *location)
13709 {
13710 struct remote_state *rs = get_remote_state ();
13711
13712 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13713 location->owner->number,
13714 phex (location->address, sizeof (CORE_ADDR)));
13715 putpkt (rs->buf);
13716 remote_get_noisy_reply ();
13717 if (rs->buf[0] == '\0')
13718 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13719 if (strcmp (rs->buf.data (), "OK") != 0)
13720 error (_("Error on target while enabling tracepoint."));
13721 }
13722
13723 void
13724 remote_target::disable_tracepoint (struct bp_location *location)
13725 {
13726 struct remote_state *rs = get_remote_state ();
13727
13728 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13729 location->owner->number,
13730 phex (location->address, sizeof (CORE_ADDR)));
13731 putpkt (rs->buf);
13732 remote_get_noisy_reply ();
13733 if (rs->buf[0] == '\0')
13734 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13735 if (strcmp (rs->buf.data (), "OK") != 0)
13736 error (_("Error on target while disabling tracepoint."));
13737 }
13738
13739 void
13740 remote_target::trace_set_readonly_regions ()
13741 {
13742 asection *s;
13743 bfd_size_type size;
13744 bfd_vma vma;
13745 int anysecs = 0;
13746 int offset = 0;
13747 bfd *abfd = current_program_space->exec_bfd ();
13748
13749 if (!abfd)
13750 return; /* No information to give. */
13751
13752 struct remote_state *rs = get_remote_state ();
13753
13754 strcpy (rs->buf.data (), "QTro");
13755 offset = strlen (rs->buf.data ());
13756 for (s = abfd->sections; s; s = s->next)
13757 {
13758 char tmp1[40], tmp2[40];
13759 int sec_length;
13760
13761 if ((s->flags & SEC_LOAD) == 0
13762 /* || (s->flags & SEC_CODE) == 0 */
13763 || (s->flags & SEC_READONLY) == 0)
13764 continue;
13765
13766 anysecs = 1;
13767 vma = bfd_section_vma (s);
13768 size = bfd_section_size (s);
13769 bfd_sprintf_vma (abfd, tmp1, vma);
13770 bfd_sprintf_vma (abfd, tmp2, vma + size);
13771 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13772 if (offset + sec_length + 1 > rs->buf.size ())
13773 {
13774 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13775 != PACKET_ENABLE)
13776 warning (_("\
13777 Too many sections for read-only sections definition packet."));
13778 break;
13779 }
13780 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13781 tmp1, tmp2);
13782 offset += sec_length;
13783 }
13784 if (anysecs)
13785 {
13786 putpkt (rs->buf);
13787 getpkt (&rs->buf);
13788 }
13789 }
13790
13791 void
13792 remote_target::trace_start ()
13793 {
13794 struct remote_state *rs = get_remote_state ();
13795
13796 putpkt ("QTStart");
13797 remote_get_noisy_reply ();
13798 if (rs->buf[0] == '\0')
13799 error (_("Target does not support this command."));
13800 if (strcmp (rs->buf.data (), "OK") != 0)
13801 error (_("Bogus reply from target: %s"), rs->buf.data ());
13802 }
13803
13804 int
13805 remote_target::get_trace_status (struct trace_status *ts)
13806 {
13807 /* Initialize it just to avoid a GCC false warning. */
13808 char *p = NULL;
13809 enum packet_result result;
13810 struct remote_state *rs = get_remote_state ();
13811
13812 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13813 return -1;
13814
13815 /* FIXME we need to get register block size some other way. */
13816 trace_regblock_size
13817 = rs->get_remote_arch_state (current_inferior ()->arch ())->sizeof_g_packet;
13818
13819 putpkt ("qTStatus");
13820
13821 try
13822 {
13823 p = remote_get_noisy_reply ();
13824 }
13825 catch (const gdb_exception_error &ex)
13826 {
13827 if (ex.error != TARGET_CLOSE_ERROR)
13828 {
13829 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13830 return -1;
13831 }
13832 throw;
13833 }
13834
13835 result = m_features.packet_ok (p, PACKET_qTStatus);
13836
13837 /* If the remote target doesn't do tracing, flag it. */
13838 if (result == PACKET_UNKNOWN)
13839 return -1;
13840
13841 /* We're working with a live target. */
13842 ts->filename = NULL;
13843
13844 if (*p++ != 'T')
13845 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13846
13847 /* Function 'parse_trace_status' sets default value of each field of
13848 'ts' at first, so we don't have to do it here. */
13849 parse_trace_status (p, ts);
13850
13851 return ts->running;
13852 }
13853
13854 void
13855 remote_target::get_tracepoint_status (tracepoint *tp,
13856 struct uploaded_tp *utp)
13857 {
13858 struct remote_state *rs = get_remote_state ();
13859 char *reply;
13860 size_t size = get_remote_packet_size ();
13861
13862 if (tp)
13863 {
13864 tp->hit_count = 0;
13865 tp->traceframe_usage = 0;
13866 for (bp_location &loc : tp->locations ())
13867 {
13868 /* If the tracepoint was never downloaded, don't go asking for
13869 any status. */
13870 if (tp->number_on_target == 0)
13871 continue;
13872 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13873 phex_nz (loc.address, 0));
13874 putpkt (rs->buf);
13875 reply = remote_get_noisy_reply ();
13876 if (reply && *reply)
13877 {
13878 if (*reply == 'V')
13879 parse_tracepoint_status (reply + 1, tp, utp);
13880 }
13881 }
13882 }
13883 else if (utp)
13884 {
13885 utp->hit_count = 0;
13886 utp->traceframe_usage = 0;
13887 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13888 phex_nz (utp->addr, 0));
13889 putpkt (rs->buf);
13890 reply = remote_get_noisy_reply ();
13891 if (reply && *reply)
13892 {
13893 if (*reply == 'V')
13894 parse_tracepoint_status (reply + 1, tp, utp);
13895 }
13896 }
13897 }
13898
13899 void
13900 remote_target::trace_stop ()
13901 {
13902 struct remote_state *rs = get_remote_state ();
13903
13904 putpkt ("QTStop");
13905 remote_get_noisy_reply ();
13906 if (rs->buf[0] == '\0')
13907 error (_("Target does not support this command."));
13908 if (strcmp (rs->buf.data (), "OK") != 0)
13909 error (_("Bogus reply from target: %s"), rs->buf.data ());
13910 }
13911
13912 int
13913 remote_target::trace_find (enum trace_find_type type, int num,
13914 CORE_ADDR addr1, CORE_ADDR addr2,
13915 int *tpp)
13916 {
13917 struct remote_state *rs = get_remote_state ();
13918 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13919 char *p, *reply;
13920 int target_frameno = -1, target_tracept = -1;
13921
13922 /* Lookups other than by absolute frame number depend on the current
13923 trace selected, so make sure it is correct on the remote end
13924 first. */
13925 if (type != tfind_number)
13926 set_remote_traceframe ();
13927
13928 p = rs->buf.data ();
13929 strcpy (p, "QTFrame:");
13930 p = strchr (p, '\0');
13931 switch (type)
13932 {
13933 case tfind_number:
13934 xsnprintf (p, endbuf - p, "%x", num);
13935 break;
13936 case tfind_pc:
13937 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13938 break;
13939 case tfind_tp:
13940 xsnprintf (p, endbuf - p, "tdp:%x", num);
13941 break;
13942 case tfind_range:
13943 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13944 phex_nz (addr2, 0));
13945 break;
13946 case tfind_outside:
13947 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13948 phex_nz (addr2, 0));
13949 break;
13950 default:
13951 error (_("Unknown trace find type %d"), type);
13952 }
13953
13954 putpkt (rs->buf);
13955 reply = remote_get_noisy_reply ();
13956 if (*reply == '\0')
13957 error (_("Target does not support this command."));
13958
13959 while (reply && *reply)
13960 switch (*reply)
13961 {
13962 case 'F':
13963 p = ++reply;
13964 target_frameno = (int) strtol (p, &reply, 16);
13965 if (reply == p)
13966 error (_("Unable to parse trace frame number"));
13967 /* Don't update our remote traceframe number cache on failure
13968 to select a remote traceframe. */
13969 if (target_frameno == -1)
13970 return -1;
13971 break;
13972 case 'T':
13973 p = ++reply;
13974 target_tracept = (int) strtol (p, &reply, 16);
13975 if (reply == p)
13976 error (_("Unable to parse tracepoint number"));
13977 break;
13978 case 'O': /* "OK"? */
13979 if (reply[1] == 'K' && reply[2] == '\0')
13980 reply += 2;
13981 else
13982 error (_("Bogus reply from target: %s"), reply);
13983 break;
13984 default:
13985 error (_("Bogus reply from target: %s"), reply);
13986 }
13987 if (tpp)
13988 *tpp = target_tracept;
13989
13990 rs->remote_traceframe_number = target_frameno;
13991 return target_frameno;
13992 }
13993
13994 bool
13995 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13996 {
13997 struct remote_state *rs = get_remote_state ();
13998 char *reply;
13999 ULONGEST uval;
14000
14001 set_remote_traceframe ();
14002
14003 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
14004 putpkt (rs->buf);
14005 reply = remote_get_noisy_reply ();
14006 if (reply && *reply)
14007 {
14008 if (*reply == 'V')
14009 {
14010 unpack_varlen_hex (reply + 1, &uval);
14011 *val = (LONGEST) uval;
14012 return true;
14013 }
14014 }
14015 return false;
14016 }
14017
14018 int
14019 remote_target::save_trace_data (const char *filename)
14020 {
14021 struct remote_state *rs = get_remote_state ();
14022 char *p, *reply;
14023
14024 p = rs->buf.data ();
14025 strcpy (p, "QTSave:");
14026 p += strlen (p);
14027 if ((p - rs->buf.data ()) + strlen (filename) * 2
14028 >= get_remote_packet_size ())
14029 error (_("Remote file name too long for trace save packet"));
14030 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
14031 *p++ = '\0';
14032 putpkt (rs->buf);
14033 reply = remote_get_noisy_reply ();
14034 if (*reply == '\0')
14035 error (_("Target does not support this command."));
14036 if (strcmp (reply, "OK") != 0)
14037 error (_("Bogus reply from target: %s"), reply);
14038 return 0;
14039 }
14040
14041 /* This is basically a memory transfer, but needs to be its own packet
14042 because we don't know how the target actually organizes its trace
14043 memory, plus we want to be able to ask for as much as possible, but
14044 not be unhappy if we don't get as much as we ask for. */
14045
14046 LONGEST
14047 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
14048 {
14049 struct remote_state *rs = get_remote_state ();
14050 char *reply;
14051 char *p;
14052 int rslt;
14053
14054 p = rs->buf.data ();
14055 strcpy (p, "qTBuffer:");
14056 p += strlen (p);
14057 p += hexnumstr (p, offset);
14058 *p++ = ',';
14059 p += hexnumstr (p, len);
14060 *p++ = '\0';
14061
14062 putpkt (rs->buf);
14063 reply = remote_get_noisy_reply ();
14064 if (reply && *reply)
14065 {
14066 /* 'l' by itself means we're at the end of the buffer and
14067 there is nothing more to get. */
14068 if (*reply == 'l')
14069 return 0;
14070
14071 /* Convert the reply into binary. Limit the number of bytes to
14072 convert according to our passed-in buffer size, rather than
14073 what was returned in the packet; if the target is
14074 unexpectedly generous and gives us a bigger reply than we
14075 asked for, we don't want to crash. */
14076 rslt = hex2bin (reply, buf, len);
14077 return rslt;
14078 }
14079
14080 /* Something went wrong, flag as an error. */
14081 return -1;
14082 }
14083
14084 void
14085 remote_target::set_disconnected_tracing (int val)
14086 {
14087 struct remote_state *rs = get_remote_state ();
14088
14089 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
14090 == PACKET_ENABLE)
14091 {
14092 char *reply;
14093
14094 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14095 "QTDisconnected:%x", val);
14096 putpkt (rs->buf);
14097 reply = remote_get_noisy_reply ();
14098 if (*reply == '\0')
14099 error (_("Target does not support this command."));
14100 if (strcmp (reply, "OK") != 0)
14101 error (_("Bogus reply from target: %s"), reply);
14102 }
14103 else if (val)
14104 warning (_("Target does not support disconnected tracing."));
14105 }
14106
14107 int
14108 remote_target::core_of_thread (ptid_t ptid)
14109 {
14110 thread_info *info = this->find_thread (ptid);
14111
14112 if (info != NULL && info->priv != NULL)
14113 return get_remote_thread_info (info)->core;
14114
14115 return -1;
14116 }
14117
14118 void
14119 remote_target::set_circular_trace_buffer (int val)
14120 {
14121 struct remote_state *rs = get_remote_state ();
14122 char *reply;
14123
14124 xsnprintf (rs->buf.data (), get_remote_packet_size (),
14125 "QTBuffer:circular:%x", val);
14126 putpkt (rs->buf);
14127 reply = remote_get_noisy_reply ();
14128 if (*reply == '\0')
14129 error (_("Target does not support this command."));
14130 if (strcmp (reply, "OK") != 0)
14131 error (_("Bogus reply from target: %s"), reply);
14132 }
14133
14134 traceframe_info_up
14135 remote_target::traceframe_info ()
14136 {
14137 gdb::optional<gdb::char_vector> text
14138 = target_read_stralloc (current_inferior ()->top_target (),
14139 TARGET_OBJECT_TRACEFRAME_INFO,
14140 NULL);
14141 if (text)
14142 return parse_traceframe_info (text->data ());
14143
14144 return NULL;
14145 }
14146
14147 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14148 instruction on which a fast tracepoint may be placed. Returns -1
14149 if the packet is not supported, and 0 if the minimum instruction
14150 length is unknown. */
14151
14152 int
14153 remote_target::get_min_fast_tracepoint_insn_len ()
14154 {
14155 struct remote_state *rs = get_remote_state ();
14156 char *reply;
14157
14158 /* If we're not debugging a process yet, the IPA can't be
14159 loaded. */
14160 if (!target_has_execution ())
14161 return 0;
14162
14163 /* Make sure the remote is pointing at the right process. */
14164 set_general_process ();
14165
14166 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14167 putpkt (rs->buf);
14168 reply = remote_get_noisy_reply ();
14169 if (*reply == '\0')
14170 return -1;
14171 else
14172 {
14173 ULONGEST min_insn_len;
14174
14175 unpack_varlen_hex (reply, &min_insn_len);
14176
14177 return (int) min_insn_len;
14178 }
14179 }
14180
14181 void
14182 remote_target::set_trace_buffer_size (LONGEST val)
14183 {
14184 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14185 {
14186 struct remote_state *rs = get_remote_state ();
14187 char *buf = rs->buf.data ();
14188 char *endbuf = buf + get_remote_packet_size ();
14189 enum packet_result result;
14190
14191 gdb_assert (val >= 0 || val == -1);
14192 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14193 /* Send -1 as literal "-1" to avoid host size dependency. */
14194 if (val < 0)
14195 {
14196 *buf++ = '-';
14197 buf += hexnumstr (buf, (ULONGEST) -val);
14198 }
14199 else
14200 buf += hexnumstr (buf, (ULONGEST) val);
14201
14202 putpkt (rs->buf);
14203 remote_get_noisy_reply ();
14204 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14205
14206 if (result != PACKET_OK)
14207 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14208 }
14209 }
14210
14211 bool
14212 remote_target::set_trace_notes (const char *user, const char *notes,
14213 const char *stop_notes)
14214 {
14215 struct remote_state *rs = get_remote_state ();
14216 char *reply;
14217 char *buf = rs->buf.data ();
14218 char *endbuf = buf + get_remote_packet_size ();
14219 int nbytes;
14220
14221 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14222 if (user)
14223 {
14224 buf += xsnprintf (buf, endbuf - buf, "user:");
14225 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14226 buf += 2 * nbytes;
14227 *buf++ = ';';
14228 }
14229 if (notes)
14230 {
14231 buf += xsnprintf (buf, endbuf - buf, "notes:");
14232 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14233 buf += 2 * nbytes;
14234 *buf++ = ';';
14235 }
14236 if (stop_notes)
14237 {
14238 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14239 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14240 buf += 2 * nbytes;
14241 *buf++ = ';';
14242 }
14243 /* Ensure the buffer is terminated. */
14244 *buf = '\0';
14245
14246 putpkt (rs->buf);
14247 reply = remote_get_noisy_reply ();
14248 if (*reply == '\0')
14249 return false;
14250
14251 if (strcmp (reply, "OK") != 0)
14252 error (_("Bogus reply from target: %s"), reply);
14253
14254 return true;
14255 }
14256
14257 bool
14258 remote_target::use_agent (bool use)
14259 {
14260 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14261 {
14262 struct remote_state *rs = get_remote_state ();
14263
14264 /* If the stub supports QAgent. */
14265 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14266 putpkt (rs->buf);
14267 getpkt (&rs->buf);
14268
14269 if (strcmp (rs->buf.data (), "OK") == 0)
14270 {
14271 ::use_agent = use;
14272 return true;
14273 }
14274 }
14275
14276 return false;
14277 }
14278
14279 bool
14280 remote_target::can_use_agent ()
14281 {
14282 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14283 }
14284
14285 #if defined (HAVE_LIBEXPAT)
14286
14287 /* Check the btrace document version. */
14288
14289 static void
14290 check_xml_btrace_version (struct gdb_xml_parser *parser,
14291 const struct gdb_xml_element *element,
14292 void *user_data,
14293 std::vector<gdb_xml_value> &attributes)
14294 {
14295 const char *version
14296 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
14297
14298 if (strcmp (version, "1.0") != 0)
14299 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
14300 }
14301
14302 /* Parse a btrace "block" xml record. */
14303
14304 static void
14305 parse_xml_btrace_block (struct gdb_xml_parser *parser,
14306 const struct gdb_xml_element *element,
14307 void *user_data,
14308 std::vector<gdb_xml_value> &attributes)
14309 {
14310 struct btrace_data *btrace;
14311 ULONGEST *begin, *end;
14312
14313 btrace = (struct btrace_data *) user_data;
14314
14315 switch (btrace->format)
14316 {
14317 case BTRACE_FORMAT_BTS:
14318 break;
14319
14320 case BTRACE_FORMAT_NONE:
14321 btrace->format = BTRACE_FORMAT_BTS;
14322 btrace->variant.bts.blocks = new std::vector<btrace_block>;
14323 break;
14324
14325 default:
14326 gdb_xml_error (parser, _("Btrace format error."));
14327 }
14328
14329 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
14330 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
14331 btrace->variant.bts.blocks->emplace_back (*begin, *end);
14332 }
14333
14334 /* Parse a "raw" xml record. */
14335
14336 static void
14337 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
14338 gdb_byte **pdata, size_t *psize)
14339 {
14340 gdb_byte *bin;
14341 size_t len, size;
14342
14343 len = strlen (body_text);
14344 if (len % 2 != 0)
14345 gdb_xml_error (parser, _("Bad raw data size."));
14346
14347 size = len / 2;
14348
14349 gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
14350 bin = data.get ();
14351
14352 /* We use hex encoding - see gdbsupport/rsp-low.h. */
14353 while (len > 0)
14354 {
14355 char hi, lo;
14356
14357 hi = *body_text++;
14358 lo = *body_text++;
14359
14360 if (hi == 0 || lo == 0)
14361 gdb_xml_error (parser, _("Bad hex encoding."));
14362
14363 *bin++ = fromhex (hi) * 16 + fromhex (lo);
14364 len -= 2;
14365 }
14366
14367 *pdata = data.release ();
14368 *psize = size;
14369 }
14370
14371 /* Parse a btrace pt-config "cpu" xml record. */
14372
14373 static void
14374 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
14375 const struct gdb_xml_element *element,
14376 void *user_data,
14377 std::vector<gdb_xml_value> &attributes)
14378 {
14379 struct btrace_data *btrace;
14380 const char *vendor;
14381 ULONGEST *family, *model, *stepping;
14382
14383 vendor
14384 = (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
14385 family
14386 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
14387 model
14388 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
14389 stepping
14390 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
14391
14392 btrace = (struct btrace_data *) user_data;
14393
14394 if (strcmp (vendor, "GenuineIntel") == 0)
14395 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
14396
14397 btrace->variant.pt.config.cpu.family = *family;
14398 btrace->variant.pt.config.cpu.model = *model;
14399 btrace->variant.pt.config.cpu.stepping = *stepping;
14400 }
14401
14402 /* Parse a btrace pt "raw" xml record. */
14403
14404 static void
14405 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
14406 const struct gdb_xml_element *element,
14407 void *user_data, const char *body_text)
14408 {
14409 struct btrace_data *btrace;
14410
14411 btrace = (struct btrace_data *) user_data;
14412 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
14413 &btrace->variant.pt.size);
14414 }
14415
14416 /* Parse a btrace "pt" xml record. */
14417
14418 static void
14419 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
14420 const struct gdb_xml_element *element,
14421 void *user_data,
14422 std::vector<gdb_xml_value> &attributes)
14423 {
14424 struct btrace_data *btrace;
14425
14426 btrace = (struct btrace_data *) user_data;
14427 btrace->format = BTRACE_FORMAT_PT;
14428 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
14429 btrace->variant.pt.data = NULL;
14430 btrace->variant.pt.size = 0;
14431 }
14432
14433 static const struct gdb_xml_attribute block_attributes[] = {
14434 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14435 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14436 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14437 };
14438
14439 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
14440 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
14441 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14442 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14443 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
14444 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14445 };
14446
14447 static const struct gdb_xml_element btrace_pt_config_children[] = {
14448 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
14449 parse_xml_btrace_pt_config_cpu, NULL },
14450 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14451 };
14452
14453 static const struct gdb_xml_element btrace_pt_children[] = {
14454 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
14455 NULL },
14456 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
14457 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14458 };
14459
14460 static const struct gdb_xml_attribute btrace_attributes[] = {
14461 { "version", GDB_XML_AF_NONE, NULL, NULL },
14462 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14463 };
14464
14465 static const struct gdb_xml_element btrace_children[] = {
14466 { "block", block_attributes, NULL,
14467 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
14468 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
14469 NULL },
14470 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14471 };
14472
14473 static const struct gdb_xml_element btrace_elements[] = {
14474 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
14475 check_xml_btrace_version, NULL },
14476 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14477 };
14478
14479 #endif /* defined (HAVE_LIBEXPAT) */
14480
14481 /* Parse a branch trace xml document XML into DATA. */
14482
14483 static void
14484 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
14485 {
14486 #if defined (HAVE_LIBEXPAT)
14487
14488 int errcode;
14489 btrace_data result;
14490 result.format = BTRACE_FORMAT_NONE;
14491
14492 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
14493 buffer, &result);
14494 if (errcode != 0)
14495 error (_("Error parsing branch trace."));
14496
14497 /* Keep parse results. */
14498 *btrace = std::move (result);
14499
14500 #else /* !defined (HAVE_LIBEXPAT) */
14501
14502 error (_("Cannot process branch trace. XML support was disabled at "
14503 "compile time."));
14504
14505 #endif /* !defined (HAVE_LIBEXPAT) */
14506 }
14507
14508 #if defined (HAVE_LIBEXPAT)
14509
14510 /* Parse a btrace-conf "bts" xml record. */
14511
14512 static void
14513 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
14514 const struct gdb_xml_element *element,
14515 void *user_data,
14516 std::vector<gdb_xml_value> &attributes)
14517 {
14518 struct btrace_config *conf;
14519 struct gdb_xml_value *size;
14520
14521 conf = (struct btrace_config *) user_data;
14522 conf->format = BTRACE_FORMAT_BTS;
14523 conf->bts.size = 0;
14524
14525 size = xml_find_attribute (attributes, "size");
14526 if (size != NULL)
14527 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
14528 }
14529
14530 /* Parse a btrace-conf "pt" xml record. */
14531
14532 static void
14533 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
14534 const struct gdb_xml_element *element,
14535 void *user_data,
14536 std::vector<gdb_xml_value> &attributes)
14537 {
14538 struct btrace_config *conf;
14539 struct gdb_xml_value *size;
14540
14541 conf = (struct btrace_config *) user_data;
14542 conf->format = BTRACE_FORMAT_PT;
14543 conf->pt.size = 0;
14544
14545 size = xml_find_attribute (attributes, "size");
14546 if (size != NULL)
14547 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
14548 }
14549
14550 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
14551 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14552 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14553 };
14554
14555 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
14556 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
14557 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14558 };
14559
14560 static const struct gdb_xml_element btrace_conf_children[] = {
14561 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
14562 parse_xml_btrace_conf_bts, NULL },
14563 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
14564 parse_xml_btrace_conf_pt, NULL },
14565 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14566 };
14567
14568 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
14569 { "version", GDB_XML_AF_NONE, NULL, NULL },
14570 { NULL, GDB_XML_AF_NONE, NULL, NULL }
14571 };
14572
14573 static const struct gdb_xml_element btrace_conf_elements[] = {
14574 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
14575 GDB_XML_EF_NONE, NULL, NULL },
14576 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
14577 };
14578
14579 #endif /* defined (HAVE_LIBEXPAT) */
14580
14581 /* Parse a branch trace configuration xml document XML into CONF. */
14582
14583 static void
14584 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
14585 {
14586 #if defined (HAVE_LIBEXPAT)
14587
14588 int errcode;
14589 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
14590 btrace_conf_elements, xml, conf);
14591 if (errcode != 0)
14592 error (_("Error parsing branch trace configuration."));
14593
14594 #else /* !defined (HAVE_LIBEXPAT) */
14595
14596 error (_("Cannot process the branch trace configuration. XML support "
14597 "was disabled at compile time."));
14598
14599 #endif /* !defined (HAVE_LIBEXPAT) */
14600 }
14601
14602 /* Reset our idea of our target's btrace configuration. */
14603
14604 static void
14605 remote_btrace_reset (remote_state *rs)
14606 {
14607 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14608 }
14609
14610 /* Synchronize the configuration with the target. */
14611
14612 void
14613 remote_target::btrace_sync_conf (const btrace_config *conf)
14614 {
14615 struct remote_state *rs;
14616 char *buf, *pos, *endbuf;
14617
14618 rs = get_remote_state ();
14619 buf = rs->buf.data ();
14620 endbuf = buf + get_remote_packet_size ();
14621
14622 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14623 && conf->bts.size != rs->btrace_config.bts.size)
14624 {
14625 pos = buf;
14626 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14627 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14628 conf->bts.size);
14629
14630 putpkt (buf);
14631 getpkt (&rs->buf);
14632
14633 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14634 == PACKET_ERROR)
14635 {
14636 if (buf[0] == 'E' && buf[1] == '.')
14637 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14638 else
14639 error (_("Failed to configure the BTS buffer size."));
14640 }
14641
14642 rs->btrace_config.bts.size = conf->bts.size;
14643 }
14644
14645 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14646 && conf->pt.size != rs->btrace_config.pt.size)
14647 {
14648 pos = buf;
14649 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14650 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14651 conf->pt.size);
14652
14653 putpkt (buf);
14654 getpkt (&rs->buf);
14655
14656 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14657 == PACKET_ERROR)
14658 {
14659 if (buf[0] == 'E' && buf[1] == '.')
14660 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14661 else
14662 error (_("Failed to configure the trace buffer size."));
14663 }
14664
14665 rs->btrace_config.pt.size = conf->pt.size;
14666 }
14667 }
14668
14669 /* Read TP's btrace configuration from the target and store it into CONF. */
14670
14671 static void
14672 btrace_read_config (thread_info *tp, btrace_config *conf)
14673 {
14674 /* target_read_stralloc relies on INFERIOR_PTID. */
14675 scoped_restore_current_thread restore_thread;
14676 switch_to_thread (tp);
14677
14678 gdb::optional<gdb::char_vector> xml
14679 = target_read_stralloc (current_inferior ()->top_target (),
14680 TARGET_OBJECT_BTRACE_CONF, "");
14681 if (xml)
14682 parse_xml_btrace_conf (conf, xml->data ());
14683 }
14684
14685 /* Maybe reopen target btrace. */
14686
14687 void
14688 remote_target::remote_btrace_maybe_reopen ()
14689 {
14690 struct remote_state *rs = get_remote_state ();
14691 int btrace_target_pushed = 0;
14692 #if !defined (HAVE_LIBIPT)
14693 int warned = 0;
14694 #endif
14695
14696 /* Don't bother walking the entirety of the remote thread list when
14697 we know the feature isn't supported by the remote. */
14698 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14699 return;
14700
14701 for (thread_info *tp : all_non_exited_threads (this))
14702 {
14703 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14704 btrace_read_config (tp, &rs->btrace_config);
14705
14706 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14707 continue;
14708
14709 #if !defined (HAVE_LIBIPT)
14710 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14711 {
14712 if (!warned)
14713 {
14714 warned = 1;
14715 warning (_("Target is recording using Intel Processor Trace "
14716 "but support was disabled at compile time."));
14717 }
14718
14719 continue;
14720 }
14721 #endif /* !defined (HAVE_LIBIPT) */
14722
14723 /* Push target, once, but before anything else happens. This way our
14724 changes to the threads will be cleaned up by unpushing the target
14725 in case btrace_read_config () throws. */
14726 if (!btrace_target_pushed)
14727 {
14728 btrace_target_pushed = 1;
14729 record_btrace_push_target ();
14730 gdb_printf (_("Target is recording using %s.\n"),
14731 btrace_format_string (rs->btrace_config.format));
14732 }
14733
14734 tp->btrace.target
14735 = new btrace_target_info { tp->ptid, rs->btrace_config };
14736 }
14737 }
14738
14739 /* Enable branch tracing. */
14740
14741 struct btrace_target_info *
14742 remote_target::enable_btrace (thread_info *tp,
14743 const struct btrace_config *conf)
14744 {
14745 struct packet_config *packet = NULL;
14746 struct remote_state *rs = get_remote_state ();
14747 char *buf = rs->buf.data ();
14748 char *endbuf = buf + get_remote_packet_size ();
14749
14750 unsigned int which_packet;
14751 switch (conf->format)
14752 {
14753 case BTRACE_FORMAT_BTS:
14754 which_packet = PACKET_Qbtrace_bts;
14755 break;
14756 case BTRACE_FORMAT_PT:
14757 which_packet = PACKET_Qbtrace_pt;
14758 break;
14759 default:
14760 internal_error (_("Bad branch btrace format: %u."),
14761 (unsigned int) conf->format);
14762 }
14763
14764 packet = &m_features.m_protocol_packets[which_packet];
14765 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14766 error (_("Target does not support branch tracing."));
14767
14768 btrace_sync_conf (conf);
14769
14770 ptid_t ptid = tp->ptid;
14771 set_general_thread (ptid);
14772
14773 buf += xsnprintf (buf, endbuf - buf, "%s",
14774 packets_descriptions[which_packet].name);
14775 putpkt (rs->buf);
14776 getpkt (&rs->buf);
14777
14778 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14779 {
14780 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14781 error (_("Could not enable branch tracing for %s: %s"),
14782 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14783 else
14784 error (_("Could not enable branch tracing for %s."),
14785 target_pid_to_str (ptid).c_str ());
14786 }
14787
14788 btrace_target_info *tinfo = new btrace_target_info { ptid };
14789
14790 /* If we fail to read the configuration, we lose some information, but the
14791 tracing itself is not impacted. */
14792 try
14793 {
14794 btrace_read_config (tp, &tinfo->conf);
14795 }
14796 catch (const gdb_exception_error &err)
14797 {
14798 if (err.message != NULL)
14799 warning ("%s", err.what ());
14800 }
14801
14802 return tinfo;
14803 }
14804
14805 /* Disable branch tracing. */
14806
14807 void
14808 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14809 {
14810 struct remote_state *rs = get_remote_state ();
14811 char *buf = rs->buf.data ();
14812 char *endbuf = buf + get_remote_packet_size ();
14813
14814 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14815 error (_("Target does not support branch tracing."));
14816
14817 set_general_thread (tinfo->ptid);
14818
14819 buf += xsnprintf (buf, endbuf - buf, "%s",
14820 packets_descriptions[PACKET_Qbtrace_off].name);
14821 putpkt (rs->buf);
14822 getpkt (&rs->buf);
14823
14824 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14825 {
14826 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14827 error (_("Could not disable branch tracing for %s: %s"),
14828 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14829 else
14830 error (_("Could not disable branch tracing for %s."),
14831 target_pid_to_str (tinfo->ptid).c_str ());
14832 }
14833
14834 delete tinfo;
14835 }
14836
14837 /* Teardown branch tracing. */
14838
14839 void
14840 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14841 {
14842 /* We must not talk to the target during teardown. */
14843 delete tinfo;
14844 }
14845
14846 /* Read the branch trace. */
14847
14848 enum btrace_error
14849 remote_target::read_btrace (struct btrace_data *btrace,
14850 struct btrace_target_info *tinfo,
14851 enum btrace_read_type type)
14852 {
14853 const char *annex;
14854
14855 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14856 error (_("Target does not support branch tracing."));
14857
14858 #if !defined(HAVE_LIBEXPAT)
14859 error (_("Cannot process branch tracing result. XML parsing not supported."));
14860 #endif
14861
14862 switch (type)
14863 {
14864 case BTRACE_READ_ALL:
14865 annex = "all";
14866 break;
14867 case BTRACE_READ_NEW:
14868 annex = "new";
14869 break;
14870 case BTRACE_READ_DELTA:
14871 annex = "delta";
14872 break;
14873 default:
14874 internal_error (_("Bad branch tracing read type: %u."),
14875 (unsigned int) type);
14876 }
14877
14878 gdb::optional<gdb::char_vector> xml
14879 = target_read_stralloc (current_inferior ()->top_target (),
14880 TARGET_OBJECT_BTRACE, annex);
14881 if (!xml)
14882 return BTRACE_ERR_UNKNOWN;
14883
14884 parse_xml_btrace (btrace, xml->data ());
14885
14886 return BTRACE_ERR_NONE;
14887 }
14888
14889 const struct btrace_config *
14890 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14891 {
14892 return &tinfo->conf;
14893 }
14894
14895 bool
14896 remote_target::augmented_libraries_svr4_read ()
14897 {
14898 return
14899 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14900 == PACKET_ENABLE);
14901 }
14902
14903 /* Implementation of to_load. */
14904
14905 void
14906 remote_target::load (const char *name, int from_tty)
14907 {
14908 generic_load (name, from_tty);
14909 }
14910
14911 /* Accepts an integer PID; returns a string representing a file that
14912 can be opened on the remote side to get the symbols for the child
14913 process. Returns NULL if the operation is not supported. */
14914
14915 const char *
14916 remote_target::pid_to_exec_file (int pid)
14917 {
14918 static gdb::optional<gdb::char_vector> filename;
14919 char *annex = NULL;
14920
14921 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14922 return NULL;
14923
14924 inferior *inf = find_inferior_pid (this, pid);
14925 if (inf == NULL)
14926 internal_error (_("not currently attached to process %d"), pid);
14927
14928 if (!inf->fake_pid_p)
14929 {
14930 const int annex_size = 9;
14931
14932 annex = (char *) alloca (annex_size);
14933 xsnprintf (annex, annex_size, "%x", pid);
14934 }
14935
14936 filename = target_read_stralloc (current_inferior ()->top_target (),
14937 TARGET_OBJECT_EXEC_FILE, annex);
14938
14939 return filename ? filename->data () : nullptr;
14940 }
14941
14942 /* Implement the to_can_do_single_step target_ops method. */
14943
14944 int
14945 remote_target::can_do_single_step ()
14946 {
14947 /* We can only tell whether target supports single step or not by
14948 supported s and S vCont actions if the stub supports vContSupported
14949 feature. If the stub doesn't support vContSupported feature,
14950 we have conservatively to think target doesn't supports single
14951 step. */
14952 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14953 {
14954 struct remote_state *rs = get_remote_state ();
14955
14956 return rs->supports_vCont.s && rs->supports_vCont.S;
14957 }
14958 else
14959 return 0;
14960 }
14961
14962 /* Implementation of the to_execution_direction method for the remote
14963 target. */
14964
14965 enum exec_direction_kind
14966 remote_target::execution_direction ()
14967 {
14968 struct remote_state *rs = get_remote_state ();
14969
14970 return rs->last_resume_exec_dir;
14971 }
14972
14973 /* Return pointer to the thread_info struct which corresponds to
14974 THREAD_HANDLE (having length HANDLE_LEN). */
14975
14976 thread_info *
14977 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14978 int handle_len,
14979 inferior *inf)
14980 {
14981 for (thread_info *tp : all_non_exited_threads (this))
14982 {
14983 remote_thread_info *priv = get_remote_thread_info (tp);
14984
14985 if (tp->inf == inf && priv != NULL)
14986 {
14987 if (handle_len != priv->thread_handle.size ())
14988 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14989 handle_len, priv->thread_handle.size ());
14990 if (memcmp (thread_handle, priv->thread_handle.data (),
14991 handle_len) == 0)
14992 return tp;
14993 }
14994 }
14995
14996 return NULL;
14997 }
14998
14999 gdb::array_view<const gdb_byte>
15000 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
15001 {
15002 remote_thread_info *priv = get_remote_thread_info (tp);
15003 return priv->thread_handle;
15004 }
15005
15006 bool
15007 remote_target::can_async_p ()
15008 {
15009 /* This flag should be checked in the common target.c code. */
15010 gdb_assert (target_async_permitted);
15011
15012 /* We're async whenever the serial device can. */
15013 return get_remote_state ()->can_async_p ();
15014 }
15015
15016 bool
15017 remote_target::is_async_p ()
15018 {
15019 /* We're async whenever the serial device is. */
15020 return get_remote_state ()->is_async_p ();
15021 }
15022
15023 /* Pass the SERIAL event on and up to the client. One day this code
15024 will be able to delay notifying the client of an event until the
15025 point where an entire packet has been received. */
15026
15027 static serial_event_ftype remote_async_serial_handler;
15028
15029 static void
15030 remote_async_serial_handler (struct serial *scb, void *context)
15031 {
15032 /* Don't propogate error information up to the client. Instead let
15033 the client find out about the error by querying the target. */
15034 inferior_event_handler (INF_REG_EVENT);
15035 }
15036
15037 int
15038 remote_target::async_wait_fd ()
15039 {
15040 struct remote_state *rs = get_remote_state ();
15041 return rs->remote_desc->fd;
15042 }
15043
15044 void
15045 remote_target::async (bool enable)
15046 {
15047 struct remote_state *rs = get_remote_state ();
15048
15049 if (enable)
15050 {
15051 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
15052
15053 /* If there are pending events in the stop reply queue tell the
15054 event loop to process them. */
15055 if (!rs->stop_reply_queue.empty ())
15056 rs->mark_async_event_handler ();
15057
15058 /* For simplicity, below we clear the pending events token
15059 without remembering whether it is marked, so here we always
15060 mark it. If there's actually no pending notification to
15061 process, this ends up being a no-op (other than a spurious
15062 event-loop wakeup). */
15063 if (target_is_non_stop_p ())
15064 mark_async_event_handler (rs->notif_state->get_pending_events_token);
15065 }
15066 else
15067 {
15068 serial_async (rs->remote_desc, NULL, NULL);
15069 /* If the core is disabling async, it doesn't want to be
15070 disturbed with target events. Clear all async event sources
15071 too. */
15072 rs->clear_async_event_handler ();
15073
15074 if (target_is_non_stop_p ())
15075 clear_async_event_handler (rs->notif_state->get_pending_events_token);
15076 }
15077 }
15078
15079 /* Implementation of the to_thread_events method. */
15080
15081 void
15082 remote_target::thread_events (int enable)
15083 {
15084 struct remote_state *rs = get_remote_state ();
15085 size_t size = get_remote_packet_size ();
15086
15087 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
15088 return;
15089
15090 if (rs->last_thread_events == enable)
15091 return;
15092
15093 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
15094 putpkt (rs->buf);
15095 getpkt (&rs->buf);
15096
15097 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
15098 {
15099 case PACKET_OK:
15100 if (strcmp (rs->buf.data (), "OK") != 0)
15101 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
15102 rs->last_thread_events = enable;
15103 break;
15104 case PACKET_ERROR:
15105 warning (_("Remote failure reply: %s"), rs->buf.data ());
15106 break;
15107 case PACKET_UNKNOWN:
15108 break;
15109 }
15110 }
15111
15112 /* Implementation of the supports_set_thread_options target
15113 method. */
15114
15115 bool
15116 remote_target::supports_set_thread_options (gdb_thread_options options)
15117 {
15118 remote_state *rs = get_remote_state ();
15119 return (m_features.packet_support (PACKET_QThreadOptions) == PACKET_ENABLE
15120 && (rs->supported_thread_options & options) == options);
15121 }
15122
15123 /* For coalescing reasons, actually sending the options to the target
15124 happens at resume time, via this function. See target_resume for
15125 all-stop, and target_commit_resumed for non-stop. */
15126
15127 void
15128 remote_target::commit_requested_thread_options ()
15129 {
15130 struct remote_state *rs = get_remote_state ();
15131
15132 if (m_features.packet_support (PACKET_QThreadOptions) != PACKET_ENABLE)
15133 return;
15134
15135 char *p = rs->buf.data ();
15136 char *endp = p + get_remote_packet_size ();
15137
15138 /* Clear options for all threads by default. Note that unlike
15139 vCont, the rightmost options that match a thread apply, so we
15140 don't have to worry about whether we can use wildcard ptids. */
15141 strcpy (p, "QThreadOptions;0");
15142 p += strlen (p);
15143
15144 /* Send the QThreadOptions packet stored in P. */
15145 auto flush = [&] ()
15146 {
15147 *p++ = '\0';
15148
15149 putpkt (rs->buf);
15150 getpkt (&rs->buf, 0);
15151
15152 switch (m_features.packet_ok (rs->buf, PACKET_QThreadOptions))
15153 {
15154 case PACKET_OK:
15155 if (strcmp (rs->buf.data (), "OK") != 0)
15156 error (_("Remote refused setting thread options: %s"), rs->buf.data ());
15157 break;
15158 case PACKET_ERROR:
15159 error (_("Remote failure reply: %s"), rs->buf.data ());
15160 case PACKET_UNKNOWN:
15161 gdb_assert_not_reached ("PACKET_UNKNOWN");
15162 break;
15163 }
15164 };
15165
15166 /* Prepare P for another QThreadOptions packet. */
15167 auto restart = [&] ()
15168 {
15169 p = rs->buf.data ();
15170 strcpy (p, "QThreadOptions");
15171 p += strlen (p);
15172 };
15173
15174 /* Now set non-zero options for threads that need them. We don't
15175 bother with the case of all threads of a process wanting the same
15176 non-zero options as that's not an expected scenario. */
15177 for (thread_info *tp : all_non_exited_threads (this))
15178 {
15179 gdb_thread_options options = tp->thread_options ();
15180
15181 if (options == 0)
15182 continue;
15183
15184 /* It might be possible to we have more threads with options
15185 than can fit a single QThreadOptions packet. So build each
15186 options/thread pair in this separate buffer to make sure it
15187 fits. */
15188 constexpr size_t max_options_size = 100;
15189 char obuf[max_options_size];
15190 char *obuf_p = obuf;
15191 char *obuf_endp = obuf + max_options_size;
15192
15193 *obuf_p++ = ';';
15194 obuf_p += xsnprintf (obuf_p, obuf_endp - obuf_p, "%s",
15195 phex_nz (options, sizeof (options)));
15196 if (tp->ptid != magic_null_ptid)
15197 {
15198 *obuf_p++ = ':';
15199 obuf_p = write_ptid (obuf_p, obuf_endp, tp->ptid);
15200 }
15201
15202 size_t osize = obuf_p - obuf;
15203 if (osize > endp - p)
15204 {
15205 /* This new options/thread pair doesn't fit the packet
15206 buffer. Send what we have already. */
15207 flush ();
15208 restart ();
15209
15210 /* Should now fit. */
15211 gdb_assert (osize <= endp - p);
15212 }
15213
15214 memcpy (p, obuf, osize);
15215 p += osize;
15216 }
15217
15218 flush ();
15219 }
15220
15221 static void
15222 show_remote_cmd (const char *args, int from_tty)
15223 {
15224 /* We can't just use cmd_show_list here, because we want to skip
15225 the redundant "show remote Z-packet" and the legacy aliases. */
15226 struct cmd_list_element *list = remote_show_cmdlist;
15227 struct ui_out *uiout = current_uiout;
15228
15229 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
15230 for (; list != NULL; list = list->next)
15231 if (strcmp (list->name, "Z-packet") == 0)
15232 continue;
15233 else if (list->type == not_set_cmd)
15234 /* Alias commands are exactly like the original, except they
15235 don't have the normal type. */
15236 continue;
15237 else
15238 {
15239 ui_out_emit_tuple option_emitter (uiout, "option");
15240
15241 uiout->field_string ("name", list->name);
15242 uiout->text (": ");
15243 if (list->type == show_cmd)
15244 do_show_command (NULL, from_tty, list);
15245 else
15246 cmd_func (list, NULL, from_tty);
15247 }
15248 }
15249
15250 /* Some change happened in PSPACE's objfile list (obfiles added or removed),
15251 offer all inferiors using that program space a change to look up symbols. */
15252
15253 static void
15254 remote_objfile_changed_check_symbols (program_space *pspace)
15255 {
15256 /* The affected program space is possibly shared by multiple inferiors.
15257 Consider sending a qSymbol packet for each of the inferiors using that
15258 program space. */
15259 for (inferior *inf : all_inferiors ())
15260 {
15261 if (inf->pspace != pspace)
15262 continue;
15263
15264 /* Check whether the inferior's process target is a remote target. */
15265 remote_target *remote = as_remote_target (inf->process_target ());
15266 if (remote == nullptr)
15267 continue;
15268
15269 /* When we are attaching or handling a fork child and the shared library
15270 subsystem reads the list of loaded libraries, we receive new objfile
15271 events in between each found library. The libraries are read in an
15272 undefined order, so if we gave the remote side a chance to look up
15273 symbols between each objfile, we might give it an inconsistent picture
15274 of the inferior. It could appear that a library A appears loaded but
15275 a library B does not, even though library A requires library B. That
15276 would present a state that couldn't normally exist in the inferior.
15277
15278 So, skip these events, we'll give the remote a chance to look up
15279 symbols once all the loaded libraries and their symbols are known to
15280 GDB. */
15281 if (inf->in_initial_library_scan)
15282 continue;
15283
15284 if (!remote->has_execution (inf))
15285 continue;
15286
15287 /* Need to switch to a specific thread, because remote_check_symbols will
15288 set the general thread using INFERIOR_PTID.
15289
15290 It's possible to have inferiors with no thread here, because we are
15291 called very early in the connection process, while the inferior is
15292 being set up, before threads are added. Just skip it, start_remote_1
15293 also calls remote_check_symbols when it's done setting things up. */
15294 thread_info *thread = any_thread_of_inferior (inf);
15295 if (thread != nullptr)
15296 {
15297 scoped_restore_current_thread restore_thread;
15298 switch_to_thread (thread);
15299 remote->remote_check_symbols ();
15300 }
15301 }
15302 }
15303
15304 /* Function to be called whenever a new objfile (shlib) is detected. */
15305
15306 static void
15307 remote_new_objfile (struct objfile *objfile)
15308 {
15309 remote_objfile_changed_check_symbols (objfile->pspace);
15310 }
15311
15312 /* Pull all the tracepoints defined on the target and create local
15313 data structures representing them. We don't want to create real
15314 tracepoints yet, we don't want to mess up the user's existing
15315 collection. */
15316
15317 int
15318 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
15319 {
15320 struct remote_state *rs = get_remote_state ();
15321 char *p;
15322
15323 /* Ask for a first packet of tracepoint definition. */
15324 putpkt ("qTfP");
15325 getpkt (&rs->buf);
15326 p = rs->buf.data ();
15327 while (*p && *p != 'l')
15328 {
15329 parse_tracepoint_definition (p, utpp);
15330 /* Ask for another packet of tracepoint definition. */
15331 putpkt ("qTsP");
15332 getpkt (&rs->buf);
15333 p = rs->buf.data ();
15334 }
15335 return 0;
15336 }
15337
15338 int
15339 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
15340 {
15341 struct remote_state *rs = get_remote_state ();
15342 char *p;
15343
15344 /* Ask for a first packet of variable definition. */
15345 putpkt ("qTfV");
15346 getpkt (&rs->buf);
15347 p = rs->buf.data ();
15348 while (*p && *p != 'l')
15349 {
15350 parse_tsv_definition (p, utsvp);
15351 /* Ask for another packet of variable definition. */
15352 putpkt ("qTsV");
15353 getpkt (&rs->buf);
15354 p = rs->buf.data ();
15355 }
15356 return 0;
15357 }
15358
15359 /* The "set/show range-stepping" show hook. */
15360
15361 static void
15362 show_range_stepping (struct ui_file *file, int from_tty,
15363 struct cmd_list_element *c,
15364 const char *value)
15365 {
15366 gdb_printf (file,
15367 _("Debugger's willingness to use range stepping "
15368 "is %s.\n"), value);
15369 }
15370
15371 /* Return true if the vCont;r action is supported by the remote
15372 stub. */
15373
15374 bool
15375 remote_target::vcont_r_supported ()
15376 {
15377 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
15378 && get_remote_state ()->supports_vCont.r);
15379 }
15380
15381 /* The "set/show range-stepping" set hook. */
15382
15383 static void
15384 set_range_stepping (const char *ignore_args, int from_tty,
15385 struct cmd_list_element *c)
15386 {
15387 /* When enabling, check whether range stepping is actually supported
15388 by the target, and warn if not. */
15389 if (use_range_stepping)
15390 {
15391 remote_target *remote = get_current_remote_target ();
15392 if (remote == NULL
15393 || !remote->vcont_r_supported ())
15394 warning (_("Range stepping is not supported by the current target"));
15395 }
15396 }
15397
15398 static void
15399 show_remote_debug (struct ui_file *file, int from_tty,
15400 struct cmd_list_element *c, const char *value)
15401 {
15402 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
15403 value);
15404 }
15405
15406 static void
15407 show_remote_timeout (struct ui_file *file, int from_tty,
15408 struct cmd_list_element *c, const char *value)
15409 {
15410 gdb_printf (file,
15411 _("Timeout limit to wait for target to respond is %s.\n"),
15412 value);
15413 }
15414
15415 /* Implement the "supports_memory_tagging" target_ops method. */
15416
15417 bool
15418 remote_target::supports_memory_tagging ()
15419 {
15420 return m_features.remote_memory_tagging_p ();
15421 }
15422
15423 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
15424
15425 static void
15426 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15427 size_t len, int type)
15428 {
15429 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15430
15431 std::string request = string_printf ("qMemTags:%s,%s:%s",
15432 phex_nz (address, addr_size),
15433 phex_nz (len, sizeof (len)),
15434 phex_nz (type, sizeof (type)));
15435
15436 strcpy (packet.data (), request.c_str ());
15437 }
15438
15439 /* Parse the qMemTags packet reply into TAGS.
15440
15441 Return true if successful, false otherwise. */
15442
15443 static bool
15444 parse_fetch_memtags_reply (const gdb::char_vector &reply,
15445 gdb::byte_vector &tags)
15446 {
15447 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
15448 return false;
15449
15450 /* Copy the tag data. */
15451 tags = hex2bin (reply.data () + 1);
15452
15453 return true;
15454 }
15455
15456 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
15457
15458 static void
15459 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
15460 size_t len, int type,
15461 const gdb::byte_vector &tags)
15462 {
15463 int addr_size = gdbarch_addr_bit (current_inferior ()->arch ()) / 8;
15464
15465 /* Put together the main packet, address and length. */
15466 std::string request = string_printf ("QMemTags:%s,%s:%s:",
15467 phex_nz (address, addr_size),
15468 phex_nz (len, sizeof (len)),
15469 phex_nz (type, sizeof (type)));
15470 request += bin2hex (tags.data (), tags.size ());
15471
15472 /* Check if we have exceeded the maximum packet size. */
15473 if (packet.size () < request.length ())
15474 error (_("Contents too big for packet QMemTags."));
15475
15476 strcpy (packet.data (), request.c_str ());
15477 }
15478
15479 /* Implement the "fetch_memtags" target_ops method. */
15480
15481 bool
15482 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
15483 gdb::byte_vector &tags, int type)
15484 {
15485 /* Make sure the qMemTags packet is supported. */
15486 if (!m_features.remote_memory_tagging_p ())
15487 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
15488
15489 struct remote_state *rs = get_remote_state ();
15490
15491 create_fetch_memtags_request (rs->buf, address, len, type);
15492
15493 putpkt (rs->buf);
15494 getpkt (&rs->buf);
15495
15496 return parse_fetch_memtags_reply (rs->buf, tags);
15497 }
15498
15499 /* Implement the "store_memtags" target_ops method. */
15500
15501 bool
15502 remote_target::store_memtags (CORE_ADDR address, size_t len,
15503 const gdb::byte_vector &tags, int type)
15504 {
15505 /* Make sure the QMemTags packet is supported. */
15506 if (!m_features.remote_memory_tagging_p ())
15507 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
15508
15509 struct remote_state *rs = get_remote_state ();
15510
15511 create_store_memtags_request (rs->buf, address, len, type, tags);
15512
15513 putpkt (rs->buf);
15514 getpkt (&rs->buf);
15515
15516 /* Verify if the request was successful. */
15517 return packet_check_result (rs->buf.data ()) == PACKET_OK;
15518 }
15519
15520 /* Return true if remote target T is non-stop. */
15521
15522 bool
15523 remote_target_is_non_stop_p (remote_target *t)
15524 {
15525 scoped_restore_current_thread restore_thread;
15526 switch_to_target_no_thread (t);
15527
15528 return target_is_non_stop_p ();
15529 }
15530
15531 #if GDB_SELF_TEST
15532
15533 namespace selftests {
15534
15535 static void
15536 test_memory_tagging_functions ()
15537 {
15538 remote_target remote;
15539
15540 struct packet_config *config
15541 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
15542
15543 scoped_restore restore_memtag_support_
15544 = make_scoped_restore (&config->support);
15545
15546 /* Test memory tagging packet support. */
15547 config->support = PACKET_SUPPORT_UNKNOWN;
15548 SELF_CHECK (remote.supports_memory_tagging () == false);
15549 config->support = PACKET_DISABLE;
15550 SELF_CHECK (remote.supports_memory_tagging () == false);
15551 config->support = PACKET_ENABLE;
15552 SELF_CHECK (remote.supports_memory_tagging () == true);
15553
15554 /* Setup testing. */
15555 gdb::char_vector packet;
15556 gdb::byte_vector tags, bv;
15557 std::string expected, reply;
15558 packet.resize (32000);
15559
15560 /* Test creating a qMemTags request. */
15561
15562 expected = "qMemTags:0,0:0";
15563 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15564 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15565
15566 expected = "qMemTags:deadbeef,10:1";
15567 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15568 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15569
15570 /* Test parsing a qMemTags reply. */
15571
15572 /* Error reply, tags vector unmodified. */
15573 reply = "E00";
15574 strcpy (packet.data (), reply.c_str ());
15575 tags.resize (0);
15576 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15577 SELF_CHECK (tags.size () == 0);
15578
15579 /* Valid reply, tags vector updated. */
15580 tags.resize (0);
15581 bv.resize (0);
15582
15583 for (int i = 0; i < 5; i++)
15584 bv.push_back (i);
15585
15586 reply = "m" + bin2hex (bv.data (), bv.size ());
15587 strcpy (packet.data (), reply.c_str ());
15588
15589 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15590 SELF_CHECK (tags.size () == 5);
15591
15592 for (int i = 0; i < 5; i++)
15593 SELF_CHECK (tags[i] == i);
15594
15595 /* Test creating a QMemTags request. */
15596
15597 /* Empty tag data. */
15598 tags.resize (0);
15599 expected = "QMemTags:0,0:0:";
15600 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15601 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15602 expected.length ()) == 0);
15603
15604 /* Non-empty tag data. */
15605 tags.resize (0);
15606 for (int i = 0; i < 5; i++)
15607 tags.push_back (i);
15608 expected = "QMemTags:deadbeef,ff:1:0001020304";
15609 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15610 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15611 expected.length ()) == 0);
15612 }
15613
15614 } // namespace selftests
15615 #endif /* GDB_SELF_TEST */
15616
15617 void _initialize_remote ();
15618 void
15619 _initialize_remote ()
15620 {
15621 add_target (remote_target_info, remote_target::open);
15622 add_target (extended_remote_target_info, extended_remote_target::open);
15623
15624 /* Hook into new objfile notification. */
15625 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15626 gdb::observers::all_objfiles_removed.attach
15627 (remote_objfile_changed_check_symbols, "remote");
15628
15629 #if 0
15630 init_remote_threadtests ();
15631 #endif
15632
15633 /* set/show remote ... */
15634
15635 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15636 Remote protocol specific variables.\n\
15637 Configure various remote-protocol specific variables such as\n\
15638 the packets being used."),
15639 &remote_set_cmdlist,
15640 0 /* allow-unknown */, &setlist);
15641 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15642 Remote protocol specific variables.\n\
15643 Configure various remote-protocol specific variables such as\n\
15644 the packets being used."),
15645 &remote_show_cmdlist,
15646 0 /* allow-unknown */, &showlist);
15647
15648 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15649 Compare section data on target to the exec file.\n\
15650 Argument is a single section name (default: all loaded sections).\n\
15651 To compare only read-only loaded sections, specify the -r option."),
15652 &cmdlist);
15653
15654 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15655 Send an arbitrary packet to a remote target.\n\
15656 maintenance packet TEXT\n\
15657 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15658 this command sends the string TEXT to the inferior, and displays the\n\
15659 response packet. GDB supplies the initial `$' character, and the\n\
15660 terminating `#' character and checksum."),
15661 &maintenancelist);
15662
15663 set_show_commands remotebreak_cmds
15664 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15665 Set whether to send break if interrupted."), _("\
15666 Show whether to send break if interrupted."), _("\
15667 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15668 set_remotebreak, show_remotebreak,
15669 &setlist, &showlist);
15670 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15671 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15672
15673 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15674 interrupt_sequence_modes, &interrupt_sequence_mode,
15675 _("\
15676 Set interrupt sequence to remote target."), _("\
15677 Show interrupt sequence to remote target."), _("\
15678 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15679 NULL, show_interrupt_sequence,
15680 &remote_set_cmdlist,
15681 &remote_show_cmdlist);
15682
15683 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15684 &interrupt_on_connect, _("\
15685 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15686 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15687 If set, interrupt sequence is sent to remote target."),
15688 NULL, NULL,
15689 &remote_set_cmdlist, &remote_show_cmdlist);
15690
15691 /* Install commands for configuring memory read/write packets. */
15692
15693 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15694 Set the maximum number of bytes per memory write packet (deprecated)."),
15695 &setlist);
15696 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15697 Show the maximum number of bytes per memory write packet (deprecated)."),
15698 &showlist);
15699 add_cmd ("memory-write-packet-size", no_class,
15700 set_memory_write_packet_size, _("\
15701 Set the maximum number of bytes per memory-write packet.\n\
15702 Specify the number of bytes in a packet or 0 (zero) for the\n\
15703 default packet size. The actual limit is further reduced\n\
15704 dependent on the target. Specify \"fixed\" to disable the\n\
15705 further restriction and \"limit\" to enable that restriction."),
15706 &remote_set_cmdlist);
15707 add_cmd ("memory-read-packet-size", no_class,
15708 set_memory_read_packet_size, _("\
15709 Set the maximum number of bytes per memory-read packet.\n\
15710 Specify the number of bytes in a packet or 0 (zero) for the\n\
15711 default packet size. The actual limit is further reduced\n\
15712 dependent on the target. Specify \"fixed\" to disable the\n\
15713 further restriction and \"limit\" to enable that restriction."),
15714 &remote_set_cmdlist);
15715 add_cmd ("memory-write-packet-size", no_class,
15716 show_memory_write_packet_size,
15717 _("Show the maximum number of bytes per memory-write packet."),
15718 &remote_show_cmdlist);
15719 add_cmd ("memory-read-packet-size", no_class,
15720 show_memory_read_packet_size,
15721 _("Show the maximum number of bytes per memory-read packet."),
15722 &remote_show_cmdlist);
15723
15724 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15725 &remote_hw_watchpoint_limit, _("\
15726 Set the maximum number of target hardware watchpoints."), _("\
15727 Show the maximum number of target hardware watchpoints."), _("\
15728 Specify \"unlimited\" for unlimited hardware watchpoints."),
15729 NULL, show_hardware_watchpoint_limit,
15730 &remote_set_cmdlist,
15731 &remote_show_cmdlist);
15732 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15733 no_class,
15734 &remote_hw_watchpoint_length_limit, _("\
15735 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15736 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15737 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15738 NULL, show_hardware_watchpoint_length_limit,
15739 &remote_set_cmdlist, &remote_show_cmdlist);
15740 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15741 &remote_hw_breakpoint_limit, _("\
15742 Set the maximum number of target hardware breakpoints."), _("\
15743 Show the maximum number of target hardware breakpoints."), _("\
15744 Specify \"unlimited\" for unlimited hardware breakpoints."),
15745 NULL, show_hardware_breakpoint_limit,
15746 &remote_set_cmdlist, &remote_show_cmdlist);
15747
15748 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15749 &remote_address_size, _("\
15750 Set the maximum size of the address (in bits) in a memory packet."), _("\
15751 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15752 NULL,
15753 NULL, /* FIXME: i18n: */
15754 &setlist, &showlist);
15755
15756 init_all_packet_configs ();
15757
15758 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15759
15760 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15761
15762 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15763 0);
15764
15765 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15766 "catch-syscalls", 0);
15767
15768 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15769 "program-signals", 0);
15770
15771 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15772 "set-working-dir", 0);
15773
15774 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15775 "startup-with-shell", 0);
15776
15777 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15778 "environment-hex-encoded", 0);
15779
15780 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15781 "environment-reset", 0);
15782
15783 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15784 "environment-unset", 0);
15785
15786 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15787
15788 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15789
15790 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15791
15792 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15793
15794 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15795
15796 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15797
15798 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15799
15800 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15801
15802 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15803 "read-aux-vector", 0);
15804
15805 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15806 "pid-to-exec-file", 0);
15807
15808 add_packet_config_cmd (PACKET_qXfer_features,
15809 "qXfer:features:read", "target-features", 0);
15810
15811 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15812 "library-info", 0);
15813
15814 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15815 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15816
15817 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15818 "memory-map", 0);
15819
15820 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15821
15822 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15823 0);
15824
15825 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15826 "read-siginfo-object", 0);
15827
15828 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15829 "write-siginfo-object", 0);
15830
15831 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15832 "qXfer:traceframe-info:read", "traceframe-info", 0);
15833
15834 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15835 "unwind-info-block", 0);
15836
15837 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15838 "get-thread-local-storage-address", 0);
15839
15840 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15841 "get-thread-information-block-address", 0);
15842
15843 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15844
15845 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15846
15847 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15848 0);
15849
15850 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15851 "search-memory", 0);
15852
15853 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15854
15855 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15856
15857 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15858
15859 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15860
15861 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15862 0);
15863
15864 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15865
15866 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15867 0);
15868
15869 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15870 "hostio-readlink", 0);
15871
15872 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15873
15874 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15875
15876 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15877
15878 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15879
15880 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15881
15882 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15883
15884 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15885 "ConditionalTracepoints", "conditional-tracepoints",
15886 0);
15887
15888 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15889 "ConditionalBreakpoints", "conditional-breakpoints",
15890 0);
15891
15892 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15893 "breakpoint-commands", 0);
15894
15895 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15896 "fast-tracepoints", 0);
15897
15898 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15899 "TracepointSource", 0);
15900
15901 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15902
15903 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15904 "static-tracepoints", 0);
15905
15906 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15907 "install-in-trace", 0);
15908
15909 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15910 "qXfer:statictrace:read", "read-sdata-object", 0);
15911
15912 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15913 "read-fdpic-loadmap", 0);
15914
15915 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15916 "disable-randomization", 0);
15917
15918 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15919
15920 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15921 "trace-buffer-size", 0);
15922
15923 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15924 0);
15925
15926 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15927 0);
15928
15929 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15930 0);
15931
15932 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15933
15934 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15935 "read-btrace-conf", 0);
15936
15937 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15938 "btrace-conf-bts-size", 0);
15939
15940 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15941 "multiprocess-feature", 0);
15942
15943 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15944 "swbreak-feature", 0);
15945
15946 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15947 "hwbreak-feature", 0);
15948
15949 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15950 "fork-event-feature", 0);
15951
15952 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15953 "vfork-event-feature", 0);
15954
15955 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15956 "btrace-conf-pt-size", 0);
15957
15958 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15959 "verbose-resume-supported", 0);
15960
15961 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15962 "exec-event-feature", 0);
15963
15964 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15965
15966 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15967 0);
15968
15969 add_packet_config_cmd (PACKET_QThreadOptions, "QThreadOptions",
15970 "thread-options", 0);
15971
15972 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15973 "no-resumed-stop-reply", 0);
15974
15975 add_packet_config_cmd (PACKET_memory_tagging_feature,
15976 "memory-tagging-feature", "memory-tagging-feature", 0);
15977
15978 /* Assert that we've registered "set remote foo-packet" commands
15979 for all packet configs. */
15980 {
15981 int i;
15982
15983 for (i = 0; i < PACKET_MAX; i++)
15984 {
15985 /* Ideally all configs would have a command associated. Some
15986 still don't though. */
15987 int excepted;
15988
15989 switch (i)
15990 {
15991 case PACKET_QNonStop:
15992 case PACKET_EnableDisableTracepoints_feature:
15993 case PACKET_tracenz_feature:
15994 case PACKET_DisconnectedTracing_feature:
15995 case PACKET_augmented_libraries_svr4_read_feature:
15996 case PACKET_qCRC:
15997 /* Additions to this list need to be well justified:
15998 pre-existing packets are OK; new packets are not. */
15999 excepted = 1;
16000 break;
16001 default:
16002 excepted = 0;
16003 break;
16004 }
16005
16006 /* This catches both forgetting to add a config command, and
16007 forgetting to remove a packet from the exception list. */
16008 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
16009 }
16010 }
16011
16012 /* Keep the old ``set remote Z-packet ...'' working. Each individual
16013 Z sub-packet has its own set and show commands, but users may
16014 have sets to this variable in their .gdbinit files (or in their
16015 documentation). */
16016 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
16017 &remote_Z_packet_detect, _("\
16018 Set use of remote protocol `Z' packets."), _("\
16019 Show use of remote protocol `Z' packets."), _("\
16020 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
16021 packets."),
16022 set_remote_protocol_Z_packet_cmd,
16023 show_remote_protocol_Z_packet_cmd,
16024 /* FIXME: i18n: Use of remote protocol
16025 `Z' packets is %s. */
16026 &remote_set_cmdlist, &remote_show_cmdlist);
16027
16028 add_basic_prefix_cmd ("remote", class_files, _("\
16029 Manipulate files on the remote system.\n\
16030 Transfer files to and from the remote target system."),
16031 &remote_cmdlist,
16032 0 /* allow-unknown */, &cmdlist);
16033
16034 add_cmd ("put", class_files, remote_put_command,
16035 _("Copy a local file to the remote system."),
16036 &remote_cmdlist);
16037
16038 add_cmd ("get", class_files, remote_get_command,
16039 _("Copy a remote file to the local system."),
16040 &remote_cmdlist);
16041
16042 add_cmd ("delete", class_files, remote_delete_command,
16043 _("Delete a remote file."),
16044 &remote_cmdlist);
16045
16046 add_setshow_string_noescape_cmd ("exec-file", class_files,
16047 &remote_exec_file_var, _("\
16048 Set the remote pathname for \"run\"."), _("\
16049 Show the remote pathname for \"run\"."), NULL,
16050 set_remote_exec_file,
16051 show_remote_exec_file,
16052 &remote_set_cmdlist,
16053 &remote_show_cmdlist);
16054
16055 add_setshow_boolean_cmd ("range-stepping", class_run,
16056 &use_range_stepping, _("\
16057 Enable or disable range stepping."), _("\
16058 Show whether target-assisted range stepping is enabled."), _("\
16059 If on, and the target supports it, when stepping a source line, GDB\n\
16060 tells the target to step the corresponding range of addresses itself instead\n\
16061 of issuing multiple single-steps. This speeds up source level\n\
16062 stepping. If off, GDB always issues single-steps, even if range\n\
16063 stepping is supported by the target. The default is on."),
16064 set_range_stepping,
16065 show_range_stepping,
16066 &setlist,
16067 &showlist);
16068
16069 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
16070 Set watchdog timer."), _("\
16071 Show watchdog timer."), _("\
16072 When non-zero, this timeout is used instead of waiting forever for a target\n\
16073 to finish a low-level step or continue operation. If the specified amount\n\
16074 of time passes without a response from the target, an error occurs."),
16075 NULL,
16076 show_watchdog,
16077 &setlist, &showlist);
16078
16079 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
16080 &remote_packet_max_chars, _("\
16081 Set the maximum number of characters to display for each remote packet."), _("\
16082 Show the maximum number of characters to display for each remote packet."), _("\
16083 Specify \"unlimited\" to display all the characters."),
16084 NULL, show_remote_packet_max_chars,
16085 &setdebuglist, &showdebuglist);
16086
16087 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
16088 _("Set debugging of remote protocol."),
16089 _("Show debugging of remote protocol."),
16090 _("\
16091 When enabled, each packet sent or received with the remote target\n\
16092 is displayed."),
16093 NULL,
16094 show_remote_debug,
16095 &setdebuglist, &showdebuglist);
16096
16097 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
16098 &remote_timeout, _("\
16099 Set timeout limit to wait for target to respond."), _("\
16100 Show timeout limit to wait for target to respond."), _("\
16101 This value is used to set the time limit for gdb to wait for a response\n\
16102 from the target."),
16103 NULL,
16104 show_remote_timeout,
16105 &setlist, &showlist);
16106
16107 /* Eventually initialize fileio. See fileio.c */
16108 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
16109
16110 #if GDB_SELF_TEST
16111 selftests::register_test ("remote_memory_tagging",
16112 selftests::test_memory_tagging_functions);
16113 #endif
16114 }