Remove getpkt_sane
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988-2023 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* See the GDB User Guide for details of the GDB remote protocol. */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 #include "process-stratum-target.h"
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdbthread.h"
34 #include "remote.h"
35 #include "remote-notif.h"
36 #include "regcache.h"
37 #include "value.h"
38 #include "observable.h"
39 #include "solib.h"
40 #include "cli/cli-decode.h"
41 #include "cli/cli-setshow.h"
42 #include "target-descriptions.h"
43 #include "gdb_bfd.h"
44 #include "gdbsupport/filestuff.h"
45 #include "gdbsupport/rsp-low.h"
46 #include "disasm.h"
47 #include "location.h"
48
49 #include "gdbsupport/gdb_sys_time.h"
50
51 #include "gdbsupport/event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
54
55 #include <signal.h>
56 #include "serial.h"
57
58 #include "gdbcore.h"
59
60 #include "remote-fileio.h"
61 #include "gdbsupport/fileio.h"
62 #include <sys/stat.h>
63 #include "xml-support.h"
64
65 #include "memory-map.h"
66
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70 #include "gdbsupport/agent.h"
71 #include "btrace.h"
72 #include "record-btrace.h"
73 #include "gdbsupport/scoped_restore.h"
74 #include "gdbsupport/environ.h"
75 #include "gdbsupport/byte-vector.h"
76 #include "gdbsupport/search.h"
77 #include <algorithm>
78 #include <iterator>
79 #include <unordered_map>
80 #include "async-event.h"
81 #include "gdbsupport/selftest.h"
82
83 /* The remote target. */
84
85 static const char remote_doc[] = N_("\
86 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
87 Specify the serial device it is connected to\n\
88 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
89
90 /* See remote.h */
91
92 bool remote_debug = false;
93
94 #define OPAQUETHREADBYTES 8
95
96 /* a 64 bit opaque identifier */
97 typedef unsigned char threadref[OPAQUETHREADBYTES];
98
99 struct gdb_ext_thread_info;
100 struct threads_listing_context;
101 typedef int (*rmt_thread_action) (threadref *ref, void *context);
102 struct protocol_feature;
103 struct packet_reg;
104
105 struct stop_reply;
106 typedef std::unique_ptr<stop_reply> stop_reply_up;
107
108 /* Generic configuration support for packets the stub optionally
109 supports. Allows the user to specify the use of the packet as well
110 as allowing GDB to auto-detect support in the remote stub. */
111
112 enum packet_support
113 {
114 PACKET_SUPPORT_UNKNOWN = 0,
115 PACKET_ENABLE,
116 PACKET_DISABLE
117 };
118
119 /* Convert the packet support auto_boolean to a name used for gdb printing. */
120
121 static const char *
122 get_packet_support_name (auto_boolean support)
123 {
124 switch (support)
125 {
126 case AUTO_BOOLEAN_TRUE:
127 return "on";
128 case AUTO_BOOLEAN_FALSE:
129 return "off";
130 case AUTO_BOOLEAN_AUTO:
131 return "auto";
132 default:
133 gdb_assert_not_reached ("invalid var_auto_boolean");
134 }
135 }
136
137 /* Convert the target type (future remote target or currently connected target)
138 to a name used for gdb printing. */
139
140 static const char *
141 get_target_type_name (bool target_connected)
142 {
143 if (target_connected)
144 return _("on the current remote target");
145 else
146 return _("on future remote targets");
147 }
148
149 /* Analyze a packet's return value and update the packet config
150 accordingly. */
151
152 enum packet_result
153 {
154 PACKET_ERROR,
155 PACKET_OK,
156 PACKET_UNKNOWN
157 };
158
159 /* Enumeration of packets for a remote target. */
160
161 enum {
162 PACKET_vCont = 0,
163 PACKET_X,
164 PACKET_qSymbol,
165 PACKET_P,
166 PACKET_p,
167 PACKET_Z0,
168 PACKET_Z1,
169 PACKET_Z2,
170 PACKET_Z3,
171 PACKET_Z4,
172 PACKET_vFile_setfs,
173 PACKET_vFile_open,
174 PACKET_vFile_pread,
175 PACKET_vFile_pwrite,
176 PACKET_vFile_close,
177 PACKET_vFile_unlink,
178 PACKET_vFile_readlink,
179 PACKET_vFile_fstat,
180 PACKET_qXfer_auxv,
181 PACKET_qXfer_features,
182 PACKET_qXfer_exec_file,
183 PACKET_qXfer_libraries,
184 PACKET_qXfer_libraries_svr4,
185 PACKET_qXfer_memory_map,
186 PACKET_qXfer_osdata,
187 PACKET_qXfer_threads,
188 PACKET_qXfer_statictrace_read,
189 PACKET_qXfer_traceframe_info,
190 PACKET_qXfer_uib,
191 PACKET_qGetTIBAddr,
192 PACKET_qGetTLSAddr,
193 PACKET_qSupported,
194 PACKET_qTStatus,
195 PACKET_QPassSignals,
196 PACKET_QCatchSyscalls,
197 PACKET_QProgramSignals,
198 PACKET_QSetWorkingDir,
199 PACKET_QStartupWithShell,
200 PACKET_QEnvironmentHexEncoded,
201 PACKET_QEnvironmentReset,
202 PACKET_QEnvironmentUnset,
203 PACKET_qCRC,
204 PACKET_qSearch_memory,
205 PACKET_vAttach,
206 PACKET_vRun,
207 PACKET_QStartNoAckMode,
208 PACKET_vKill,
209 PACKET_qXfer_siginfo_read,
210 PACKET_qXfer_siginfo_write,
211 PACKET_qAttached,
212
213 /* Support for conditional tracepoints. */
214 PACKET_ConditionalTracepoints,
215
216 /* Support for target-side breakpoint conditions. */
217 PACKET_ConditionalBreakpoints,
218
219 /* Support for target-side breakpoint commands. */
220 PACKET_BreakpointCommands,
221
222 /* Support for fast tracepoints. */
223 PACKET_FastTracepoints,
224
225 /* Support for static tracepoints. */
226 PACKET_StaticTracepoints,
227
228 /* Support for installing tracepoints while a trace experiment is
229 running. */
230 PACKET_InstallInTrace,
231
232 PACKET_bc,
233 PACKET_bs,
234 PACKET_TracepointSource,
235 PACKET_QAllow,
236 PACKET_qXfer_fdpic,
237 PACKET_QDisableRandomization,
238 PACKET_QAgent,
239 PACKET_QTBuffer_size,
240 PACKET_Qbtrace_off,
241 PACKET_Qbtrace_bts,
242 PACKET_Qbtrace_pt,
243 PACKET_qXfer_btrace,
244
245 /* Support for the QNonStop packet. */
246 PACKET_QNonStop,
247
248 /* Support for the QThreadEvents packet. */
249 PACKET_QThreadEvents,
250
251 /* Support for multi-process extensions. */
252 PACKET_multiprocess_feature,
253
254 /* Support for enabling and disabling tracepoints while a trace
255 experiment is running. */
256 PACKET_EnableDisableTracepoints_feature,
257
258 /* Support for collecting strings using the tracenz bytecode. */
259 PACKET_tracenz_feature,
260
261 /* Support for continuing to run a trace experiment while GDB is
262 disconnected. */
263 PACKET_DisconnectedTracing_feature,
264
265 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
266 PACKET_augmented_libraries_svr4_read_feature,
267
268 /* Support for the qXfer:btrace-conf:read packet. */
269 PACKET_qXfer_btrace_conf,
270
271 /* Support for the Qbtrace-conf:bts:size packet. */
272 PACKET_Qbtrace_conf_bts_size,
273
274 /* Support for swbreak+ feature. */
275 PACKET_swbreak_feature,
276
277 /* Support for hwbreak+ feature. */
278 PACKET_hwbreak_feature,
279
280 /* Support for fork events. */
281 PACKET_fork_event_feature,
282
283 /* Support for vfork events. */
284 PACKET_vfork_event_feature,
285
286 /* Support for the Qbtrace-conf:pt:size packet. */
287 PACKET_Qbtrace_conf_pt_size,
288
289 /* Support for exec events. */
290 PACKET_exec_event_feature,
291
292 /* Support for query supported vCont actions. */
293 PACKET_vContSupported,
294
295 /* Support remote CTRL-C. */
296 PACKET_vCtrlC,
297
298 /* Support TARGET_WAITKIND_NO_RESUMED. */
299 PACKET_no_resumed,
300
301 /* Support for memory tagging, allocation tag fetch/store
302 packets and the tag violation stop replies. */
303 PACKET_memory_tagging_feature,
304
305 PACKET_MAX
306 };
307
308 struct threads_listing_context;
309
310 /* Stub vCont actions support.
311
312 Each field is a boolean flag indicating whether the stub reports
313 support for the corresponding action. */
314
315 struct vCont_action_support
316 {
317 /* vCont;t */
318 bool t = false;
319
320 /* vCont;r */
321 bool r = false;
322
323 /* vCont;s */
324 bool s = false;
325
326 /* vCont;S */
327 bool S = false;
328 };
329
330 /* About this many threadids fit in a packet. */
331
332 #define MAXTHREADLISTRESULTS 32
333
334 /* Data for the vFile:pread readahead cache. */
335
336 struct readahead_cache
337 {
338 /* Invalidate the readahead cache. */
339 void invalidate ();
340
341 /* Invalidate the readahead cache if it is holding data for FD. */
342 void invalidate_fd (int fd);
343
344 /* Serve pread from the readahead cache. Returns number of bytes
345 read, or 0 if the request can't be served from the cache. */
346 int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
347
348 /* The file descriptor for the file that is being cached. -1 if the
349 cache is invalid. */
350 int fd = -1;
351
352 /* The offset into the file that the cache buffer corresponds
353 to. */
354 ULONGEST offset = 0;
355
356 /* The buffer holding the cache contents. */
357 gdb::byte_vector buf;
358
359 /* Cache hit and miss counters. */
360 ULONGEST hit_count = 0;
361 ULONGEST miss_count = 0;
362 };
363
364 /* Description of the remote protocol for a given architecture. */
365
366 struct packet_reg
367 {
368 long offset; /* Offset into G packet. */
369 long regnum; /* GDB's internal register number. */
370 LONGEST pnum; /* Remote protocol register number. */
371 int in_g_packet; /* Always part of G packet. */
372 /* long size in bytes; == register_size (target_gdbarch (), regnum);
373 at present. */
374 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
375 at present. */
376 };
377
378 struct remote_arch_state
379 {
380 explicit remote_arch_state (struct gdbarch *gdbarch);
381
382 /* Description of the remote protocol registers. */
383 long sizeof_g_packet;
384
385 /* Description of the remote protocol registers indexed by REGNUM
386 (making an array gdbarch_num_regs in size). */
387 std::unique_ptr<packet_reg[]> regs;
388
389 /* This is the size (in chars) of the first response to the ``g''
390 packet. It is used as a heuristic when determining the maximum
391 size of memory-read and memory-write packets. A target will
392 typically only reserve a buffer large enough to hold the ``g''
393 packet. The size does not include packet overhead (headers and
394 trailers). */
395 long actual_register_packet_size;
396
397 /* This is the maximum size (in chars) of a non read/write packet.
398 It is also used as a cap on the size of read/write packets. */
399 long remote_packet_size;
400 };
401
402 /* Description of the remote protocol state for the currently
403 connected target. This is per-target state, and independent of the
404 selected architecture. */
405
406 class remote_state
407 {
408 public:
409
410 remote_state ();
411 ~remote_state ();
412
413 /* Get the remote arch state for GDBARCH. */
414 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
415
416 public: /* data */
417
418 /* A buffer to use for incoming packets, and its current size. The
419 buffer is grown dynamically for larger incoming packets.
420 Outgoing packets may also be constructed in this buffer.
421 The size of the buffer is always at least REMOTE_PACKET_SIZE;
422 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
423 packets. */
424 gdb::char_vector buf;
425
426 /* True if we're going through initial connection setup (finding out
427 about the remote side's threads, relocating symbols, etc.). */
428 bool starting_up = false;
429
430 /* If we negotiated packet size explicitly (and thus can bypass
431 heuristics for the largest packet size that will not overflow
432 a buffer in the stub), this will be set to that packet size.
433 Otherwise zero, meaning to use the guessed size. */
434 long explicit_packet_size = 0;
435
436 /* True, if in no ack mode. That is, neither GDB nor the stub will
437 expect acks from each other. The connection is assumed to be
438 reliable. */
439 bool noack_mode = false;
440
441 /* True if we're connected in extended remote mode. */
442 bool extended = false;
443
444 /* True if we resumed the target and we're waiting for the target to
445 stop. In the mean time, we can't start another command/query.
446 The remote server wouldn't be ready to process it, so we'd
447 timeout waiting for a reply that would never come and eventually
448 we'd close the connection. This can happen in asynchronous mode
449 because we allow GDB commands while the target is running. */
450 bool waiting_for_stop_reply = false;
451
452 /* The status of the stub support for the various vCont actions. */
453 vCont_action_support supports_vCont;
454
455 /* True if the user has pressed Ctrl-C, but the target hasn't
456 responded to that. */
457 bool ctrlc_pending_p = false;
458
459 /* True if we saw a Ctrl-C while reading or writing from/to the
460 remote descriptor. At that point it is not safe to send a remote
461 interrupt packet, so we instead remember we saw the Ctrl-C and
462 process it once we're done with sending/receiving the current
463 packet, which should be shortly. If however that takes too long,
464 and the user presses Ctrl-C again, we offer to disconnect. */
465 bool got_ctrlc_during_io = false;
466
467 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
468 remote_open knows that we don't have a file open when the program
469 starts. */
470 struct serial *remote_desc = nullptr;
471
472 /* These are the threads which we last sent to the remote system. The
473 TID member will be -1 for all or -2 for not sent yet. */
474 ptid_t general_thread = null_ptid;
475 ptid_t continue_thread = null_ptid;
476
477 /* This is the traceframe which we last selected on the remote system.
478 It will be -1 if no traceframe is selected. */
479 int remote_traceframe_number = -1;
480
481 char *last_pass_packet = nullptr;
482
483 /* The last QProgramSignals packet sent to the target. We bypass
484 sending a new program signals list down to the target if the new
485 packet is exactly the same as the last we sent. IOW, we only let
486 the target know about program signals list changes. */
487 char *last_program_signals_packet = nullptr;
488
489 gdb_signal last_sent_signal = GDB_SIGNAL_0;
490
491 bool last_sent_step = false;
492
493 /* The execution direction of the last resume we got. */
494 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
495
496 char *finished_object = nullptr;
497 char *finished_annex = nullptr;
498 ULONGEST finished_offset = 0;
499
500 /* Should we try the 'ThreadInfo' query packet?
501
502 This variable (NOT available to the user: auto-detect only!)
503 determines whether GDB will use the new, simpler "ThreadInfo"
504 query or the older, more complex syntax for thread queries.
505 This is an auto-detect variable (set to true at each connect,
506 and set to false when the target fails to recognize it). */
507 bool use_threadinfo_query = false;
508 bool use_threadextra_query = false;
509
510 threadref echo_nextthread {};
511 threadref nextthread {};
512 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
513
514 /* The state of remote notification. */
515 struct remote_notif_state *notif_state = nullptr;
516
517 /* The branch trace configuration. */
518 struct btrace_config btrace_config {};
519
520 /* The argument to the last "vFile:setfs:" packet we sent, used
521 to avoid sending repeated unnecessary "vFile:setfs:" packets.
522 Initialized to -1 to indicate that no "vFile:setfs:" packet
523 has yet been sent. */
524 int fs_pid = -1;
525
526 /* A readahead cache for vFile:pread. Often, reading a binary
527 involves a sequence of small reads. E.g., when parsing an ELF
528 file. A readahead cache helps mostly the case of remote
529 debugging on a connection with higher latency, due to the
530 request/reply nature of the RSP. We only cache data for a single
531 file descriptor at a time. */
532 struct readahead_cache readahead_cache;
533
534 /* The list of already fetched and acknowledged stop events. This
535 queue is used for notification Stop, and other notifications
536 don't need queue for their events, because the notification
537 events of Stop can't be consumed immediately, so that events
538 should be queued first, and be consumed by remote_wait_{ns,as}
539 one per time. Other notifications can consume their events
540 immediately, so queue is not needed for them. */
541 std::vector<stop_reply_up> stop_reply_queue;
542
543 /* Asynchronous signal handle registered as event loop source for
544 when we have pending events ready to be passed to the core. */
545 struct async_event_handler *remote_async_inferior_event_token = nullptr;
546
547 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
548 ``forever'' still use the normal timeout mechanism. This is
549 currently used by the ASYNC code to guarentee that target reads
550 during the initial connect always time-out. Once getpkt has been
551 modified to return a timeout indication and, in turn
552 remote_wait()/wait_for_inferior() have gained a timeout parameter
553 this can go away. */
554 int wait_forever_enabled_p = 1;
555
556 private:
557 /* Mapping of remote protocol data for each gdbarch. Usually there
558 is only one entry here, though we may see more with stubs that
559 support multi-process. */
560 std::unordered_map<struct gdbarch *, remote_arch_state>
561 m_arch_states;
562 };
563
564 static const target_info remote_target_info = {
565 "remote",
566 N_("Remote target using gdb-specific protocol"),
567 remote_doc
568 };
569
570 /* Description of a remote packet. */
571
572 struct packet_description
573 {
574 /* Name of the packet used for gdb output. */
575 const char *name;
576
577 /* Title of the packet, used by the set/show remote name-packet
578 commands to identify the individual packages and gdb output. */
579 const char *title;
580 };
581
582 /* Configuration of a remote packet. */
583
584 struct packet_config
585 {
586 /* If auto, GDB auto-detects support for this packet or feature,
587 either through qSupported, or by trying the packet and looking
588 at the response. If true, GDB assumes the target supports this
589 packet. If false, the packet is disabled. Configs that don't
590 have an associated command always have this set to auto. */
591 enum auto_boolean detect;
592
593 /* Does the target support this packet? */
594 enum packet_support support;
595 };
596
597 /* User configurable variables for the number of characters in a
598 memory read/write packet. MIN (rsa->remote_packet_size,
599 rsa->sizeof_g_packet) is the default. Some targets need smaller
600 values (fifo overruns, et.al.) and some users need larger values
601 (speed up transfers). The variables ``preferred_*'' (the user
602 request), ``current_*'' (what was actually set) and ``forced_*''
603 (Positive - a soft limit, negative - a hard limit). */
604
605 struct memory_packet_config
606 {
607 const char *name;
608 long size;
609 int fixed_p;
610 };
611
612 /* These global variables contain the default configuration for every new
613 remote_feature object. */
614 static memory_packet_config memory_read_packet_config =
615 {
616 "memory-read-packet-size",
617 };
618 static memory_packet_config memory_write_packet_config =
619 {
620 "memory-write-packet-size",
621 };
622
623 /* This global array contains packet descriptions (name and title). */
624 static packet_description packets_descriptions[PACKET_MAX];
625 /* This global array contains the default configuration for every new
626 per-remote target array. */
627 static packet_config remote_protocol_packets[PACKET_MAX];
628
629 /* Description of a remote target's features. It stores the configuration
630 and provides functions to determine supported features of the target. */
631
632 struct remote_features
633 {
634 remote_features ()
635 {
636 m_memory_read_packet_config = memory_read_packet_config;
637 m_memory_write_packet_config = memory_write_packet_config;
638
639 std::copy (std::begin (remote_protocol_packets),
640 std::end (remote_protocol_packets),
641 std::begin (m_protocol_packets));
642 }
643 ~remote_features () = default;
644
645 DISABLE_COPY_AND_ASSIGN (remote_features);
646
647 /* Returns whether a given packet defined by its enum value is supported. */
648 enum packet_support packet_support (int) const;
649
650 /* Returns the packet's corresponding "set remote foo-packet" command
651 state. See struct packet_config for more details. */
652 enum auto_boolean packet_set_cmd_state (int packet) const
653 { return m_protocol_packets[packet].detect; }
654
655 /* Returns true if the multi-process extensions are in effect. */
656 int remote_multi_process_p () const
657 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
658
659 /* Returns true if fork events are supported. */
660 int remote_fork_event_p () const
661 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
662
663 /* Returns true if vfork events are supported. */
664 int remote_vfork_event_p () const
665 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
666
667 /* Returns true if exec events are supported. */
668 int remote_exec_event_p () const
669 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
670
671 /* Returns true if memory tagging is supported, false otherwise. */
672 bool remote_memory_tagging_p () const
673 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
674
675 /* Reset all packets back to "unknown support". Called when opening a
676 new connection to a remote target. */
677 void reset_all_packet_configs_support ();
678
679 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
680 support configuration accordingly. */
681 packet_result packet_ok (const char *buf, const int which_packet);
682 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
683
684 /* Configuration of a remote target's memory read packet. */
685 memory_packet_config m_memory_read_packet_config;
686 /* Configuration of a remote target's memory write packet. */
687 memory_packet_config m_memory_write_packet_config;
688
689 /* The per-remote target array which stores a remote's packet
690 configurations. */
691 packet_config m_protocol_packets[PACKET_MAX];
692 };
693
694 class remote_target : public process_stratum_target
695 {
696 public:
697 remote_target () = default;
698 ~remote_target () override;
699
700 const target_info &info () const override
701 { return remote_target_info; }
702
703 const char *connection_string () override;
704
705 thread_control_capabilities get_thread_control_capabilities () override
706 { return tc_schedlock; }
707
708 /* Open a remote connection. */
709 static void open (const char *, int);
710
711 void close () override;
712
713 void detach (inferior *, int) override;
714 void disconnect (const char *, int) override;
715
716 void commit_resumed () override;
717 void resume (ptid_t, int, enum gdb_signal) override;
718 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
719 bool has_pending_events () override;
720
721 void fetch_registers (struct regcache *, int) override;
722 void store_registers (struct regcache *, int) override;
723 void prepare_to_store (struct regcache *) override;
724
725 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
726
727 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
728 enum remove_bp_reason) override;
729
730
731 bool stopped_by_sw_breakpoint () override;
732 bool supports_stopped_by_sw_breakpoint () override;
733
734 bool stopped_by_hw_breakpoint () override;
735
736 bool supports_stopped_by_hw_breakpoint () override;
737
738 bool stopped_by_watchpoint () override;
739
740 bool stopped_data_address (CORE_ADDR *) override;
741
742 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
743
744 int can_use_hw_breakpoint (enum bptype, int, int) override;
745
746 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
747
748 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
749
750 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
751
752 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
753 struct expression *) override;
754
755 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
756 struct expression *) override;
757
758 void kill () override;
759
760 void load (const char *, int) override;
761
762 void mourn_inferior () override;
763
764 void pass_signals (gdb::array_view<const unsigned char>) override;
765
766 int set_syscall_catchpoint (int, bool, int,
767 gdb::array_view<const int>) override;
768
769 void program_signals (gdb::array_view<const unsigned char>) override;
770
771 bool thread_alive (ptid_t ptid) override;
772
773 const char *thread_name (struct thread_info *) override;
774
775 void update_thread_list () override;
776
777 std::string pid_to_str (ptid_t) override;
778
779 const char *extra_thread_info (struct thread_info *) override;
780
781 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
782
783 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
784 int handle_len,
785 inferior *inf) override;
786
787 gdb::array_view<const gdb_byte> thread_info_to_thread_handle (struct thread_info *tp)
788 override;
789
790 void stop (ptid_t) override;
791
792 void interrupt () override;
793
794 void pass_ctrlc () override;
795
796 enum target_xfer_status xfer_partial (enum target_object object,
797 const char *annex,
798 gdb_byte *readbuf,
799 const gdb_byte *writebuf,
800 ULONGEST offset, ULONGEST len,
801 ULONGEST *xfered_len) override;
802
803 ULONGEST get_memory_xfer_limit () override;
804
805 void rcmd (const char *command, struct ui_file *output) override;
806
807 const char *pid_to_exec_file (int pid) override;
808
809 void log_command (const char *cmd) override
810 {
811 serial_log_command (this, cmd);
812 }
813
814 CORE_ADDR get_thread_local_address (ptid_t ptid,
815 CORE_ADDR load_module_addr,
816 CORE_ADDR offset) override;
817
818 bool can_execute_reverse () override;
819
820 std::vector<mem_region> memory_map () override;
821
822 void flash_erase (ULONGEST address, LONGEST length) override;
823
824 void flash_done () override;
825
826 const struct target_desc *read_description () override;
827
828 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
829 const gdb_byte *pattern, ULONGEST pattern_len,
830 CORE_ADDR *found_addrp) override;
831
832 bool can_async_p () override;
833
834 bool is_async_p () override;
835
836 void async (bool) override;
837
838 int async_wait_fd () override;
839
840 void thread_events (int) override;
841
842 int can_do_single_step () override;
843
844 void terminal_inferior () override;
845
846 void terminal_ours () override;
847
848 bool supports_non_stop () override;
849
850 bool supports_multi_process () override;
851
852 bool supports_disable_randomization () override;
853
854 bool filesystem_is_local () override;
855
856
857 int fileio_open (struct inferior *inf, const char *filename,
858 int flags, int mode, int warn_if_slow,
859 fileio_error *target_errno) override;
860
861 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
862 ULONGEST offset, fileio_error *target_errno) override;
863
864 int fileio_pread (int fd, gdb_byte *read_buf, int len,
865 ULONGEST offset, fileio_error *target_errno) override;
866
867 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
868
869 int fileio_close (int fd, fileio_error *target_errno) override;
870
871 int fileio_unlink (struct inferior *inf,
872 const char *filename,
873 fileio_error *target_errno) override;
874
875 gdb::optional<std::string>
876 fileio_readlink (struct inferior *inf,
877 const char *filename,
878 fileio_error *target_errno) override;
879
880 bool supports_enable_disable_tracepoint () override;
881
882 bool supports_string_tracing () override;
883
884 int remote_supports_cond_tracepoints ();
885
886 bool supports_evaluation_of_breakpoint_conditions () override;
887
888 int remote_supports_fast_tracepoints ();
889
890 int remote_supports_static_tracepoints ();
891
892 int remote_supports_install_in_trace ();
893
894 bool can_run_breakpoint_commands () override;
895
896 void trace_init () override;
897
898 void download_tracepoint (struct bp_location *location) override;
899
900 bool can_download_tracepoint () override;
901
902 void download_trace_state_variable (const trace_state_variable &tsv) override;
903
904 void enable_tracepoint (struct bp_location *location) override;
905
906 void disable_tracepoint (struct bp_location *location) override;
907
908 void trace_set_readonly_regions () override;
909
910 void trace_start () override;
911
912 int get_trace_status (struct trace_status *ts) override;
913
914 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
915 override;
916
917 void trace_stop () override;
918
919 int trace_find (enum trace_find_type type, int num,
920 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
921
922 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
923
924 int save_trace_data (const char *filename) override;
925
926 int upload_tracepoints (struct uploaded_tp **utpp) override;
927
928 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
929
930 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
931
932 int get_min_fast_tracepoint_insn_len () override;
933
934 void set_disconnected_tracing (int val) override;
935
936 void set_circular_trace_buffer (int val) override;
937
938 void set_trace_buffer_size (LONGEST val) override;
939
940 bool set_trace_notes (const char *user, const char *notes,
941 const char *stopnotes) override;
942
943 int core_of_thread (ptid_t ptid) override;
944
945 int verify_memory (const gdb_byte *data,
946 CORE_ADDR memaddr, ULONGEST size) override;
947
948
949 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
950
951 void set_permissions () override;
952
953 bool static_tracepoint_marker_at (CORE_ADDR,
954 struct static_tracepoint_marker *marker)
955 override;
956
957 std::vector<static_tracepoint_marker>
958 static_tracepoint_markers_by_strid (const char *id) override;
959
960 traceframe_info_up traceframe_info () override;
961
962 bool use_agent (bool use) override;
963 bool can_use_agent () override;
964
965 struct btrace_target_info *
966 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
967
968 void disable_btrace (struct btrace_target_info *tinfo) override;
969
970 void teardown_btrace (struct btrace_target_info *tinfo) override;
971
972 enum btrace_error read_btrace (struct btrace_data *data,
973 struct btrace_target_info *btinfo,
974 enum btrace_read_type type) override;
975
976 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
977 bool augmented_libraries_svr4_read () override;
978 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
979 void follow_exec (inferior *, ptid_t, const char *) override;
980 int insert_fork_catchpoint (int) override;
981 int remove_fork_catchpoint (int) override;
982 int insert_vfork_catchpoint (int) override;
983 int remove_vfork_catchpoint (int) override;
984 int insert_exec_catchpoint (int) override;
985 int remove_exec_catchpoint (int) override;
986 enum exec_direction_kind execution_direction () override;
987
988 bool supports_memory_tagging () override;
989
990 bool fetch_memtags (CORE_ADDR address, size_t len,
991 gdb::byte_vector &tags, int type) override;
992
993 bool store_memtags (CORE_ADDR address, size_t len,
994 const gdb::byte_vector &tags, int type) override;
995
996 public: /* Remote specific methods. */
997
998 void remote_download_command_source (int num, ULONGEST addr,
999 struct command_line *cmds);
1000
1001 void remote_file_put (const char *local_file, const char *remote_file,
1002 int from_tty);
1003 void remote_file_get (const char *remote_file, const char *local_file,
1004 int from_tty);
1005 void remote_file_delete (const char *remote_file, int from_tty);
1006
1007 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1008 ULONGEST offset, fileio_error *remote_errno);
1009 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1010 ULONGEST offset, fileio_error *remote_errno);
1011 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1012 ULONGEST offset, fileio_error *remote_errno);
1013
1014 int remote_hostio_send_command (int command_bytes, int which_packet,
1015 fileio_error *remote_errno, const char **attachment,
1016 int *attachment_len);
1017 int remote_hostio_set_filesystem (struct inferior *inf,
1018 fileio_error *remote_errno);
1019 /* We should get rid of this and use fileio_open directly. */
1020 int remote_hostio_open (struct inferior *inf, const char *filename,
1021 int flags, int mode, int warn_if_slow,
1022 fileio_error *remote_errno);
1023 int remote_hostio_close (int fd, fileio_error *remote_errno);
1024
1025 int remote_hostio_unlink (inferior *inf, const char *filename,
1026 fileio_error *remote_errno);
1027
1028 struct remote_state *get_remote_state ();
1029
1030 long get_remote_packet_size (void);
1031 long get_memory_packet_size (struct memory_packet_config *config);
1032
1033 long get_memory_write_packet_size ();
1034 long get_memory_read_packet_size ();
1035
1036 char *append_pending_thread_resumptions (char *p, char *endp,
1037 ptid_t ptid);
1038 static void open_1 (const char *name, int from_tty, int extended_p);
1039 void start_remote (int from_tty, int extended_p);
1040 void remote_detach_1 (struct inferior *inf, int from_tty);
1041
1042 char *append_resumption (char *p, char *endp,
1043 ptid_t ptid, int step, gdb_signal siggnal);
1044 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1045 gdb_signal siggnal);
1046
1047 thread_info *add_current_inferior_and_thread (const char *wait_status);
1048
1049 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1050 target_wait_flags options);
1051 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1052 target_wait_flags options);
1053
1054 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1055 target_waitstatus *status);
1056
1057 ptid_t select_thread_for_ambiguous_stop_reply
1058 (const struct target_waitstatus &status);
1059
1060 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1061
1062 void print_one_stopped_thread (thread_info *thread);
1063 void process_initial_stop_replies (int from_tty);
1064
1065 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1066 bool silent_p);
1067
1068 void btrace_sync_conf (const btrace_config *conf);
1069
1070 void remote_btrace_maybe_reopen ();
1071
1072 void remove_new_fork_children (threads_listing_context *context);
1073 void kill_new_fork_children (inferior *inf);
1074 void discard_pending_stop_replies (struct inferior *inf);
1075 int stop_reply_queue_length ();
1076
1077 void check_pending_events_prevent_wildcard_vcont
1078 (bool *may_global_wildcard_vcont);
1079
1080 void discard_pending_stop_replies_in_queue ();
1081 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1082 struct stop_reply *queued_stop_reply (ptid_t ptid);
1083 int peek_stop_reply (ptid_t ptid);
1084 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1085
1086 void remote_stop_ns (ptid_t ptid);
1087 void remote_interrupt_as ();
1088 void remote_interrupt_ns ();
1089
1090 char *remote_get_noisy_reply ();
1091 int remote_query_attached (int pid);
1092 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1093 int try_open_exec);
1094
1095 ptid_t remote_current_thread (ptid_t oldpid);
1096 ptid_t get_current_thread (const char *wait_status);
1097
1098 void set_thread (ptid_t ptid, int gen);
1099 void set_general_thread (ptid_t ptid);
1100 void set_continue_thread (ptid_t ptid);
1101 void set_general_process ();
1102
1103 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1104
1105 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1106 gdb_ext_thread_info *info);
1107 int remote_get_threadinfo (threadref *threadid, int fieldset,
1108 gdb_ext_thread_info *info);
1109
1110 int parse_threadlist_response (const char *pkt, int result_limit,
1111 threadref *original_echo,
1112 threadref *resultlist,
1113 int *doneflag);
1114 int remote_get_threadlist (int startflag, threadref *nextthread,
1115 int result_limit, int *done, int *result_count,
1116 threadref *threadlist);
1117
1118 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1119 void *context, int looplimit);
1120
1121 int remote_get_threads_with_ql (threads_listing_context *context);
1122 int remote_get_threads_with_qxfer (threads_listing_context *context);
1123 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1124
1125 void extended_remote_restart ();
1126
1127 void get_offsets ();
1128
1129 void remote_check_symbols ();
1130
1131 void remote_supported_packet (const struct protocol_feature *feature,
1132 enum packet_support support,
1133 const char *argument);
1134
1135 void remote_query_supported ();
1136
1137 void remote_packet_size (const protocol_feature *feature,
1138 packet_support support, const char *value);
1139
1140 void remote_serial_quit_handler ();
1141
1142 void remote_detach_pid (int pid);
1143
1144 void remote_vcont_probe ();
1145
1146 void remote_resume_with_hc (ptid_t ptid, int step,
1147 gdb_signal siggnal);
1148
1149 void send_interrupt_sequence ();
1150 void interrupt_query ();
1151
1152 void remote_notif_get_pending_events (const notif_client *nc);
1153
1154 int fetch_register_using_p (struct regcache *regcache,
1155 packet_reg *reg);
1156 int send_g_packet ();
1157 void process_g_packet (struct regcache *regcache);
1158 void fetch_registers_using_g (struct regcache *regcache);
1159 int store_register_using_P (const struct regcache *regcache,
1160 packet_reg *reg);
1161 void store_registers_using_G (const struct regcache *regcache);
1162
1163 void set_remote_traceframe ();
1164
1165 void check_binary_download (CORE_ADDR addr);
1166
1167 target_xfer_status remote_write_bytes_aux (const char *header,
1168 CORE_ADDR memaddr,
1169 const gdb_byte *myaddr,
1170 ULONGEST len_units,
1171 int unit_size,
1172 ULONGEST *xfered_len_units,
1173 char packet_format,
1174 int use_length);
1175
1176 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1177 const gdb_byte *myaddr, ULONGEST len,
1178 int unit_size, ULONGEST *xfered_len);
1179
1180 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1181 ULONGEST len_units,
1182 int unit_size, ULONGEST *xfered_len_units);
1183
1184 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1185 ULONGEST memaddr,
1186 ULONGEST len,
1187 int unit_size,
1188 ULONGEST *xfered_len);
1189
1190 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1191 gdb_byte *myaddr, ULONGEST len,
1192 int unit_size,
1193 ULONGEST *xfered_len);
1194
1195 packet_result remote_send_printf (const char *format, ...)
1196 ATTRIBUTE_PRINTF (2, 3);
1197
1198 target_xfer_status remote_flash_write (ULONGEST address,
1199 ULONGEST length, ULONGEST *xfered_len,
1200 const gdb_byte *data);
1201
1202 int readchar (int timeout);
1203
1204 void remote_serial_write (const char *str, int len);
1205
1206 int putpkt (const char *buf);
1207 int putpkt_binary (const char *buf, int cnt);
1208
1209 int putpkt (const gdb::char_vector &buf)
1210 {
1211 return putpkt (buf.data ());
1212 }
1213
1214 void skip_frame ();
1215 long read_frame (gdb::char_vector *buf_p);
1216 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
1217 int expecting_notif, int *is_notif);
1218 int getpkt (gdb::char_vector *buf, int forever);
1219 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
1220 int *is_notif);
1221 int remote_vkill (int pid);
1222 void remote_kill_k ();
1223
1224 void extended_remote_disable_randomization (int val);
1225 int extended_remote_run (const std::string &args);
1226
1227 void send_environment_packet (const char *action,
1228 const char *packet,
1229 const char *value);
1230
1231 void extended_remote_environment_support ();
1232 void extended_remote_set_inferior_cwd ();
1233
1234 target_xfer_status remote_write_qxfer (const char *object_name,
1235 const char *annex,
1236 const gdb_byte *writebuf,
1237 ULONGEST offset, LONGEST len,
1238 ULONGEST *xfered_len,
1239 const unsigned int which_packet);
1240
1241 target_xfer_status remote_read_qxfer (const char *object_name,
1242 const char *annex,
1243 gdb_byte *readbuf, ULONGEST offset,
1244 LONGEST len,
1245 ULONGEST *xfered_len,
1246 const unsigned int which_packet);
1247
1248 void push_stop_reply (struct stop_reply *new_event);
1249
1250 bool vcont_r_supported ();
1251
1252 remote_features m_features;
1253
1254 private:
1255
1256 bool start_remote_1 (int from_tty, int extended_p);
1257
1258 /* The remote state. Don't reference this directly. Use the
1259 get_remote_state method instead. */
1260 remote_state m_remote_state;
1261 };
1262
1263 static const target_info extended_remote_target_info = {
1264 "extended-remote",
1265 N_("Extended remote target using gdb-specific protocol"),
1266 remote_doc
1267 };
1268
1269 /* Set up the extended remote target by extending the standard remote
1270 target and adding to it. */
1271
1272 class extended_remote_target final : public remote_target
1273 {
1274 public:
1275 const target_info &info () const override
1276 { return extended_remote_target_info; }
1277
1278 /* Open an extended-remote connection. */
1279 static void open (const char *, int);
1280
1281 bool can_create_inferior () override { return true; }
1282 void create_inferior (const char *, const std::string &,
1283 char **, int) override;
1284
1285 void detach (inferior *, int) override;
1286
1287 bool can_attach () override { return true; }
1288 void attach (const char *, int) override;
1289
1290 void post_attach (int) override;
1291 bool supports_disable_randomization () override;
1292 };
1293
1294 struct stop_reply : public notif_event
1295 {
1296 ~stop_reply ();
1297
1298 /* The identifier of the thread about this event */
1299 ptid_t ptid;
1300
1301 /* The remote state this event is associated with. When the remote
1302 connection, represented by a remote_state object, is closed,
1303 all the associated stop_reply events should be released. */
1304 struct remote_state *rs;
1305
1306 struct target_waitstatus ws;
1307
1308 /* The architecture associated with the expedited registers. */
1309 gdbarch *arch;
1310
1311 /* Expedited registers. This makes remote debugging a bit more
1312 efficient for those targets that provide critical registers as
1313 part of their normal status mechanism (as another roundtrip to
1314 fetch them is avoided). */
1315 std::vector<cached_reg_t> regcache;
1316
1317 enum target_stop_reason stop_reason;
1318
1319 CORE_ADDR watch_data_address;
1320
1321 int core;
1322 };
1323
1324 /* Return TARGET as a remote_target if it is one, else nullptr. */
1325
1326 static remote_target *
1327 as_remote_target (process_stratum_target *target)
1328 {
1329 return dynamic_cast<remote_target *> (target);
1330 }
1331
1332 /* See remote.h. */
1333
1334 bool
1335 is_remote_target (process_stratum_target *target)
1336 {
1337 return as_remote_target (target) != nullptr;
1338 }
1339
1340 /* Per-program-space data key. */
1341 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1342 remote_pspace_data;
1343
1344 /* The variable registered as the control variable used by the
1345 remote exec-file commands. While the remote exec-file setting is
1346 per-program-space, the set/show machinery uses this as the
1347 location of the remote exec-file value. */
1348 static std::string remote_exec_file_var;
1349
1350 /* The size to align memory write packets, when practical. The protocol
1351 does not guarantee any alignment, and gdb will generate short
1352 writes and unaligned writes, but even as a best-effort attempt this
1353 can improve bulk transfers. For instance, if a write is misaligned
1354 relative to the target's data bus, the stub may need to make an extra
1355 round trip fetching data from the target. This doesn't make a
1356 huge difference, but it's easy to do, so we try to be helpful.
1357
1358 The alignment chosen is arbitrary; usually data bus width is
1359 important here, not the possibly larger cache line size. */
1360 enum { REMOTE_ALIGN_WRITES = 16 };
1361
1362 /* Prototypes for local functions. */
1363
1364 static int hexnumlen (ULONGEST num);
1365
1366 static int stubhex (int ch);
1367
1368 static int hexnumstr (char *, ULONGEST);
1369
1370 static int hexnumnstr (char *, ULONGEST, int);
1371
1372 static CORE_ADDR remote_address_masked (CORE_ADDR);
1373
1374 static int stub_unpack_int (const char *buff, int fieldlength);
1375
1376 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1377 cmd_list_element *c);
1378
1379 static void show_packet_config_cmd (ui_file *file,
1380 const unsigned int which_packet,
1381 remote_target *remote);
1382
1383 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1384 int from_tty,
1385 struct cmd_list_element *c,
1386 const char *value);
1387
1388 static ptid_t read_ptid (const char *buf, const char **obuf);
1389
1390 static void remote_async_inferior_event_handler (gdb_client_data);
1391
1392 static bool remote_read_description_p (struct target_ops *target);
1393
1394 static void remote_console_output (const char *msg);
1395
1396 static void remote_btrace_reset (remote_state *rs);
1397
1398 static void remote_unpush_and_throw (remote_target *target);
1399
1400 /* For "remote". */
1401
1402 static struct cmd_list_element *remote_cmdlist;
1403
1404 /* For "set remote" and "show remote". */
1405
1406 static struct cmd_list_element *remote_set_cmdlist;
1407 static struct cmd_list_element *remote_show_cmdlist;
1408
1409 /* Controls whether GDB is willing to use range stepping. */
1410
1411 static bool use_range_stepping = true;
1412
1413 /* From the remote target's point of view, each thread is in one of these three
1414 states. */
1415 enum class resume_state
1416 {
1417 /* Not resumed - we haven't been asked to resume this thread. */
1418 NOT_RESUMED,
1419
1420 /* We have been asked to resume this thread, but haven't sent a vCont action
1421 for it yet. We'll need to consider it next time commit_resume is
1422 called. */
1423 RESUMED_PENDING_VCONT,
1424
1425 /* We have been asked to resume this thread, and we have sent a vCont action
1426 for it. */
1427 RESUMED,
1428 };
1429
1430 /* Information about a thread's pending vCont-resume. Used when a thread is in
1431 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1432 stores this information which is then picked up by
1433 remote_target::commit_resume to know which is the proper action for this
1434 thread to include in the vCont packet. */
1435 struct resumed_pending_vcont_info
1436 {
1437 /* True if the last resume call for this thread was a step request, false
1438 if a continue request. */
1439 bool step;
1440
1441 /* The signal specified in the last resume call for this thread. */
1442 gdb_signal sig;
1443 };
1444
1445 /* Private data that we'll store in (struct thread_info)->priv. */
1446 struct remote_thread_info : public private_thread_info
1447 {
1448 std::string extra;
1449 std::string name;
1450 int core = -1;
1451
1452 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1453 sequence of bytes. */
1454 gdb::byte_vector thread_handle;
1455
1456 /* Whether the target stopped for a breakpoint/watchpoint. */
1457 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1458
1459 /* This is set to the data address of the access causing the target
1460 to stop for a watchpoint. */
1461 CORE_ADDR watch_data_address = 0;
1462
1463 /* Get the thread's resume state. */
1464 enum resume_state get_resume_state () const
1465 {
1466 return m_resume_state;
1467 }
1468
1469 /* Put the thread in the NOT_RESUMED state. */
1470 void set_not_resumed ()
1471 {
1472 m_resume_state = resume_state::NOT_RESUMED;
1473 }
1474
1475 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1476 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1477 {
1478 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1479 m_resumed_pending_vcont_info.step = step;
1480 m_resumed_pending_vcont_info.sig = sig;
1481 }
1482
1483 /* Get the information this thread's pending vCont-resumption.
1484
1485 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1486 state. */
1487 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1488 {
1489 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1490
1491 return m_resumed_pending_vcont_info;
1492 }
1493
1494 /* Put the thread in the VCONT_RESUMED state. */
1495 void set_resumed ()
1496 {
1497 m_resume_state = resume_state::RESUMED;
1498 }
1499
1500 private:
1501 /* Resume state for this thread. This is used to implement vCont action
1502 coalescing (only when the target operates in non-stop mode).
1503
1504 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1505 which notes that this thread must be considered in the next commit_resume
1506 call.
1507
1508 remote_target::commit_resume sends a vCont packet with actions for the
1509 threads in the RESUMED_PENDING_VCONT state and moves them to the
1510 VCONT_RESUMED state.
1511
1512 When reporting a stop to the core for a thread, that thread is moved back
1513 to the NOT_RESUMED state. */
1514 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1515
1516 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1517 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1518 };
1519
1520 remote_state::remote_state ()
1521 : buf (400)
1522 {
1523 }
1524
1525 remote_state::~remote_state ()
1526 {
1527 xfree (this->last_pass_packet);
1528 xfree (this->last_program_signals_packet);
1529 xfree (this->finished_object);
1530 xfree (this->finished_annex);
1531 }
1532
1533 /* Utility: generate error from an incoming stub packet. */
1534 static void
1535 trace_error (char *buf)
1536 {
1537 if (*buf++ != 'E')
1538 return; /* not an error msg */
1539 switch (*buf)
1540 {
1541 case '1': /* malformed packet error */
1542 if (*++buf == '0') /* general case: */
1543 error (_("remote.c: error in outgoing packet."));
1544 else
1545 error (_("remote.c: error in outgoing packet at field #%ld."),
1546 strtol (buf, NULL, 16));
1547 default:
1548 error (_("Target returns error code '%s'."), buf);
1549 }
1550 }
1551
1552 /* Utility: wait for reply from stub, while accepting "O" packets. */
1553
1554 char *
1555 remote_target::remote_get_noisy_reply ()
1556 {
1557 struct remote_state *rs = get_remote_state ();
1558
1559 do /* Loop on reply from remote stub. */
1560 {
1561 char *buf;
1562
1563 QUIT; /* Allow user to bail out with ^C. */
1564 getpkt (&rs->buf, 0);
1565 buf = rs->buf.data ();
1566 if (buf[0] == 'E')
1567 trace_error (buf);
1568 else if (startswith (buf, "qRelocInsn:"))
1569 {
1570 ULONGEST ul;
1571 CORE_ADDR from, to, org_to;
1572 const char *p, *pp;
1573 int adjusted_size = 0;
1574 int relocated = 0;
1575
1576 p = buf + strlen ("qRelocInsn:");
1577 pp = unpack_varlen_hex (p, &ul);
1578 if (*pp != ';')
1579 error (_("invalid qRelocInsn packet: %s"), buf);
1580 from = ul;
1581
1582 p = pp + 1;
1583 unpack_varlen_hex (p, &ul);
1584 to = ul;
1585
1586 org_to = to;
1587
1588 try
1589 {
1590 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1591 relocated = 1;
1592 }
1593 catch (const gdb_exception &ex)
1594 {
1595 if (ex.error == MEMORY_ERROR)
1596 {
1597 /* Propagate memory errors silently back to the
1598 target. The stub may have limited the range of
1599 addresses we can write to, for example. */
1600 }
1601 else
1602 {
1603 /* Something unexpectedly bad happened. Be verbose
1604 so we can tell what, and propagate the error back
1605 to the stub, so it doesn't get stuck waiting for
1606 a response. */
1607 exception_fprintf (gdb_stderr, ex,
1608 _("warning: relocating instruction: "));
1609 }
1610 putpkt ("E01");
1611 }
1612
1613 if (relocated)
1614 {
1615 adjusted_size = to - org_to;
1616
1617 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1618 putpkt (buf);
1619 }
1620 }
1621 else if (buf[0] == 'O' && buf[1] != 'K')
1622 remote_console_output (buf + 1); /* 'O' message from stub */
1623 else
1624 return buf; /* Here's the actual reply. */
1625 }
1626 while (1);
1627 }
1628
1629 struct remote_arch_state *
1630 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1631 {
1632 remote_arch_state *rsa;
1633
1634 auto it = this->m_arch_states.find (gdbarch);
1635 if (it == this->m_arch_states.end ())
1636 {
1637 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1638 std::forward_as_tuple (gdbarch),
1639 std::forward_as_tuple (gdbarch));
1640 rsa = &p.first->second;
1641
1642 /* Make sure that the packet buffer is plenty big enough for
1643 this architecture. */
1644 if (this->buf.size () < rsa->remote_packet_size)
1645 this->buf.resize (2 * rsa->remote_packet_size);
1646 }
1647 else
1648 rsa = &it->second;
1649
1650 return rsa;
1651 }
1652
1653 /* Fetch the global remote target state. */
1654
1655 remote_state *
1656 remote_target::get_remote_state ()
1657 {
1658 /* Make sure that the remote architecture state has been
1659 initialized, because doing so might reallocate rs->buf. Any
1660 function which calls getpkt also needs to be mindful of changes
1661 to rs->buf, but this call limits the number of places which run
1662 into trouble. */
1663 m_remote_state.get_remote_arch_state (target_gdbarch ());
1664
1665 return &m_remote_state;
1666 }
1667
1668 /* Fetch the remote exec-file from the current program space. */
1669
1670 static const char *
1671 get_remote_exec_file (void)
1672 {
1673 char *remote_exec_file;
1674
1675 remote_exec_file = remote_pspace_data.get (current_program_space);
1676 if (remote_exec_file == NULL)
1677 return "";
1678
1679 return remote_exec_file;
1680 }
1681
1682 /* Set the remote exec file for PSPACE. */
1683
1684 static void
1685 set_pspace_remote_exec_file (struct program_space *pspace,
1686 const char *remote_exec_file)
1687 {
1688 char *old_file = remote_pspace_data.get (pspace);
1689
1690 xfree (old_file);
1691 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1692 }
1693
1694 /* The "set/show remote exec-file" set command hook. */
1695
1696 static void
1697 set_remote_exec_file (const char *ignored, int from_tty,
1698 struct cmd_list_element *c)
1699 {
1700 set_pspace_remote_exec_file (current_program_space,
1701 remote_exec_file_var.c_str ());
1702 }
1703
1704 /* The "set/show remote exec-file" show command hook. */
1705
1706 static void
1707 show_remote_exec_file (struct ui_file *file, int from_tty,
1708 struct cmd_list_element *cmd, const char *value)
1709 {
1710 gdb_printf (file, "%s\n", get_remote_exec_file ());
1711 }
1712
1713 static int
1714 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1715 {
1716 int regnum, num_remote_regs, offset;
1717 struct packet_reg **remote_regs;
1718
1719 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1720 {
1721 struct packet_reg *r = &regs[regnum];
1722
1723 if (register_size (gdbarch, regnum) == 0)
1724 /* Do not try to fetch zero-sized (placeholder) registers. */
1725 r->pnum = -1;
1726 else
1727 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1728
1729 r->regnum = regnum;
1730 }
1731
1732 /* Define the g/G packet format as the contents of each register
1733 with a remote protocol number, in order of ascending protocol
1734 number. */
1735
1736 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1737 for (num_remote_regs = 0, regnum = 0;
1738 regnum < gdbarch_num_regs (gdbarch);
1739 regnum++)
1740 if (regs[regnum].pnum != -1)
1741 remote_regs[num_remote_regs++] = &regs[regnum];
1742
1743 std::sort (remote_regs, remote_regs + num_remote_regs,
1744 [] (const packet_reg *a, const packet_reg *b)
1745 { return a->pnum < b->pnum; });
1746
1747 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1748 {
1749 remote_regs[regnum]->in_g_packet = 1;
1750 remote_regs[regnum]->offset = offset;
1751 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1752 }
1753
1754 return offset;
1755 }
1756
1757 /* Given the architecture described by GDBARCH, return the remote
1758 protocol register's number and the register's offset in the g/G
1759 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1760 If the target does not have a mapping for REGNUM, return false,
1761 otherwise, return true. */
1762
1763 int
1764 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1765 int *pnum, int *poffset)
1766 {
1767 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1768
1769 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1770
1771 map_regcache_remote_table (gdbarch, regs.data ());
1772
1773 *pnum = regs[regnum].pnum;
1774 *poffset = regs[regnum].offset;
1775
1776 return *pnum != -1;
1777 }
1778
1779 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1780 {
1781 /* Use the architecture to build a regnum<->pnum table, which will be
1782 1:1 unless a feature set specifies otherwise. */
1783 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1784
1785 /* Record the maximum possible size of the g packet - it may turn out
1786 to be smaller. */
1787 this->sizeof_g_packet
1788 = map_regcache_remote_table (gdbarch, this->regs.get ());
1789
1790 /* Default maximum number of characters in a packet body. Many
1791 remote stubs have a hardwired buffer size of 400 bytes
1792 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1793 as the maximum packet-size to ensure that the packet and an extra
1794 NUL character can always fit in the buffer. This stops GDB
1795 trashing stubs that try to squeeze an extra NUL into what is
1796 already a full buffer (As of 1999-12-04 that was most stubs). */
1797 this->remote_packet_size = 400 - 1;
1798
1799 /* This one is filled in when a ``g'' packet is received. */
1800 this->actual_register_packet_size = 0;
1801
1802 /* Should rsa->sizeof_g_packet needs more space than the
1803 default, adjust the size accordingly. Remember that each byte is
1804 encoded as two characters. 32 is the overhead for the packet
1805 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1806 (``$NN:G...#NN'') is a better guess, the below has been padded a
1807 little. */
1808 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1809 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1810 }
1811
1812 /* Get a pointer to the current remote target. If not connected to a
1813 remote target, return NULL. */
1814
1815 static remote_target *
1816 get_current_remote_target ()
1817 {
1818 target_ops *proc_target = current_inferior ()->process_target ();
1819 return dynamic_cast<remote_target *> (proc_target);
1820 }
1821
1822 /* Return the current allowed size of a remote packet. This is
1823 inferred from the current architecture, and should be used to
1824 limit the length of outgoing packets. */
1825 long
1826 remote_target::get_remote_packet_size ()
1827 {
1828 struct remote_state *rs = get_remote_state ();
1829 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1830
1831 if (rs->explicit_packet_size)
1832 return rs->explicit_packet_size;
1833
1834 return rsa->remote_packet_size;
1835 }
1836
1837 static struct packet_reg *
1838 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1839 long regnum)
1840 {
1841 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1842 return NULL;
1843 else
1844 {
1845 struct packet_reg *r = &rsa->regs[regnum];
1846
1847 gdb_assert (r->regnum == regnum);
1848 return r;
1849 }
1850 }
1851
1852 static struct packet_reg *
1853 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1854 LONGEST pnum)
1855 {
1856 int i;
1857
1858 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1859 {
1860 struct packet_reg *r = &rsa->regs[i];
1861
1862 if (r->pnum == pnum)
1863 return r;
1864 }
1865 return NULL;
1866 }
1867
1868 /* Allow the user to specify what sequence to send to the remote
1869 when he requests a program interruption: Although ^C is usually
1870 what remote systems expect (this is the default, here), it is
1871 sometimes preferable to send a break. On other systems such
1872 as the Linux kernel, a break followed by g, which is Magic SysRq g
1873 is required in order to interrupt the execution. */
1874 const char interrupt_sequence_control_c[] = "Ctrl-C";
1875 const char interrupt_sequence_break[] = "BREAK";
1876 const char interrupt_sequence_break_g[] = "BREAK-g";
1877 static const char *const interrupt_sequence_modes[] =
1878 {
1879 interrupt_sequence_control_c,
1880 interrupt_sequence_break,
1881 interrupt_sequence_break_g,
1882 NULL
1883 };
1884 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1885
1886 static void
1887 show_interrupt_sequence (struct ui_file *file, int from_tty,
1888 struct cmd_list_element *c,
1889 const char *value)
1890 {
1891 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1892 gdb_printf (file,
1893 _("Send the ASCII ETX character (Ctrl-c) "
1894 "to the remote target to interrupt the "
1895 "execution of the program.\n"));
1896 else if (interrupt_sequence_mode == interrupt_sequence_break)
1897 gdb_printf (file,
1898 _("send a break signal to the remote target "
1899 "to interrupt the execution of the program.\n"));
1900 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1901 gdb_printf (file,
1902 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1903 "the remote target to interrupt the execution "
1904 "of Linux kernel.\n"));
1905 else
1906 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1907 interrupt_sequence_mode);
1908 }
1909
1910 /* This boolean variable specifies whether interrupt_sequence is sent
1911 to the remote target when gdb connects to it.
1912 This is mostly needed when you debug the Linux kernel: The Linux kernel
1913 expects BREAK g which is Magic SysRq g for connecting gdb. */
1914 static bool interrupt_on_connect = false;
1915
1916 /* This variable is used to implement the "set/show remotebreak" commands.
1917 Since these commands are now deprecated in favor of "set/show remote
1918 interrupt-sequence", it no longer has any effect on the code. */
1919 static bool remote_break;
1920
1921 static void
1922 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1923 {
1924 if (remote_break)
1925 interrupt_sequence_mode = interrupt_sequence_break;
1926 else
1927 interrupt_sequence_mode = interrupt_sequence_control_c;
1928 }
1929
1930 static void
1931 show_remotebreak (struct ui_file *file, int from_tty,
1932 struct cmd_list_element *c,
1933 const char *value)
1934 {
1935 }
1936
1937 /* This variable sets the number of bits in an address that are to be
1938 sent in a memory ("M" or "m") packet. Normally, after stripping
1939 leading zeros, the entire address would be sent. This variable
1940 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1941 initial implementation of remote.c restricted the address sent in
1942 memory packets to ``host::sizeof long'' bytes - (typically 32
1943 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1944 address was never sent. Since fixing this bug may cause a break in
1945 some remote targets this variable is principally provided to
1946 facilitate backward compatibility. */
1947
1948 static unsigned int remote_address_size;
1949
1950 \f
1951 /* The default max memory-write-packet-size, when the setting is
1952 "fixed". The 16k is historical. (It came from older GDB's using
1953 alloca for buffers and the knowledge (folklore?) that some hosts
1954 don't cope very well with large alloca calls.) */
1955 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1956
1957 /* The minimum remote packet size for memory transfers. Ensures we
1958 can write at least one byte. */
1959 #define MIN_MEMORY_PACKET_SIZE 20
1960
1961 /* Get the memory packet size, assuming it is fixed. */
1962
1963 static long
1964 get_fixed_memory_packet_size (struct memory_packet_config *config)
1965 {
1966 gdb_assert (config->fixed_p);
1967
1968 if (config->size <= 0)
1969 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1970 else
1971 return config->size;
1972 }
1973
1974 /* Compute the current size of a read/write packet. Since this makes
1975 use of ``actual_register_packet_size'' the computation is dynamic. */
1976
1977 long
1978 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1979 {
1980 struct remote_state *rs = get_remote_state ();
1981 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1982
1983 long what_they_get;
1984 if (config->fixed_p)
1985 what_they_get = get_fixed_memory_packet_size (config);
1986 else
1987 {
1988 what_they_get = get_remote_packet_size ();
1989 /* Limit the packet to the size specified by the user. */
1990 if (config->size > 0
1991 && what_they_get > config->size)
1992 what_they_get = config->size;
1993
1994 /* Limit it to the size of the targets ``g'' response unless we have
1995 permission from the stub to use a larger packet size. */
1996 if (rs->explicit_packet_size == 0
1997 && rsa->actual_register_packet_size > 0
1998 && what_they_get > rsa->actual_register_packet_size)
1999 what_they_get = rsa->actual_register_packet_size;
2000 }
2001 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2002 what_they_get = MIN_MEMORY_PACKET_SIZE;
2003
2004 /* Make sure there is room in the global buffer for this packet
2005 (including its trailing NUL byte). */
2006 if (rs->buf.size () < what_they_get + 1)
2007 rs->buf.resize (2 * what_they_get);
2008
2009 return what_they_get;
2010 }
2011
2012 /* Update the size of a read/write packet. If they user wants
2013 something really big then do a sanity check. */
2014
2015 static void
2016 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2017 bool target_connected)
2018 {
2019 int fixed_p = config->fixed_p;
2020 long size = config->size;
2021
2022 if (args == NULL)
2023 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2024 else if (strcmp (args, "hard") == 0
2025 || strcmp (args, "fixed") == 0)
2026 fixed_p = 1;
2027 else if (strcmp (args, "soft") == 0
2028 || strcmp (args, "limit") == 0)
2029 fixed_p = 0;
2030 else
2031 {
2032 char *end;
2033
2034 size = strtoul (args, &end, 0);
2035 if (args == end)
2036 error (_("Invalid %s (bad syntax)."), config->name);
2037
2038 /* Instead of explicitly capping the size of a packet to or
2039 disallowing it, the user is allowed to set the size to
2040 something arbitrarily large. */
2041 }
2042
2043 /* Extra checks? */
2044 if (fixed_p && !config->fixed_p)
2045 {
2046 /* So that the query shows the correct value. */
2047 long query_size = (size <= 0
2048 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2049 : size);
2050
2051 if (target_connected
2052 && !query (_("The target may not be able to correctly handle a %s\n"
2053 "of %ld bytes. Change the packet size? "),
2054 config->name, query_size))
2055 error (_("Packet size not changed."));
2056 else if (!target_connected
2057 && !query (_("Future remote targets may not be able to "
2058 "correctly handle a %s\nof %ld bytes. Change the "
2059 "packet size for future remote targets? "),
2060 config->name, query_size))
2061 error (_("Packet size not changed."));
2062 }
2063 /* Update the config. */
2064 config->fixed_p = fixed_p;
2065 config->size = size;
2066
2067 const char *target_type = get_target_type_name (target_connected);
2068 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2069 args);
2070
2071 }
2072
2073 /* Show the memory-read or write-packet size configuration CONFIG of the
2074 target REMOTE. If REMOTE is nullptr, the default configuration for future
2075 remote targets should be passed in CONFIG. */
2076
2077 static void
2078 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2079 {
2080 const char *target_type = get_target_type_name (remote != nullptr);
2081
2082 if (config->size == 0)
2083 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2084 else
2085 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2086 config->size);
2087
2088 if (config->fixed_p)
2089 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2090 get_fixed_memory_packet_size (config));
2091 else
2092 {
2093 if (remote != nullptr)
2094 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2095 remote->get_memory_packet_size (config));
2096 else
2097 gdb_puts ("The actual limit will be further reduced "
2098 "dependent on the target.\n");
2099 }
2100 }
2101
2102 /* Configure the memory-write-packet size of the currently selected target. If
2103 no target is available, the default configuration for future remote targets
2104 is configured. */
2105
2106 static void
2107 set_memory_write_packet_size (const char *args, int from_tty)
2108 {
2109 remote_target *remote = get_current_remote_target ();
2110 if (remote != nullptr)
2111 {
2112 set_memory_packet_size
2113 (args, &remote->m_features.m_memory_write_packet_config, true);
2114 }
2115 else
2116 {
2117 memory_packet_config* config = &memory_write_packet_config;
2118 set_memory_packet_size (args, config, false);
2119 }
2120 }
2121
2122 /* Display the memory-write-packet size of the currently selected target. If
2123 no target is available, the default configuration for future remote targets
2124 is shown. */
2125
2126 static void
2127 show_memory_write_packet_size (const char *args, int from_tty)
2128 {
2129 remote_target *remote = get_current_remote_target ();
2130 if (remote != nullptr)
2131 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2132 remote);
2133 else
2134 show_memory_packet_size (&memory_write_packet_config, nullptr);
2135 }
2136
2137 /* Show the number of hardware watchpoints that can be used. */
2138
2139 static void
2140 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2141 struct cmd_list_element *c,
2142 const char *value)
2143 {
2144 gdb_printf (file, _("The maximum number of target hardware "
2145 "watchpoints is %s.\n"), value);
2146 }
2147
2148 /* Show the length limit (in bytes) for hardware watchpoints. */
2149
2150 static void
2151 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2152 struct cmd_list_element *c,
2153 const char *value)
2154 {
2155 gdb_printf (file, _("The maximum length (in bytes) of a target "
2156 "hardware watchpoint is %s.\n"), value);
2157 }
2158
2159 /* Show the number of hardware breakpoints that can be used. */
2160
2161 static void
2162 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2163 struct cmd_list_element *c,
2164 const char *value)
2165 {
2166 gdb_printf (file, _("The maximum number of target hardware "
2167 "breakpoints is %s.\n"), value);
2168 }
2169
2170 /* Controls the maximum number of characters to display in the debug output
2171 for each remote packet. The remaining characters are omitted. */
2172
2173 static int remote_packet_max_chars = 512;
2174
2175 /* Show the maximum number of characters to display for each remote packet
2176 when remote debugging is enabled. */
2177
2178 static void
2179 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2180 struct cmd_list_element *c,
2181 const char *value)
2182 {
2183 gdb_printf (file, _("Number of remote packet characters to "
2184 "display is %s.\n"), value);
2185 }
2186
2187 long
2188 remote_target::get_memory_write_packet_size ()
2189 {
2190 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2191 }
2192
2193 /* Configure the memory-read-packet size of the currently selected target. If
2194 no target is available, the default configuration for future remote targets
2195 is adapted. */
2196
2197 static void
2198 set_memory_read_packet_size (const char *args, int from_tty)
2199 {
2200 remote_target *remote = get_current_remote_target ();
2201 if (remote != nullptr)
2202 set_memory_packet_size
2203 (args, &remote->m_features.m_memory_read_packet_config, true);
2204 else
2205 {
2206 memory_packet_config* config = &memory_read_packet_config;
2207 set_memory_packet_size (args, config, false);
2208 }
2209
2210 }
2211
2212 /* Display the memory-read-packet size of the currently selected target. If
2213 no target is available, the default configuration for future remote targets
2214 is shown. */
2215
2216 static void
2217 show_memory_read_packet_size (const char *args, int from_tty)
2218 {
2219 remote_target *remote = get_current_remote_target ();
2220 if (remote != nullptr)
2221 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2222 remote);
2223 else
2224 show_memory_packet_size (&memory_read_packet_config, nullptr);
2225 }
2226
2227 long
2228 remote_target::get_memory_read_packet_size ()
2229 {
2230 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2231
2232 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2233 extra buffer size argument before the memory read size can be
2234 increased beyond this. */
2235 if (size > get_remote_packet_size ())
2236 size = get_remote_packet_size ();
2237 return size;
2238 }
2239
2240 static enum packet_support packet_config_support (const packet_config *config);
2241
2242
2243 static void
2244 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2245 cmd_list_element *c)
2246 {
2247 remote_target *remote = get_current_remote_target ();
2248 gdb_assert (c->var.has_value ());
2249
2250 auto *default_config = static_cast<packet_config *> (c->context ());
2251 const int packet_idx = std::distance (remote_protocol_packets,
2252 default_config);
2253
2254 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2255 {
2256 const char *name = packets_descriptions[packet_idx].name;
2257 const auto_boolean value = c->var->get<auto_boolean> ();
2258 const char *support = get_packet_support_name (value);
2259 const char *target_type = get_target_type_name (remote != nullptr);
2260
2261 if (remote != nullptr)
2262 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2263 else
2264 remote_protocol_packets[packet_idx].detect = value;
2265
2266 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2267 target_type, support);
2268 return;
2269 }
2270
2271 internal_error (_("Could not find config for %s"), c->name);
2272 }
2273
2274 static void
2275 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2276 remote_target *remote)
2277 {
2278 const char *support = "internal-error";
2279 const char *target_type = get_target_type_name (remote != nullptr);
2280
2281 packet_config *config;
2282 if (remote != nullptr)
2283 config = &remote->m_features.m_protocol_packets[which_packet];
2284 else
2285 config = &remote_protocol_packets[which_packet];
2286
2287 switch (packet_config_support (config))
2288 {
2289 case PACKET_ENABLE:
2290 support = "enabled";
2291 break;
2292 case PACKET_DISABLE:
2293 support = "disabled";
2294 break;
2295 case PACKET_SUPPORT_UNKNOWN:
2296 support = "unknown";
2297 break;
2298 }
2299 switch (config->detect)
2300 {
2301 case AUTO_BOOLEAN_AUTO:
2302 gdb_printf (file,
2303 _("Support for the '%s' packet %s is \"auto\", "
2304 "currently %s.\n"),
2305 packets_descriptions[which_packet].name, target_type,
2306 support);
2307 break;
2308 case AUTO_BOOLEAN_TRUE:
2309 case AUTO_BOOLEAN_FALSE:
2310 gdb_printf (file,
2311 _("Support for the '%s' packet %s is \"%s\".\n"),
2312 packets_descriptions[which_packet].name, target_type,
2313 get_packet_support_name (config->detect));
2314 break;
2315 }
2316 }
2317
2318 static void
2319 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2320 const char *title, int legacy)
2321 {
2322 packets_descriptions[which_packet].name = name;
2323 packets_descriptions[which_packet].title = title;
2324
2325 packet_config *config = &remote_protocol_packets[which_packet];
2326
2327 gdb::unique_xmalloc_ptr<char> set_doc
2328 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2329 name, title);
2330 gdb::unique_xmalloc_ptr<char> show_doc
2331 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2332 name, title);
2333 /* set/show TITLE-packet {auto,on,off} */
2334 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2335 set_show_commands cmds
2336 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2337 &config->detect, set_doc.get (),
2338 show_doc.get (), NULL, /* help_doc */
2339 set_remote_protocol_packet_cmd,
2340 show_remote_protocol_packet_cmd,
2341 &remote_set_cmdlist, &remote_show_cmdlist);
2342 cmds.show->set_context (config);
2343 cmds.set->set_context (config);
2344
2345 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2346 if (legacy)
2347 {
2348 /* It's not clear who should take ownership of the LEGACY_NAME string
2349 created below, so, for now, place the string into a static vector
2350 which ensures the strings is released when GDB exits. */
2351 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2352 gdb::unique_xmalloc_ptr<char> legacy_name
2353 = xstrprintf ("%s-packet", name);
2354 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2355 &remote_set_cmdlist);
2356 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2357 &remote_show_cmdlist);
2358 legacy_names.emplace_back (std::move (legacy_name));
2359 }
2360 }
2361
2362 static enum packet_result
2363 packet_check_result (const char *buf)
2364 {
2365 if (buf[0] != '\0')
2366 {
2367 /* The stub recognized the packet request. Check that the
2368 operation succeeded. */
2369 if (buf[0] == 'E'
2370 && isxdigit (buf[1]) && isxdigit (buf[2])
2371 && buf[3] == '\0')
2372 /* "Enn" - definitely an error. */
2373 return PACKET_ERROR;
2374
2375 /* Always treat "E." as an error. This will be used for
2376 more verbose error messages, such as E.memtypes. */
2377 if (buf[0] == 'E' && buf[1] == '.')
2378 return PACKET_ERROR;
2379
2380 /* The packet may or may not be OK. Just assume it is. */
2381 return PACKET_OK;
2382 }
2383 else
2384 /* The stub does not support the packet. */
2385 return PACKET_UNKNOWN;
2386 }
2387
2388 static enum packet_result
2389 packet_check_result (const gdb::char_vector &buf)
2390 {
2391 return packet_check_result (buf.data ());
2392 }
2393
2394 packet_result
2395 remote_features::packet_ok (const char *buf, const int which_packet)
2396 {
2397 packet_config *config = &m_protocol_packets[which_packet];
2398 packet_description *descr = &packets_descriptions[which_packet];
2399
2400 enum packet_result result;
2401
2402 if (config->detect != AUTO_BOOLEAN_TRUE
2403 && config->support == PACKET_DISABLE)
2404 internal_error (_("packet_ok: attempt to use a disabled packet"));
2405
2406 result = packet_check_result (buf);
2407 switch (result)
2408 {
2409 case PACKET_OK:
2410 case PACKET_ERROR:
2411 /* The stub recognized the packet request. */
2412 if (config->support == PACKET_SUPPORT_UNKNOWN)
2413 {
2414 remote_debug_printf ("Packet %s (%s) is supported",
2415 descr->name, descr->title);
2416 config->support = PACKET_ENABLE;
2417 }
2418 break;
2419 case PACKET_UNKNOWN:
2420 /* The stub does not support the packet. */
2421 if (config->detect == AUTO_BOOLEAN_AUTO
2422 && config->support == PACKET_ENABLE)
2423 {
2424 /* If the stub previously indicated that the packet was
2425 supported then there is a protocol error. */
2426 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2427 descr->name, descr->title);
2428 }
2429 else if (config->detect == AUTO_BOOLEAN_TRUE)
2430 {
2431 /* The user set it wrong. */
2432 error (_("Enabled packet %s (%s) not recognized by stub"),
2433 descr->name, descr->title);
2434 }
2435
2436 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2437 descr->title);
2438 config->support = PACKET_DISABLE;
2439 break;
2440 }
2441
2442 return result;
2443 }
2444
2445 packet_result
2446 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2447 {
2448 return packet_ok (buf.data (), which_packet);
2449 }
2450
2451 /* Returns whether a given packet or feature is supported. This takes
2452 into account the state of the corresponding "set remote foo-packet"
2453 command, which may be used to bypass auto-detection. */
2454
2455 static enum packet_support
2456 packet_config_support (const packet_config *config)
2457 {
2458 switch (config->detect)
2459 {
2460 case AUTO_BOOLEAN_TRUE:
2461 return PACKET_ENABLE;
2462 case AUTO_BOOLEAN_FALSE:
2463 return PACKET_DISABLE;
2464 case AUTO_BOOLEAN_AUTO:
2465 return config->support;
2466 default:
2467 gdb_assert_not_reached ("bad switch");
2468 }
2469 }
2470
2471 packet_support
2472 remote_features::packet_support (int packet) const
2473 {
2474 const packet_config *config = &m_protocol_packets[packet];
2475 return packet_config_support (config);
2476 }
2477
2478 static void
2479 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2480 struct cmd_list_element *c,
2481 const char *value)
2482 {
2483 remote_target *remote = get_current_remote_target ();
2484 gdb_assert (c->var.has_value ());
2485
2486 auto *default_config = static_cast<packet_config *> (c->context ());
2487 const int packet_idx = std::distance (remote_protocol_packets,
2488 default_config);
2489
2490 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2491 {
2492 show_packet_config_cmd (file, packet_idx, remote);
2493 return;
2494 }
2495 internal_error (_("Could not find config for %s"), c->name);
2496 }
2497
2498 /* Should we try one of the 'Z' requests? */
2499
2500 enum Z_packet_type
2501 {
2502 Z_PACKET_SOFTWARE_BP,
2503 Z_PACKET_HARDWARE_BP,
2504 Z_PACKET_WRITE_WP,
2505 Z_PACKET_READ_WP,
2506 Z_PACKET_ACCESS_WP,
2507 NR_Z_PACKET_TYPES
2508 };
2509
2510 /* For compatibility with older distributions. Provide a ``set remote
2511 Z-packet ...'' command that updates all the Z packet types. */
2512
2513 static enum auto_boolean remote_Z_packet_detect;
2514
2515 static void
2516 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2517 struct cmd_list_element *c)
2518 {
2519 remote_target *remote = get_current_remote_target ();
2520 int i;
2521
2522 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2523 {
2524 if (remote != nullptr)
2525 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2526 = remote_Z_packet_detect;
2527 else
2528 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2529 }
2530
2531 const char *support = get_packet_support_name (remote_Z_packet_detect);
2532 const char *target_type = get_target_type_name (remote != nullptr);
2533 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2534 support);
2535
2536 }
2537
2538 static void
2539 show_remote_protocol_Z_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 int i;
2545
2546 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2547 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2548 }
2549
2550 /* Insert fork catchpoint target routine. If fork events are enabled
2551 then return success, nothing more to do. */
2552
2553 int
2554 remote_target::insert_fork_catchpoint (int pid)
2555 {
2556 return !m_features.remote_fork_event_p ();
2557 }
2558
2559 /* Remove fork catchpoint target routine. Nothing to do, just
2560 return success. */
2561
2562 int
2563 remote_target::remove_fork_catchpoint (int pid)
2564 {
2565 return 0;
2566 }
2567
2568 /* Insert vfork catchpoint target routine. If vfork events are enabled
2569 then return success, nothing more to do. */
2570
2571 int
2572 remote_target::insert_vfork_catchpoint (int pid)
2573 {
2574 return !m_features.remote_vfork_event_p ();
2575 }
2576
2577 /* Remove vfork catchpoint target routine. Nothing to do, just
2578 return success. */
2579
2580 int
2581 remote_target::remove_vfork_catchpoint (int pid)
2582 {
2583 return 0;
2584 }
2585
2586 /* Insert exec catchpoint target routine. If exec events are
2587 enabled, just return success. */
2588
2589 int
2590 remote_target::insert_exec_catchpoint (int pid)
2591 {
2592 return !m_features.remote_exec_event_p ();
2593 }
2594
2595 /* Remove exec catchpoint target routine. Nothing to do, just
2596 return success. */
2597
2598 int
2599 remote_target::remove_exec_catchpoint (int pid)
2600 {
2601 return 0;
2602 }
2603
2604 \f
2605
2606 /* Take advantage of the fact that the TID field is not used, to tag
2607 special ptids with it set to != 0. */
2608 static const ptid_t magic_null_ptid (42000, -1, 1);
2609 static const ptid_t not_sent_ptid (42000, -2, 1);
2610 static const ptid_t any_thread_ptid (42000, 0, 1);
2611
2612 /* Find out if the stub attached to PID (and hence GDB should offer to
2613 detach instead of killing it when bailing out). */
2614
2615 int
2616 remote_target::remote_query_attached (int pid)
2617 {
2618 struct remote_state *rs = get_remote_state ();
2619 size_t size = get_remote_packet_size ();
2620
2621 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2622 return 0;
2623
2624 if (m_features.remote_multi_process_p ())
2625 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2626 else
2627 xsnprintf (rs->buf.data (), size, "qAttached");
2628
2629 putpkt (rs->buf);
2630 getpkt (&rs->buf, 0);
2631
2632 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2633 {
2634 case PACKET_OK:
2635 if (strcmp (rs->buf.data (), "1") == 0)
2636 return 1;
2637 break;
2638 case PACKET_ERROR:
2639 warning (_("Remote failure reply: %s"), rs->buf.data ());
2640 break;
2641 case PACKET_UNKNOWN:
2642 break;
2643 }
2644
2645 return 0;
2646 }
2647
2648 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2649 has been invented by GDB, instead of reported by the target. Since
2650 we can be connected to a remote system before before knowing about
2651 any inferior, mark the target with execution when we find the first
2652 inferior. If ATTACHED is 1, then we had just attached to this
2653 inferior. If it is 0, then we just created this inferior. If it
2654 is -1, then try querying the remote stub to find out if it had
2655 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2656 attempt to open this inferior's executable as the main executable
2657 if no main executable is open already. */
2658
2659 inferior *
2660 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2661 int try_open_exec)
2662 {
2663 struct inferior *inf;
2664
2665 /* Check whether this process we're learning about is to be
2666 considered attached, or if is to be considered to have been
2667 spawned by the stub. */
2668 if (attached == -1)
2669 attached = remote_query_attached (pid);
2670
2671 if (gdbarch_has_global_solist (target_gdbarch ()))
2672 {
2673 /* If the target shares code across all inferiors, then every
2674 attach adds a new inferior. */
2675 inf = add_inferior (pid);
2676
2677 /* ... and every inferior is bound to the same program space.
2678 However, each inferior may still have its own address
2679 space. */
2680 inf->aspace = maybe_new_address_space ();
2681 inf->pspace = current_program_space;
2682 }
2683 else
2684 {
2685 /* In the traditional debugging scenario, there's a 1-1 match
2686 between program/address spaces. We simply bind the inferior
2687 to the program space's address space. */
2688 inf = current_inferior ();
2689
2690 /* However, if the current inferior is already bound to a
2691 process, find some other empty inferior. */
2692 if (inf->pid != 0)
2693 {
2694 inf = nullptr;
2695 for (inferior *it : all_inferiors ())
2696 if (it->pid == 0)
2697 {
2698 inf = it;
2699 break;
2700 }
2701 }
2702 if (inf == nullptr)
2703 {
2704 /* Since all inferiors were already bound to a process, add
2705 a new inferior. */
2706 inf = add_inferior_with_spaces ();
2707 }
2708 switch_to_inferior_no_thread (inf);
2709 inf->push_target (this);
2710 inferior_appeared (inf, pid);
2711 }
2712
2713 inf->attach_flag = attached;
2714 inf->fake_pid_p = fake_pid_p;
2715
2716 /* If no main executable is currently open then attempt to
2717 open the file that was executed to create this inferior. */
2718 if (try_open_exec && get_exec_file (0) == NULL)
2719 exec_file_locate_attach (pid, 0, 1);
2720
2721 /* Check for exec file mismatch, and let the user solve it. */
2722 validate_exec_file (1);
2723
2724 return inf;
2725 }
2726
2727 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2728 static remote_thread_info *get_remote_thread_info (remote_target *target,
2729 ptid_t ptid);
2730
2731 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2732 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2733 remote_state::starting_up flag) is true then the new thread is added
2734 silently, otherwise the new thread will be announced to the user. */
2735
2736 thread_info *
2737 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2738 bool silent_p)
2739 {
2740 struct remote_state *rs = get_remote_state ();
2741 struct thread_info *thread;
2742
2743 /* GDB historically didn't pull threads in the initial connection
2744 setup. If the remote target doesn't even have a concept of
2745 threads (e.g., a bare-metal target), even if internally we
2746 consider that a single-threaded target, mentioning a new thread
2747 might be confusing to the user. Be silent then, preserving the
2748 age old behavior. */
2749 if (rs->starting_up || silent_p)
2750 thread = add_thread_silent (this, ptid);
2751 else
2752 thread = add_thread (this, ptid);
2753
2754 /* We start by assuming threads are resumed. That state then gets updated
2755 when we process a matching stop reply. */
2756 get_remote_thread_info (thread)->set_resumed ();
2757
2758 set_executing (this, ptid, executing);
2759 set_running (this, ptid, running);
2760
2761 return thread;
2762 }
2763
2764 /* Come here when we learn about a thread id from the remote target.
2765 It may be the first time we hear about such thread, so take the
2766 opportunity to add it to GDB's thread list. In case this is the
2767 first time we're noticing its corresponding inferior, add it to
2768 GDB's inferior list as well. EXECUTING indicates whether the
2769 thread is (internally) executing or stopped. */
2770
2771 void
2772 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2773 {
2774 /* In non-stop mode, we assume new found threads are (externally)
2775 running until proven otherwise with a stop reply. In all-stop,
2776 we can only get here if all threads are stopped. */
2777 bool running = target_is_non_stop_p ();
2778
2779 /* If this is a new thread, add it to GDB's thread list.
2780 If we leave it up to WFI to do this, bad things will happen. */
2781
2782 thread_info *tp = this->find_thread (currthread);
2783 if (tp != NULL && tp->state == THREAD_EXITED)
2784 {
2785 /* We're seeing an event on a thread id we knew had exited.
2786 This has to be a new thread reusing the old id. Add it. */
2787 remote_add_thread (currthread, running, executing, false);
2788 return;
2789 }
2790
2791 if (!in_thread_list (this, currthread))
2792 {
2793 struct inferior *inf = NULL;
2794 int pid = currthread.pid ();
2795
2796 if (inferior_ptid.is_pid ()
2797 && pid == inferior_ptid.pid ())
2798 {
2799 /* inferior_ptid has no thread member yet. This can happen
2800 with the vAttach -> remote_wait,"TAAthread:" path if the
2801 stub doesn't support qC. This is the first stop reported
2802 after an attach, so this is the main thread. Update the
2803 ptid in the thread list. */
2804 if (in_thread_list (this, ptid_t (pid)))
2805 thread_change_ptid (this, inferior_ptid, currthread);
2806 else
2807 {
2808 thread_info *thr
2809 = remote_add_thread (currthread, running, executing, false);
2810 switch_to_thread (thr);
2811 }
2812 return;
2813 }
2814
2815 if (magic_null_ptid == inferior_ptid)
2816 {
2817 /* inferior_ptid is not set yet. This can happen with the
2818 vRun -> remote_wait,"TAAthread:" path if the stub
2819 doesn't support qC. This is the first stop reported
2820 after an attach, so this is the main thread. Update the
2821 ptid in the thread list. */
2822 thread_change_ptid (this, inferior_ptid, currthread);
2823 return;
2824 }
2825
2826 /* When connecting to a target remote, or to a target
2827 extended-remote which already was debugging an inferior, we
2828 may not know about it yet. Add it before adding its child
2829 thread, so notifications are emitted in a sensible order. */
2830 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2831 {
2832 bool fake_pid_p = !m_features.remote_multi_process_p ();
2833
2834 inf = remote_add_inferior (fake_pid_p,
2835 currthread.pid (), -1, 1);
2836 }
2837
2838 /* This is really a new thread. Add it. */
2839 thread_info *new_thr
2840 = remote_add_thread (currthread, running, executing, false);
2841
2842 /* If we found a new inferior, let the common code do whatever
2843 it needs to with it (e.g., read shared libraries, insert
2844 breakpoints), unless we're just setting up an all-stop
2845 connection. */
2846 if (inf != NULL)
2847 {
2848 struct remote_state *rs = get_remote_state ();
2849
2850 if (!rs->starting_up)
2851 notice_new_inferior (new_thr, executing, 0);
2852 }
2853 }
2854 }
2855
2856 /* Return THREAD's private thread data, creating it if necessary. */
2857
2858 static remote_thread_info *
2859 get_remote_thread_info (thread_info *thread)
2860 {
2861 gdb_assert (thread != NULL);
2862
2863 if (thread->priv == NULL)
2864 thread->priv.reset (new remote_thread_info);
2865
2866 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2867 }
2868
2869 /* Return PTID's private thread data, creating it if necessary. */
2870
2871 static remote_thread_info *
2872 get_remote_thread_info (remote_target *target, ptid_t ptid)
2873 {
2874 thread_info *thr = target->find_thread (ptid);
2875 return get_remote_thread_info (thr);
2876 }
2877
2878 /* Call this function as a result of
2879 1) A halt indication (T packet) containing a thread id
2880 2) A direct query of currthread
2881 3) Successful execution of set thread */
2882
2883 static void
2884 record_currthread (struct remote_state *rs, ptid_t currthread)
2885 {
2886 rs->general_thread = currthread;
2887 }
2888
2889 /* If 'QPassSignals' is supported, tell the remote stub what signals
2890 it can simply pass through to the inferior without reporting. */
2891
2892 void
2893 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2894 {
2895 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2896 {
2897 char *pass_packet, *p;
2898 int count = 0;
2899 struct remote_state *rs = get_remote_state ();
2900
2901 gdb_assert (pass_signals.size () < 256);
2902 for (size_t i = 0; i < pass_signals.size (); i++)
2903 {
2904 if (pass_signals[i])
2905 count++;
2906 }
2907 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2908 strcpy (pass_packet, "QPassSignals:");
2909 p = pass_packet + strlen (pass_packet);
2910 for (size_t i = 0; i < pass_signals.size (); i++)
2911 {
2912 if (pass_signals[i])
2913 {
2914 if (i >= 16)
2915 *p++ = tohex (i >> 4);
2916 *p++ = tohex (i & 15);
2917 if (count)
2918 *p++ = ';';
2919 else
2920 break;
2921 count--;
2922 }
2923 }
2924 *p = 0;
2925 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2926 {
2927 putpkt (pass_packet);
2928 getpkt (&rs->buf, 0);
2929 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2930 xfree (rs->last_pass_packet);
2931 rs->last_pass_packet = pass_packet;
2932 }
2933 else
2934 xfree (pass_packet);
2935 }
2936 }
2937
2938 /* If 'QCatchSyscalls' is supported, tell the remote stub
2939 to report syscalls to GDB. */
2940
2941 int
2942 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2943 gdb::array_view<const int> syscall_counts)
2944 {
2945 const char *catch_packet;
2946 enum packet_result result;
2947 int n_sysno = 0;
2948
2949 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2950 {
2951 /* Not supported. */
2952 return 1;
2953 }
2954
2955 if (needed && any_count == 0)
2956 {
2957 /* Count how many syscalls are to be caught. */
2958 for (size_t i = 0; i < syscall_counts.size (); i++)
2959 {
2960 if (syscall_counts[i] != 0)
2961 n_sysno++;
2962 }
2963 }
2964
2965 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2966 pid, needed, any_count, n_sysno);
2967
2968 std::string built_packet;
2969 if (needed)
2970 {
2971 /* Prepare a packet with the sysno list, assuming max 8+1
2972 characters for a sysno. If the resulting packet size is too
2973 big, fallback on the non-selective packet. */
2974 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2975 built_packet.reserve (maxpktsz);
2976 built_packet = "QCatchSyscalls:1";
2977 if (any_count == 0)
2978 {
2979 /* Add in each syscall to be caught. */
2980 for (size_t i = 0; i < syscall_counts.size (); i++)
2981 {
2982 if (syscall_counts[i] != 0)
2983 string_appendf (built_packet, ";%zx", i);
2984 }
2985 }
2986 if (built_packet.size () > get_remote_packet_size ())
2987 {
2988 /* catch_packet too big. Fallback to less efficient
2989 non selective mode, with GDB doing the filtering. */
2990 catch_packet = "QCatchSyscalls:1";
2991 }
2992 else
2993 catch_packet = built_packet.c_str ();
2994 }
2995 else
2996 catch_packet = "QCatchSyscalls:0";
2997
2998 struct remote_state *rs = get_remote_state ();
2999
3000 putpkt (catch_packet);
3001 getpkt (&rs->buf, 0);
3002 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3003 if (result == PACKET_OK)
3004 return 0;
3005 else
3006 return -1;
3007 }
3008
3009 /* If 'QProgramSignals' is supported, tell the remote stub what
3010 signals it should pass through to the inferior when detaching. */
3011
3012 void
3013 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3014 {
3015 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3016 {
3017 char *packet, *p;
3018 int count = 0;
3019 struct remote_state *rs = get_remote_state ();
3020
3021 gdb_assert (signals.size () < 256);
3022 for (size_t i = 0; i < signals.size (); i++)
3023 {
3024 if (signals[i])
3025 count++;
3026 }
3027 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3028 strcpy (packet, "QProgramSignals:");
3029 p = packet + strlen (packet);
3030 for (size_t i = 0; i < signals.size (); i++)
3031 {
3032 if (signal_pass_state (i))
3033 {
3034 if (i >= 16)
3035 *p++ = tohex (i >> 4);
3036 *p++ = tohex (i & 15);
3037 if (count)
3038 *p++ = ';';
3039 else
3040 break;
3041 count--;
3042 }
3043 }
3044 *p = 0;
3045 if (!rs->last_program_signals_packet
3046 || strcmp (rs->last_program_signals_packet, packet) != 0)
3047 {
3048 putpkt (packet);
3049 getpkt (&rs->buf, 0);
3050 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3051 xfree (rs->last_program_signals_packet);
3052 rs->last_program_signals_packet = packet;
3053 }
3054 else
3055 xfree (packet);
3056 }
3057 }
3058
3059 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3060 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3061 thread. If GEN is set, set the general thread, if not, then set
3062 the step/continue thread. */
3063 void
3064 remote_target::set_thread (ptid_t ptid, int gen)
3065 {
3066 struct remote_state *rs = get_remote_state ();
3067 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3068 char *buf = rs->buf.data ();
3069 char *endbuf = buf + get_remote_packet_size ();
3070
3071 if (state == ptid)
3072 return;
3073
3074 *buf++ = 'H';
3075 *buf++ = gen ? 'g' : 'c';
3076 if (ptid == magic_null_ptid)
3077 xsnprintf (buf, endbuf - buf, "0");
3078 else if (ptid == any_thread_ptid)
3079 xsnprintf (buf, endbuf - buf, "0");
3080 else if (ptid == minus_one_ptid)
3081 xsnprintf (buf, endbuf - buf, "-1");
3082 else
3083 write_ptid (buf, endbuf, ptid);
3084 putpkt (rs->buf);
3085 getpkt (&rs->buf, 0);
3086 if (gen)
3087 rs->general_thread = ptid;
3088 else
3089 rs->continue_thread = ptid;
3090 }
3091
3092 void
3093 remote_target::set_general_thread (ptid_t ptid)
3094 {
3095 set_thread (ptid, 1);
3096 }
3097
3098 void
3099 remote_target::set_continue_thread (ptid_t ptid)
3100 {
3101 set_thread (ptid, 0);
3102 }
3103
3104 /* Change the remote current process. Which thread within the process
3105 ends up selected isn't important, as long as it is the same process
3106 as what INFERIOR_PTID points to.
3107
3108 This comes from that fact that there is no explicit notion of
3109 "selected process" in the protocol. The selected process for
3110 general operations is the process the selected general thread
3111 belongs to. */
3112
3113 void
3114 remote_target::set_general_process ()
3115 {
3116 /* If the remote can't handle multiple processes, don't bother. */
3117 if (!m_features.remote_multi_process_p ())
3118 return;
3119
3120 remote_state *rs = get_remote_state ();
3121
3122 /* We only need to change the remote current thread if it's pointing
3123 at some other process. */
3124 if (rs->general_thread.pid () != inferior_ptid.pid ())
3125 set_general_thread (inferior_ptid);
3126 }
3127
3128 \f
3129 /* Return nonzero if this is the main thread that we made up ourselves
3130 to model non-threaded targets as single-threaded. */
3131
3132 static int
3133 remote_thread_always_alive (ptid_t ptid)
3134 {
3135 if (ptid == magic_null_ptid)
3136 /* The main thread is always alive. */
3137 return 1;
3138
3139 if (ptid.pid () != 0 && ptid.lwp () == 0)
3140 /* The main thread is always alive. This can happen after a
3141 vAttach, if the remote side doesn't support
3142 multi-threading. */
3143 return 1;
3144
3145 return 0;
3146 }
3147
3148 /* Return nonzero if the thread PTID is still alive on the remote
3149 system. */
3150
3151 bool
3152 remote_target::thread_alive (ptid_t ptid)
3153 {
3154 struct remote_state *rs = get_remote_state ();
3155 char *p, *endp;
3156
3157 /* Check if this is a thread that we made up ourselves to model
3158 non-threaded targets as single-threaded. */
3159 if (remote_thread_always_alive (ptid))
3160 return 1;
3161
3162 p = rs->buf.data ();
3163 endp = p + get_remote_packet_size ();
3164
3165 *p++ = 'T';
3166 write_ptid (p, endp, ptid);
3167
3168 putpkt (rs->buf);
3169 getpkt (&rs->buf, 0);
3170 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3171 }
3172
3173 /* Return a pointer to a thread name if we know it and NULL otherwise.
3174 The thread_info object owns the memory for the name. */
3175
3176 const char *
3177 remote_target::thread_name (struct thread_info *info)
3178 {
3179 if (info->priv != NULL)
3180 {
3181 const std::string &name = get_remote_thread_info (info)->name;
3182 return !name.empty () ? name.c_str () : NULL;
3183 }
3184
3185 return NULL;
3186 }
3187
3188 /* About these extended threadlist and threadinfo packets. They are
3189 variable length packets but, the fields within them are often fixed
3190 length. They are redundant enough to send over UDP as is the
3191 remote protocol in general. There is a matching unit test module
3192 in libstub. */
3193
3194 /* WARNING: This threadref data structure comes from the remote O.S.,
3195 libstub protocol encoding, and remote.c. It is not particularly
3196 changeable. */
3197
3198 /* Right now, the internal structure is int. We want it to be bigger.
3199 Plan to fix this. */
3200
3201 typedef int gdb_threadref; /* Internal GDB thread reference. */
3202
3203 /* gdb_ext_thread_info is an internal GDB data structure which is
3204 equivalent to the reply of the remote threadinfo packet. */
3205
3206 struct gdb_ext_thread_info
3207 {
3208 threadref threadid; /* External form of thread reference. */
3209 int active; /* Has state interesting to GDB?
3210 regs, stack. */
3211 char display[256]; /* Brief state display, name,
3212 blocked/suspended. */
3213 char shortname[32]; /* To be used to name threads. */
3214 char more_display[256]; /* Long info, statistics, queue depth,
3215 whatever. */
3216 };
3217
3218 /* The volume of remote transfers can be limited by submitting
3219 a mask containing bits specifying the desired information.
3220 Use a union of these values as the 'selection' parameter to
3221 get_thread_info. FIXME: Make these TAG names more thread specific. */
3222
3223 #define TAG_THREADID 1
3224 #define TAG_EXISTS 2
3225 #define TAG_DISPLAY 4
3226 #define TAG_THREADNAME 8
3227 #define TAG_MOREDISPLAY 16
3228
3229 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3230
3231 static const char *unpack_nibble (const char *buf, int *val);
3232
3233 static const char *unpack_byte (const char *buf, int *value);
3234
3235 static char *pack_int (char *buf, int value);
3236
3237 static const char *unpack_int (const char *buf, int *value);
3238
3239 static const char *unpack_string (const char *src, char *dest, int length);
3240
3241 static char *pack_threadid (char *pkt, threadref *id);
3242
3243 static const char *unpack_threadid (const char *inbuf, threadref *id);
3244
3245 void int_to_threadref (threadref *id, int value);
3246
3247 static int threadref_to_int (threadref *ref);
3248
3249 static void copy_threadref (threadref *dest, threadref *src);
3250
3251 static int threadmatch (threadref *dest, threadref *src);
3252
3253 static char *pack_threadinfo_request (char *pkt, int mode,
3254 threadref *id);
3255
3256 static char *pack_threadlist_request (char *pkt, int startflag,
3257 int threadcount,
3258 threadref *nextthread);
3259
3260 static int remote_newthread_step (threadref *ref, void *context);
3261
3262
3263 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3264 buffer we're allowed to write to. Returns
3265 BUF+CHARACTERS_WRITTEN. */
3266
3267 char *
3268 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3269 {
3270 int pid, tid;
3271
3272 if (m_features.remote_multi_process_p ())
3273 {
3274 pid = ptid.pid ();
3275 if (pid < 0)
3276 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3277 else
3278 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3279 }
3280 tid = ptid.lwp ();
3281 if (tid < 0)
3282 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3283 else
3284 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3285
3286 return buf;
3287 }
3288
3289 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3290 last parsed char. Returns null_ptid if no thread id is found, and
3291 throws an error if the thread id has an invalid format. */
3292
3293 static ptid_t
3294 read_ptid (const char *buf, const char **obuf)
3295 {
3296 const char *p = buf;
3297 const char *pp;
3298 ULONGEST pid = 0, tid = 0;
3299
3300 if (*p == 'p')
3301 {
3302 /* Multi-process ptid. */
3303 pp = unpack_varlen_hex (p + 1, &pid);
3304 if (*pp != '.')
3305 error (_("invalid remote ptid: %s"), p);
3306
3307 p = pp;
3308 pp = unpack_varlen_hex (p + 1, &tid);
3309 if (obuf)
3310 *obuf = pp;
3311 return ptid_t (pid, tid);
3312 }
3313
3314 /* No multi-process. Just a tid. */
3315 pp = unpack_varlen_hex (p, &tid);
3316
3317 /* Return null_ptid when no thread id is found. */
3318 if (p == pp)
3319 {
3320 if (obuf)
3321 *obuf = pp;
3322 return null_ptid;
3323 }
3324
3325 /* Since the stub is not sending a process id, default to what's
3326 current_inferior, unless it doesn't have a PID yet. If so,
3327 then since there's no way to know the pid of the reported
3328 threads, use the magic number. */
3329 inferior *inf = current_inferior ();
3330 if (inf->pid == 0)
3331 pid = magic_null_ptid.pid ();
3332 else
3333 pid = inf->pid;
3334
3335 if (obuf)
3336 *obuf = pp;
3337 return ptid_t (pid, tid);
3338 }
3339
3340 static int
3341 stubhex (int ch)
3342 {
3343 if (ch >= 'a' && ch <= 'f')
3344 return ch - 'a' + 10;
3345 if (ch >= '0' && ch <= '9')
3346 return ch - '0';
3347 if (ch >= 'A' && ch <= 'F')
3348 return ch - 'A' + 10;
3349 return -1;
3350 }
3351
3352 static int
3353 stub_unpack_int (const char *buff, int fieldlength)
3354 {
3355 int nibble;
3356 int retval = 0;
3357
3358 while (fieldlength)
3359 {
3360 nibble = stubhex (*buff++);
3361 retval |= nibble;
3362 fieldlength--;
3363 if (fieldlength)
3364 retval = retval << 4;
3365 }
3366 return retval;
3367 }
3368
3369 static const char *
3370 unpack_nibble (const char *buf, int *val)
3371 {
3372 *val = fromhex (*buf++);
3373 return buf;
3374 }
3375
3376 static const char *
3377 unpack_byte (const char *buf, int *value)
3378 {
3379 *value = stub_unpack_int (buf, 2);
3380 return buf + 2;
3381 }
3382
3383 static char *
3384 pack_int (char *buf, int value)
3385 {
3386 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3387 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3388 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3389 buf = pack_hex_byte (buf, (value & 0xff));
3390 return buf;
3391 }
3392
3393 static const char *
3394 unpack_int (const char *buf, int *value)
3395 {
3396 *value = stub_unpack_int (buf, 8);
3397 return buf + 8;
3398 }
3399
3400 #if 0 /* Currently unused, uncomment when needed. */
3401 static char *pack_string (char *pkt, char *string);
3402
3403 static char *
3404 pack_string (char *pkt, char *string)
3405 {
3406 char ch;
3407 int len;
3408
3409 len = strlen (string);
3410 if (len > 200)
3411 len = 200; /* Bigger than most GDB packets, junk??? */
3412 pkt = pack_hex_byte (pkt, len);
3413 while (len-- > 0)
3414 {
3415 ch = *string++;
3416 if ((ch == '\0') || (ch == '#'))
3417 ch = '*'; /* Protect encapsulation. */
3418 *pkt++ = ch;
3419 }
3420 return pkt;
3421 }
3422 #endif /* 0 (unused) */
3423
3424 static const char *
3425 unpack_string (const char *src, char *dest, int length)
3426 {
3427 while (length--)
3428 *dest++ = *src++;
3429 *dest = '\0';
3430 return src;
3431 }
3432
3433 static char *
3434 pack_threadid (char *pkt, threadref *id)
3435 {
3436 char *limit;
3437 unsigned char *altid;
3438
3439 altid = (unsigned char *) id;
3440 limit = pkt + BUF_THREAD_ID_SIZE;
3441 while (pkt < limit)
3442 pkt = pack_hex_byte (pkt, *altid++);
3443 return pkt;
3444 }
3445
3446
3447 static const char *
3448 unpack_threadid (const char *inbuf, threadref *id)
3449 {
3450 char *altref;
3451 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3452 int x, y;
3453
3454 altref = (char *) id;
3455
3456 while (inbuf < limit)
3457 {
3458 x = stubhex (*inbuf++);
3459 y = stubhex (*inbuf++);
3460 *altref++ = (x << 4) | y;
3461 }
3462 return inbuf;
3463 }
3464
3465 /* Externally, threadrefs are 64 bits but internally, they are still
3466 ints. This is due to a mismatch of specifications. We would like
3467 to use 64bit thread references internally. This is an adapter
3468 function. */
3469
3470 void
3471 int_to_threadref (threadref *id, int value)
3472 {
3473 unsigned char *scan;
3474
3475 scan = (unsigned char *) id;
3476 {
3477 int i = 4;
3478 while (i--)
3479 *scan++ = 0;
3480 }
3481 *scan++ = (value >> 24) & 0xff;
3482 *scan++ = (value >> 16) & 0xff;
3483 *scan++ = (value >> 8) & 0xff;
3484 *scan++ = (value & 0xff);
3485 }
3486
3487 static int
3488 threadref_to_int (threadref *ref)
3489 {
3490 int i, value = 0;
3491 unsigned char *scan;
3492
3493 scan = *ref;
3494 scan += 4;
3495 i = 4;
3496 while (i-- > 0)
3497 value = (value << 8) | ((*scan++) & 0xff);
3498 return value;
3499 }
3500
3501 static void
3502 copy_threadref (threadref *dest, threadref *src)
3503 {
3504 int i;
3505 unsigned char *csrc, *cdest;
3506
3507 csrc = (unsigned char *) src;
3508 cdest = (unsigned char *) dest;
3509 i = 8;
3510 while (i--)
3511 *cdest++ = *csrc++;
3512 }
3513
3514 static int
3515 threadmatch (threadref *dest, threadref *src)
3516 {
3517 /* Things are broken right now, so just assume we got a match. */
3518 #if 0
3519 unsigned char *srcp, *destp;
3520 int i, result;
3521 srcp = (char *) src;
3522 destp = (char *) dest;
3523
3524 result = 1;
3525 while (i-- > 0)
3526 result &= (*srcp++ == *destp++) ? 1 : 0;
3527 return result;
3528 #endif
3529 return 1;
3530 }
3531
3532 /*
3533 threadid:1, # always request threadid
3534 context_exists:2,
3535 display:4,
3536 unique_name:8,
3537 more_display:16
3538 */
3539
3540 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3541
3542 static char *
3543 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3544 {
3545 *pkt++ = 'q'; /* Info Query */
3546 *pkt++ = 'P'; /* process or thread info */
3547 pkt = pack_int (pkt, mode); /* mode */
3548 pkt = pack_threadid (pkt, id); /* threadid */
3549 *pkt = '\0'; /* terminate */
3550 return pkt;
3551 }
3552
3553 /* These values tag the fields in a thread info response packet. */
3554 /* Tagging the fields allows us to request specific fields and to
3555 add more fields as time goes by. */
3556
3557 #define TAG_THREADID 1 /* Echo the thread identifier. */
3558 #define TAG_EXISTS 2 /* Is this process defined enough to
3559 fetch registers and its stack? */
3560 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3561 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3562 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3563 the process. */
3564
3565 int
3566 remote_target::remote_unpack_thread_info_response (const char *pkt,
3567 threadref *expectedref,
3568 gdb_ext_thread_info *info)
3569 {
3570 struct remote_state *rs = get_remote_state ();
3571 int mask, length;
3572 int tag;
3573 threadref ref;
3574 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3575 int retval = 1;
3576
3577 /* info->threadid = 0; FIXME: implement zero_threadref. */
3578 info->active = 0;
3579 info->display[0] = '\0';
3580 info->shortname[0] = '\0';
3581 info->more_display[0] = '\0';
3582
3583 /* Assume the characters indicating the packet type have been
3584 stripped. */
3585 pkt = unpack_int (pkt, &mask); /* arg mask */
3586 pkt = unpack_threadid (pkt, &ref);
3587
3588 if (mask == 0)
3589 warning (_("Incomplete response to threadinfo request."));
3590 if (!threadmatch (&ref, expectedref))
3591 { /* This is an answer to a different request. */
3592 warning (_("ERROR RMT Thread info mismatch."));
3593 return 0;
3594 }
3595 copy_threadref (&info->threadid, &ref);
3596
3597 /* Loop on tagged fields , try to bail if something goes wrong. */
3598
3599 /* Packets are terminated with nulls. */
3600 while ((pkt < limit) && mask && *pkt)
3601 {
3602 pkt = unpack_int (pkt, &tag); /* tag */
3603 pkt = unpack_byte (pkt, &length); /* length */
3604 if (!(tag & mask)) /* Tags out of synch with mask. */
3605 {
3606 warning (_("ERROR RMT: threadinfo tag mismatch."));
3607 retval = 0;
3608 break;
3609 }
3610 if (tag == TAG_THREADID)
3611 {
3612 if (length != 16)
3613 {
3614 warning (_("ERROR RMT: length of threadid is not 16."));
3615 retval = 0;
3616 break;
3617 }
3618 pkt = unpack_threadid (pkt, &ref);
3619 mask = mask & ~TAG_THREADID;
3620 continue;
3621 }
3622 if (tag == TAG_EXISTS)
3623 {
3624 info->active = stub_unpack_int (pkt, length);
3625 pkt += length;
3626 mask = mask & ~(TAG_EXISTS);
3627 if (length > 8)
3628 {
3629 warning (_("ERROR RMT: 'exists' length too long."));
3630 retval = 0;
3631 break;
3632 }
3633 continue;
3634 }
3635 if (tag == TAG_THREADNAME)
3636 {
3637 pkt = unpack_string (pkt, &info->shortname[0], length);
3638 mask = mask & ~TAG_THREADNAME;
3639 continue;
3640 }
3641 if (tag == TAG_DISPLAY)
3642 {
3643 pkt = unpack_string (pkt, &info->display[0], length);
3644 mask = mask & ~TAG_DISPLAY;
3645 continue;
3646 }
3647 if (tag == TAG_MOREDISPLAY)
3648 {
3649 pkt = unpack_string (pkt, &info->more_display[0], length);
3650 mask = mask & ~TAG_MOREDISPLAY;
3651 continue;
3652 }
3653 warning (_("ERROR RMT: unknown thread info tag."));
3654 break; /* Not a tag we know about. */
3655 }
3656 return retval;
3657 }
3658
3659 int
3660 remote_target::remote_get_threadinfo (threadref *threadid,
3661 int fieldset,
3662 gdb_ext_thread_info *info)
3663 {
3664 struct remote_state *rs = get_remote_state ();
3665 int result;
3666
3667 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3668 putpkt (rs->buf);
3669 getpkt (&rs->buf, 0);
3670
3671 if (rs->buf[0] == '\0')
3672 return 0;
3673
3674 result = remote_unpack_thread_info_response (&rs->buf[2],
3675 threadid, info);
3676 return result;
3677 }
3678
3679 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3680
3681 static char *
3682 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3683 threadref *nextthread)
3684 {
3685 *pkt++ = 'q'; /* info query packet */
3686 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3687 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3688 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3689 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3690 *pkt = '\0';
3691 return pkt;
3692 }
3693
3694 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3695
3696 int
3697 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3698 threadref *original_echo,
3699 threadref *resultlist,
3700 int *doneflag)
3701 {
3702 struct remote_state *rs = get_remote_state ();
3703 int count, resultcount, done;
3704
3705 resultcount = 0;
3706 /* Assume the 'q' and 'M chars have been stripped. */
3707 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3708 /* done parse past here */
3709 pkt = unpack_byte (pkt, &count); /* count field */
3710 pkt = unpack_nibble (pkt, &done);
3711 /* The first threadid is the argument threadid. */
3712 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3713 while ((count-- > 0) && (pkt < limit))
3714 {
3715 pkt = unpack_threadid (pkt, resultlist++);
3716 if (resultcount++ >= result_limit)
3717 break;
3718 }
3719 if (doneflag)
3720 *doneflag = done;
3721 return resultcount;
3722 }
3723
3724 /* Fetch the next batch of threads from the remote. Returns -1 if the
3725 qL packet is not supported, 0 on error and 1 on success. */
3726
3727 int
3728 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3729 int result_limit, int *done, int *result_count,
3730 threadref *threadlist)
3731 {
3732 struct remote_state *rs = get_remote_state ();
3733 int result = 1;
3734
3735 /* Truncate result limit to be smaller than the packet size. */
3736 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3737 >= get_remote_packet_size ())
3738 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3739
3740 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3741 nextthread);
3742 putpkt (rs->buf);
3743 getpkt (&rs->buf, 0);
3744 if (rs->buf[0] == '\0')
3745 {
3746 /* Packet not supported. */
3747 return -1;
3748 }
3749
3750 *result_count =
3751 parse_threadlist_response (&rs->buf[2], result_limit,
3752 &rs->echo_nextthread, threadlist, done);
3753
3754 if (!threadmatch (&rs->echo_nextthread, nextthread))
3755 {
3756 /* FIXME: This is a good reason to drop the packet. */
3757 /* Possibly, there is a duplicate response. */
3758 /* Possibilities :
3759 retransmit immediatly - race conditions
3760 retransmit after timeout - yes
3761 exit
3762 wait for packet, then exit
3763 */
3764 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3765 return 0; /* I choose simply exiting. */
3766 }
3767 if (*result_count <= 0)
3768 {
3769 if (*done != 1)
3770 {
3771 warning (_("RMT ERROR : failed to get remote thread list."));
3772 result = 0;
3773 }
3774 return result; /* break; */
3775 }
3776 if (*result_count > result_limit)
3777 {
3778 *result_count = 0;
3779 warning (_("RMT ERROR: threadlist response longer than requested."));
3780 return 0;
3781 }
3782 return result;
3783 }
3784
3785 /* Fetch the list of remote threads, with the qL packet, and call
3786 STEPFUNCTION for each thread found. Stops iterating and returns 1
3787 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3788 STEPFUNCTION returns false. If the packet is not supported,
3789 returns -1. */
3790
3791 int
3792 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3793 void *context, int looplimit)
3794 {
3795 struct remote_state *rs = get_remote_state ();
3796 int done, i, result_count;
3797 int startflag = 1;
3798 int result = 1;
3799 int loopcount = 0;
3800
3801 done = 0;
3802 while (!done)
3803 {
3804 if (loopcount++ > looplimit)
3805 {
3806 result = 0;
3807 warning (_("Remote fetch threadlist -infinite loop-."));
3808 break;
3809 }
3810 result = remote_get_threadlist (startflag, &rs->nextthread,
3811 MAXTHREADLISTRESULTS,
3812 &done, &result_count,
3813 rs->resultthreadlist);
3814 if (result <= 0)
3815 break;
3816 /* Clear for later iterations. */
3817 startflag = 0;
3818 /* Setup to resume next batch of thread references, set nextthread. */
3819 if (result_count >= 1)
3820 copy_threadref (&rs->nextthread,
3821 &rs->resultthreadlist[result_count - 1]);
3822 i = 0;
3823 while (result_count--)
3824 {
3825 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3826 {
3827 result = 0;
3828 break;
3829 }
3830 }
3831 }
3832 return result;
3833 }
3834
3835 /* A thread found on the remote target. */
3836
3837 struct thread_item
3838 {
3839 explicit thread_item (ptid_t ptid_)
3840 : ptid (ptid_)
3841 {}
3842
3843 thread_item (thread_item &&other) = default;
3844 thread_item &operator= (thread_item &&other) = default;
3845
3846 DISABLE_COPY_AND_ASSIGN (thread_item);
3847
3848 /* The thread's PTID. */
3849 ptid_t ptid;
3850
3851 /* The thread's extra info. */
3852 std::string extra;
3853
3854 /* The thread's name. */
3855 std::string name;
3856
3857 /* The core the thread was running on. -1 if not known. */
3858 int core = -1;
3859
3860 /* The thread handle associated with the thread. */
3861 gdb::byte_vector thread_handle;
3862 };
3863
3864 /* Context passed around to the various methods listing remote
3865 threads. As new threads are found, they're added to the ITEMS
3866 vector. */
3867
3868 struct threads_listing_context
3869 {
3870 /* Return true if this object contains an entry for a thread with ptid
3871 PTID. */
3872
3873 bool contains_thread (ptid_t ptid) const
3874 {
3875 auto match_ptid = [&] (const thread_item &item)
3876 {
3877 return item.ptid == ptid;
3878 };
3879
3880 auto it = std::find_if (this->items.begin (),
3881 this->items.end (),
3882 match_ptid);
3883
3884 return it != this->items.end ();
3885 }
3886
3887 /* Remove the thread with ptid PTID. */
3888
3889 void remove_thread (ptid_t ptid)
3890 {
3891 auto match_ptid = [&] (const thread_item &item)
3892 {
3893 return item.ptid == ptid;
3894 };
3895
3896 auto it = std::remove_if (this->items.begin (),
3897 this->items.end (),
3898 match_ptid);
3899
3900 if (it != this->items.end ())
3901 this->items.erase (it);
3902 }
3903
3904 /* The threads found on the remote target. */
3905 std::vector<thread_item> items;
3906 };
3907
3908 static int
3909 remote_newthread_step (threadref *ref, void *data)
3910 {
3911 struct threads_listing_context *context
3912 = (struct threads_listing_context *) data;
3913 int pid = inferior_ptid.pid ();
3914 int lwp = threadref_to_int (ref);
3915 ptid_t ptid (pid, lwp);
3916
3917 context->items.emplace_back (ptid);
3918
3919 return 1; /* continue iterator */
3920 }
3921
3922 #define CRAZY_MAX_THREADS 1000
3923
3924 ptid_t
3925 remote_target::remote_current_thread (ptid_t oldpid)
3926 {
3927 struct remote_state *rs = get_remote_state ();
3928
3929 putpkt ("qC");
3930 getpkt (&rs->buf, 0);
3931 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3932 {
3933 const char *obuf;
3934 ptid_t result;
3935
3936 result = read_ptid (&rs->buf[2], &obuf);
3937 if (*obuf != '\0')
3938 remote_debug_printf ("warning: garbage in qC reply");
3939
3940 return result;
3941 }
3942 else
3943 return oldpid;
3944 }
3945
3946 /* List remote threads using the deprecated qL packet. */
3947
3948 int
3949 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3950 {
3951 if (remote_threadlist_iterator (remote_newthread_step, context,
3952 CRAZY_MAX_THREADS) >= 0)
3953 return 1;
3954
3955 return 0;
3956 }
3957
3958 #if defined(HAVE_LIBEXPAT)
3959
3960 static void
3961 start_thread (struct gdb_xml_parser *parser,
3962 const struct gdb_xml_element *element,
3963 void *user_data,
3964 std::vector<gdb_xml_value> &attributes)
3965 {
3966 struct threads_listing_context *data
3967 = (struct threads_listing_context *) user_data;
3968 struct gdb_xml_value *attr;
3969
3970 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3971 ptid_t ptid = read_ptid (id, NULL);
3972
3973 data->items.emplace_back (ptid);
3974 thread_item &item = data->items.back ();
3975
3976 attr = xml_find_attribute (attributes, "core");
3977 if (attr != NULL)
3978 item.core = *(ULONGEST *) attr->value.get ();
3979
3980 attr = xml_find_attribute (attributes, "name");
3981 if (attr != NULL)
3982 item.name = (const char *) attr->value.get ();
3983
3984 attr = xml_find_attribute (attributes, "handle");
3985 if (attr != NULL)
3986 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3987 }
3988
3989 static void
3990 end_thread (struct gdb_xml_parser *parser,
3991 const struct gdb_xml_element *element,
3992 void *user_data, const char *body_text)
3993 {
3994 struct threads_listing_context *data
3995 = (struct threads_listing_context *) user_data;
3996
3997 if (body_text != NULL && *body_text != '\0')
3998 data->items.back ().extra = body_text;
3999 }
4000
4001 const struct gdb_xml_attribute thread_attributes[] = {
4002 { "id", GDB_XML_AF_NONE, NULL, NULL },
4003 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4004 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4005 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4006 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4007 };
4008
4009 const struct gdb_xml_element thread_children[] = {
4010 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4011 };
4012
4013 const struct gdb_xml_element threads_children[] = {
4014 { "thread", thread_attributes, thread_children,
4015 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4016 start_thread, end_thread },
4017 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4018 };
4019
4020 const struct gdb_xml_element threads_elements[] = {
4021 { "threads", NULL, threads_children,
4022 GDB_XML_EF_NONE, NULL, NULL },
4023 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4024 };
4025
4026 #endif
4027
4028 /* List remote threads using qXfer:threads:read. */
4029
4030 int
4031 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4032 {
4033 #if defined(HAVE_LIBEXPAT)
4034 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4035 {
4036 gdb::optional<gdb::char_vector> xml
4037 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4038
4039 if (xml && (*xml)[0] != '\0')
4040 {
4041 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4042 threads_elements, xml->data (), context);
4043 }
4044
4045 return 1;
4046 }
4047 #endif
4048
4049 return 0;
4050 }
4051
4052 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4053
4054 int
4055 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4056 {
4057 struct remote_state *rs = get_remote_state ();
4058
4059 if (rs->use_threadinfo_query)
4060 {
4061 const char *bufp;
4062
4063 putpkt ("qfThreadInfo");
4064 getpkt (&rs->buf, 0);
4065 bufp = rs->buf.data ();
4066 if (bufp[0] != '\0') /* q packet recognized */
4067 {
4068 while (*bufp++ == 'm') /* reply contains one or more TID */
4069 {
4070 do
4071 {
4072 ptid_t ptid = read_ptid (bufp, &bufp);
4073 context->items.emplace_back (ptid);
4074 }
4075 while (*bufp++ == ','); /* comma-separated list */
4076 putpkt ("qsThreadInfo");
4077 getpkt (&rs->buf, 0);
4078 bufp = rs->buf.data ();
4079 }
4080 return 1;
4081 }
4082 else
4083 {
4084 /* Packet not recognized. */
4085 rs->use_threadinfo_query = 0;
4086 }
4087 }
4088
4089 return 0;
4090 }
4091
4092 /* Return true if INF only has one non-exited thread. */
4093
4094 static bool
4095 has_single_non_exited_thread (inferior *inf)
4096 {
4097 int count = 0;
4098 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4099 if (++count > 1)
4100 break;
4101 return count == 1;
4102 }
4103
4104 /* Implement the to_update_thread_list function for the remote
4105 targets. */
4106
4107 void
4108 remote_target::update_thread_list ()
4109 {
4110 struct threads_listing_context context;
4111 int got_list = 0;
4112
4113 /* We have a few different mechanisms to fetch the thread list. Try
4114 them all, starting with the most preferred one first, falling
4115 back to older methods. */
4116 if (remote_get_threads_with_qxfer (&context)
4117 || remote_get_threads_with_qthreadinfo (&context)
4118 || remote_get_threads_with_ql (&context))
4119 {
4120 got_list = 1;
4121
4122 if (context.items.empty ()
4123 && remote_thread_always_alive (inferior_ptid))
4124 {
4125 /* Some targets don't really support threads, but still
4126 reply an (empty) thread list in response to the thread
4127 listing packets, instead of replying "packet not
4128 supported". Exit early so we don't delete the main
4129 thread. */
4130 return;
4131 }
4132
4133 /* CONTEXT now holds the current thread list on the remote
4134 target end. Delete GDB-side threads no longer found on the
4135 target. */
4136 for (thread_info *tp : all_threads_safe ())
4137 {
4138 if (tp->inf->process_target () != this)
4139 continue;
4140
4141 if (!context.contains_thread (tp->ptid))
4142 {
4143 /* Do not remove the thread if it is the last thread in
4144 the inferior. This situation happens when we have a
4145 pending exit process status to process. Otherwise we
4146 may end up with a seemingly live inferior (i.e. pid
4147 != 0) that has no threads. */
4148 if (has_single_non_exited_thread (tp->inf))
4149 continue;
4150
4151 /* Not found. */
4152 delete_thread (tp);
4153 }
4154 }
4155
4156 /* Remove any unreported fork child threads from CONTEXT so
4157 that we don't interfere with follow fork, which is where
4158 creation of such threads is handled. */
4159 remove_new_fork_children (&context);
4160
4161 /* And now add threads we don't know about yet to our list. */
4162 for (thread_item &item : context.items)
4163 {
4164 if (item.ptid != null_ptid)
4165 {
4166 /* In non-stop mode, we assume new found threads are
4167 executing until proven otherwise with a stop reply.
4168 In all-stop, we can only get here if all threads are
4169 stopped. */
4170 bool executing = target_is_non_stop_p ();
4171
4172 remote_notice_new_inferior (item.ptid, executing);
4173
4174 thread_info *tp = this->find_thread (item.ptid);
4175 remote_thread_info *info = get_remote_thread_info (tp);
4176 info->core = item.core;
4177 info->extra = std::move (item.extra);
4178 info->name = std::move (item.name);
4179 info->thread_handle = std::move (item.thread_handle);
4180 }
4181 }
4182 }
4183
4184 if (!got_list)
4185 {
4186 /* If no thread listing method is supported, then query whether
4187 each known thread is alive, one by one, with the T packet.
4188 If the target doesn't support threads at all, then this is a
4189 no-op. See remote_thread_alive. */
4190 prune_threads ();
4191 }
4192 }
4193
4194 /*
4195 * Collect a descriptive string about the given thread.
4196 * The target may say anything it wants to about the thread
4197 * (typically info about its blocked / runnable state, name, etc.).
4198 * This string will appear in the info threads display.
4199 *
4200 * Optional: targets are not required to implement this function.
4201 */
4202
4203 const char *
4204 remote_target::extra_thread_info (thread_info *tp)
4205 {
4206 struct remote_state *rs = get_remote_state ();
4207 int set;
4208 threadref id;
4209 struct gdb_ext_thread_info threadinfo;
4210
4211 if (rs->remote_desc == 0) /* paranoia */
4212 internal_error (_("remote_threads_extra_info"));
4213
4214 if (tp->ptid == magic_null_ptid
4215 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4216 /* This is the main thread which was added by GDB. The remote
4217 server doesn't know about it. */
4218 return NULL;
4219
4220 std::string &extra = get_remote_thread_info (tp)->extra;
4221
4222 /* If already have cached info, use it. */
4223 if (!extra.empty ())
4224 return extra.c_str ();
4225
4226 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4227 {
4228 /* If we're using qXfer:threads:read, then the extra info is
4229 included in the XML. So if we didn't have anything cached,
4230 it's because there's really no extra info. */
4231 return NULL;
4232 }
4233
4234 if (rs->use_threadextra_query)
4235 {
4236 char *b = rs->buf.data ();
4237 char *endb = b + get_remote_packet_size ();
4238
4239 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4240 b += strlen (b);
4241 write_ptid (b, endb, tp->ptid);
4242
4243 putpkt (rs->buf);
4244 getpkt (&rs->buf, 0);
4245 if (rs->buf[0] != 0)
4246 {
4247 extra.resize (strlen (rs->buf.data ()) / 2);
4248 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4249 return extra.c_str ();
4250 }
4251 }
4252
4253 /* If the above query fails, fall back to the old method. */
4254 rs->use_threadextra_query = 0;
4255 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4256 | TAG_MOREDISPLAY | TAG_DISPLAY;
4257 int_to_threadref (&id, tp->ptid.lwp ());
4258 if (remote_get_threadinfo (&id, set, &threadinfo))
4259 if (threadinfo.active)
4260 {
4261 if (*threadinfo.shortname)
4262 string_appendf (extra, " Name: %s", threadinfo.shortname);
4263 if (*threadinfo.display)
4264 {
4265 if (!extra.empty ())
4266 extra += ',';
4267 string_appendf (extra, " State: %s", threadinfo.display);
4268 }
4269 if (*threadinfo.more_display)
4270 {
4271 if (!extra.empty ())
4272 extra += ',';
4273 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4274 }
4275 return extra.c_str ();
4276 }
4277 return NULL;
4278 }
4279 \f
4280
4281 bool
4282 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4283 struct static_tracepoint_marker *marker)
4284 {
4285 struct remote_state *rs = get_remote_state ();
4286 char *p = rs->buf.data ();
4287
4288 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4289 p += strlen (p);
4290 p += hexnumstr (p, addr);
4291 putpkt (rs->buf);
4292 getpkt (&rs->buf, 0);
4293 p = rs->buf.data ();
4294
4295 if (*p == 'E')
4296 error (_("Remote failure reply: %s"), p);
4297
4298 if (*p++ == 'm')
4299 {
4300 parse_static_tracepoint_marker_definition (p, NULL, marker);
4301 return true;
4302 }
4303
4304 return false;
4305 }
4306
4307 std::vector<static_tracepoint_marker>
4308 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4309 {
4310 struct remote_state *rs = get_remote_state ();
4311 std::vector<static_tracepoint_marker> markers;
4312 const char *p;
4313 static_tracepoint_marker marker;
4314
4315 /* Ask for a first packet of static tracepoint marker
4316 definition. */
4317 putpkt ("qTfSTM");
4318 getpkt (&rs->buf, 0);
4319 p = rs->buf.data ();
4320 if (*p == 'E')
4321 error (_("Remote failure reply: %s"), p);
4322
4323 while (*p++ == 'm')
4324 {
4325 do
4326 {
4327 parse_static_tracepoint_marker_definition (p, &p, &marker);
4328
4329 if (strid == NULL || marker.str_id == strid)
4330 markers.push_back (std::move (marker));
4331 }
4332 while (*p++ == ','); /* comma-separated list */
4333 /* Ask for another packet of static tracepoint definition. */
4334 putpkt ("qTsSTM");
4335 getpkt (&rs->buf, 0);
4336 p = rs->buf.data ();
4337 }
4338
4339 return markers;
4340 }
4341
4342 \f
4343 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4344
4345 ptid_t
4346 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4347 {
4348 return ptid_t (inferior_ptid.pid (), lwp);
4349 }
4350 \f
4351
4352 /* Restart the remote side; this is an extended protocol operation. */
4353
4354 void
4355 remote_target::extended_remote_restart ()
4356 {
4357 struct remote_state *rs = get_remote_state ();
4358
4359 /* Send the restart command; for reasons I don't understand the
4360 remote side really expects a number after the "R". */
4361 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4362 putpkt (rs->buf);
4363
4364 remote_fileio_reset ();
4365 }
4366 \f
4367 /* Clean up connection to a remote debugger. */
4368
4369 void
4370 remote_target::close ()
4371 {
4372 /* Make sure we leave stdin registered in the event loop. */
4373 terminal_ours ();
4374
4375 trace_reset_local_state ();
4376
4377 delete this;
4378 }
4379
4380 remote_target::~remote_target ()
4381 {
4382 struct remote_state *rs = get_remote_state ();
4383
4384 /* Check for NULL because we may get here with a partially
4385 constructed target/connection. */
4386 if (rs->remote_desc == nullptr)
4387 return;
4388
4389 serial_close (rs->remote_desc);
4390
4391 /* We are destroying the remote target, so we should discard
4392 everything of this target. */
4393 discard_pending_stop_replies_in_queue ();
4394
4395 if (rs->remote_async_inferior_event_token)
4396 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4397
4398 delete rs->notif_state;
4399 }
4400
4401 /* Query the remote side for the text, data and bss offsets. */
4402
4403 void
4404 remote_target::get_offsets ()
4405 {
4406 struct remote_state *rs = get_remote_state ();
4407 char *buf;
4408 char *ptr;
4409 int lose, num_segments = 0, do_sections, do_segments;
4410 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4411
4412 if (current_program_space->symfile_object_file == NULL)
4413 return;
4414
4415 putpkt ("qOffsets");
4416 getpkt (&rs->buf, 0);
4417 buf = rs->buf.data ();
4418
4419 if (buf[0] == '\000')
4420 return; /* Return silently. Stub doesn't support
4421 this command. */
4422 if (buf[0] == 'E')
4423 {
4424 warning (_("Remote failure reply: %s"), buf);
4425 return;
4426 }
4427
4428 /* Pick up each field in turn. This used to be done with scanf, but
4429 scanf will make trouble if CORE_ADDR size doesn't match
4430 conversion directives correctly. The following code will work
4431 with any size of CORE_ADDR. */
4432 text_addr = data_addr = bss_addr = 0;
4433 ptr = buf;
4434 lose = 0;
4435
4436 if (startswith (ptr, "Text="))
4437 {
4438 ptr += 5;
4439 /* Don't use strtol, could lose on big values. */
4440 while (*ptr && *ptr != ';')
4441 text_addr = (text_addr << 4) + fromhex (*ptr++);
4442
4443 if (startswith (ptr, ";Data="))
4444 {
4445 ptr += 6;
4446 while (*ptr && *ptr != ';')
4447 data_addr = (data_addr << 4) + fromhex (*ptr++);
4448 }
4449 else
4450 lose = 1;
4451
4452 if (!lose && startswith (ptr, ";Bss="))
4453 {
4454 ptr += 5;
4455 while (*ptr && *ptr != ';')
4456 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4457
4458 if (bss_addr != data_addr)
4459 warning (_("Target reported unsupported offsets: %s"), buf);
4460 }
4461 else
4462 lose = 1;
4463 }
4464 else if (startswith (ptr, "TextSeg="))
4465 {
4466 ptr += 8;
4467 /* Don't use strtol, could lose on big values. */
4468 while (*ptr && *ptr != ';')
4469 text_addr = (text_addr << 4) + fromhex (*ptr++);
4470 num_segments = 1;
4471
4472 if (startswith (ptr, ";DataSeg="))
4473 {
4474 ptr += 9;
4475 while (*ptr && *ptr != ';')
4476 data_addr = (data_addr << 4) + fromhex (*ptr++);
4477 num_segments++;
4478 }
4479 }
4480 else
4481 lose = 1;
4482
4483 if (lose)
4484 error (_("Malformed response to offset query, %s"), buf);
4485 else if (*ptr != '\0')
4486 warning (_("Target reported unsupported offsets: %s"), buf);
4487
4488 objfile *objf = current_program_space->symfile_object_file;
4489 section_offsets offs = objf->section_offsets;
4490
4491 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4492 do_segments = (data != NULL);
4493 do_sections = num_segments == 0;
4494
4495 if (num_segments > 0)
4496 {
4497 segments[0] = text_addr;
4498 segments[1] = data_addr;
4499 }
4500 /* If we have two segments, we can still try to relocate everything
4501 by assuming that the .text and .data offsets apply to the whole
4502 text and data segments. Convert the offsets given in the packet
4503 to base addresses for symfile_map_offsets_to_segments. */
4504 else if (data != nullptr && data->segments.size () == 2)
4505 {
4506 segments[0] = data->segments[0].base + text_addr;
4507 segments[1] = data->segments[1].base + data_addr;
4508 num_segments = 2;
4509 }
4510 /* If the object file has only one segment, assume that it is text
4511 rather than data; main programs with no writable data are rare,
4512 but programs with no code are useless. Of course the code might
4513 have ended up in the data segment... to detect that we would need
4514 the permissions here. */
4515 else if (data && data->segments.size () == 1)
4516 {
4517 segments[0] = data->segments[0].base + text_addr;
4518 num_segments = 1;
4519 }
4520 /* There's no way to relocate by segment. */
4521 else
4522 do_segments = 0;
4523
4524 if (do_segments)
4525 {
4526 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4527 data.get (), offs,
4528 num_segments, segments);
4529
4530 if (ret == 0 && !do_sections)
4531 error (_("Can not handle qOffsets TextSeg "
4532 "response with this symbol file"));
4533
4534 if (ret > 0)
4535 do_sections = 0;
4536 }
4537
4538 if (do_sections)
4539 {
4540 offs[SECT_OFF_TEXT (objf)] = text_addr;
4541
4542 /* This is a temporary kludge to force data and bss to use the
4543 same offsets because that's what nlmconv does now. The real
4544 solution requires changes to the stub and remote.c that I
4545 don't have time to do right now. */
4546
4547 offs[SECT_OFF_DATA (objf)] = data_addr;
4548 offs[SECT_OFF_BSS (objf)] = data_addr;
4549 }
4550
4551 objfile_relocate (objf, offs);
4552 }
4553
4554 /* Send interrupt_sequence to remote target. */
4555
4556 void
4557 remote_target::send_interrupt_sequence ()
4558 {
4559 struct remote_state *rs = get_remote_state ();
4560
4561 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4562 remote_serial_write ("\x03", 1);
4563 else if (interrupt_sequence_mode == interrupt_sequence_break)
4564 serial_send_break (rs->remote_desc);
4565 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4566 {
4567 serial_send_break (rs->remote_desc);
4568 remote_serial_write ("g", 1);
4569 }
4570 else
4571 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4572 interrupt_sequence_mode);
4573 }
4574
4575
4576 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4577 and extract the PTID. Returns NULL_PTID if not found. */
4578
4579 static ptid_t
4580 stop_reply_extract_thread (const char *stop_reply)
4581 {
4582 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4583 {
4584 const char *p;
4585
4586 /* Txx r:val ; r:val (...) */
4587 p = &stop_reply[3];
4588
4589 /* Look for "register" named "thread". */
4590 while (*p != '\0')
4591 {
4592 const char *p1;
4593
4594 p1 = strchr (p, ':');
4595 if (p1 == NULL)
4596 return null_ptid;
4597
4598 if (strncmp (p, "thread", p1 - p) == 0)
4599 return read_ptid (++p1, &p);
4600
4601 p1 = strchr (p, ';');
4602 if (p1 == NULL)
4603 return null_ptid;
4604 p1++;
4605
4606 p = p1;
4607 }
4608 }
4609
4610 return null_ptid;
4611 }
4612
4613 /* Determine the remote side's current thread. If we have a stop
4614 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4615 "thread" register we can extract the current thread from. If not,
4616 ask the remote which is the current thread with qC. The former
4617 method avoids a roundtrip. */
4618
4619 ptid_t
4620 remote_target::get_current_thread (const char *wait_status)
4621 {
4622 ptid_t ptid = null_ptid;
4623
4624 /* Note we don't use remote_parse_stop_reply as that makes use of
4625 the target architecture, which we haven't yet fully determined at
4626 this point. */
4627 if (wait_status != NULL)
4628 ptid = stop_reply_extract_thread (wait_status);
4629 if (ptid == null_ptid)
4630 ptid = remote_current_thread (inferior_ptid);
4631
4632 return ptid;
4633 }
4634
4635 /* Query the remote target for which is the current thread/process,
4636 add it to our tables, and update INFERIOR_PTID. The caller is
4637 responsible for setting the state such that the remote end is ready
4638 to return the current thread.
4639
4640 This function is called after handling the '?' or 'vRun' packets,
4641 whose response is a stop reply from which we can also try
4642 extracting the thread. If the target doesn't support the explicit
4643 qC query, we infer the current thread from that stop reply, passed
4644 in in WAIT_STATUS, which may be NULL.
4645
4646 The function returns pointer to the main thread of the inferior. */
4647
4648 thread_info *
4649 remote_target::add_current_inferior_and_thread (const char *wait_status)
4650 {
4651 bool fake_pid_p = false;
4652
4653 switch_to_no_thread ();
4654
4655 /* Now, if we have thread information, update the current thread's
4656 ptid. */
4657 ptid_t curr_ptid = get_current_thread (wait_status);
4658
4659 if (curr_ptid != null_ptid)
4660 {
4661 if (!m_features.remote_multi_process_p ())
4662 fake_pid_p = true;
4663 }
4664 else
4665 {
4666 /* Without this, some commands which require an active target
4667 (such as kill) won't work. This variable serves (at least)
4668 double duty as both the pid of the target process (if it has
4669 such), and as a flag indicating that a target is active. */
4670 curr_ptid = magic_null_ptid;
4671 fake_pid_p = true;
4672 }
4673
4674 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4675
4676 /* Add the main thread and switch to it. Don't try reading
4677 registers yet, since we haven't fetched the target description
4678 yet. */
4679 thread_info *tp = add_thread_silent (this, curr_ptid);
4680 switch_to_thread_no_regs (tp);
4681
4682 return tp;
4683 }
4684
4685 /* Print info about a thread that was found already stopped on
4686 connection. */
4687
4688 void
4689 remote_target::print_one_stopped_thread (thread_info *thread)
4690 {
4691 target_waitstatus ws;
4692
4693 /* If there is a pending waitstatus, use it. If there isn't it's because
4694 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4695 and process_initial_stop_replies decided it wasn't interesting to save
4696 and report to the core. */
4697 if (thread->has_pending_waitstatus ())
4698 {
4699 ws = thread->pending_waitstatus ();
4700 thread->clear_pending_waitstatus ();
4701 }
4702 else
4703 {
4704 ws.set_stopped (GDB_SIGNAL_0);
4705 }
4706
4707 switch_to_thread (thread);
4708 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4709 set_current_sal_from_frame (get_current_frame ());
4710
4711 /* For "info program". */
4712 set_last_target_status (this, thread->ptid, ws);
4713
4714 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4715 {
4716 enum gdb_signal sig = ws.sig ();
4717
4718 if (signal_print_state (sig))
4719 notify_signal_received (sig);
4720 }
4721
4722 notify_normal_stop (nullptr, 1);
4723 }
4724
4725 /* Process all initial stop replies the remote side sent in response
4726 to the ? packet. These indicate threads that were already stopped
4727 on initial connection. We mark these threads as stopped and print
4728 their current frame before giving the user the prompt. */
4729
4730 void
4731 remote_target::process_initial_stop_replies (int from_tty)
4732 {
4733 int pending_stop_replies = stop_reply_queue_length ();
4734 struct thread_info *selected = NULL;
4735 struct thread_info *lowest_stopped = NULL;
4736 struct thread_info *first = NULL;
4737
4738 /* This is only used when the target is non-stop. */
4739 gdb_assert (target_is_non_stop_p ());
4740
4741 /* Consume the initial pending events. */
4742 while (pending_stop_replies-- > 0)
4743 {
4744 ptid_t waiton_ptid = minus_one_ptid;
4745 ptid_t event_ptid;
4746 struct target_waitstatus ws;
4747 int ignore_event = 0;
4748
4749 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4750 if (remote_debug)
4751 print_target_wait_results (waiton_ptid, event_ptid, ws);
4752
4753 switch (ws.kind ())
4754 {
4755 case TARGET_WAITKIND_IGNORE:
4756 case TARGET_WAITKIND_NO_RESUMED:
4757 case TARGET_WAITKIND_SIGNALLED:
4758 case TARGET_WAITKIND_EXITED:
4759 /* We shouldn't see these, but if we do, just ignore. */
4760 remote_debug_printf ("event ignored");
4761 ignore_event = 1;
4762 break;
4763
4764 default:
4765 break;
4766 }
4767
4768 if (ignore_event)
4769 continue;
4770
4771 thread_info *evthread = this->find_thread (event_ptid);
4772
4773 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4774 {
4775 enum gdb_signal sig = ws.sig ();
4776
4777 /* Stubs traditionally report SIGTRAP as initial signal,
4778 instead of signal 0. Suppress it. */
4779 if (sig == GDB_SIGNAL_TRAP)
4780 sig = GDB_SIGNAL_0;
4781 evthread->set_stop_signal (sig);
4782 ws.set_stopped (sig);
4783 }
4784
4785 if (ws.kind () != TARGET_WAITKIND_STOPPED
4786 || ws.sig () != GDB_SIGNAL_0)
4787 evthread->set_pending_waitstatus (ws);
4788
4789 set_executing (this, event_ptid, false);
4790 set_running (this, event_ptid, false);
4791 get_remote_thread_info (evthread)->set_not_resumed ();
4792 }
4793
4794 /* "Notice" the new inferiors before anything related to
4795 registers/memory. */
4796 for (inferior *inf : all_non_exited_inferiors (this))
4797 {
4798 inf->needs_setup = true;
4799
4800 if (non_stop)
4801 {
4802 thread_info *thread = any_live_thread_of_inferior (inf);
4803 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4804 from_tty);
4805 }
4806 }
4807
4808 /* If all-stop on top of non-stop, pause all threads. Note this
4809 records the threads' stop pc, so must be done after "noticing"
4810 the inferiors. */
4811 if (!non_stop)
4812 {
4813 {
4814 /* At this point, the remote target is not async. It needs to be for
4815 the poll in stop_all_threads to consider events from it, so enable
4816 it temporarily. */
4817 gdb_assert (!this->is_async_p ());
4818 SCOPE_EXIT { target_async (false); };
4819 target_async (true);
4820 stop_all_threads ("remote connect in all-stop");
4821 }
4822
4823 /* If all threads of an inferior were already stopped, we
4824 haven't setup the inferior yet. */
4825 for (inferior *inf : all_non_exited_inferiors (this))
4826 {
4827 if (inf->needs_setup)
4828 {
4829 thread_info *thread = any_live_thread_of_inferior (inf);
4830 switch_to_thread_no_regs (thread);
4831 setup_inferior (0);
4832 }
4833 }
4834 }
4835
4836 /* Now go over all threads that are stopped, and print their current
4837 frame. If all-stop, then if there's a signalled thread, pick
4838 that as current. */
4839 for (thread_info *thread : all_non_exited_threads (this))
4840 {
4841 if (first == NULL)
4842 first = thread;
4843
4844 if (!non_stop)
4845 thread->set_running (false);
4846 else if (thread->state != THREAD_STOPPED)
4847 continue;
4848
4849 if (selected == nullptr && thread->has_pending_waitstatus ())
4850 selected = thread;
4851
4852 if (lowest_stopped == NULL
4853 || thread->inf->num < lowest_stopped->inf->num
4854 || thread->per_inf_num < lowest_stopped->per_inf_num)
4855 lowest_stopped = thread;
4856
4857 if (non_stop)
4858 print_one_stopped_thread (thread);
4859 }
4860
4861 /* In all-stop, we only print the status of one thread, and leave
4862 others with their status pending. */
4863 if (!non_stop)
4864 {
4865 thread_info *thread = selected;
4866 if (thread == NULL)
4867 thread = lowest_stopped;
4868 if (thread == NULL)
4869 thread = first;
4870
4871 print_one_stopped_thread (thread);
4872 }
4873 }
4874
4875 /* Mark a remote_target as starting (by setting the starting_up flag within
4876 its remote_state) for the lifetime of this object. The reference count
4877 on the remote target is temporarily incremented, to prevent the target
4878 being deleted under our feet. */
4879
4880 struct scoped_mark_target_starting
4881 {
4882 /* Constructor, TARGET is the target to be marked as starting, its
4883 reference count will be incremented. */
4884 scoped_mark_target_starting (remote_target *target)
4885 : m_remote_target (remote_target_ref::new_reference (target)),
4886 m_restore_starting_up (set_starting_up_flag (target))
4887 { /* Nothing. */ }
4888
4889 private:
4890
4891 /* Helper function, set the starting_up flag on TARGET and return an
4892 object which, when it goes out of scope, will restore the previous
4893 value of the starting_up flag. */
4894 static scoped_restore_tmpl<bool>
4895 set_starting_up_flag (remote_target *target)
4896 {
4897 remote_state *rs = target->get_remote_state ();
4898 gdb_assert (!rs->starting_up);
4899 return make_scoped_restore (&rs->starting_up, true);
4900 }
4901
4902 /* A gdb::ref_ptr pointer to a remote_target. */
4903 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4904
4905 /* A reference to the target on which we are operating. */
4906 remote_target_ref m_remote_target;
4907
4908 /* An object which restores the previous value of the starting_up flag
4909 when it goes out of scope. */
4910 scoped_restore_tmpl<bool> m_restore_starting_up;
4911 };
4912
4913 /* Helper for remote_target::start_remote, start the remote connection and
4914 sync state. Return true if everything goes OK, otherwise, return false.
4915 This function exists so that the scoped_restore created within it will
4916 expire before we return to remote_target::start_remote. */
4917
4918 bool
4919 remote_target::start_remote_1 (int from_tty, int extended_p)
4920 {
4921 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4922
4923 struct remote_state *rs = get_remote_state ();
4924
4925 /* Signal other parts that we're going through the initial setup,
4926 and so things may not be stable yet. E.g., we don't try to
4927 install tracepoints until we've relocated symbols. Also, a
4928 Ctrl-C before we're connected and synced up can't interrupt the
4929 target. Instead, it offers to drop the (potentially wedged)
4930 connection. */
4931 scoped_mark_target_starting target_is_starting (this);
4932
4933 QUIT;
4934
4935 if (interrupt_on_connect)
4936 send_interrupt_sequence ();
4937
4938 /* Ack any packet which the remote side has already sent. */
4939 remote_serial_write ("+", 1);
4940
4941 /* The first packet we send to the target is the optional "supported
4942 packets" request. If the target can answer this, it will tell us
4943 which later probes to skip. */
4944 remote_query_supported ();
4945
4946 /* Check vCont support and set the remote state's vCont_action_support
4947 attribute. */
4948 remote_vcont_probe ();
4949
4950 /* If the stub wants to get a QAllow, compose one and send it. */
4951 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4952 set_permissions ();
4953
4954 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4955 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4956 as a reply to known packet. For packet "vFile:setfs:" it is an
4957 invalid reply and GDB would return error in
4958 remote_hostio_set_filesystem, making remote files access impossible.
4959 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4960 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4961 {
4962 const char v_mustreplyempty[] = "vMustReplyEmpty";
4963
4964 putpkt (v_mustreplyempty);
4965 getpkt (&rs->buf, 0);
4966 if (strcmp (rs->buf.data (), "OK") == 0)
4967 {
4968 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4969 = PACKET_DISABLE;
4970 }
4971 else if (strcmp (rs->buf.data (), "") != 0)
4972 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4973 rs->buf.data ());
4974 }
4975
4976 /* Next, we possibly activate noack mode.
4977
4978 If the QStartNoAckMode packet configuration is set to AUTO,
4979 enable noack mode if the stub reported a wish for it with
4980 qSupported.
4981
4982 If set to TRUE, then enable noack mode even if the stub didn't
4983 report it in qSupported. If the stub doesn't reply OK, the
4984 session ends with an error.
4985
4986 If FALSE, then don't activate noack mode, regardless of what the
4987 stub claimed should be the default with qSupported. */
4988
4989 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
4990 {
4991 putpkt ("QStartNoAckMode");
4992 getpkt (&rs->buf, 0);
4993 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
4994 rs->noack_mode = 1;
4995 }
4996
4997 if (extended_p)
4998 {
4999 /* Tell the remote that we are using the extended protocol. */
5000 putpkt ("!");
5001 getpkt (&rs->buf, 0);
5002 }
5003
5004 /* Let the target know which signals it is allowed to pass down to
5005 the program. */
5006 update_signals_program_target ();
5007
5008 /* Next, if the target can specify a description, read it. We do
5009 this before anything involving memory or registers. */
5010 target_find_description ();
5011
5012 /* Next, now that we know something about the target, update the
5013 address spaces in the program spaces. */
5014 update_address_spaces ();
5015
5016 /* On OSs where the list of libraries is global to all
5017 processes, we fetch them early. */
5018 if (gdbarch_has_global_solist (target_gdbarch ()))
5019 solib_add (NULL, from_tty, auto_solib_add);
5020
5021 if (target_is_non_stop_p ())
5022 {
5023 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5024 error (_("Non-stop mode requested, but remote "
5025 "does not support non-stop"));
5026
5027 putpkt ("QNonStop:1");
5028 getpkt (&rs->buf, 0);
5029
5030 if (strcmp (rs->buf.data (), "OK") != 0)
5031 error (_("Remote refused setting non-stop mode with: %s"),
5032 rs->buf.data ());
5033
5034 /* Find about threads and processes the stub is already
5035 controlling. We default to adding them in the running state.
5036 The '?' query below will then tell us about which threads are
5037 stopped. */
5038 this->update_thread_list ();
5039 }
5040 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5041 {
5042 /* Don't assume that the stub can operate in all-stop mode.
5043 Request it explicitly. */
5044 putpkt ("QNonStop:0");
5045 getpkt (&rs->buf, 0);
5046
5047 if (strcmp (rs->buf.data (), "OK") != 0)
5048 error (_("Remote refused setting all-stop mode with: %s"),
5049 rs->buf.data ());
5050 }
5051
5052 /* Upload TSVs regardless of whether the target is running or not. The
5053 remote stub, such as GDBserver, may have some predefined or builtin
5054 TSVs, even if the target is not running. */
5055 if (get_trace_status (current_trace_status ()) != -1)
5056 {
5057 struct uploaded_tsv *uploaded_tsvs = NULL;
5058
5059 upload_trace_state_variables (&uploaded_tsvs);
5060 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5061 }
5062
5063 /* Check whether the target is running now. */
5064 putpkt ("?");
5065 getpkt (&rs->buf, 0);
5066
5067 if (!target_is_non_stop_p ())
5068 {
5069 char *wait_status = NULL;
5070
5071 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5072 {
5073 if (!extended_p)
5074 error (_("The target is not running (try extended-remote?)"));
5075 return false;
5076 }
5077 else
5078 {
5079 /* Save the reply for later. */
5080 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5081 strcpy (wait_status, rs->buf.data ());
5082 }
5083
5084 /* Fetch thread list. */
5085 target_update_thread_list ();
5086
5087 /* Let the stub know that we want it to return the thread. */
5088 set_continue_thread (minus_one_ptid);
5089
5090 if (thread_count (this) == 0)
5091 {
5092 /* Target has no concept of threads at all. GDB treats
5093 non-threaded target as single-threaded; add a main
5094 thread. */
5095 thread_info *tp = add_current_inferior_and_thread (wait_status);
5096 get_remote_thread_info (tp)->set_resumed ();
5097 }
5098 else
5099 {
5100 /* We have thread information; select the thread the target
5101 says should be current. If we're reconnecting to a
5102 multi-threaded program, this will ideally be the thread
5103 that last reported an event before GDB disconnected. */
5104 ptid_t curr_thread = get_current_thread (wait_status);
5105 if (curr_thread == null_ptid)
5106 {
5107 /* Odd... The target was able to list threads, but not
5108 tell us which thread was current (no "thread"
5109 register in T stop reply?). Just pick the first
5110 thread in the thread list then. */
5111
5112 remote_debug_printf ("warning: couldn't determine remote "
5113 "current thread; picking first in list.");
5114
5115 for (thread_info *tp : all_non_exited_threads (this,
5116 minus_one_ptid))
5117 {
5118 switch_to_thread (tp);
5119 break;
5120 }
5121 }
5122 else
5123 switch_to_thread (this->find_thread (curr_thread));
5124 }
5125
5126 /* init_wait_for_inferior should be called before get_offsets in order
5127 to manage `inserted' flag in bp loc in a correct state.
5128 breakpoint_init_inferior, called from init_wait_for_inferior, set
5129 `inserted' flag to 0, while before breakpoint_re_set, called from
5130 start_remote, set `inserted' flag to 1. In the initialization of
5131 inferior, breakpoint_init_inferior should be called first, and then
5132 breakpoint_re_set can be called. If this order is broken, state of
5133 `inserted' flag is wrong, and cause some problems on breakpoint
5134 manipulation. */
5135 init_wait_for_inferior ();
5136
5137 get_offsets (); /* Get text, data & bss offsets. */
5138
5139 /* If we could not find a description using qXfer, and we know
5140 how to do it some other way, try again. This is not
5141 supported for non-stop; it could be, but it is tricky if
5142 there are no stopped threads when we connect. */
5143 if (remote_read_description_p (this)
5144 && gdbarch_target_desc (target_gdbarch ()) == NULL)
5145 {
5146 target_clear_description ();
5147 target_find_description ();
5148 }
5149
5150 /* Use the previously fetched status. */
5151 gdb_assert (wait_status != NULL);
5152 struct notif_event *reply
5153 = remote_notif_parse (this, &notif_client_stop, wait_status);
5154 push_stop_reply ((struct stop_reply *) reply);
5155
5156 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5157 }
5158 else
5159 {
5160 /* Clear WFI global state. Do this before finding about new
5161 threads and inferiors, and setting the current inferior.
5162 Otherwise we would clear the proceed status of the current
5163 inferior when we want its stop_soon state to be preserved
5164 (see notice_new_inferior). */
5165 init_wait_for_inferior ();
5166
5167 /* In non-stop, we will either get an "OK", meaning that there
5168 are no stopped threads at this time; or, a regular stop
5169 reply. In the latter case, there may be more than one thread
5170 stopped --- we pull them all out using the vStopped
5171 mechanism. */
5172 if (strcmp (rs->buf.data (), "OK") != 0)
5173 {
5174 const notif_client *notif = &notif_client_stop;
5175
5176 /* remote_notif_get_pending_replies acks this one, and gets
5177 the rest out. */
5178 rs->notif_state->pending_event[notif_client_stop.id]
5179 = remote_notif_parse (this, notif, rs->buf.data ());
5180 remote_notif_get_pending_events (notif);
5181 }
5182
5183 if (thread_count (this) == 0)
5184 {
5185 if (!extended_p)
5186 error (_("The target is not running (try extended-remote?)"));
5187 return false;
5188 }
5189
5190 /* Report all signals during attach/startup. */
5191 pass_signals ({});
5192
5193 /* If there are already stopped threads, mark them stopped and
5194 report their stops before giving the prompt to the user. */
5195 process_initial_stop_replies (from_tty);
5196
5197 if (target_can_async_p ())
5198 target_async (true);
5199 }
5200
5201 /* Give the target a chance to look up symbols. */
5202 for (inferior *inf : all_inferiors (this))
5203 {
5204 /* The inferiors that exist at this point were created from what
5205 was found already running on the remote side, so we know they
5206 have execution. */
5207 gdb_assert (this->has_execution (inf));
5208
5209 /* No use without a symbol-file. */
5210 if (inf->pspace->symfile_object_file == nullptr)
5211 continue;
5212
5213 /* Need to switch to a specific thread, because remote_check_symbols
5214 uses INFERIOR_PTID to set the general thread. */
5215 scoped_restore_current_thread restore_thread;
5216 thread_info *thread = any_thread_of_inferior (inf);
5217 switch_to_thread (thread);
5218 this->remote_check_symbols ();
5219 }
5220
5221 /* Possibly the target has been engaged in a trace run started
5222 previously; find out where things are at. */
5223 if (get_trace_status (current_trace_status ()) != -1)
5224 {
5225 struct uploaded_tp *uploaded_tps = NULL;
5226
5227 if (current_trace_status ()->running)
5228 gdb_printf (_("Trace is already running on the target.\n"));
5229
5230 upload_tracepoints (&uploaded_tps);
5231
5232 merge_uploaded_tracepoints (&uploaded_tps);
5233 }
5234
5235 /* Possibly the target has been engaged in a btrace record started
5236 previously; find out where things are at. */
5237 remote_btrace_maybe_reopen ();
5238
5239 return true;
5240 }
5241
5242 /* Start the remote connection and sync state. */
5243
5244 void
5245 remote_target::start_remote (int from_tty, int extended_p)
5246 {
5247 if (start_remote_1 (from_tty, extended_p)
5248 && breakpoints_should_be_inserted_now ())
5249 insert_breakpoints ();
5250 }
5251
5252 const char *
5253 remote_target::connection_string ()
5254 {
5255 remote_state *rs = get_remote_state ();
5256
5257 if (rs->remote_desc->name != NULL)
5258 return rs->remote_desc->name;
5259 else
5260 return NULL;
5261 }
5262
5263 /* Open a connection to a remote debugger.
5264 NAME is the filename used for communication. */
5265
5266 void
5267 remote_target::open (const char *name, int from_tty)
5268 {
5269 open_1 (name, from_tty, 0);
5270 }
5271
5272 /* Open a connection to a remote debugger using the extended
5273 remote gdb protocol. NAME is the filename used for communication. */
5274
5275 void
5276 extended_remote_target::open (const char *name, int from_tty)
5277 {
5278 open_1 (name, from_tty, 1 /*extended_p */);
5279 }
5280
5281 void
5282 remote_features::reset_all_packet_configs_support ()
5283 {
5284 int i;
5285
5286 for (i = 0; i < PACKET_MAX; i++)
5287 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5288 }
5289
5290 /* Initialize all packet configs. */
5291
5292 static void
5293 init_all_packet_configs (void)
5294 {
5295 int i;
5296
5297 for (i = 0; i < PACKET_MAX; i++)
5298 {
5299 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5300 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5301 }
5302 }
5303
5304 /* Symbol look-up. */
5305
5306 void
5307 remote_target::remote_check_symbols ()
5308 {
5309 char *tmp;
5310 int end;
5311
5312 /* It doesn't make sense to send a qSymbol packet for an inferior that
5313 doesn't have execution, because the remote side doesn't know about
5314 inferiors without execution. */
5315 gdb_assert (target_has_execution ());
5316
5317 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5318 return;
5319
5320 /* Make sure the remote is pointing at the right process. Note
5321 there's no way to select "no process". */
5322 set_general_process ();
5323
5324 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5325 because we need both at the same time. */
5326 gdb::char_vector msg (get_remote_packet_size ());
5327 gdb::char_vector reply (get_remote_packet_size ());
5328
5329 /* Invite target to request symbol lookups. */
5330
5331 putpkt ("qSymbol::");
5332 getpkt (&reply, 0);
5333 m_features.packet_ok (reply, PACKET_qSymbol);
5334
5335 while (startswith (reply.data (), "qSymbol:"))
5336 {
5337 struct bound_minimal_symbol sym;
5338
5339 tmp = &reply[8];
5340 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5341 strlen (tmp) / 2);
5342 msg[end] = '\0';
5343 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5344 if (sym.minsym == NULL)
5345 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5346 &reply[8]);
5347 else
5348 {
5349 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5350 CORE_ADDR sym_addr = sym.value_address ();
5351
5352 /* If this is a function address, return the start of code
5353 instead of any data function descriptor. */
5354 sym_addr = gdbarch_convert_from_func_ptr_addr
5355 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5356
5357 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5358 phex_nz (sym_addr, addr_size), &reply[8]);
5359 }
5360
5361 putpkt (msg.data ());
5362 getpkt (&reply, 0);
5363 }
5364 }
5365
5366 static struct serial *
5367 remote_serial_open (const char *name)
5368 {
5369 static int udp_warning = 0;
5370
5371 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5372 of in ser-tcp.c, because it is the remote protocol assuming that the
5373 serial connection is reliable and not the serial connection promising
5374 to be. */
5375 if (!udp_warning && startswith (name, "udp:"))
5376 {
5377 warning (_("The remote protocol may be unreliable over UDP.\n"
5378 "Some events may be lost, rendering further debugging "
5379 "impossible."));
5380 udp_warning = 1;
5381 }
5382
5383 return serial_open (name);
5384 }
5385
5386 /* Inform the target of our permission settings. The permission flags
5387 work without this, but if the target knows the settings, it can do
5388 a couple things. First, it can add its own check, to catch cases
5389 that somehow manage to get by the permissions checks in target
5390 methods. Second, if the target is wired to disallow particular
5391 settings (for instance, a system in the field that is not set up to
5392 be able to stop at a breakpoint), it can object to any unavailable
5393 permissions. */
5394
5395 void
5396 remote_target::set_permissions ()
5397 {
5398 struct remote_state *rs = get_remote_state ();
5399
5400 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5401 "WriteReg:%x;WriteMem:%x;"
5402 "InsertBreak:%x;InsertTrace:%x;"
5403 "InsertFastTrace:%x;Stop:%x",
5404 may_write_registers, may_write_memory,
5405 may_insert_breakpoints, may_insert_tracepoints,
5406 may_insert_fast_tracepoints, may_stop);
5407 putpkt (rs->buf);
5408 getpkt (&rs->buf, 0);
5409
5410 /* If the target didn't like the packet, warn the user. Do not try
5411 to undo the user's settings, that would just be maddening. */
5412 if (strcmp (rs->buf.data (), "OK") != 0)
5413 warning (_("Remote refused setting permissions with: %s"),
5414 rs->buf.data ());
5415 }
5416
5417 /* This type describes each known response to the qSupported
5418 packet. */
5419 struct protocol_feature
5420 {
5421 /* The name of this protocol feature. */
5422 const char *name;
5423
5424 /* The default for this protocol feature. */
5425 enum packet_support default_support;
5426
5427 /* The function to call when this feature is reported, or after
5428 qSupported processing if the feature is not supported.
5429 The first argument points to this structure. The second
5430 argument indicates whether the packet requested support be
5431 enabled, disabled, or probed (or the default, if this function
5432 is being called at the end of processing and this feature was
5433 not reported). The third argument may be NULL; if not NULL, it
5434 is a NUL-terminated string taken from the packet following
5435 this feature's name and an equals sign. */
5436 void (*func) (remote_target *remote, const struct protocol_feature *,
5437 enum packet_support, const char *);
5438
5439 /* The corresponding packet for this feature. Only used if
5440 FUNC is remote_supported_packet. */
5441 int packet;
5442 };
5443
5444 static void
5445 remote_supported_packet (remote_target *remote,
5446 const struct protocol_feature *feature,
5447 enum packet_support support,
5448 const char *argument)
5449 {
5450 if (argument)
5451 {
5452 warning (_("Remote qSupported response supplied an unexpected value for"
5453 " \"%s\"."), feature->name);
5454 return;
5455 }
5456
5457 remote->m_features.m_protocol_packets[feature->packet].support = support;
5458 }
5459
5460 void
5461 remote_target::remote_packet_size (const protocol_feature *feature,
5462 enum packet_support support, const char *value)
5463 {
5464 struct remote_state *rs = get_remote_state ();
5465
5466 int packet_size;
5467 char *value_end;
5468
5469 if (support != PACKET_ENABLE)
5470 return;
5471
5472 if (value == NULL || *value == '\0')
5473 {
5474 warning (_("Remote target reported \"%s\" without a size."),
5475 feature->name);
5476 return;
5477 }
5478
5479 errno = 0;
5480 packet_size = strtol (value, &value_end, 16);
5481 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5482 {
5483 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5484 feature->name, value);
5485 return;
5486 }
5487
5488 /* Record the new maximum packet size. */
5489 rs->explicit_packet_size = packet_size;
5490 }
5491
5492 static void
5493 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5494 enum packet_support support, const char *value)
5495 {
5496 remote->remote_packet_size (feature, support, value);
5497 }
5498
5499 static const struct protocol_feature remote_protocol_features[] = {
5500 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5501 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5502 PACKET_qXfer_auxv },
5503 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5504 PACKET_qXfer_exec_file },
5505 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5506 PACKET_qXfer_features },
5507 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5508 PACKET_qXfer_libraries },
5509 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5510 PACKET_qXfer_libraries_svr4 },
5511 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5512 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5513 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5514 PACKET_qXfer_memory_map },
5515 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5516 PACKET_qXfer_osdata },
5517 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5518 PACKET_qXfer_threads },
5519 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5520 PACKET_qXfer_traceframe_info },
5521 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5522 PACKET_QPassSignals },
5523 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5524 PACKET_QCatchSyscalls },
5525 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5526 PACKET_QProgramSignals },
5527 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5528 PACKET_QSetWorkingDir },
5529 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5530 PACKET_QStartupWithShell },
5531 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5532 PACKET_QEnvironmentHexEncoded },
5533 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5534 PACKET_QEnvironmentReset },
5535 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5536 PACKET_QEnvironmentUnset },
5537 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5538 PACKET_QStartNoAckMode },
5539 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5540 PACKET_multiprocess_feature },
5541 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5542 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5543 PACKET_qXfer_siginfo_read },
5544 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5545 PACKET_qXfer_siginfo_write },
5546 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5547 PACKET_ConditionalTracepoints },
5548 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5549 PACKET_ConditionalBreakpoints },
5550 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5551 PACKET_BreakpointCommands },
5552 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5553 PACKET_FastTracepoints },
5554 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5555 PACKET_StaticTracepoints },
5556 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5557 PACKET_InstallInTrace},
5558 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5559 PACKET_DisconnectedTracing_feature },
5560 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5561 PACKET_bc },
5562 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5563 PACKET_bs },
5564 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5565 PACKET_TracepointSource },
5566 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_QAllow },
5568 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_EnableDisableTracepoints_feature },
5570 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_qXfer_fdpic },
5572 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_qXfer_uib },
5574 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_QDisableRandomization },
5576 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5577 { "QTBuffer:size", PACKET_DISABLE,
5578 remote_supported_packet, PACKET_QTBuffer_size},
5579 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5580 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5581 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5582 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5583 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5584 PACKET_qXfer_btrace },
5585 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5586 PACKET_qXfer_btrace_conf },
5587 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5588 PACKET_Qbtrace_conf_bts_size },
5589 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5590 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5591 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5592 PACKET_fork_event_feature },
5593 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5594 PACKET_vfork_event_feature },
5595 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5596 PACKET_exec_event_feature },
5597 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5598 PACKET_Qbtrace_conf_pt_size },
5599 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5600 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5601 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5602 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5603 PACKET_memory_tagging_feature },
5604 };
5605
5606 static char *remote_support_xml;
5607
5608 /* Register string appended to "xmlRegisters=" in qSupported query. */
5609
5610 void
5611 register_remote_support_xml (const char *xml)
5612 {
5613 #if defined(HAVE_LIBEXPAT)
5614 if (remote_support_xml == NULL)
5615 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5616 else
5617 {
5618 char *copy = xstrdup (remote_support_xml + 13);
5619 char *saveptr;
5620 char *p = strtok_r (copy, ",", &saveptr);
5621
5622 do
5623 {
5624 if (strcmp (p, xml) == 0)
5625 {
5626 /* already there */
5627 xfree (copy);
5628 return;
5629 }
5630 }
5631 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5632 xfree (copy);
5633
5634 remote_support_xml = reconcat (remote_support_xml,
5635 remote_support_xml, ",", xml,
5636 (char *) NULL);
5637 }
5638 #endif
5639 }
5640
5641 static void
5642 remote_query_supported_append (std::string *msg, const char *append)
5643 {
5644 if (!msg->empty ())
5645 msg->append (";");
5646 msg->append (append);
5647 }
5648
5649 void
5650 remote_target::remote_query_supported ()
5651 {
5652 struct remote_state *rs = get_remote_state ();
5653 char *next;
5654 int i;
5655 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5656
5657 /* The packet support flags are handled differently for this packet
5658 than for most others. We treat an error, a disabled packet, and
5659 an empty response identically: any features which must be reported
5660 to be used will be automatically disabled. An empty buffer
5661 accomplishes this, since that is also the representation for a list
5662 containing no features. */
5663
5664 rs->buf[0] = 0;
5665 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5666 {
5667 std::string q;
5668
5669 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5670 != AUTO_BOOLEAN_FALSE)
5671 remote_query_supported_append (&q, "multiprocess+");
5672
5673 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5674 != AUTO_BOOLEAN_FALSE)
5675 remote_query_supported_append (&q, "swbreak+");
5676
5677 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5678 != AUTO_BOOLEAN_FALSE)
5679 remote_query_supported_append (&q, "hwbreak+");
5680
5681 remote_query_supported_append (&q, "qRelocInsn+");
5682
5683 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5684 != AUTO_BOOLEAN_FALSE)
5685 remote_query_supported_append (&q, "fork-events+");
5686
5687 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5688 != AUTO_BOOLEAN_FALSE)
5689 remote_query_supported_append (&q, "vfork-events+");
5690
5691 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5692 != AUTO_BOOLEAN_FALSE)
5693 remote_query_supported_append (&q, "exec-events+");
5694
5695 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5696 != AUTO_BOOLEAN_FALSE)
5697 remote_query_supported_append (&q, "vContSupported+");
5698
5699 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5700 != AUTO_BOOLEAN_FALSE)
5701 remote_query_supported_append (&q, "QThreadEvents+");
5702
5703 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5704 != AUTO_BOOLEAN_FALSE)
5705 remote_query_supported_append (&q, "no-resumed+");
5706
5707 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5708 != AUTO_BOOLEAN_FALSE)
5709 remote_query_supported_append (&q, "memory-tagging+");
5710
5711 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5712 the qSupported:xmlRegisters=i386 handling. */
5713 if (remote_support_xml != NULL
5714 && (m_features.packet_support (PACKET_qXfer_features)
5715 != PACKET_DISABLE))
5716 remote_query_supported_append (&q, remote_support_xml);
5717
5718 q = "qSupported:" + q;
5719 putpkt (q.c_str ());
5720
5721 getpkt (&rs->buf, 0);
5722
5723 /* If an error occurred, warn, but do not return - just reset the
5724 buffer to empty and go on to disable features. */
5725 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5726 {
5727 warning (_("Remote failure reply: %s"), rs->buf.data ());
5728 rs->buf[0] = 0;
5729 }
5730 }
5731
5732 memset (seen, 0, sizeof (seen));
5733
5734 next = rs->buf.data ();
5735 while (*next)
5736 {
5737 enum packet_support is_supported;
5738 char *p, *end, *name_end, *value;
5739
5740 /* First separate out this item from the rest of the packet. If
5741 there's another item after this, we overwrite the separator
5742 (terminated strings are much easier to work with). */
5743 p = next;
5744 end = strchr (p, ';');
5745 if (end == NULL)
5746 {
5747 end = p + strlen (p);
5748 next = end;
5749 }
5750 else
5751 {
5752 *end = '\0';
5753 next = end + 1;
5754
5755 if (end == p)
5756 {
5757 warning (_("empty item in \"qSupported\" response"));
5758 continue;
5759 }
5760 }
5761
5762 name_end = strchr (p, '=');
5763 if (name_end)
5764 {
5765 /* This is a name=value entry. */
5766 is_supported = PACKET_ENABLE;
5767 value = name_end + 1;
5768 *name_end = '\0';
5769 }
5770 else
5771 {
5772 value = NULL;
5773 switch (end[-1])
5774 {
5775 case '+':
5776 is_supported = PACKET_ENABLE;
5777 break;
5778
5779 case '-':
5780 is_supported = PACKET_DISABLE;
5781 break;
5782
5783 case '?':
5784 is_supported = PACKET_SUPPORT_UNKNOWN;
5785 break;
5786
5787 default:
5788 warning (_("unrecognized item \"%s\" "
5789 "in \"qSupported\" response"), p);
5790 continue;
5791 }
5792 end[-1] = '\0';
5793 }
5794
5795 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5796 if (strcmp (remote_protocol_features[i].name, p) == 0)
5797 {
5798 const struct protocol_feature *feature;
5799
5800 seen[i] = 1;
5801 feature = &remote_protocol_features[i];
5802 feature->func (this, feature, is_supported, value);
5803 break;
5804 }
5805 }
5806
5807 /* If we increased the packet size, make sure to increase the global
5808 buffer size also. We delay this until after parsing the entire
5809 qSupported packet, because this is the same buffer we were
5810 parsing. */
5811 if (rs->buf.size () < rs->explicit_packet_size)
5812 rs->buf.resize (rs->explicit_packet_size);
5813
5814 /* Handle the defaults for unmentioned features. */
5815 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5816 if (!seen[i])
5817 {
5818 const struct protocol_feature *feature;
5819
5820 feature = &remote_protocol_features[i];
5821 feature->func (this, feature, feature->default_support, NULL);
5822 }
5823 }
5824
5825 /* Serial QUIT handler for the remote serial descriptor.
5826
5827 Defers handling a Ctrl-C until we're done with the current
5828 command/response packet sequence, unless:
5829
5830 - We're setting up the connection. Don't send a remote interrupt
5831 request, as we're not fully synced yet. Quit immediately
5832 instead.
5833
5834 - The target has been resumed in the foreground
5835 (target_terminal::is_ours is false) with a synchronous resume
5836 packet, and we're blocked waiting for the stop reply, thus a
5837 Ctrl-C should be immediately sent to the target.
5838
5839 - We get a second Ctrl-C while still within the same serial read or
5840 write. In that case the serial is seemingly wedged --- offer to
5841 quit/disconnect.
5842
5843 - We see a second Ctrl-C without target response, after having
5844 previously interrupted the target. In that case the target/stub
5845 is probably wedged --- offer to quit/disconnect.
5846 */
5847
5848 void
5849 remote_target::remote_serial_quit_handler ()
5850 {
5851 struct remote_state *rs = get_remote_state ();
5852
5853 if (check_quit_flag ())
5854 {
5855 /* If we're starting up, we're not fully synced yet. Quit
5856 immediately. */
5857 if (rs->starting_up)
5858 quit ();
5859 else if (rs->got_ctrlc_during_io)
5860 {
5861 if (query (_("The target is not responding to GDB commands.\n"
5862 "Stop debugging it? ")))
5863 remote_unpush_and_throw (this);
5864 }
5865 /* If ^C has already been sent once, offer to disconnect. */
5866 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5867 interrupt_query ();
5868 /* All-stop protocol, and blocked waiting for stop reply. Send
5869 an interrupt request. */
5870 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5871 target_interrupt ();
5872 else
5873 rs->got_ctrlc_during_io = 1;
5874 }
5875 }
5876
5877 /* The remote_target that is current while the quit handler is
5878 overridden with remote_serial_quit_handler. */
5879 static remote_target *curr_quit_handler_target;
5880
5881 static void
5882 remote_serial_quit_handler ()
5883 {
5884 curr_quit_handler_target->remote_serial_quit_handler ();
5885 }
5886
5887 /* Remove the remote target from the target stack of each inferior
5888 that is using it. Upper targets depend on it so remove them
5889 first. */
5890
5891 static void
5892 remote_unpush_target (remote_target *target)
5893 {
5894 /* We have to unpush the target from all inferiors, even those that
5895 aren't running. */
5896 scoped_restore_current_inferior restore_current_inferior;
5897
5898 for (inferior *inf : all_inferiors (target))
5899 {
5900 switch_to_inferior_no_thread (inf);
5901 inf->pop_all_targets_at_and_above (process_stratum);
5902 generic_mourn_inferior ();
5903 }
5904
5905 /* Don't rely on target_close doing this when the target is popped
5906 from the last remote inferior above, because something may be
5907 holding a reference to the target higher up on the stack, meaning
5908 target_close won't be called yet. We lost the connection to the
5909 target, so clear these now, otherwise we may later throw
5910 TARGET_CLOSE_ERROR while trying to tell the remote target to
5911 close the file. */
5912 fileio_handles_invalidate_target (target);
5913 }
5914
5915 static void
5916 remote_unpush_and_throw (remote_target *target)
5917 {
5918 remote_unpush_target (target);
5919 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5920 }
5921
5922 void
5923 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5924 {
5925 remote_target *curr_remote = get_current_remote_target ();
5926
5927 if (name == 0)
5928 error (_("To open a remote debug connection, you need to specify what\n"
5929 "serial device is attached to the remote system\n"
5930 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5931
5932 /* If we're connected to a running target, target_preopen will kill it.
5933 Ask this question first, before target_preopen has a chance to kill
5934 anything. */
5935 if (curr_remote != NULL && !target_has_execution ())
5936 {
5937 if (from_tty
5938 && !query (_("Already connected to a remote target. Disconnect? ")))
5939 error (_("Still connected."));
5940 }
5941
5942 /* Here the possibly existing remote target gets unpushed. */
5943 target_preopen (from_tty);
5944
5945 remote_fileio_reset ();
5946 reopen_exec_file ();
5947 reread_symbols (from_tty);
5948
5949 remote_target *remote
5950 = (extended_p ? new extended_remote_target () : new remote_target ());
5951 target_ops_up target_holder (remote);
5952
5953 remote_state *rs = remote->get_remote_state ();
5954
5955 /* See FIXME above. */
5956 if (!target_async_permitted)
5957 rs->wait_forever_enabled_p = 1;
5958
5959 rs->remote_desc = remote_serial_open (name);
5960 if (!rs->remote_desc)
5961 perror_with_name (name);
5962
5963 if (baud_rate != -1)
5964 {
5965 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5966 {
5967 /* The requested speed could not be set. Error out to
5968 top level after closing remote_desc. Take care to
5969 set remote_desc to NULL to avoid closing remote_desc
5970 more than once. */
5971 serial_close (rs->remote_desc);
5972 rs->remote_desc = NULL;
5973 perror_with_name (name);
5974 }
5975 }
5976
5977 serial_setparity (rs->remote_desc, serial_parity);
5978 serial_raw (rs->remote_desc);
5979
5980 /* If there is something sitting in the buffer we might take it as a
5981 response to a command, which would be bad. */
5982 serial_flush_input (rs->remote_desc);
5983
5984 if (from_tty)
5985 {
5986 gdb_puts ("Remote debugging using ");
5987 gdb_puts (name);
5988 gdb_puts ("\n");
5989 }
5990
5991 /* Switch to using the remote target now. */
5992 current_inferior ()->push_target (std::move (target_holder));
5993
5994 /* Register extra event sources in the event loop. */
5995 rs->remote_async_inferior_event_token
5996 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
5997 "remote");
5998 rs->notif_state = remote_notif_state_allocate (remote);
5999
6000 /* Reset the target state; these things will be queried either by
6001 remote_query_supported or as they are needed. */
6002 remote->m_features.reset_all_packet_configs_support ();
6003 rs->explicit_packet_size = 0;
6004 rs->noack_mode = 0;
6005 rs->extended = extended_p;
6006 rs->waiting_for_stop_reply = 0;
6007 rs->ctrlc_pending_p = 0;
6008 rs->got_ctrlc_during_io = 0;
6009
6010 rs->general_thread = not_sent_ptid;
6011 rs->continue_thread = not_sent_ptid;
6012 rs->remote_traceframe_number = -1;
6013
6014 rs->last_resume_exec_dir = EXEC_FORWARD;
6015
6016 /* Probe for ability to use "ThreadInfo" query, as required. */
6017 rs->use_threadinfo_query = 1;
6018 rs->use_threadextra_query = 1;
6019
6020 rs->readahead_cache.invalidate ();
6021
6022 if (target_async_permitted)
6023 {
6024 /* FIXME: cagney/1999-09-23: During the initial connection it is
6025 assumed that the target is already ready and able to respond to
6026 requests. Unfortunately remote_start_remote() eventually calls
6027 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6028 around this. Eventually a mechanism that allows
6029 wait_for_inferior() to expect/get timeouts will be
6030 implemented. */
6031 rs->wait_forever_enabled_p = 0;
6032 }
6033
6034 /* First delete any symbols previously loaded from shared libraries. */
6035 no_shared_libraries (NULL, 0);
6036
6037 /* Start the remote connection. If error() or QUIT, discard this
6038 target (we'd otherwise be in an inconsistent state) and then
6039 propogate the error on up the exception chain. This ensures that
6040 the caller doesn't stumble along blindly assuming that the
6041 function succeeded. The CLI doesn't have this problem but other
6042 UI's, such as MI do.
6043
6044 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6045 this function should return an error indication letting the
6046 caller restore the previous state. Unfortunately the command
6047 ``target remote'' is directly wired to this function making that
6048 impossible. On a positive note, the CLI side of this problem has
6049 been fixed - the function set_cmd_context() makes it possible for
6050 all the ``target ....'' commands to share a common callback
6051 function. See cli-dump.c. */
6052 {
6053
6054 try
6055 {
6056 remote->start_remote (from_tty, extended_p);
6057 }
6058 catch (const gdb_exception &ex)
6059 {
6060 /* Pop the partially set up target - unless something else did
6061 already before throwing the exception. */
6062 if (ex.error != TARGET_CLOSE_ERROR)
6063 remote_unpush_target (remote);
6064 throw;
6065 }
6066 }
6067
6068 remote_btrace_reset (rs);
6069
6070 if (target_async_permitted)
6071 rs->wait_forever_enabled_p = 1;
6072 }
6073
6074 /* Determine if WS represents a fork status. */
6075
6076 static bool
6077 is_fork_status (target_waitkind kind)
6078 {
6079 return (kind == TARGET_WAITKIND_FORKED
6080 || kind == TARGET_WAITKIND_VFORKED);
6081 }
6082
6083 /* Return THREAD's pending status if it is a pending fork parent, else
6084 return nullptr. */
6085
6086 static const target_waitstatus *
6087 thread_pending_fork_status (struct thread_info *thread)
6088 {
6089 const target_waitstatus &ws
6090 = (thread->has_pending_waitstatus ()
6091 ? thread->pending_waitstatus ()
6092 : thread->pending_follow);
6093
6094 if (!is_fork_status (ws.kind ()))
6095 return nullptr;
6096
6097 return &ws;
6098 }
6099
6100 /* Detach the specified process. */
6101
6102 void
6103 remote_target::remote_detach_pid (int pid)
6104 {
6105 struct remote_state *rs = get_remote_state ();
6106
6107 /* This should not be necessary, but the handling for D;PID in
6108 GDBserver versions prior to 8.2 incorrectly assumes that the
6109 selected process points to the same process we're detaching,
6110 leading to misbehavior (and possibly GDBserver crashing) when it
6111 does not. Since it's easy and cheap, work around it by forcing
6112 GDBserver to select GDB's current process. */
6113 set_general_process ();
6114
6115 if (m_features.remote_multi_process_p ())
6116 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6117 else
6118 strcpy (rs->buf.data (), "D");
6119
6120 putpkt (rs->buf);
6121 getpkt (&rs->buf, 0);
6122
6123 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6124 ;
6125 else if (rs->buf[0] == '\0')
6126 error (_("Remote doesn't know how to detach"));
6127 else
6128 error (_("Can't detach process."));
6129 }
6130
6131 /* This detaches a program to which we previously attached, using
6132 inferior_ptid to identify the process. After this is done, GDB
6133 can be used to debug some other program. We better not have left
6134 any breakpoints in the target program or it'll die when it hits
6135 one. */
6136
6137 void
6138 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6139 {
6140 int pid = inferior_ptid.pid ();
6141 struct remote_state *rs = get_remote_state ();
6142 int is_fork_parent;
6143
6144 if (!target_has_execution ())
6145 error (_("No process to detach from."));
6146
6147 target_announce_detach (from_tty);
6148
6149 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
6150 {
6151 /* If we're in breakpoints-always-inserted mode, or the inferior
6152 is running, we have to remove breakpoints before detaching.
6153 We don't do this in common code instead because not all
6154 targets support removing breakpoints while the target is
6155 running. The remote target / gdbserver does, though. */
6156 remove_breakpoints_inf (current_inferior ());
6157 }
6158
6159 /* Tell the remote target to detach. */
6160 remote_detach_pid (pid);
6161
6162 /* Exit only if this is the only active inferior. */
6163 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6164 gdb_puts (_("Ending remote debugging.\n"));
6165
6166 /* See if any thread of the inferior we are detaching has a pending fork
6167 status. In that case, we must detach from the child resulting from
6168 that fork. */
6169 for (thread_info *thread : inf->non_exited_threads ())
6170 {
6171 const target_waitstatus *ws = thread_pending_fork_status (thread);
6172
6173 if (ws == nullptr)
6174 continue;
6175
6176 remote_detach_pid (ws->child_ptid ().pid ());
6177 }
6178
6179 /* Check also for any pending fork events in the stop reply queue. */
6180 remote_notif_get_pending_events (&notif_client_stop);
6181 for (stop_reply_up &reply : rs->stop_reply_queue)
6182 {
6183 if (reply->ptid.pid () != pid)
6184 continue;
6185
6186 if (!is_fork_status (reply->ws.kind ()))
6187 continue;
6188
6189 remote_detach_pid (reply->ws.child_ptid ().pid ());
6190 }
6191
6192 thread_info *tp = this->find_thread (inferior_ptid);
6193
6194 /* Check to see if we are detaching a fork parent. Note that if we
6195 are detaching a fork child, tp == NULL. */
6196 is_fork_parent = (tp != NULL
6197 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6198
6199 /* If doing detach-on-fork, we don't mourn, because that will delete
6200 breakpoints that should be available for the followed inferior. */
6201 if (!is_fork_parent)
6202 {
6203 /* Save the pid as a string before mourning, since that will
6204 unpush the remote target, and we need the string after. */
6205 std::string infpid = target_pid_to_str (ptid_t (pid));
6206
6207 target_mourn_inferior (inferior_ptid);
6208 if (print_inferior_events)
6209 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6210 inf->num, infpid.c_str ());
6211 }
6212 else
6213 {
6214 switch_to_no_thread ();
6215 detach_inferior (current_inferior ());
6216 }
6217 }
6218
6219 void
6220 remote_target::detach (inferior *inf, int from_tty)
6221 {
6222 remote_detach_1 (inf, from_tty);
6223 }
6224
6225 void
6226 extended_remote_target::detach (inferior *inf, int from_tty)
6227 {
6228 remote_detach_1 (inf, from_tty);
6229 }
6230
6231 /* Target follow-fork function for remote targets. On entry, and
6232 at return, the current inferior is the fork parent.
6233
6234 Note that although this is currently only used for extended-remote,
6235 it is named remote_follow_fork in anticipation of using it for the
6236 remote target as well. */
6237
6238 void
6239 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6240 target_waitkind fork_kind, bool follow_child,
6241 bool detach_fork)
6242 {
6243 process_stratum_target::follow_fork (child_inf, child_ptid,
6244 fork_kind, follow_child, detach_fork);
6245
6246 if ((fork_kind == TARGET_WAITKIND_FORKED
6247 && m_features.remote_fork_event_p ())
6248 || (fork_kind == TARGET_WAITKIND_VFORKED
6249 && m_features.remote_vfork_event_p ()))
6250 {
6251 /* When following the parent and detaching the child, we detach
6252 the child here. For the case of following the child and
6253 detaching the parent, the detach is done in the target-
6254 independent follow fork code in infrun.c. We can't use
6255 target_detach when detaching an unfollowed child because
6256 the client side doesn't know anything about the child. */
6257 if (detach_fork && !follow_child)
6258 {
6259 /* Detach the fork child. */
6260 remote_detach_pid (child_ptid.pid ());
6261 }
6262 }
6263 }
6264
6265 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6266 in the program space of the new inferior. */
6267
6268 void
6269 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6270 const char *execd_pathname)
6271 {
6272 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6273
6274 /* We know that this is a target file name, so if it has the "target:"
6275 prefix we strip it off before saving it in the program space. */
6276 if (is_target_filename (execd_pathname))
6277 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6278
6279 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6280 }
6281
6282 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6283
6284 void
6285 remote_target::disconnect (const char *args, int from_tty)
6286 {
6287 if (args)
6288 error (_("Argument given to \"disconnect\" when remotely debugging."));
6289
6290 /* Make sure we unpush even the extended remote targets. Calling
6291 target_mourn_inferior won't unpush, and
6292 remote_target::mourn_inferior won't unpush if there is more than
6293 one inferior left. */
6294 remote_unpush_target (this);
6295
6296 if (from_tty)
6297 gdb_puts ("Ending remote debugging.\n");
6298 }
6299
6300 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6301 be chatty about it. */
6302
6303 void
6304 extended_remote_target::attach (const char *args, int from_tty)
6305 {
6306 struct remote_state *rs = get_remote_state ();
6307 int pid;
6308 char *wait_status = NULL;
6309
6310 pid = parse_pid_to_attach (args);
6311
6312 /* Remote PID can be freely equal to getpid, do not check it here the same
6313 way as in other targets. */
6314
6315 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6316 error (_("This target does not support attaching to a process"));
6317
6318 target_announce_attach (from_tty, pid);
6319
6320 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6321 putpkt (rs->buf);
6322 getpkt (&rs->buf, 0);
6323
6324 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6325 {
6326 case PACKET_OK:
6327 if (!target_is_non_stop_p ())
6328 {
6329 /* Save the reply for later. */
6330 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6331 strcpy (wait_status, rs->buf.data ());
6332 }
6333 else if (strcmp (rs->buf.data (), "OK") != 0)
6334 error (_("Attaching to %s failed with: %s"),
6335 target_pid_to_str (ptid_t (pid)).c_str (),
6336 rs->buf.data ());
6337 break;
6338 case PACKET_UNKNOWN:
6339 error (_("This target does not support attaching to a process"));
6340 default:
6341 error (_("Attaching to %s failed"),
6342 target_pid_to_str (ptid_t (pid)).c_str ());
6343 }
6344
6345 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6346
6347 inferior_ptid = ptid_t (pid);
6348
6349 if (target_is_non_stop_p ())
6350 {
6351 /* Get list of threads. */
6352 update_thread_list ();
6353
6354 thread_info *thread = first_thread_of_inferior (current_inferior ());
6355 if (thread != nullptr)
6356 switch_to_thread (thread);
6357
6358 /* Invalidate our notion of the remote current thread. */
6359 record_currthread (rs, minus_one_ptid);
6360 }
6361 else
6362 {
6363 /* Now, if we have thread information, update the main thread's
6364 ptid. */
6365 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6366
6367 /* Add the main thread to the thread list. We add the thread
6368 silently in this case (the final true parameter). */
6369 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6370
6371 switch_to_thread (thr);
6372 }
6373
6374 /* Next, if the target can specify a description, read it. We do
6375 this before anything involving memory or registers. */
6376 target_find_description ();
6377
6378 if (!target_is_non_stop_p ())
6379 {
6380 /* Use the previously fetched status. */
6381 gdb_assert (wait_status != NULL);
6382
6383 struct notif_event *reply
6384 = remote_notif_parse (this, &notif_client_stop, wait_status);
6385
6386 push_stop_reply ((struct stop_reply *) reply);
6387 }
6388 else
6389 {
6390 gdb_assert (wait_status == NULL);
6391
6392 gdb_assert (target_can_async_p ());
6393 }
6394 }
6395
6396 /* Implementation of the to_post_attach method. */
6397
6398 void
6399 extended_remote_target::post_attach (int pid)
6400 {
6401 /* Get text, data & bss offsets. */
6402 get_offsets ();
6403
6404 /* In certain cases GDB might not have had the chance to start
6405 symbol lookup up until now. This could happen if the debugged
6406 binary is not using shared libraries, the vsyscall page is not
6407 present (on Linux) and the binary itself hadn't changed since the
6408 debugging process was started. */
6409 if (current_program_space->symfile_object_file != NULL)
6410 remote_check_symbols();
6411 }
6412
6413 \f
6414 /* Check for the availability of vCont. This function should also check
6415 the response. */
6416
6417 void
6418 remote_target::remote_vcont_probe ()
6419 {
6420 remote_state *rs = get_remote_state ();
6421 char *buf;
6422
6423 strcpy (rs->buf.data (), "vCont?");
6424 putpkt (rs->buf);
6425 getpkt (&rs->buf, 0);
6426 buf = rs->buf.data ();
6427
6428 /* Make sure that the features we assume are supported. */
6429 if (startswith (buf, "vCont"))
6430 {
6431 char *p = &buf[5];
6432 int support_c, support_C;
6433
6434 rs->supports_vCont.s = 0;
6435 rs->supports_vCont.S = 0;
6436 support_c = 0;
6437 support_C = 0;
6438 rs->supports_vCont.t = 0;
6439 rs->supports_vCont.r = 0;
6440 while (p && *p == ';')
6441 {
6442 p++;
6443 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6444 rs->supports_vCont.s = 1;
6445 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6446 rs->supports_vCont.S = 1;
6447 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6448 support_c = 1;
6449 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6450 support_C = 1;
6451 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6452 rs->supports_vCont.t = 1;
6453 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6454 rs->supports_vCont.r = 1;
6455
6456 p = strchr (p, ';');
6457 }
6458
6459 /* If c, and C are not all supported, we can't use vCont. Clearing
6460 BUF will make packet_ok disable the packet. */
6461 if (!support_c || !support_C)
6462 buf[0] = 0;
6463 }
6464
6465 m_features.packet_ok (rs->buf, PACKET_vCont);
6466 }
6467
6468 /* Helper function for building "vCont" resumptions. Write a
6469 resumption to P. ENDP points to one-passed-the-end of the buffer
6470 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6471 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6472 resumed thread should be single-stepped and/or signalled. If PTID
6473 equals minus_one_ptid, then all threads are resumed; if PTID
6474 represents a process, then all threads of the process are
6475 resumed. */
6476
6477 char *
6478 remote_target::append_resumption (char *p, char *endp,
6479 ptid_t ptid, int step, gdb_signal siggnal)
6480 {
6481 struct remote_state *rs = get_remote_state ();
6482
6483 if (step && siggnal != GDB_SIGNAL_0)
6484 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6485 else if (step
6486 /* GDB is willing to range step. */
6487 && use_range_stepping
6488 /* Target supports range stepping. */
6489 && rs->supports_vCont.r
6490 /* We don't currently support range stepping multiple
6491 threads with a wildcard (though the protocol allows it,
6492 so stubs shouldn't make an active effort to forbid
6493 it). */
6494 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6495 {
6496 struct thread_info *tp;
6497
6498 if (ptid == minus_one_ptid)
6499 {
6500 /* If we don't know about the target thread's tid, then
6501 we're resuming magic_null_ptid (see caller). */
6502 tp = this->find_thread (magic_null_ptid);
6503 }
6504 else
6505 tp = this->find_thread (ptid);
6506 gdb_assert (tp != NULL);
6507
6508 if (tp->control.may_range_step)
6509 {
6510 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6511
6512 p += xsnprintf (p, endp - p, ";r%s,%s",
6513 phex_nz (tp->control.step_range_start,
6514 addr_size),
6515 phex_nz (tp->control.step_range_end,
6516 addr_size));
6517 }
6518 else
6519 p += xsnprintf (p, endp - p, ";s");
6520 }
6521 else if (step)
6522 p += xsnprintf (p, endp - p, ";s");
6523 else if (siggnal != GDB_SIGNAL_0)
6524 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6525 else
6526 p += xsnprintf (p, endp - p, ";c");
6527
6528 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6529 {
6530 ptid_t nptid;
6531
6532 /* All (-1) threads of process. */
6533 nptid = ptid_t (ptid.pid (), -1);
6534
6535 p += xsnprintf (p, endp - p, ":");
6536 p = write_ptid (p, endp, nptid);
6537 }
6538 else if (ptid != minus_one_ptid)
6539 {
6540 p += xsnprintf (p, endp - p, ":");
6541 p = write_ptid (p, endp, ptid);
6542 }
6543
6544 return p;
6545 }
6546
6547 /* Clear the thread's private info on resume. */
6548
6549 static void
6550 resume_clear_thread_private_info (struct thread_info *thread)
6551 {
6552 if (thread->priv != NULL)
6553 {
6554 remote_thread_info *priv = get_remote_thread_info (thread);
6555
6556 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6557 priv->watch_data_address = 0;
6558 }
6559 }
6560
6561 /* Append a vCont continue-with-signal action for threads that have a
6562 non-zero stop signal. */
6563
6564 char *
6565 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6566 ptid_t ptid)
6567 {
6568 for (thread_info *thread : all_non_exited_threads (this, ptid))
6569 if (inferior_ptid != thread->ptid
6570 && thread->stop_signal () != GDB_SIGNAL_0)
6571 {
6572 p = append_resumption (p, endp, thread->ptid,
6573 0, thread->stop_signal ());
6574 thread->set_stop_signal (GDB_SIGNAL_0);
6575 resume_clear_thread_private_info (thread);
6576 }
6577
6578 return p;
6579 }
6580
6581 /* Set the target running, using the packets that use Hc
6582 (c/s/C/S). */
6583
6584 void
6585 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6586 gdb_signal siggnal)
6587 {
6588 struct remote_state *rs = get_remote_state ();
6589 char *buf;
6590
6591 rs->last_sent_signal = siggnal;
6592 rs->last_sent_step = step;
6593
6594 /* The c/s/C/S resume packets use Hc, so set the continue
6595 thread. */
6596 if (ptid == minus_one_ptid)
6597 set_continue_thread (any_thread_ptid);
6598 else
6599 set_continue_thread (ptid);
6600
6601 for (thread_info *thread : all_non_exited_threads (this))
6602 resume_clear_thread_private_info (thread);
6603
6604 buf = rs->buf.data ();
6605 if (::execution_direction == EXEC_REVERSE)
6606 {
6607 /* We don't pass signals to the target in reverse exec mode. */
6608 if (info_verbose && siggnal != GDB_SIGNAL_0)
6609 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6610 siggnal);
6611
6612 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6613 error (_("Remote reverse-step not supported."));
6614 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6615 error (_("Remote reverse-continue not supported."));
6616
6617 strcpy (buf, step ? "bs" : "bc");
6618 }
6619 else if (siggnal != GDB_SIGNAL_0)
6620 {
6621 buf[0] = step ? 'S' : 'C';
6622 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6623 buf[2] = tohex (((int) siggnal) & 0xf);
6624 buf[3] = '\0';
6625 }
6626 else
6627 strcpy (buf, step ? "s" : "c");
6628
6629 putpkt (buf);
6630 }
6631
6632 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6633 STEP, and SIGGNAL have the same meaning as in target_resume. This
6634 function returns non-zero iff it resumes the inferior.
6635
6636 This function issues a strict subset of all possible vCont commands
6637 at the moment. */
6638
6639 int
6640 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6641 enum gdb_signal siggnal)
6642 {
6643 struct remote_state *rs = get_remote_state ();
6644 char *p;
6645 char *endp;
6646
6647 /* No reverse execution actions defined for vCont. */
6648 if (::execution_direction == EXEC_REVERSE)
6649 return 0;
6650
6651 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6652 return 0;
6653
6654 p = rs->buf.data ();
6655 endp = p + get_remote_packet_size ();
6656
6657 /* If we could generate a wider range of packets, we'd have to worry
6658 about overflowing BUF. Should there be a generic
6659 "multi-part-packet" packet? */
6660
6661 p += xsnprintf (p, endp - p, "vCont");
6662
6663 if (scope_ptid == magic_null_ptid)
6664 {
6665 /* MAGIC_NULL_PTID means that we don't have any active threads,
6666 so we don't have any TID numbers the inferior will
6667 understand. Make sure to only send forms that do not specify
6668 a TID. */
6669 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6670 }
6671 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6672 {
6673 /* Resume all threads (of all processes, or of a single
6674 process), with preference for INFERIOR_PTID. This assumes
6675 inferior_ptid belongs to the set of all threads we are about
6676 to resume. */
6677 if (step || siggnal != GDB_SIGNAL_0)
6678 {
6679 /* Step inferior_ptid, with or without signal. */
6680 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6681 }
6682
6683 /* Also pass down any pending signaled resumption for other
6684 threads not the current. */
6685 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6686
6687 /* And continue others without a signal. */
6688 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6689 }
6690 else
6691 {
6692 /* Scheduler locking; resume only SCOPE_PTID. */
6693 append_resumption (p, endp, scope_ptid, step, siggnal);
6694 }
6695
6696 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6697 putpkt (rs->buf);
6698
6699 if (target_is_non_stop_p ())
6700 {
6701 /* In non-stop, the stub replies to vCont with "OK". The stop
6702 reply will be reported asynchronously by means of a `%Stop'
6703 notification. */
6704 getpkt (&rs->buf, 0);
6705 if (strcmp (rs->buf.data (), "OK") != 0)
6706 error (_("Unexpected vCont reply in non-stop mode: %s"),
6707 rs->buf.data ());
6708 }
6709
6710 return 1;
6711 }
6712
6713 /* Tell the remote machine to resume. */
6714
6715 void
6716 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6717 {
6718 struct remote_state *rs = get_remote_state ();
6719
6720 /* When connected in non-stop mode, the core resumes threads
6721 individually. Resuming remote threads directly in target_resume
6722 would thus result in sending one packet per thread. Instead, to
6723 minimize roundtrip latency, here we just store the resume
6724 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6725 resumption will be done in remote_target::commit_resume, where we'll be
6726 able to do vCont action coalescing. */
6727 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6728 {
6729 remote_thread_info *remote_thr
6730 = get_remote_thread_info (inferior_thread ());
6731
6732 /* We don't expect the core to ask to resume an already resumed (from
6733 its point of view) thread. */
6734 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6735
6736 remote_thr->set_resumed_pending_vcont (step, siggnal);
6737
6738 /* There's actually nothing that says that the core can't
6739 request a wildcard resume in non-stop mode, though. It's
6740 just that we know it doesn't currently, so we don't bother
6741 with it. */
6742 gdb_assert (scope_ptid == inferior_ptid);
6743 return;
6744 }
6745
6746 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6747 (explained in remote-notif.c:handle_notification) so
6748 remote_notif_process is not called. We need find a place where
6749 it is safe to start a 'vNotif' sequence. It is good to do it
6750 before resuming inferior, because inferior was stopped and no RSP
6751 traffic at that moment. */
6752 if (!target_is_non_stop_p ())
6753 remote_notif_process (rs->notif_state, &notif_client_stop);
6754
6755 rs->last_resume_exec_dir = ::execution_direction;
6756
6757 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6758 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6759 remote_resume_with_hc (scope_ptid, step, siggnal);
6760
6761 /* Update resumed state tracked by the remote target. */
6762 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6763 get_remote_thread_info (tp)->set_resumed ();
6764
6765 /* We've just told the target to resume. The remote server will
6766 wait for the inferior to stop, and then send a stop reply. In
6767 the mean time, we can't start another command/query ourselves
6768 because the stub wouldn't be ready to process it. This applies
6769 only to the base all-stop protocol, however. In non-stop (which
6770 only supports vCont), the stub replies with an "OK", and is
6771 immediate able to process further serial input. */
6772 if (!target_is_non_stop_p ())
6773 rs->waiting_for_stop_reply = 1;
6774 }
6775
6776 /* Private per-inferior info for target remote processes. */
6777
6778 struct remote_inferior : public private_inferior
6779 {
6780 /* Whether we can send a wildcard vCont for this process. */
6781 bool may_wildcard_vcont = true;
6782 };
6783
6784 /* Get the remote private inferior data associated to INF. */
6785
6786 static remote_inferior *
6787 get_remote_inferior (inferior *inf)
6788 {
6789 if (inf->priv == NULL)
6790 inf->priv.reset (new remote_inferior);
6791
6792 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6793 }
6794
6795 /* Class used to track the construction of a vCont packet in the
6796 outgoing packet buffer. This is used to send multiple vCont
6797 packets if we have more actions than would fit a single packet. */
6798
6799 class vcont_builder
6800 {
6801 public:
6802 explicit vcont_builder (remote_target *remote)
6803 : m_remote (remote)
6804 {
6805 restart ();
6806 }
6807
6808 void flush ();
6809 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6810
6811 private:
6812 void restart ();
6813
6814 /* The remote target. */
6815 remote_target *m_remote;
6816
6817 /* Pointer to the first action. P points here if no action has been
6818 appended yet. */
6819 char *m_first_action;
6820
6821 /* Where the next action will be appended. */
6822 char *m_p;
6823
6824 /* The end of the buffer. Must never write past this. */
6825 char *m_endp;
6826 };
6827
6828 /* Prepare the outgoing buffer for a new vCont packet. */
6829
6830 void
6831 vcont_builder::restart ()
6832 {
6833 struct remote_state *rs = m_remote->get_remote_state ();
6834
6835 m_p = rs->buf.data ();
6836 m_endp = m_p + m_remote->get_remote_packet_size ();
6837 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6838 m_first_action = m_p;
6839 }
6840
6841 /* If the vCont packet being built has any action, send it to the
6842 remote end. */
6843
6844 void
6845 vcont_builder::flush ()
6846 {
6847 struct remote_state *rs;
6848
6849 if (m_p == m_first_action)
6850 return;
6851
6852 rs = m_remote->get_remote_state ();
6853 m_remote->putpkt (rs->buf);
6854 m_remote->getpkt (&rs->buf, 0);
6855 if (strcmp (rs->buf.data (), "OK") != 0)
6856 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6857 }
6858
6859 /* The largest action is range-stepping, with its two addresses. This
6860 is more than sufficient. If a new, bigger action is created, it'll
6861 quickly trigger a failed assertion in append_resumption (and we'll
6862 just bump this). */
6863 #define MAX_ACTION_SIZE 200
6864
6865 /* Append a new vCont action in the outgoing packet being built. If
6866 the action doesn't fit the packet along with previous actions, push
6867 what we've got so far to the remote end and start over a new vCont
6868 packet (with the new action). */
6869
6870 void
6871 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6872 {
6873 char buf[MAX_ACTION_SIZE + 1];
6874
6875 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6876 ptid, step, siggnal);
6877
6878 /* Check whether this new action would fit in the vCont packet along
6879 with previous actions. If not, send what we've got so far and
6880 start a new vCont packet. */
6881 size_t rsize = endp - buf;
6882 if (rsize > m_endp - m_p)
6883 {
6884 flush ();
6885 restart ();
6886
6887 /* Should now fit. */
6888 gdb_assert (rsize <= m_endp - m_p);
6889 }
6890
6891 memcpy (m_p, buf, rsize);
6892 m_p += rsize;
6893 *m_p = '\0';
6894 }
6895
6896 /* to_commit_resume implementation. */
6897
6898 void
6899 remote_target::commit_resumed ()
6900 {
6901 /* If connected in all-stop mode, we'd send the remote resume
6902 request directly from remote_resume. Likewise if
6903 reverse-debugging, as there are no defined vCont actions for
6904 reverse execution. */
6905 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6906 return;
6907
6908 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6909 instead of resuming all threads of each process individually.
6910 However, if any thread of a process must remain halted, we can't
6911 send wildcard resumes and must send one action per thread.
6912
6913 Care must be taken to not resume threads/processes the server
6914 side already told us are stopped, but the core doesn't know about
6915 yet, because the events are still in the vStopped notification
6916 queue. For example:
6917
6918 #1 => vCont s:p1.1;c
6919 #2 <= OK
6920 #3 <= %Stopped T05 p1.1
6921 #4 => vStopped
6922 #5 <= T05 p1.2
6923 #6 => vStopped
6924 #7 <= OK
6925 #8 (infrun handles the stop for p1.1 and continues stepping)
6926 #9 => vCont s:p1.1;c
6927
6928 The last vCont above would resume thread p1.2 by mistake, because
6929 the server has no idea that the event for p1.2 had not been
6930 handled yet.
6931
6932 The server side must similarly ignore resume actions for the
6933 thread that has a pending %Stopped notification (and any other
6934 threads with events pending), until GDB acks the notification
6935 with vStopped. Otherwise, e.g., the following case is
6936 mishandled:
6937
6938 #1 => g (or any other packet)
6939 #2 <= [registers]
6940 #3 <= %Stopped T05 p1.2
6941 #4 => vCont s:p1.1;c
6942 #5 <= OK
6943
6944 Above, the server must not resume thread p1.2. GDB can't know
6945 that p1.2 stopped until it acks the %Stopped notification, and
6946 since from GDB's perspective all threads should be running, it
6947 sends a "c" action.
6948
6949 Finally, special care must also be given to handling fork/vfork
6950 events. A (v)fork event actually tells us that two processes
6951 stopped -- the parent and the child. Until we follow the fork,
6952 we must not resume the child. Therefore, if we have a pending
6953 fork follow, we must not send a global wildcard resume action
6954 (vCont;c). We can still send process-wide wildcards though. */
6955
6956 /* Start by assuming a global wildcard (vCont;c) is possible. */
6957 bool may_global_wildcard_vcont = true;
6958
6959 /* And assume every process is individually wildcard-able too. */
6960 for (inferior *inf : all_non_exited_inferiors (this))
6961 {
6962 remote_inferior *priv = get_remote_inferior (inf);
6963
6964 priv->may_wildcard_vcont = true;
6965 }
6966
6967 /* Check for any pending events (not reported or processed yet) and
6968 disable process and global wildcard resumes appropriately. */
6969 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6970
6971 bool any_pending_vcont_resume = false;
6972
6973 for (thread_info *tp : all_non_exited_threads (this))
6974 {
6975 remote_thread_info *priv = get_remote_thread_info (tp);
6976
6977 /* If a thread of a process is not meant to be resumed, then we
6978 can't wildcard that process. */
6979 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6980 {
6981 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6982
6983 /* And if we can't wildcard a process, we can't wildcard
6984 everything either. */
6985 may_global_wildcard_vcont = false;
6986 continue;
6987 }
6988
6989 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6990 any_pending_vcont_resume = true;
6991
6992 /* If a thread is the parent of an unfollowed fork, then we
6993 can't do a global wildcard, as that would resume the fork
6994 child. */
6995 if (thread_pending_fork_status (tp) != nullptr)
6996 may_global_wildcard_vcont = false;
6997 }
6998
6999 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7000 do. */
7001 if (!any_pending_vcont_resume)
7002 return;
7003
7004 /* Now let's build the vCont packet(s). Actions must be appended
7005 from narrower to wider scopes (thread -> process -> global). If
7006 we end up with too many actions for a single packet vcont_builder
7007 flushes the current vCont packet to the remote side and starts a
7008 new one. */
7009 struct vcont_builder vcont_builder (this);
7010
7011 /* Threads first. */
7012 for (thread_info *tp : all_non_exited_threads (this))
7013 {
7014 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7015
7016 /* If the thread was previously vCont-resumed, no need to send a specific
7017 action for it. If we didn't receive a resume request for it, don't
7018 send an action for it either. */
7019 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7020 continue;
7021
7022 gdb_assert (!thread_is_in_step_over_chain (tp));
7023
7024 /* We should never be commit-resuming a thread that has a stop reply.
7025 Otherwise, we would end up reporting a stop event for a thread while
7026 it is running on the remote target. */
7027 remote_state *rs = get_remote_state ();
7028 for (const auto &stop_reply : rs->stop_reply_queue)
7029 gdb_assert (stop_reply->ptid != tp->ptid);
7030
7031 const resumed_pending_vcont_info &info
7032 = remote_thr->resumed_pending_vcont_info ();
7033
7034 /* Check if we need to send a specific action for this thread. If not,
7035 it will be included in a wildcard resume instead. */
7036 if (info.step || info.sig != GDB_SIGNAL_0
7037 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7038 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7039
7040 remote_thr->set_resumed ();
7041 }
7042
7043 /* Now check whether we can send any process-wide wildcard. This is
7044 to avoid sending a global wildcard in the case nothing is
7045 supposed to be resumed. */
7046 bool any_process_wildcard = false;
7047
7048 for (inferior *inf : all_non_exited_inferiors (this))
7049 {
7050 if (get_remote_inferior (inf)->may_wildcard_vcont)
7051 {
7052 any_process_wildcard = true;
7053 break;
7054 }
7055 }
7056
7057 if (any_process_wildcard)
7058 {
7059 /* If all processes are wildcard-able, then send a single "c"
7060 action, otherwise, send an "all (-1) threads of process"
7061 continue action for each running process, if any. */
7062 if (may_global_wildcard_vcont)
7063 {
7064 vcont_builder.push_action (minus_one_ptid,
7065 false, GDB_SIGNAL_0);
7066 }
7067 else
7068 {
7069 for (inferior *inf : all_non_exited_inferiors (this))
7070 {
7071 if (get_remote_inferior (inf)->may_wildcard_vcont)
7072 {
7073 vcont_builder.push_action (ptid_t (inf->pid),
7074 false, GDB_SIGNAL_0);
7075 }
7076 }
7077 }
7078 }
7079
7080 vcont_builder.flush ();
7081 }
7082
7083 /* Implementation of target_has_pending_events. */
7084
7085 bool
7086 remote_target::has_pending_events ()
7087 {
7088 if (target_can_async_p ())
7089 {
7090 remote_state *rs = get_remote_state ();
7091
7092 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
7093 return true;
7094
7095 /* Note that BUFCNT can be negative, indicating sticky
7096 error. */
7097 if (rs->remote_desc->bufcnt != 0)
7098 return true;
7099 }
7100 return false;
7101 }
7102
7103 \f
7104
7105 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7106 thread, all threads of a remote process, or all threads of all
7107 processes. */
7108
7109 void
7110 remote_target::remote_stop_ns (ptid_t ptid)
7111 {
7112 struct remote_state *rs = get_remote_state ();
7113 char *p = rs->buf.data ();
7114 char *endp = p + get_remote_packet_size ();
7115
7116 /* If any thread that needs to stop was resumed but pending a vCont
7117 resume, generate a phony stop_reply. However, first check
7118 whether the thread wasn't resumed with a signal. Generating a
7119 phony stop in that case would result in losing the signal. */
7120 bool needs_commit = false;
7121 for (thread_info *tp : all_non_exited_threads (this, ptid))
7122 {
7123 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7124
7125 if (remote_thr->get_resume_state ()
7126 == resume_state::RESUMED_PENDING_VCONT)
7127 {
7128 const resumed_pending_vcont_info &info
7129 = remote_thr->resumed_pending_vcont_info ();
7130 if (info.sig != GDB_SIGNAL_0)
7131 {
7132 /* This signal must be forwarded to the inferior. We
7133 could commit-resume just this thread, but its simpler
7134 to just commit-resume everything. */
7135 needs_commit = true;
7136 break;
7137 }
7138 }
7139 }
7140
7141 if (needs_commit)
7142 commit_resumed ();
7143 else
7144 for (thread_info *tp : all_non_exited_threads (this, ptid))
7145 {
7146 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7147
7148 if (remote_thr->get_resume_state ()
7149 == resume_state::RESUMED_PENDING_VCONT)
7150 {
7151 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7152 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7153 tp->ptid.lwp (),
7154 pulongest (tp->ptid.tid ()));
7155
7156 /* Check that the thread wasn't resumed with a signal.
7157 Generating a phony stop would result in losing the
7158 signal. */
7159 const resumed_pending_vcont_info &info
7160 = remote_thr->resumed_pending_vcont_info ();
7161 gdb_assert (info.sig == GDB_SIGNAL_0);
7162
7163 stop_reply *sr = new stop_reply ();
7164 sr->ptid = tp->ptid;
7165 sr->rs = rs;
7166 sr->ws.set_stopped (GDB_SIGNAL_0);
7167 sr->arch = tp->inf->gdbarch;
7168 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7169 sr->watch_data_address = 0;
7170 sr->core = 0;
7171 this->push_stop_reply (sr);
7172
7173 /* Pretend that this thread was actually resumed on the
7174 remote target, then stopped. If we leave it in the
7175 RESUMED_PENDING_VCONT state and the commit_resumed
7176 method is called while the stop reply is still in the
7177 queue, we'll end up reporting a stop event to the core
7178 for that thread while it is running on the remote
7179 target... that would be bad. */
7180 remote_thr->set_resumed ();
7181 }
7182 }
7183
7184 if (!rs->supports_vCont.t)
7185 error (_("Remote server does not support stopping threads"));
7186
7187 if (ptid == minus_one_ptid
7188 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7189 p += xsnprintf (p, endp - p, "vCont;t");
7190 else
7191 {
7192 ptid_t nptid;
7193
7194 p += xsnprintf (p, endp - p, "vCont;t:");
7195
7196 if (ptid.is_pid ())
7197 /* All (-1) threads of process. */
7198 nptid = ptid_t (ptid.pid (), -1);
7199 else
7200 {
7201 /* Small optimization: if we already have a stop reply for
7202 this thread, no use in telling the stub we want this
7203 stopped. */
7204 if (peek_stop_reply (ptid))
7205 return;
7206
7207 nptid = ptid;
7208 }
7209
7210 write_ptid (p, endp, nptid);
7211 }
7212
7213 /* In non-stop, we get an immediate OK reply. The stop reply will
7214 come in asynchronously by notification. */
7215 putpkt (rs->buf);
7216 getpkt (&rs->buf, 0);
7217 if (strcmp (rs->buf.data (), "OK") != 0)
7218 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7219 rs->buf.data ());
7220 }
7221
7222 /* All-stop version of target_interrupt. Sends a break or a ^C to
7223 interrupt the remote target. It is undefined which thread of which
7224 process reports the interrupt. */
7225
7226 void
7227 remote_target::remote_interrupt_as ()
7228 {
7229 struct remote_state *rs = get_remote_state ();
7230
7231 rs->ctrlc_pending_p = 1;
7232
7233 /* If the inferior is stopped already, but the core didn't know
7234 about it yet, just ignore the request. The pending stop events
7235 will be collected in remote_wait. */
7236 if (stop_reply_queue_length () > 0)
7237 return;
7238
7239 /* Send interrupt_sequence to remote target. */
7240 send_interrupt_sequence ();
7241 }
7242
7243 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7244 the remote target. It is undefined which thread of which process
7245 reports the interrupt. Throws an error if the packet is not
7246 supported by the server. */
7247
7248 void
7249 remote_target::remote_interrupt_ns ()
7250 {
7251 struct remote_state *rs = get_remote_state ();
7252 char *p = rs->buf.data ();
7253 char *endp = p + get_remote_packet_size ();
7254
7255 xsnprintf (p, endp - p, "vCtrlC");
7256
7257 /* In non-stop, we get an immediate OK reply. The stop reply will
7258 come in asynchronously by notification. */
7259 putpkt (rs->buf);
7260 getpkt (&rs->buf, 0);
7261
7262 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7263 {
7264 case PACKET_OK:
7265 break;
7266 case PACKET_UNKNOWN:
7267 error (_("No support for interrupting the remote target."));
7268 case PACKET_ERROR:
7269 error (_("Interrupting target failed: %s"), rs->buf.data ());
7270 }
7271 }
7272
7273 /* Implement the to_stop function for the remote targets. */
7274
7275 void
7276 remote_target::stop (ptid_t ptid)
7277 {
7278 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7279
7280 if (target_is_non_stop_p ())
7281 remote_stop_ns (ptid);
7282 else
7283 {
7284 /* We don't currently have a way to transparently pause the
7285 remote target in all-stop mode. Interrupt it instead. */
7286 remote_interrupt_as ();
7287 }
7288 }
7289
7290 /* Implement the to_interrupt function for the remote targets. */
7291
7292 void
7293 remote_target::interrupt ()
7294 {
7295 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7296
7297 if (target_is_non_stop_p ())
7298 remote_interrupt_ns ();
7299 else
7300 remote_interrupt_as ();
7301 }
7302
7303 /* Implement the to_pass_ctrlc function for the remote targets. */
7304
7305 void
7306 remote_target::pass_ctrlc ()
7307 {
7308 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7309
7310 struct remote_state *rs = get_remote_state ();
7311
7312 /* If we're starting up, we're not fully synced yet. Quit
7313 immediately. */
7314 if (rs->starting_up)
7315 quit ();
7316 /* If ^C has already been sent once, offer to disconnect. */
7317 else if (rs->ctrlc_pending_p)
7318 interrupt_query ();
7319 else
7320 target_interrupt ();
7321 }
7322
7323 /* Ask the user what to do when an interrupt is received. */
7324
7325 void
7326 remote_target::interrupt_query ()
7327 {
7328 struct remote_state *rs = get_remote_state ();
7329
7330 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7331 {
7332 if (query (_("The target is not responding to interrupt requests.\n"
7333 "Stop debugging it? ")))
7334 {
7335 remote_unpush_target (this);
7336 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7337 }
7338 }
7339 else
7340 {
7341 if (query (_("Interrupted while waiting for the program.\n"
7342 "Give up waiting? ")))
7343 quit ();
7344 }
7345 }
7346
7347 /* Enable/disable target terminal ownership. Most targets can use
7348 terminal groups to control terminal ownership. Remote targets are
7349 different in that explicit transfer of ownership to/from GDB/target
7350 is required. */
7351
7352 void
7353 remote_target::terminal_inferior ()
7354 {
7355 /* NOTE: At this point we could also register our selves as the
7356 recipient of all input. Any characters typed could then be
7357 passed on down to the target. */
7358 }
7359
7360 void
7361 remote_target::terminal_ours ()
7362 {
7363 }
7364
7365 static void
7366 remote_console_output (const char *msg)
7367 {
7368 const char *p;
7369
7370 for (p = msg; p[0] && p[1]; p += 2)
7371 {
7372 char tb[2];
7373 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7374
7375 tb[0] = c;
7376 tb[1] = 0;
7377 gdb_stdtarg->puts (tb);
7378 }
7379 gdb_stdtarg->flush ();
7380 }
7381
7382 /* Return the length of the stop reply queue. */
7383
7384 int
7385 remote_target::stop_reply_queue_length ()
7386 {
7387 remote_state *rs = get_remote_state ();
7388 return rs->stop_reply_queue.size ();
7389 }
7390
7391 static void
7392 remote_notif_stop_parse (remote_target *remote,
7393 const notif_client *self, const char *buf,
7394 struct notif_event *event)
7395 {
7396 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7397 }
7398
7399 static void
7400 remote_notif_stop_ack (remote_target *remote,
7401 const notif_client *self, const char *buf,
7402 struct notif_event *event)
7403 {
7404 struct stop_reply *stop_reply = (struct stop_reply *) event;
7405
7406 /* acknowledge */
7407 putpkt (remote, self->ack_command);
7408
7409 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7410 the notification. It was left in the queue because we need to
7411 acknowledge it and pull the rest of the notifications out. */
7412 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7413 remote->push_stop_reply (stop_reply);
7414 }
7415
7416 static int
7417 remote_notif_stop_can_get_pending_events (remote_target *remote,
7418 const notif_client *self)
7419 {
7420 /* We can't get pending events in remote_notif_process for
7421 notification stop, and we have to do this in remote_wait_ns
7422 instead. If we fetch all queued events from stub, remote stub
7423 may exit and we have no chance to process them back in
7424 remote_wait_ns. */
7425 remote_state *rs = remote->get_remote_state ();
7426 mark_async_event_handler (rs->remote_async_inferior_event_token);
7427 return 0;
7428 }
7429
7430 stop_reply::~stop_reply ()
7431 {
7432 for (cached_reg_t &reg : regcache)
7433 xfree (reg.data);
7434 }
7435
7436 static notif_event_up
7437 remote_notif_stop_alloc_reply ()
7438 {
7439 return notif_event_up (new struct stop_reply ());
7440 }
7441
7442 /* A client of notification Stop. */
7443
7444 const notif_client notif_client_stop =
7445 {
7446 "Stop",
7447 "vStopped",
7448 remote_notif_stop_parse,
7449 remote_notif_stop_ack,
7450 remote_notif_stop_can_get_pending_events,
7451 remote_notif_stop_alloc_reply,
7452 REMOTE_NOTIF_STOP,
7453 };
7454
7455 /* If CONTEXT contains any fork child threads that have not been
7456 reported yet, remove them from the CONTEXT list. If such a
7457 thread exists it is because we are stopped at a fork catchpoint
7458 and have not yet called follow_fork, which will set up the
7459 host-side data structures for the new process. */
7460
7461 void
7462 remote_target::remove_new_fork_children (threads_listing_context *context)
7463 {
7464 const notif_client *notif = &notif_client_stop;
7465
7466 /* For any threads stopped at a fork event, remove the corresponding
7467 fork child threads from the CONTEXT list. */
7468 for (thread_info *thread : all_non_exited_threads (this))
7469 {
7470 const target_waitstatus *ws = thread_pending_fork_status (thread);
7471
7472 if (ws == nullptr)
7473 continue;
7474
7475 context->remove_thread (ws->child_ptid ());
7476 }
7477
7478 /* Check for any pending fork events (not reported or processed yet)
7479 in process PID and remove those fork child threads from the
7480 CONTEXT list as well. */
7481 remote_notif_get_pending_events (notif);
7482 for (auto &event : get_remote_state ()->stop_reply_queue)
7483 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7484 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7485 context->remove_thread (event->ws.child_ptid ());
7486 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7487 context->remove_thread (event->ptid);
7488 }
7489
7490 /* Check whether any event pending in the vStopped queue would prevent a
7491 global or process wildcard vCont action. Set *may_global_wildcard to
7492 false if we can't do a global wildcard (vCont;c), and clear the event
7493 inferior's may_wildcard_vcont flag if we can't do a process-wide
7494 wildcard resume (vCont;c:pPID.-1). */
7495
7496 void
7497 remote_target::check_pending_events_prevent_wildcard_vcont
7498 (bool *may_global_wildcard)
7499 {
7500 const notif_client *notif = &notif_client_stop;
7501
7502 remote_notif_get_pending_events (notif);
7503 for (auto &event : get_remote_state ()->stop_reply_queue)
7504 {
7505 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7506 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7507 continue;
7508
7509 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7510 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7511 *may_global_wildcard = false;
7512
7513 /* This may be the first time we heard about this process.
7514 Regardless, we must not do a global wildcard resume, otherwise
7515 we'd resume this process too. */
7516 *may_global_wildcard = false;
7517 if (event->ptid != null_ptid)
7518 {
7519 inferior *inf = find_inferior_ptid (this, event->ptid);
7520 if (inf != NULL)
7521 get_remote_inferior (inf)->may_wildcard_vcont = false;
7522 }
7523 }
7524 }
7525
7526 /* Discard all pending stop replies of inferior INF. */
7527
7528 void
7529 remote_target::discard_pending_stop_replies (struct inferior *inf)
7530 {
7531 struct stop_reply *reply;
7532 struct remote_state *rs = get_remote_state ();
7533 struct remote_notif_state *rns = rs->notif_state;
7534
7535 /* This function can be notified when an inferior exists. When the
7536 target is not remote, the notification state is NULL. */
7537 if (rs->remote_desc == NULL)
7538 return;
7539
7540 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7541
7542 /* Discard the in-flight notification. */
7543 if (reply != NULL && reply->ptid.pid () == inf->pid)
7544 {
7545 /* Leave the notification pending, since the server expects that
7546 we acknowledge it with vStopped. But clear its contents, so
7547 that later on when we acknowledge it, we also discard it. */
7548 remote_debug_printf
7549 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7550 reply->ptid.to_string().c_str(),
7551 reply->ws.to_string ().c_str ());
7552 reply->ws.set_ignore ();
7553 }
7554
7555 /* Discard the stop replies we have already pulled with
7556 vStopped. */
7557 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7558 rs->stop_reply_queue.end (),
7559 [=] (const stop_reply_up &event)
7560 {
7561 return event->ptid.pid () == inf->pid;
7562 });
7563 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7564 remote_debug_printf
7565 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7566 (*it)->ptid.to_string().c_str(),
7567 (*it)->ws.to_string ().c_str ());
7568 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7569 }
7570
7571 /* Discard the stop replies for RS in stop_reply_queue. */
7572
7573 void
7574 remote_target::discard_pending_stop_replies_in_queue ()
7575 {
7576 remote_state *rs = get_remote_state ();
7577
7578 /* Discard the stop replies we have already pulled with
7579 vStopped. */
7580 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7581 rs->stop_reply_queue.end (),
7582 [=] (const stop_reply_up &event)
7583 {
7584 return event->rs == rs;
7585 });
7586 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7587 }
7588
7589 /* Remove the first reply in 'stop_reply_queue' which matches
7590 PTID. */
7591
7592 struct stop_reply *
7593 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7594 {
7595 remote_state *rs = get_remote_state ();
7596
7597 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7598 rs->stop_reply_queue.end (),
7599 [=] (const stop_reply_up &event)
7600 {
7601 return event->ptid.matches (ptid);
7602 });
7603 struct stop_reply *result;
7604 if (iter == rs->stop_reply_queue.end ())
7605 result = nullptr;
7606 else
7607 {
7608 result = iter->release ();
7609 rs->stop_reply_queue.erase (iter);
7610 }
7611
7612 if (notif_debug)
7613 gdb_printf (gdb_stdlog,
7614 "notif: discard queued event: 'Stop' in %s\n",
7615 ptid.to_string ().c_str ());
7616
7617 return result;
7618 }
7619
7620 /* Look for a queued stop reply belonging to PTID. If one is found,
7621 remove it from the queue, and return it. Returns NULL if none is
7622 found. If there are still queued events left to process, tell the
7623 event loop to get back to target_wait soon. */
7624
7625 struct stop_reply *
7626 remote_target::queued_stop_reply (ptid_t ptid)
7627 {
7628 remote_state *rs = get_remote_state ();
7629 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7630
7631 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7632 {
7633 /* There's still at least an event left. */
7634 mark_async_event_handler (rs->remote_async_inferior_event_token);
7635 }
7636
7637 return r;
7638 }
7639
7640 /* Push a fully parsed stop reply in the stop reply queue. Since we
7641 know that we now have at least one queued event left to pass to the
7642 core side, tell the event loop to get back to target_wait soon. */
7643
7644 void
7645 remote_target::push_stop_reply (struct stop_reply *new_event)
7646 {
7647 remote_state *rs = get_remote_state ();
7648 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7649
7650 if (notif_debug)
7651 gdb_printf (gdb_stdlog,
7652 "notif: push 'Stop' %s to queue %d\n",
7653 new_event->ptid.to_string ().c_str (),
7654 int (rs->stop_reply_queue.size ()));
7655
7656 /* Mark the pending event queue only if async mode is currently enabled.
7657 If async mode is not currently enabled, then, if it later becomes
7658 enabled, and there are events in this queue, we will mark the event
7659 token at that point, see remote_target::async. */
7660 if (target_is_async_p ())
7661 mark_async_event_handler (rs->remote_async_inferior_event_token);
7662 }
7663
7664 /* Returns true if we have a stop reply for PTID. */
7665
7666 int
7667 remote_target::peek_stop_reply (ptid_t ptid)
7668 {
7669 remote_state *rs = get_remote_state ();
7670 for (auto &event : rs->stop_reply_queue)
7671 if (ptid == event->ptid
7672 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7673 return 1;
7674 return 0;
7675 }
7676
7677 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7678 starting with P and ending with PEND matches PREFIX. */
7679
7680 static int
7681 strprefix (const char *p, const char *pend, const char *prefix)
7682 {
7683 for ( ; p < pend; p++, prefix++)
7684 if (*p != *prefix)
7685 return 0;
7686 return *prefix == '\0';
7687 }
7688
7689 /* Parse the stop reply in BUF. Either the function succeeds, and the
7690 result is stored in EVENT, or throws an error. */
7691
7692 void
7693 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7694 {
7695 remote_arch_state *rsa = NULL;
7696 ULONGEST addr;
7697 const char *p;
7698 int skipregs = 0;
7699
7700 event->ptid = null_ptid;
7701 event->rs = get_remote_state ();
7702 event->ws.set_ignore ();
7703 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7704 event->regcache.clear ();
7705 event->core = -1;
7706
7707 switch (buf[0])
7708 {
7709 case 'T': /* Status with PC, SP, FP, ... */
7710 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7711 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7712 ss = signal number
7713 n... = register number
7714 r... = register contents
7715 */
7716
7717 p = &buf[3]; /* after Txx */
7718 while (*p)
7719 {
7720 const char *p1;
7721 int fieldsize;
7722
7723 p1 = strchr (p, ':');
7724 if (p1 == NULL)
7725 error (_("Malformed packet(a) (missing colon): %s\n\
7726 Packet: '%s'\n"),
7727 p, buf);
7728 if (p == p1)
7729 error (_("Malformed packet(a) (missing register number): %s\n\
7730 Packet: '%s'\n"),
7731 p, buf);
7732
7733 /* Some "registers" are actually extended stop information.
7734 Note if you're adding a new entry here: GDB 7.9 and
7735 earlier assume that all register "numbers" that start
7736 with an hex digit are real register numbers. Make sure
7737 the server only sends such a packet if it knows the
7738 client understands it. */
7739
7740 if (strprefix (p, p1, "thread"))
7741 event->ptid = read_ptid (++p1, &p);
7742 else if (strprefix (p, p1, "syscall_entry"))
7743 {
7744 ULONGEST sysno;
7745
7746 p = unpack_varlen_hex (++p1, &sysno);
7747 event->ws.set_syscall_entry ((int) sysno);
7748 }
7749 else if (strprefix (p, p1, "syscall_return"))
7750 {
7751 ULONGEST sysno;
7752
7753 p = unpack_varlen_hex (++p1, &sysno);
7754 event->ws.set_syscall_return ((int) sysno);
7755 }
7756 else if (strprefix (p, p1, "watch")
7757 || strprefix (p, p1, "rwatch")
7758 || strprefix (p, p1, "awatch"))
7759 {
7760 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7761 p = unpack_varlen_hex (++p1, &addr);
7762 event->watch_data_address = (CORE_ADDR) addr;
7763 }
7764 else if (strprefix (p, p1, "swbreak"))
7765 {
7766 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7767
7768 /* Make sure the stub doesn't forget to indicate support
7769 with qSupported. */
7770 if (m_features.packet_support (PACKET_swbreak_feature)
7771 != PACKET_ENABLE)
7772 error (_("Unexpected swbreak stop reason"));
7773
7774 /* The value part is documented as "must be empty",
7775 though we ignore it, in case we ever decide to make
7776 use of it in a backward compatible way. */
7777 p = strchrnul (p1 + 1, ';');
7778 }
7779 else if (strprefix (p, p1, "hwbreak"))
7780 {
7781 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7782
7783 /* Make sure the stub doesn't forget to indicate support
7784 with qSupported. */
7785 if (m_features.packet_support (PACKET_hwbreak_feature)
7786 != PACKET_ENABLE)
7787 error (_("Unexpected hwbreak stop reason"));
7788
7789 /* See above. */
7790 p = strchrnul (p1 + 1, ';');
7791 }
7792 else if (strprefix (p, p1, "library"))
7793 {
7794 event->ws.set_loaded ();
7795 p = strchrnul (p1 + 1, ';');
7796 }
7797 else if (strprefix (p, p1, "replaylog"))
7798 {
7799 event->ws.set_no_history ();
7800 /* p1 will indicate "begin" or "end", but it makes
7801 no difference for now, so ignore it. */
7802 p = strchrnul (p1 + 1, ';');
7803 }
7804 else if (strprefix (p, p1, "core"))
7805 {
7806 ULONGEST c;
7807
7808 p = unpack_varlen_hex (++p1, &c);
7809 event->core = c;
7810 }
7811 else if (strprefix (p, p1, "fork"))
7812 event->ws.set_forked (read_ptid (++p1, &p));
7813 else if (strprefix (p, p1, "vfork"))
7814 event->ws.set_vforked (read_ptid (++p1, &p));
7815 else if (strprefix (p, p1, "vforkdone"))
7816 {
7817 event->ws.set_vfork_done ();
7818 p = strchrnul (p1 + 1, ';');
7819 }
7820 else if (strprefix (p, p1, "exec"))
7821 {
7822 ULONGEST ignored;
7823 int pathlen;
7824
7825 /* Determine the length of the execd pathname. */
7826 p = unpack_varlen_hex (++p1, &ignored);
7827 pathlen = (p - p1) / 2;
7828
7829 /* Save the pathname for event reporting and for
7830 the next run command. */
7831 gdb::unique_xmalloc_ptr<char> pathname
7832 ((char *) xmalloc (pathlen + 1));
7833 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7834 pathname.get ()[pathlen] = '\0';
7835
7836 /* This is freed during event handling. */
7837 event->ws.set_execd (std::move (pathname));
7838
7839 /* Skip the registers included in this packet, since
7840 they may be for an architecture different from the
7841 one used by the original program. */
7842 skipregs = 1;
7843 }
7844 else if (strprefix (p, p1, "create"))
7845 {
7846 event->ws.set_thread_created ();
7847 p = strchrnul (p1 + 1, ';');
7848 }
7849 else
7850 {
7851 ULONGEST pnum;
7852 const char *p_temp;
7853
7854 if (skipregs)
7855 {
7856 p = strchrnul (p1 + 1, ';');
7857 p++;
7858 continue;
7859 }
7860
7861 /* Maybe a real ``P'' register number. */
7862 p_temp = unpack_varlen_hex (p, &pnum);
7863 /* If the first invalid character is the colon, we got a
7864 register number. Otherwise, it's an unknown stop
7865 reason. */
7866 if (p_temp == p1)
7867 {
7868 /* If we haven't parsed the event's thread yet, find
7869 it now, in order to find the architecture of the
7870 reported expedited registers. */
7871 if (event->ptid == null_ptid)
7872 {
7873 /* If there is no thread-id information then leave
7874 the event->ptid as null_ptid. Later in
7875 process_stop_reply we will pick a suitable
7876 thread. */
7877 const char *thr = strstr (p1 + 1, ";thread:");
7878 if (thr != NULL)
7879 event->ptid = read_ptid (thr + strlen (";thread:"),
7880 NULL);
7881 }
7882
7883 if (rsa == NULL)
7884 {
7885 inferior *inf
7886 = (event->ptid == null_ptid
7887 ? NULL
7888 : find_inferior_ptid (this, event->ptid));
7889 /* If this is the first time we learn anything
7890 about this process, skip the registers
7891 included in this packet, since we don't yet
7892 know which architecture to use to parse them.
7893 We'll determine the architecture later when
7894 we process the stop reply and retrieve the
7895 target description, via
7896 remote_notice_new_inferior ->
7897 post_create_inferior. */
7898 if (inf == NULL)
7899 {
7900 p = strchrnul (p1 + 1, ';');
7901 p++;
7902 continue;
7903 }
7904
7905 event->arch = inf->gdbarch;
7906 rsa = event->rs->get_remote_arch_state (event->arch);
7907 }
7908
7909 packet_reg *reg
7910 = packet_reg_from_pnum (event->arch, rsa, pnum);
7911 cached_reg_t cached_reg;
7912
7913 if (reg == NULL)
7914 error (_("Remote sent bad register number %s: %s\n\
7915 Packet: '%s'\n"),
7916 hex_string (pnum), p, buf);
7917
7918 cached_reg.num = reg->regnum;
7919 cached_reg.data = (gdb_byte *)
7920 xmalloc (register_size (event->arch, reg->regnum));
7921
7922 p = p1 + 1;
7923 fieldsize = hex2bin (p, cached_reg.data,
7924 register_size (event->arch, reg->regnum));
7925 p += 2 * fieldsize;
7926 if (fieldsize < register_size (event->arch, reg->regnum))
7927 warning (_("Remote reply is too short: %s"), buf);
7928
7929 event->regcache.push_back (cached_reg);
7930 }
7931 else
7932 {
7933 /* Not a number. Silently skip unknown optional
7934 info. */
7935 p = strchrnul (p1 + 1, ';');
7936 }
7937 }
7938
7939 if (*p != ';')
7940 error (_("Remote register badly formatted: %s\nhere: %s"),
7941 buf, p);
7942 ++p;
7943 }
7944
7945 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7946 break;
7947
7948 /* fall through */
7949 case 'S': /* Old style status, just signal only. */
7950 {
7951 int sig;
7952
7953 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7954 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7955 event->ws.set_stopped ((enum gdb_signal) sig);
7956 else
7957 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7958 }
7959 break;
7960 case 'w': /* Thread exited. */
7961 {
7962 ULONGEST value;
7963
7964 p = unpack_varlen_hex (&buf[1], &value);
7965 event->ws.set_thread_exited (value);
7966 if (*p != ';')
7967 error (_("stop reply packet badly formatted: %s"), buf);
7968 event->ptid = read_ptid (++p, NULL);
7969 break;
7970 }
7971 case 'W': /* Target exited. */
7972 case 'X':
7973 {
7974 ULONGEST value;
7975
7976 /* GDB used to accept only 2 hex chars here. Stubs should
7977 only send more if they detect GDB supports multi-process
7978 support. */
7979 p = unpack_varlen_hex (&buf[1], &value);
7980
7981 if (buf[0] == 'W')
7982 {
7983 /* The remote process exited. */
7984 event->ws.set_exited (value);
7985 }
7986 else
7987 {
7988 /* The remote process exited with a signal. */
7989 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7990 event->ws.set_signalled ((enum gdb_signal) value);
7991 else
7992 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7993 }
7994
7995 /* If no process is specified, return null_ptid, and let the
7996 caller figure out the right process to use. */
7997 int pid = 0;
7998 if (*p == '\0')
7999 ;
8000 else if (*p == ';')
8001 {
8002 p++;
8003
8004 if (*p == '\0')
8005 ;
8006 else if (startswith (p, "process:"))
8007 {
8008 ULONGEST upid;
8009
8010 p += sizeof ("process:") - 1;
8011 unpack_varlen_hex (p, &upid);
8012 pid = upid;
8013 }
8014 else
8015 error (_("unknown stop reply packet: %s"), buf);
8016 }
8017 else
8018 error (_("unknown stop reply packet: %s"), buf);
8019 event->ptid = ptid_t (pid);
8020 }
8021 break;
8022 case 'N':
8023 event->ws.set_no_resumed ();
8024 event->ptid = minus_one_ptid;
8025 break;
8026 }
8027 }
8028
8029 /* When the stub wants to tell GDB about a new notification reply, it
8030 sends a notification (%Stop, for example). Those can come it at
8031 any time, hence, we have to make sure that any pending
8032 putpkt/getpkt sequence we're making is finished, before querying
8033 the stub for more events with the corresponding ack command
8034 (vStopped, for example). E.g., if we started a vStopped sequence
8035 immediately upon receiving the notification, something like this
8036 could happen:
8037
8038 1.1) --> Hg 1
8039 1.2) <-- OK
8040 1.3) --> g
8041 1.4) <-- %Stop
8042 1.5) --> vStopped
8043 1.6) <-- (registers reply to step #1.3)
8044
8045 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8046 query.
8047
8048 To solve this, whenever we parse a %Stop notification successfully,
8049 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8050 doing whatever we were doing:
8051
8052 2.1) --> Hg 1
8053 2.2) <-- OK
8054 2.3) --> g
8055 2.4) <-- %Stop
8056 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8057 2.5) <-- (registers reply to step #2.3)
8058
8059 Eventually after step #2.5, we return to the event loop, which
8060 notices there's an event on the
8061 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8062 associated callback --- the function below. At this point, we're
8063 always safe to start a vStopped sequence. :
8064
8065 2.6) --> vStopped
8066 2.7) <-- T05 thread:2
8067 2.8) --> vStopped
8068 2.9) --> OK
8069 */
8070
8071 void
8072 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8073 {
8074 struct remote_state *rs = get_remote_state ();
8075
8076 if (rs->notif_state->pending_event[nc->id] != NULL)
8077 {
8078 if (notif_debug)
8079 gdb_printf (gdb_stdlog,
8080 "notif: process: '%s' ack pending event\n",
8081 nc->name);
8082
8083 /* acknowledge */
8084 nc->ack (this, nc, rs->buf.data (),
8085 rs->notif_state->pending_event[nc->id]);
8086 rs->notif_state->pending_event[nc->id] = NULL;
8087
8088 while (1)
8089 {
8090 getpkt (&rs->buf, 0);
8091 if (strcmp (rs->buf.data (), "OK") == 0)
8092 break;
8093 else
8094 remote_notif_ack (this, nc, rs->buf.data ());
8095 }
8096 }
8097 else
8098 {
8099 if (notif_debug)
8100 gdb_printf (gdb_stdlog,
8101 "notif: process: '%s' no pending reply\n",
8102 nc->name);
8103 }
8104 }
8105
8106 /* Wrapper around remote_target::remote_notif_get_pending_events to
8107 avoid having to export the whole remote_target class. */
8108
8109 void
8110 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8111 {
8112 remote->remote_notif_get_pending_events (nc);
8113 }
8114
8115 /* Called from process_stop_reply when the stop packet we are responding
8116 to didn't include a process-id or thread-id. STATUS is the stop event
8117 we are responding to.
8118
8119 It is the task of this function to select a suitable thread (or process)
8120 and return its ptid, this is the thread (or process) we will assume the
8121 stop event came from.
8122
8123 In some cases there isn't really any choice about which thread (or
8124 process) is selected, a basic remote with a single process containing a
8125 single thread might choose not to send any process-id or thread-id in
8126 its stop packets, this function will select and return the one and only
8127 thread.
8128
8129 However, if a target supports multiple threads (or processes) and still
8130 doesn't include a thread-id (or process-id) in its stop packet then
8131 first, this is a badly behaving target, and second, we're going to have
8132 to select a thread (or process) at random and use that. This function
8133 will print a warning to the user if it detects that there is the
8134 possibility that GDB is guessing which thread (or process) to
8135 report.
8136
8137 Note that this is called before GDB fetches the updated thread list from the
8138 target. So it's possible for the stop reply to be ambiguous and for GDB to
8139 not realize it. For example, if there's initially one thread, the target
8140 spawns a second thread, and then sends a stop reply without an id that
8141 concerns the first thread. GDB will assume the stop reply is about the
8142 first thread - the only thread it knows about - without printing a warning.
8143 Anyway, if the remote meant for the stop reply to be about the second thread,
8144 then it would be really broken, because GDB doesn't know about that thread
8145 yet. */
8146
8147 ptid_t
8148 remote_target::select_thread_for_ambiguous_stop_reply
8149 (const target_waitstatus &status)
8150 {
8151 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8152
8153 /* Some stop events apply to all threads in an inferior, while others
8154 only apply to a single thread. */
8155 bool process_wide_stop
8156 = (status.kind () == TARGET_WAITKIND_EXITED
8157 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8158
8159 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8160
8161 thread_info *first_resumed_thread = nullptr;
8162 bool ambiguous = false;
8163
8164 /* Consider all non-exited threads of the target, find the first resumed
8165 one. */
8166 for (thread_info *thr : all_non_exited_threads (this))
8167 {
8168 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8169
8170 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8171 continue;
8172
8173 if (first_resumed_thread == nullptr)
8174 first_resumed_thread = thr;
8175 else if (!process_wide_stop
8176 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8177 ambiguous = true;
8178 }
8179
8180 gdb_assert (first_resumed_thread != nullptr);
8181
8182 remote_debug_printf ("first resumed thread is %s",
8183 pid_to_str (first_resumed_thread->ptid).c_str ());
8184 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8185
8186 /* Warn if the remote target is sending ambiguous stop replies. */
8187 if (ambiguous)
8188 {
8189 static bool warned = false;
8190
8191 if (!warned)
8192 {
8193 /* If you are seeing this warning then the remote target has
8194 stopped without specifying a thread-id, but the target
8195 does have multiple threads (or inferiors), and so GDB is
8196 having to guess which thread stopped.
8197
8198 Examples of what might cause this are the target sending
8199 and 'S' stop packet, or a 'T' stop packet and not
8200 including a thread-id.
8201
8202 Additionally, the target might send a 'W' or 'X packet
8203 without including a process-id, when the target has
8204 multiple running inferiors. */
8205 if (process_wide_stop)
8206 warning (_("multi-inferior target stopped without "
8207 "sending a process-id, using first "
8208 "non-exited inferior"));
8209 else
8210 warning (_("multi-threaded target stopped without "
8211 "sending a thread-id, using first "
8212 "non-exited thread"));
8213 warned = true;
8214 }
8215 }
8216
8217 /* If this is a stop for all threads then don't use a particular threads
8218 ptid, instead create a new ptid where only the pid field is set. */
8219 if (process_wide_stop)
8220 return ptid_t (first_resumed_thread->ptid.pid ());
8221 else
8222 return first_resumed_thread->ptid;
8223 }
8224
8225 /* Called when it is decided that STOP_REPLY holds the info of the
8226 event that is to be returned to the core. This function always
8227 destroys STOP_REPLY. */
8228
8229 ptid_t
8230 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8231 struct target_waitstatus *status)
8232 {
8233 *status = stop_reply->ws;
8234 ptid_t ptid = stop_reply->ptid;
8235
8236 /* If no thread/process was reported by the stub then select a suitable
8237 thread/process. */
8238 if (ptid == null_ptid)
8239 ptid = select_thread_for_ambiguous_stop_reply (*status);
8240 gdb_assert (ptid != null_ptid);
8241
8242 if (status->kind () != TARGET_WAITKIND_EXITED
8243 && status->kind () != TARGET_WAITKIND_SIGNALLED
8244 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8245 {
8246 /* Expedited registers. */
8247 if (!stop_reply->regcache.empty ())
8248 {
8249 struct regcache *regcache
8250 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8251
8252 for (cached_reg_t &reg : stop_reply->regcache)
8253 {
8254 regcache->raw_supply (reg.num, reg.data);
8255 xfree (reg.data);
8256 }
8257
8258 stop_reply->regcache.clear ();
8259 }
8260
8261 remote_notice_new_inferior (ptid, false);
8262 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8263 remote_thr->core = stop_reply->core;
8264 remote_thr->stop_reason = stop_reply->stop_reason;
8265 remote_thr->watch_data_address = stop_reply->watch_data_address;
8266
8267 if (target_is_non_stop_p ())
8268 {
8269 /* If the target works in non-stop mode, a stop-reply indicates that
8270 only this thread stopped. */
8271 remote_thr->set_not_resumed ();
8272 }
8273 else
8274 {
8275 /* If the target works in all-stop mode, a stop-reply indicates that
8276 all the target's threads stopped. */
8277 for (thread_info *tp : all_non_exited_threads (this))
8278 get_remote_thread_info (tp)->set_not_resumed ();
8279 }
8280 }
8281
8282 delete stop_reply;
8283 return ptid;
8284 }
8285
8286 /* The non-stop mode version of target_wait. */
8287
8288 ptid_t
8289 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8290 target_wait_flags options)
8291 {
8292 struct remote_state *rs = get_remote_state ();
8293 struct stop_reply *stop_reply;
8294 int ret;
8295 int is_notif = 0;
8296
8297 /* If in non-stop mode, get out of getpkt even if a
8298 notification is received. */
8299
8300 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8301 while (1)
8302 {
8303 if (ret != -1 && !is_notif)
8304 switch (rs->buf[0])
8305 {
8306 case 'E': /* Error of some sort. */
8307 /* We're out of sync with the target now. Did it continue
8308 or not? We can't tell which thread it was in non-stop,
8309 so just ignore this. */
8310 warning (_("Remote failure reply: %s"), rs->buf.data ());
8311 break;
8312 case 'O': /* Console output. */
8313 remote_console_output (&rs->buf[1]);
8314 break;
8315 default:
8316 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8317 break;
8318 }
8319
8320 /* Acknowledge a pending stop reply that may have arrived in the
8321 mean time. */
8322 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8323 remote_notif_get_pending_events (&notif_client_stop);
8324
8325 /* If indeed we noticed a stop reply, we're done. */
8326 stop_reply = queued_stop_reply (ptid);
8327 if (stop_reply != NULL)
8328 return process_stop_reply (stop_reply, status);
8329
8330 /* Still no event. If we're just polling for an event, then
8331 return to the event loop. */
8332 if (options & TARGET_WNOHANG)
8333 {
8334 status->set_ignore ();
8335 return minus_one_ptid;
8336 }
8337
8338 /* Otherwise do a blocking wait. */
8339 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8340 }
8341 }
8342
8343 /* Return the first resumed thread. */
8344
8345 static ptid_t
8346 first_remote_resumed_thread (remote_target *target)
8347 {
8348 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8349 if (tp->resumed ())
8350 return tp->ptid;
8351 return null_ptid;
8352 }
8353
8354 /* Wait until the remote machine stops, then return, storing status in
8355 STATUS just as `wait' would. */
8356
8357 ptid_t
8358 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8359 target_wait_flags options)
8360 {
8361 struct remote_state *rs = get_remote_state ();
8362 ptid_t event_ptid = null_ptid;
8363 char *buf;
8364 struct stop_reply *stop_reply;
8365
8366 again:
8367
8368 status->set_ignore ();
8369
8370 stop_reply = queued_stop_reply (ptid);
8371 if (stop_reply != NULL)
8372 {
8373 /* None of the paths that push a stop reply onto the queue should
8374 have set the waiting_for_stop_reply flag. */
8375 gdb_assert (!rs->waiting_for_stop_reply);
8376 event_ptid = process_stop_reply (stop_reply, status);
8377 }
8378 else
8379 {
8380 int forever = ((options & TARGET_WNOHANG) == 0
8381 && rs->wait_forever_enabled_p);
8382
8383 if (!rs->waiting_for_stop_reply)
8384 {
8385 status->set_no_resumed ();
8386 return minus_one_ptid;
8387 }
8388
8389 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8390 _never_ wait for ever -> test on target_is_async_p().
8391 However, before we do that we need to ensure that the caller
8392 knows how to take the target into/out of async mode. */
8393 int is_notif;
8394 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8395
8396 /* GDB gets a notification. Return to core as this event is
8397 not interesting. */
8398 if (ret != -1 && is_notif)
8399 return minus_one_ptid;
8400
8401 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8402 return minus_one_ptid;
8403
8404 buf = rs->buf.data ();
8405
8406 /* Assume that the target has acknowledged Ctrl-C unless we receive
8407 an 'F' or 'O' packet. */
8408 if (buf[0] != 'F' && buf[0] != 'O')
8409 rs->ctrlc_pending_p = 0;
8410
8411 switch (buf[0])
8412 {
8413 case 'E': /* Error of some sort. */
8414 /* We're out of sync with the target now. Did it continue or
8415 not? Not is more likely, so report a stop. */
8416 rs->waiting_for_stop_reply = 0;
8417
8418 warning (_("Remote failure reply: %s"), buf);
8419 status->set_stopped (GDB_SIGNAL_0);
8420 break;
8421 case 'F': /* File-I/O request. */
8422 /* GDB may access the inferior memory while handling the File-I/O
8423 request, but we don't want GDB accessing memory while waiting
8424 for a stop reply. See the comments in putpkt_binary. Set
8425 waiting_for_stop_reply to 0 temporarily. */
8426 rs->waiting_for_stop_reply = 0;
8427 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8428 rs->ctrlc_pending_p = 0;
8429 /* GDB handled the File-I/O request, and the target is running
8430 again. Keep waiting for events. */
8431 rs->waiting_for_stop_reply = 1;
8432 break;
8433 case 'N': case 'T': case 'S': case 'X': case 'W':
8434 {
8435 /* There is a stop reply to handle. */
8436 rs->waiting_for_stop_reply = 0;
8437
8438 stop_reply
8439 = (struct stop_reply *) remote_notif_parse (this,
8440 &notif_client_stop,
8441 rs->buf.data ());
8442
8443 event_ptid = process_stop_reply (stop_reply, status);
8444 break;
8445 }
8446 case 'O': /* Console output. */
8447 remote_console_output (buf + 1);
8448 break;
8449 case '\0':
8450 if (rs->last_sent_signal != GDB_SIGNAL_0)
8451 {
8452 /* Zero length reply means that we tried 'S' or 'C' and the
8453 remote system doesn't support it. */
8454 target_terminal::ours_for_output ();
8455 gdb_printf
8456 ("Can't send signals to this remote system. %s not sent.\n",
8457 gdb_signal_to_name (rs->last_sent_signal));
8458 rs->last_sent_signal = GDB_SIGNAL_0;
8459 target_terminal::inferior ();
8460
8461 strcpy (buf, rs->last_sent_step ? "s" : "c");
8462 putpkt (buf);
8463 break;
8464 }
8465 /* fallthrough */
8466 default:
8467 warning (_("Invalid remote reply: %s"), buf);
8468 break;
8469 }
8470 }
8471
8472 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8473 return minus_one_ptid;
8474 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8475 {
8476 /* Nothing interesting happened. If we're doing a non-blocking
8477 poll, we're done. Otherwise, go back to waiting. */
8478 if (options & TARGET_WNOHANG)
8479 return minus_one_ptid;
8480 else
8481 goto again;
8482 }
8483 else if (status->kind () != TARGET_WAITKIND_EXITED
8484 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8485 {
8486 if (event_ptid != null_ptid)
8487 record_currthread (rs, event_ptid);
8488 else
8489 event_ptid = first_remote_resumed_thread (this);
8490 }
8491 else
8492 {
8493 /* A process exit. Invalidate our notion of current thread. */
8494 record_currthread (rs, minus_one_ptid);
8495 /* It's possible that the packet did not include a pid. */
8496 if (event_ptid == null_ptid)
8497 event_ptid = first_remote_resumed_thread (this);
8498 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8499 if (event_ptid == null_ptid)
8500 event_ptid = magic_null_ptid;
8501 }
8502
8503 return event_ptid;
8504 }
8505
8506 /* Wait until the remote machine stops, then return, storing status in
8507 STATUS just as `wait' would. */
8508
8509 ptid_t
8510 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8511 target_wait_flags options)
8512 {
8513 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8514
8515 remote_state *rs = get_remote_state ();
8516
8517 /* Start by clearing the flag that asks for our wait method to be called,
8518 we'll mark it again at the end if needed. If the target is not in
8519 async mode then the async token should not be marked. */
8520 if (target_is_async_p ())
8521 clear_async_event_handler (rs->remote_async_inferior_event_token);
8522 else
8523 gdb_assert (!async_event_handler_marked
8524 (rs->remote_async_inferior_event_token));
8525
8526 ptid_t event_ptid;
8527
8528 if (target_is_non_stop_p ())
8529 event_ptid = wait_ns (ptid, status, options);
8530 else
8531 event_ptid = wait_as (ptid, status, options);
8532
8533 if (target_is_async_p ())
8534 {
8535 /* If there are events left in the queue, or unacknowledged
8536 notifications, then tell the event loop to call us again. */
8537 if (!rs->stop_reply_queue.empty ()
8538 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8539 mark_async_event_handler (rs->remote_async_inferior_event_token);
8540 }
8541
8542 return event_ptid;
8543 }
8544
8545 /* Fetch a single register using a 'p' packet. */
8546
8547 int
8548 remote_target::fetch_register_using_p (struct regcache *regcache,
8549 packet_reg *reg)
8550 {
8551 struct gdbarch *gdbarch = regcache->arch ();
8552 struct remote_state *rs = get_remote_state ();
8553 char *buf, *p;
8554 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8555 int i;
8556
8557 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8558 return 0;
8559
8560 if (reg->pnum == -1)
8561 return 0;
8562
8563 p = rs->buf.data ();
8564 *p++ = 'p';
8565 p += hexnumstr (p, reg->pnum);
8566 *p++ = '\0';
8567 putpkt (rs->buf);
8568 getpkt (&rs->buf, 0);
8569
8570 buf = rs->buf.data ();
8571
8572 switch (m_features.packet_ok (rs->buf, PACKET_p))
8573 {
8574 case PACKET_OK:
8575 break;
8576 case PACKET_UNKNOWN:
8577 return 0;
8578 case PACKET_ERROR:
8579 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8580 gdbarch_register_name (regcache->arch (),
8581 reg->regnum),
8582 buf);
8583 }
8584
8585 /* If this register is unfetchable, tell the regcache. */
8586 if (buf[0] == 'x')
8587 {
8588 regcache->raw_supply (reg->regnum, NULL);
8589 return 1;
8590 }
8591
8592 /* Otherwise, parse and supply the value. */
8593 p = buf;
8594 i = 0;
8595 while (p[0] != 0)
8596 {
8597 if (p[1] == 0)
8598 error (_("fetch_register_using_p: early buf termination"));
8599
8600 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8601 p += 2;
8602 }
8603 regcache->raw_supply (reg->regnum, regp);
8604 return 1;
8605 }
8606
8607 /* Fetch the registers included in the target's 'g' packet. */
8608
8609 int
8610 remote_target::send_g_packet ()
8611 {
8612 struct remote_state *rs = get_remote_state ();
8613 int buf_len;
8614
8615 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8616 putpkt (rs->buf);
8617 getpkt (&rs->buf, 0);
8618 if (packet_check_result (rs->buf) == PACKET_ERROR)
8619 error (_("Could not read registers; remote failure reply '%s'"),
8620 rs->buf.data ());
8621
8622 /* We can get out of synch in various cases. If the first character
8623 in the buffer is not a hex character, assume that has happened
8624 and try to fetch another packet to read. */
8625 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8626 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8627 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8628 && rs->buf[0] != 'x') /* New: unavailable register value. */
8629 {
8630 remote_debug_printf ("Bad register packet; fetching a new packet");
8631 getpkt (&rs->buf, 0);
8632 }
8633
8634 buf_len = strlen (rs->buf.data ());
8635
8636 /* Sanity check the received packet. */
8637 if (buf_len % 2 != 0)
8638 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8639
8640 return buf_len / 2;
8641 }
8642
8643 void
8644 remote_target::process_g_packet (struct regcache *regcache)
8645 {
8646 struct gdbarch *gdbarch = regcache->arch ();
8647 struct remote_state *rs = get_remote_state ();
8648 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8649 int i, buf_len;
8650 char *p;
8651 char *regs;
8652
8653 buf_len = strlen (rs->buf.data ());
8654
8655 /* Further sanity checks, with knowledge of the architecture. */
8656 if (buf_len > 2 * rsa->sizeof_g_packet)
8657 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8658 "bytes): %s"),
8659 rsa->sizeof_g_packet, buf_len / 2,
8660 rs->buf.data ());
8661
8662 /* Save the size of the packet sent to us by the target. It is used
8663 as a heuristic when determining the max size of packets that the
8664 target can safely receive. */
8665 if (rsa->actual_register_packet_size == 0)
8666 rsa->actual_register_packet_size = buf_len;
8667
8668 /* If this is smaller than we guessed the 'g' packet would be,
8669 update our records. A 'g' reply that doesn't include a register's
8670 value implies either that the register is not available, or that
8671 the 'p' packet must be used. */
8672 if (buf_len < 2 * rsa->sizeof_g_packet)
8673 {
8674 long sizeof_g_packet = buf_len / 2;
8675
8676 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8677 {
8678 long offset = rsa->regs[i].offset;
8679 long reg_size = register_size (gdbarch, i);
8680
8681 if (rsa->regs[i].pnum == -1)
8682 continue;
8683
8684 if (offset >= sizeof_g_packet)
8685 rsa->regs[i].in_g_packet = 0;
8686 else if (offset + reg_size > sizeof_g_packet)
8687 error (_("Truncated register %d in remote 'g' packet"), i);
8688 else
8689 rsa->regs[i].in_g_packet = 1;
8690 }
8691
8692 /* Looks valid enough, we can assume this is the correct length
8693 for a 'g' packet. It's important not to adjust
8694 rsa->sizeof_g_packet if we have truncated registers otherwise
8695 this "if" won't be run the next time the method is called
8696 with a packet of the same size and one of the internal errors
8697 below will trigger instead. */
8698 rsa->sizeof_g_packet = sizeof_g_packet;
8699 }
8700
8701 regs = (char *) alloca (rsa->sizeof_g_packet);
8702
8703 /* Unimplemented registers read as all bits zero. */
8704 memset (regs, 0, rsa->sizeof_g_packet);
8705
8706 /* Reply describes registers byte by byte, each byte encoded as two
8707 hex characters. Suck them all up, then supply them to the
8708 register cacheing/storage mechanism. */
8709
8710 p = rs->buf.data ();
8711 for (i = 0; i < rsa->sizeof_g_packet; i++)
8712 {
8713 if (p[0] == 0 || p[1] == 0)
8714 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8715 internal_error (_("unexpected end of 'g' packet reply"));
8716
8717 if (p[0] == 'x' && p[1] == 'x')
8718 regs[i] = 0; /* 'x' */
8719 else
8720 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8721 p += 2;
8722 }
8723
8724 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8725 {
8726 struct packet_reg *r = &rsa->regs[i];
8727 long reg_size = register_size (gdbarch, i);
8728
8729 if (r->in_g_packet)
8730 {
8731 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8732 /* This shouldn't happen - we adjusted in_g_packet above. */
8733 internal_error (_("unexpected end of 'g' packet reply"));
8734 else if (rs->buf[r->offset * 2] == 'x')
8735 {
8736 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8737 /* The register isn't available, mark it as such (at
8738 the same time setting the value to zero). */
8739 regcache->raw_supply (r->regnum, NULL);
8740 }
8741 else
8742 regcache->raw_supply (r->regnum, regs + r->offset);
8743 }
8744 }
8745 }
8746
8747 void
8748 remote_target::fetch_registers_using_g (struct regcache *regcache)
8749 {
8750 send_g_packet ();
8751 process_g_packet (regcache);
8752 }
8753
8754 /* Make the remote selected traceframe match GDB's selected
8755 traceframe. */
8756
8757 void
8758 remote_target::set_remote_traceframe ()
8759 {
8760 int newnum;
8761 struct remote_state *rs = get_remote_state ();
8762
8763 if (rs->remote_traceframe_number == get_traceframe_number ())
8764 return;
8765
8766 /* Avoid recursion, remote_trace_find calls us again. */
8767 rs->remote_traceframe_number = get_traceframe_number ();
8768
8769 newnum = target_trace_find (tfind_number,
8770 get_traceframe_number (), 0, 0, NULL);
8771
8772 /* Should not happen. If it does, all bets are off. */
8773 if (newnum != get_traceframe_number ())
8774 warning (_("could not set remote traceframe"));
8775 }
8776
8777 void
8778 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8779 {
8780 struct gdbarch *gdbarch = regcache->arch ();
8781 struct remote_state *rs = get_remote_state ();
8782 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8783 int i;
8784
8785 set_remote_traceframe ();
8786 set_general_thread (regcache->ptid ());
8787
8788 if (regnum >= 0)
8789 {
8790 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8791
8792 gdb_assert (reg != NULL);
8793
8794 /* If this register might be in the 'g' packet, try that first -
8795 we are likely to read more than one register. If this is the
8796 first 'g' packet, we might be overly optimistic about its
8797 contents, so fall back to 'p'. */
8798 if (reg->in_g_packet)
8799 {
8800 fetch_registers_using_g (regcache);
8801 if (reg->in_g_packet)
8802 return;
8803 }
8804
8805 if (fetch_register_using_p (regcache, reg))
8806 return;
8807
8808 /* This register is not available. */
8809 regcache->raw_supply (reg->regnum, NULL);
8810
8811 return;
8812 }
8813
8814 fetch_registers_using_g (regcache);
8815
8816 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8817 if (!rsa->regs[i].in_g_packet)
8818 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8819 {
8820 /* This register is not available. */
8821 regcache->raw_supply (i, NULL);
8822 }
8823 }
8824
8825 /* Prepare to store registers. Since we may send them all (using a
8826 'G' request), we have to read out the ones we don't want to change
8827 first. */
8828
8829 void
8830 remote_target::prepare_to_store (struct regcache *regcache)
8831 {
8832 struct remote_state *rs = get_remote_state ();
8833 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8834 int i;
8835
8836 /* Make sure the entire registers array is valid. */
8837 switch (m_features.packet_support (PACKET_P))
8838 {
8839 case PACKET_DISABLE:
8840 case PACKET_SUPPORT_UNKNOWN:
8841 /* Make sure all the necessary registers are cached. */
8842 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8843 if (rsa->regs[i].in_g_packet)
8844 regcache->raw_update (rsa->regs[i].regnum);
8845 break;
8846 case PACKET_ENABLE:
8847 break;
8848 }
8849 }
8850
8851 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8852 packet was not recognized. */
8853
8854 int
8855 remote_target::store_register_using_P (const struct regcache *regcache,
8856 packet_reg *reg)
8857 {
8858 struct gdbarch *gdbarch = regcache->arch ();
8859 struct remote_state *rs = get_remote_state ();
8860 /* Try storing a single register. */
8861 char *buf = rs->buf.data ();
8862 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8863 char *p;
8864
8865 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8866 return 0;
8867
8868 if (reg->pnum == -1)
8869 return 0;
8870
8871 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8872 p = buf + strlen (buf);
8873 regcache->raw_collect (reg->regnum, regp);
8874 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8875 putpkt (rs->buf);
8876 getpkt (&rs->buf, 0);
8877
8878 switch (m_features.packet_ok (rs->buf, PACKET_P))
8879 {
8880 case PACKET_OK:
8881 return 1;
8882 case PACKET_ERROR:
8883 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8884 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8885 case PACKET_UNKNOWN:
8886 return 0;
8887 default:
8888 internal_error (_("Bad result from packet_ok"));
8889 }
8890 }
8891
8892 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8893 contents of the register cache buffer. FIXME: ignores errors. */
8894
8895 void
8896 remote_target::store_registers_using_G (const struct regcache *regcache)
8897 {
8898 struct remote_state *rs = get_remote_state ();
8899 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8900 gdb_byte *regs;
8901 char *p;
8902
8903 /* Extract all the registers in the regcache copying them into a
8904 local buffer. */
8905 {
8906 int i;
8907
8908 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8909 memset (regs, 0, rsa->sizeof_g_packet);
8910 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8911 {
8912 struct packet_reg *r = &rsa->regs[i];
8913
8914 if (r->in_g_packet)
8915 regcache->raw_collect (r->regnum, regs + r->offset);
8916 }
8917 }
8918
8919 /* Command describes registers byte by byte,
8920 each byte encoded as two hex characters. */
8921 p = rs->buf.data ();
8922 *p++ = 'G';
8923 bin2hex (regs, p, rsa->sizeof_g_packet);
8924 putpkt (rs->buf);
8925 getpkt (&rs->buf, 0);
8926 if (packet_check_result (rs->buf) == PACKET_ERROR)
8927 error (_("Could not write registers; remote failure reply '%s'"),
8928 rs->buf.data ());
8929 }
8930
8931 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8932 of the register cache buffer. FIXME: ignores errors. */
8933
8934 void
8935 remote_target::store_registers (struct regcache *regcache, int regnum)
8936 {
8937 struct gdbarch *gdbarch = regcache->arch ();
8938 struct remote_state *rs = get_remote_state ();
8939 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8940 int i;
8941
8942 set_remote_traceframe ();
8943 set_general_thread (regcache->ptid ());
8944
8945 if (regnum >= 0)
8946 {
8947 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8948
8949 gdb_assert (reg != NULL);
8950
8951 /* Always prefer to store registers using the 'P' packet if
8952 possible; we often change only a small number of registers.
8953 Sometimes we change a larger number; we'd need help from a
8954 higher layer to know to use 'G'. */
8955 if (store_register_using_P (regcache, reg))
8956 return;
8957
8958 /* For now, don't complain if we have no way to write the
8959 register. GDB loses track of unavailable registers too
8960 easily. Some day, this may be an error. We don't have
8961 any way to read the register, either... */
8962 if (!reg->in_g_packet)
8963 return;
8964
8965 store_registers_using_G (regcache);
8966 return;
8967 }
8968
8969 store_registers_using_G (regcache);
8970
8971 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8972 if (!rsa->regs[i].in_g_packet)
8973 if (!store_register_using_P (regcache, &rsa->regs[i]))
8974 /* See above for why we do not issue an error here. */
8975 continue;
8976 }
8977 \f
8978
8979 /* Return the number of hex digits in num. */
8980
8981 static int
8982 hexnumlen (ULONGEST num)
8983 {
8984 int i;
8985
8986 for (i = 0; num != 0; i++)
8987 num >>= 4;
8988
8989 return std::max (i, 1);
8990 }
8991
8992 /* Set BUF to the minimum number of hex digits representing NUM. */
8993
8994 static int
8995 hexnumstr (char *buf, ULONGEST num)
8996 {
8997 int len = hexnumlen (num);
8998
8999 return hexnumnstr (buf, num, len);
9000 }
9001
9002
9003 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9004
9005 static int
9006 hexnumnstr (char *buf, ULONGEST num, int width)
9007 {
9008 int i;
9009
9010 buf[width] = '\0';
9011
9012 for (i = width - 1; i >= 0; i--)
9013 {
9014 buf[i] = "0123456789abcdef"[(num & 0xf)];
9015 num >>= 4;
9016 }
9017
9018 return width;
9019 }
9020
9021 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9022
9023 static CORE_ADDR
9024 remote_address_masked (CORE_ADDR addr)
9025 {
9026 unsigned int address_size = remote_address_size;
9027
9028 /* If "remoteaddresssize" was not set, default to target address size. */
9029 if (!address_size)
9030 address_size = gdbarch_addr_bit (target_gdbarch ());
9031
9032 if (address_size > 0
9033 && address_size < (sizeof (ULONGEST) * 8))
9034 {
9035 /* Only create a mask when that mask can safely be constructed
9036 in a ULONGEST variable. */
9037 ULONGEST mask = 1;
9038
9039 mask = (mask << address_size) - 1;
9040 addr &= mask;
9041 }
9042 return addr;
9043 }
9044
9045 /* Determine whether the remote target supports binary downloading.
9046 This is accomplished by sending a no-op memory write of zero length
9047 to the target at the specified address. It does not suffice to send
9048 the whole packet, since many stubs strip the eighth bit and
9049 subsequently compute a wrong checksum, which causes real havoc with
9050 remote_write_bytes.
9051
9052 NOTE: This can still lose if the serial line is not eight-bit
9053 clean. In cases like this, the user should clear "remote
9054 X-packet". */
9055
9056 void
9057 remote_target::check_binary_download (CORE_ADDR addr)
9058 {
9059 struct remote_state *rs = get_remote_state ();
9060
9061 switch (m_features.packet_support (PACKET_X))
9062 {
9063 case PACKET_DISABLE:
9064 break;
9065 case PACKET_ENABLE:
9066 break;
9067 case PACKET_SUPPORT_UNKNOWN:
9068 {
9069 char *p;
9070
9071 p = rs->buf.data ();
9072 *p++ = 'X';
9073 p += hexnumstr (p, (ULONGEST) addr);
9074 *p++ = ',';
9075 p += hexnumstr (p, (ULONGEST) 0);
9076 *p++ = ':';
9077 *p = '\0';
9078
9079 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9080 getpkt (&rs->buf, 0);
9081
9082 if (rs->buf[0] == '\0')
9083 {
9084 remote_debug_printf ("binary downloading NOT supported by target");
9085 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9086 }
9087 else
9088 {
9089 remote_debug_printf ("binary downloading supported by target");
9090 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9091 }
9092 break;
9093 }
9094 }
9095 }
9096
9097 /* Helper function to resize the payload in order to try to get a good
9098 alignment. We try to write an amount of data such that the next write will
9099 start on an address aligned on REMOTE_ALIGN_WRITES. */
9100
9101 static int
9102 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9103 {
9104 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9105 }
9106
9107 /* Write memory data directly to the remote machine.
9108 This does not inform the data cache; the data cache uses this.
9109 HEADER is the starting part of the packet.
9110 MEMADDR is the address in the remote memory space.
9111 MYADDR is the address of the buffer in our space.
9112 LEN_UNITS is the number of addressable units to write.
9113 UNIT_SIZE is the length in bytes of an addressable unit.
9114 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9115 should send data as binary ('X'), or hex-encoded ('M').
9116
9117 The function creates packet of the form
9118 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9119
9120 where encoding of <DATA> is terminated by PACKET_FORMAT.
9121
9122 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9123 are omitted.
9124
9125 Return the transferred status, error or OK (an
9126 'enum target_xfer_status' value). Save the number of addressable units
9127 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9128
9129 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9130 exchange between gdb and the stub could look like (?? in place of the
9131 checksum):
9132
9133 -> $m1000,4#??
9134 <- aaaabbbbccccdddd
9135
9136 -> $M1000,3:eeeeffffeeee#??
9137 <- OK
9138
9139 -> $m1000,4#??
9140 <- eeeeffffeeeedddd */
9141
9142 target_xfer_status
9143 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9144 const gdb_byte *myaddr,
9145 ULONGEST len_units,
9146 int unit_size,
9147 ULONGEST *xfered_len_units,
9148 char packet_format, int use_length)
9149 {
9150 struct remote_state *rs = get_remote_state ();
9151 char *p;
9152 char *plen = NULL;
9153 int plenlen = 0;
9154 int todo_units;
9155 int units_written;
9156 int payload_capacity_bytes;
9157 int payload_length_bytes;
9158
9159 if (packet_format != 'X' && packet_format != 'M')
9160 internal_error (_("remote_write_bytes_aux: bad packet format"));
9161
9162 if (len_units == 0)
9163 return TARGET_XFER_EOF;
9164
9165 payload_capacity_bytes = get_memory_write_packet_size ();
9166
9167 /* The packet buffer will be large enough for the payload;
9168 get_memory_packet_size ensures this. */
9169 rs->buf[0] = '\0';
9170
9171 /* Compute the size of the actual payload by subtracting out the
9172 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9173
9174 payload_capacity_bytes -= strlen ("$,:#NN");
9175 if (!use_length)
9176 /* The comma won't be used. */
9177 payload_capacity_bytes += 1;
9178 payload_capacity_bytes -= strlen (header);
9179 payload_capacity_bytes -= hexnumlen (memaddr);
9180
9181 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9182
9183 strcat (rs->buf.data (), header);
9184 p = rs->buf.data () + strlen (header);
9185
9186 /* Compute a best guess of the number of bytes actually transfered. */
9187 if (packet_format == 'X')
9188 {
9189 /* Best guess at number of bytes that will fit. */
9190 todo_units = std::min (len_units,
9191 (ULONGEST) payload_capacity_bytes / unit_size);
9192 if (use_length)
9193 payload_capacity_bytes -= hexnumlen (todo_units);
9194 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9195 }
9196 else
9197 {
9198 /* Number of bytes that will fit. */
9199 todo_units
9200 = std::min (len_units,
9201 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9202 if (use_length)
9203 payload_capacity_bytes -= hexnumlen (todo_units);
9204 todo_units = std::min (todo_units,
9205 (payload_capacity_bytes / unit_size) / 2);
9206 }
9207
9208 if (todo_units <= 0)
9209 internal_error (_("minimum packet size too small to write data"));
9210
9211 /* If we already need another packet, then try to align the end
9212 of this packet to a useful boundary. */
9213 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9214 todo_units = align_for_efficient_write (todo_units, memaddr);
9215
9216 /* Append "<memaddr>". */
9217 memaddr = remote_address_masked (memaddr);
9218 p += hexnumstr (p, (ULONGEST) memaddr);
9219
9220 if (use_length)
9221 {
9222 /* Append ",". */
9223 *p++ = ',';
9224
9225 /* Append the length and retain its location and size. It may need to be
9226 adjusted once the packet body has been created. */
9227 plen = p;
9228 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9229 p += plenlen;
9230 }
9231
9232 /* Append ":". */
9233 *p++ = ':';
9234 *p = '\0';
9235
9236 /* Append the packet body. */
9237 if (packet_format == 'X')
9238 {
9239 /* Binary mode. Send target system values byte by byte, in
9240 increasing byte addresses. Only escape certain critical
9241 characters. */
9242 payload_length_bytes =
9243 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9244 &units_written, payload_capacity_bytes);
9245
9246 /* If not all TODO units fit, then we'll need another packet. Make
9247 a second try to keep the end of the packet aligned. Don't do
9248 this if the packet is tiny. */
9249 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9250 {
9251 int new_todo_units;
9252
9253 new_todo_units = align_for_efficient_write (units_written, memaddr);
9254
9255 if (new_todo_units != units_written)
9256 payload_length_bytes =
9257 remote_escape_output (myaddr, new_todo_units, unit_size,
9258 (gdb_byte *) p, &units_written,
9259 payload_capacity_bytes);
9260 }
9261
9262 p += payload_length_bytes;
9263 if (use_length && units_written < todo_units)
9264 {
9265 /* Escape chars have filled up the buffer prematurely,
9266 and we have actually sent fewer units than planned.
9267 Fix-up the length field of the packet. Use the same
9268 number of characters as before. */
9269 plen += hexnumnstr (plen, (ULONGEST) units_written,
9270 plenlen);
9271 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9272 }
9273 }
9274 else
9275 {
9276 /* Normal mode: Send target system values byte by byte, in
9277 increasing byte addresses. Each byte is encoded as a two hex
9278 value. */
9279 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9280 units_written = todo_units;
9281 }
9282
9283 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9284 getpkt (&rs->buf, 0);
9285
9286 if (rs->buf[0] == 'E')
9287 return TARGET_XFER_E_IO;
9288
9289 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9290 send fewer units than we'd planned. */
9291 *xfered_len_units = (ULONGEST) units_written;
9292 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9293 }
9294
9295 /* Write memory data directly to the remote machine.
9296 This does not inform the data cache; the data cache uses this.
9297 MEMADDR is the address in the remote memory space.
9298 MYADDR is the address of the buffer in our space.
9299 LEN is the number of bytes.
9300
9301 Return the transferred status, error or OK (an
9302 'enum target_xfer_status' value). Save the number of bytes
9303 transferred in *XFERED_LEN. Only transfer a single packet. */
9304
9305 target_xfer_status
9306 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9307 ULONGEST len, int unit_size,
9308 ULONGEST *xfered_len)
9309 {
9310 const char *packet_format = NULL;
9311
9312 /* Check whether the target supports binary download. */
9313 check_binary_download (memaddr);
9314
9315 switch (m_features.packet_support (PACKET_X))
9316 {
9317 case PACKET_ENABLE:
9318 packet_format = "X";
9319 break;
9320 case PACKET_DISABLE:
9321 packet_format = "M";
9322 break;
9323 case PACKET_SUPPORT_UNKNOWN:
9324 internal_error (_("remote_write_bytes: bad internal state"));
9325 default:
9326 internal_error (_("bad switch"));
9327 }
9328
9329 return remote_write_bytes_aux (packet_format,
9330 memaddr, myaddr, len, unit_size, xfered_len,
9331 packet_format[0], 1);
9332 }
9333
9334 /* Read memory data directly from the remote machine.
9335 This does not use the data cache; the data cache uses this.
9336 MEMADDR is the address in the remote memory space.
9337 MYADDR is the address of the buffer in our space.
9338 LEN_UNITS is the number of addressable memory units to read..
9339 UNIT_SIZE is the length in bytes of an addressable unit.
9340
9341 Return the transferred status, error or OK (an
9342 'enum target_xfer_status' value). Save the number of bytes
9343 transferred in *XFERED_LEN_UNITS.
9344
9345 See the comment of remote_write_bytes_aux for an example of
9346 memory read/write exchange between gdb and the stub. */
9347
9348 target_xfer_status
9349 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9350 ULONGEST len_units,
9351 int unit_size, ULONGEST *xfered_len_units)
9352 {
9353 struct remote_state *rs = get_remote_state ();
9354 int buf_size_bytes; /* Max size of packet output buffer. */
9355 char *p;
9356 int todo_units;
9357 int decoded_bytes;
9358
9359 buf_size_bytes = get_memory_read_packet_size ();
9360 /* The packet buffer will be large enough for the payload;
9361 get_memory_packet_size ensures this. */
9362
9363 /* Number of units that will fit. */
9364 todo_units = std::min (len_units,
9365 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9366
9367 /* Construct "m"<memaddr>","<len>". */
9368 memaddr = remote_address_masked (memaddr);
9369 p = rs->buf.data ();
9370 *p++ = 'm';
9371 p += hexnumstr (p, (ULONGEST) memaddr);
9372 *p++ = ',';
9373 p += hexnumstr (p, (ULONGEST) todo_units);
9374 *p = '\0';
9375 putpkt (rs->buf);
9376 getpkt (&rs->buf, 0);
9377 if (rs->buf[0] == 'E'
9378 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9379 && rs->buf[3] == '\0')
9380 return TARGET_XFER_E_IO;
9381 /* Reply describes memory byte by byte, each byte encoded as two hex
9382 characters. */
9383 p = rs->buf.data ();
9384 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9385 /* Return what we have. Let higher layers handle partial reads. */
9386 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9387 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9388 }
9389
9390 /* Using the set of read-only target sections of remote, read live
9391 read-only memory.
9392
9393 For interface/parameters/return description see target.h,
9394 to_xfer_partial. */
9395
9396 target_xfer_status
9397 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9398 ULONGEST memaddr,
9399 ULONGEST len,
9400 int unit_size,
9401 ULONGEST *xfered_len)
9402 {
9403 const struct target_section *secp;
9404
9405 secp = target_section_by_addr (this, memaddr);
9406 if (secp != NULL
9407 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9408 {
9409 ULONGEST memend = memaddr + len;
9410
9411 const target_section_table *table = target_get_section_table (this);
9412 for (const target_section &p : *table)
9413 {
9414 if (memaddr >= p.addr)
9415 {
9416 if (memend <= p.endaddr)
9417 {
9418 /* Entire transfer is within this section. */
9419 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9420 xfered_len);
9421 }
9422 else if (memaddr >= p.endaddr)
9423 {
9424 /* This section ends before the transfer starts. */
9425 continue;
9426 }
9427 else
9428 {
9429 /* This section overlaps the transfer. Just do half. */
9430 len = p.endaddr - memaddr;
9431 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9432 xfered_len);
9433 }
9434 }
9435 }
9436 }
9437
9438 return TARGET_XFER_EOF;
9439 }
9440
9441 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9442 first if the requested memory is unavailable in traceframe.
9443 Otherwise, fall back to remote_read_bytes_1. */
9444
9445 target_xfer_status
9446 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9447 gdb_byte *myaddr, ULONGEST len, int unit_size,
9448 ULONGEST *xfered_len)
9449 {
9450 if (len == 0)
9451 return TARGET_XFER_EOF;
9452
9453 if (get_traceframe_number () != -1)
9454 {
9455 std::vector<mem_range> available;
9456
9457 /* If we fail to get the set of available memory, then the
9458 target does not support querying traceframe info, and so we
9459 attempt reading from the traceframe anyway (assuming the
9460 target implements the old QTro packet then). */
9461 if (traceframe_available_memory (&available, memaddr, len))
9462 {
9463 if (available.empty () || available[0].start != memaddr)
9464 {
9465 enum target_xfer_status res;
9466
9467 /* Don't read into the traceframe's available
9468 memory. */
9469 if (!available.empty ())
9470 {
9471 LONGEST oldlen = len;
9472
9473 len = available[0].start - memaddr;
9474 gdb_assert (len <= oldlen);
9475 }
9476
9477 /* This goes through the topmost target again. */
9478 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9479 len, unit_size, xfered_len);
9480 if (res == TARGET_XFER_OK)
9481 return TARGET_XFER_OK;
9482 else
9483 {
9484 /* No use trying further, we know some memory starting
9485 at MEMADDR isn't available. */
9486 *xfered_len = len;
9487 return (*xfered_len != 0) ?
9488 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9489 }
9490 }
9491
9492 /* Don't try to read more than how much is available, in
9493 case the target implements the deprecated QTro packet to
9494 cater for older GDBs (the target's knowledge of read-only
9495 sections may be outdated by now). */
9496 len = available[0].length;
9497 }
9498 }
9499
9500 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9501 }
9502
9503 \f
9504
9505 /* Sends a packet with content determined by the printf format string
9506 FORMAT and the remaining arguments, then gets the reply. Returns
9507 whether the packet was a success, a failure, or unknown. */
9508
9509 packet_result
9510 remote_target::remote_send_printf (const char *format, ...)
9511 {
9512 struct remote_state *rs = get_remote_state ();
9513 int max_size = get_remote_packet_size ();
9514 va_list ap;
9515
9516 va_start (ap, format);
9517
9518 rs->buf[0] = '\0';
9519 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9520
9521 va_end (ap);
9522
9523 if (size >= max_size)
9524 internal_error (_("Too long remote packet."));
9525
9526 if (putpkt (rs->buf) < 0)
9527 error (_("Communication problem with target."));
9528
9529 rs->buf[0] = '\0';
9530 getpkt (&rs->buf, 0);
9531
9532 return packet_check_result (rs->buf);
9533 }
9534
9535 /* Flash writing can take quite some time. We'll set
9536 effectively infinite timeout for flash operations.
9537 In future, we'll need to decide on a better approach. */
9538 static const int remote_flash_timeout = 1000;
9539
9540 void
9541 remote_target::flash_erase (ULONGEST address, LONGEST length)
9542 {
9543 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9544 enum packet_result ret;
9545 scoped_restore restore_timeout
9546 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9547
9548 ret = remote_send_printf ("vFlashErase:%s,%s",
9549 phex (address, addr_size),
9550 phex (length, 4));
9551 switch (ret)
9552 {
9553 case PACKET_UNKNOWN:
9554 error (_("Remote target does not support flash erase"));
9555 case PACKET_ERROR:
9556 error (_("Error erasing flash with vFlashErase packet"));
9557 default:
9558 break;
9559 }
9560 }
9561
9562 target_xfer_status
9563 remote_target::remote_flash_write (ULONGEST address,
9564 ULONGEST length, ULONGEST *xfered_len,
9565 const gdb_byte *data)
9566 {
9567 scoped_restore restore_timeout
9568 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9569 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9570 xfered_len,'X', 0);
9571 }
9572
9573 void
9574 remote_target::flash_done ()
9575 {
9576 int ret;
9577
9578 scoped_restore restore_timeout
9579 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9580
9581 ret = remote_send_printf ("vFlashDone");
9582
9583 switch (ret)
9584 {
9585 case PACKET_UNKNOWN:
9586 error (_("Remote target does not support vFlashDone"));
9587 case PACKET_ERROR:
9588 error (_("Error finishing flash operation"));
9589 default:
9590 break;
9591 }
9592 }
9593
9594 \f
9595 /* Stuff for dealing with the packets which are part of this protocol.
9596 See comment at top of file for details. */
9597
9598 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9599 error to higher layers. Called when a serial error is detected.
9600 The exception message is STRING, followed by a colon and a blank,
9601 the system error message for errno at function entry and final dot
9602 for output compatibility with throw_perror_with_name. */
9603
9604 static void
9605 unpush_and_perror (remote_target *target, const char *string)
9606 {
9607 int saved_errno = errno;
9608
9609 remote_unpush_target (target);
9610 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9611 safe_strerror (saved_errno));
9612 }
9613
9614 /* Read a single character from the remote end. The current quit
9615 handler is overridden to avoid quitting in the middle of packet
9616 sequence, as that would break communication with the remote server.
9617 See remote_serial_quit_handler for more detail. */
9618
9619 int
9620 remote_target::readchar (int timeout)
9621 {
9622 int ch;
9623 struct remote_state *rs = get_remote_state ();
9624
9625 {
9626 scoped_restore restore_quit_target
9627 = make_scoped_restore (&curr_quit_handler_target, this);
9628 scoped_restore restore_quit
9629 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9630
9631 rs->got_ctrlc_during_io = 0;
9632
9633 ch = serial_readchar (rs->remote_desc, timeout);
9634
9635 if (rs->got_ctrlc_during_io)
9636 set_quit_flag ();
9637 }
9638
9639 if (ch >= 0)
9640 return ch;
9641
9642 switch ((enum serial_rc) ch)
9643 {
9644 case SERIAL_EOF:
9645 remote_unpush_target (this);
9646 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9647 /* no return */
9648 case SERIAL_ERROR:
9649 unpush_and_perror (this, _("Remote communication error. "
9650 "Target disconnected"));
9651 /* no return */
9652 case SERIAL_TIMEOUT:
9653 break;
9654 }
9655 return ch;
9656 }
9657
9658 /* Wrapper for serial_write that closes the target and throws if
9659 writing fails. The current quit handler is overridden to avoid
9660 quitting in the middle of packet sequence, as that would break
9661 communication with the remote server. See
9662 remote_serial_quit_handler for more detail. */
9663
9664 void
9665 remote_target::remote_serial_write (const char *str, int len)
9666 {
9667 struct remote_state *rs = get_remote_state ();
9668
9669 scoped_restore restore_quit_target
9670 = make_scoped_restore (&curr_quit_handler_target, this);
9671 scoped_restore restore_quit
9672 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9673
9674 rs->got_ctrlc_during_io = 0;
9675
9676 if (serial_write (rs->remote_desc, str, len))
9677 {
9678 unpush_and_perror (this, _("Remote communication error. "
9679 "Target disconnected"));
9680 }
9681
9682 if (rs->got_ctrlc_during_io)
9683 set_quit_flag ();
9684 }
9685
9686 /* Return a string representing an escaped version of BUF, of len N.
9687 E.g. \n is converted to \\n, \t to \\t, etc. */
9688
9689 static std::string
9690 escape_buffer (const char *buf, int n)
9691 {
9692 string_file stb;
9693
9694 stb.putstrn (buf, n, '\\');
9695 return stb.release ();
9696 }
9697
9698 int
9699 remote_target::putpkt (const char *buf)
9700 {
9701 return putpkt_binary (buf, strlen (buf));
9702 }
9703
9704 /* Wrapper around remote_target::putpkt to avoid exporting
9705 remote_target. */
9706
9707 int
9708 putpkt (remote_target *remote, const char *buf)
9709 {
9710 return remote->putpkt (buf);
9711 }
9712
9713 /* Send a packet to the remote machine, with error checking. The data
9714 of the packet is in BUF. The string in BUF can be at most
9715 get_remote_packet_size () - 5 to account for the $, # and checksum,
9716 and for a possible /0 if we are debugging (remote_debug) and want
9717 to print the sent packet as a string. */
9718
9719 int
9720 remote_target::putpkt_binary (const char *buf, int cnt)
9721 {
9722 struct remote_state *rs = get_remote_state ();
9723 int i;
9724 unsigned char csum = 0;
9725 gdb::def_vector<char> data (cnt + 6);
9726 char *buf2 = data.data ();
9727
9728 int ch;
9729 int tcount = 0;
9730 char *p;
9731
9732 /* Catch cases like trying to read memory or listing threads while
9733 we're waiting for a stop reply. The remote server wouldn't be
9734 ready to handle this request, so we'd hang and timeout. We don't
9735 have to worry about this in synchronous mode, because in that
9736 case it's not possible to issue a command while the target is
9737 running. This is not a problem in non-stop mode, because in that
9738 case, the stub is always ready to process serial input. */
9739 if (!target_is_non_stop_p ()
9740 && target_is_async_p ()
9741 && rs->waiting_for_stop_reply)
9742 {
9743 error (_("Cannot execute this command while the target is running.\n"
9744 "Use the \"interrupt\" command to stop the target\n"
9745 "and then try again."));
9746 }
9747
9748 /* Copy the packet into buffer BUF2, encapsulating it
9749 and giving it a checksum. */
9750
9751 p = buf2;
9752 *p++ = '$';
9753
9754 for (i = 0; i < cnt; i++)
9755 {
9756 csum += buf[i];
9757 *p++ = buf[i];
9758 }
9759 *p++ = '#';
9760 *p++ = tohex ((csum >> 4) & 0xf);
9761 *p++ = tohex (csum & 0xf);
9762
9763 /* Send it over and over until we get a positive ack. */
9764
9765 while (1)
9766 {
9767 if (remote_debug)
9768 {
9769 *p = '\0';
9770
9771 int len = (int) (p - buf2);
9772 int max_chars;
9773
9774 if (remote_packet_max_chars < 0)
9775 max_chars = len;
9776 else
9777 max_chars = remote_packet_max_chars;
9778
9779 std::string str
9780 = escape_buffer (buf2, std::min (len, max_chars));
9781
9782 if (len > max_chars)
9783 remote_debug_printf_nofunc
9784 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9785 len - max_chars);
9786 else
9787 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9788 }
9789 remote_serial_write (buf2, p - buf2);
9790
9791 /* If this is a no acks version of the remote protocol, send the
9792 packet and move on. */
9793 if (rs->noack_mode)
9794 break;
9795
9796 /* Read until either a timeout occurs (-2) or '+' is read.
9797 Handle any notification that arrives in the mean time. */
9798 while (1)
9799 {
9800 ch = readchar (remote_timeout);
9801
9802 switch (ch)
9803 {
9804 case '+':
9805 remote_debug_printf_nofunc ("Received Ack");
9806 return 1;
9807 case '-':
9808 remote_debug_printf_nofunc ("Received Nak");
9809 /* FALLTHROUGH */
9810 case SERIAL_TIMEOUT:
9811 tcount++;
9812 if (tcount > 3)
9813 return 0;
9814 break; /* Retransmit buffer. */
9815 case '$':
9816 {
9817 remote_debug_printf ("Packet instead of Ack, ignoring it");
9818 /* It's probably an old response sent because an ACK
9819 was lost. Gobble up the packet and ack it so it
9820 doesn't get retransmitted when we resend this
9821 packet. */
9822 skip_frame ();
9823 remote_serial_write ("+", 1);
9824 continue; /* Now, go look for +. */
9825 }
9826
9827 case '%':
9828 {
9829 int val;
9830
9831 /* If we got a notification, handle it, and go back to looking
9832 for an ack. */
9833 /* We've found the start of a notification. Now
9834 collect the data. */
9835 val = read_frame (&rs->buf);
9836 if (val >= 0)
9837 {
9838 remote_debug_printf_nofunc
9839 (" Notification received: %s",
9840 escape_buffer (rs->buf.data (), val).c_str ());
9841
9842 handle_notification (rs->notif_state, rs->buf.data ());
9843 /* We're in sync now, rewait for the ack. */
9844 tcount = 0;
9845 }
9846 else
9847 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9848 rs->buf.data ());
9849 continue;
9850 }
9851 /* fall-through */
9852 default:
9853 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9854 rs->buf.data ());
9855 continue;
9856 }
9857 break; /* Here to retransmit. */
9858 }
9859
9860 #if 0
9861 /* This is wrong. If doing a long backtrace, the user should be
9862 able to get out next time we call QUIT, without anything as
9863 violent as interrupt_query. If we want to provide a way out of
9864 here without getting to the next QUIT, it should be based on
9865 hitting ^C twice as in remote_wait. */
9866 if (quit_flag)
9867 {
9868 quit_flag = 0;
9869 interrupt_query ();
9870 }
9871 #endif
9872 }
9873
9874 return 0;
9875 }
9876
9877 /* Come here after finding the start of a frame when we expected an
9878 ack. Do our best to discard the rest of this packet. */
9879
9880 void
9881 remote_target::skip_frame ()
9882 {
9883 int c;
9884
9885 while (1)
9886 {
9887 c = readchar (remote_timeout);
9888 switch (c)
9889 {
9890 case SERIAL_TIMEOUT:
9891 /* Nothing we can do. */
9892 return;
9893 case '#':
9894 /* Discard the two bytes of checksum and stop. */
9895 c = readchar (remote_timeout);
9896 if (c >= 0)
9897 c = readchar (remote_timeout);
9898
9899 return;
9900 case '*': /* Run length encoding. */
9901 /* Discard the repeat count. */
9902 c = readchar (remote_timeout);
9903 if (c < 0)
9904 return;
9905 break;
9906 default:
9907 /* A regular character. */
9908 break;
9909 }
9910 }
9911 }
9912
9913 /* Come here after finding the start of the frame. Collect the rest
9914 into *BUF, verifying the checksum, length, and handling run-length
9915 compression. NUL terminate the buffer. If there is not enough room,
9916 expand *BUF.
9917
9918 Returns -1 on error, number of characters in buffer (ignoring the
9919 trailing NULL) on success. (could be extended to return one of the
9920 SERIAL status indications). */
9921
9922 long
9923 remote_target::read_frame (gdb::char_vector *buf_p)
9924 {
9925 unsigned char csum;
9926 long bc;
9927 int c;
9928 char *buf = buf_p->data ();
9929 struct remote_state *rs = get_remote_state ();
9930
9931 csum = 0;
9932 bc = 0;
9933
9934 while (1)
9935 {
9936 c = readchar (remote_timeout);
9937 switch (c)
9938 {
9939 case SERIAL_TIMEOUT:
9940 remote_debug_printf ("Timeout in mid-packet, retrying");
9941 return -1;
9942
9943 case '$':
9944 remote_debug_printf ("Saw new packet start in middle of old one");
9945 return -1; /* Start a new packet, count retries. */
9946
9947 case '#':
9948 {
9949 unsigned char pktcsum;
9950 int check_0 = 0;
9951 int check_1 = 0;
9952
9953 buf[bc] = '\0';
9954
9955 check_0 = readchar (remote_timeout);
9956 if (check_0 >= 0)
9957 check_1 = readchar (remote_timeout);
9958
9959 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9960 {
9961 remote_debug_printf ("Timeout in checksum, retrying");
9962 return -1;
9963 }
9964 else if (check_0 < 0 || check_1 < 0)
9965 {
9966 remote_debug_printf ("Communication error in checksum");
9967 return -1;
9968 }
9969
9970 /* Don't recompute the checksum; with no ack packets we
9971 don't have any way to indicate a packet retransmission
9972 is necessary. */
9973 if (rs->noack_mode)
9974 return bc;
9975
9976 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9977 if (csum == pktcsum)
9978 return bc;
9979
9980 remote_debug_printf
9981 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9982 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9983
9984 /* Number of characters in buffer ignoring trailing
9985 NULL. */
9986 return -1;
9987 }
9988 case '*': /* Run length encoding. */
9989 {
9990 int repeat;
9991
9992 csum += c;
9993 c = readchar (remote_timeout);
9994 csum += c;
9995 repeat = c - ' ' + 3; /* Compute repeat count. */
9996
9997 /* The character before ``*'' is repeated. */
9998
9999 if (repeat > 0 && repeat <= 255 && bc > 0)
10000 {
10001 if (bc + repeat - 1 >= buf_p->size () - 1)
10002 {
10003 /* Make some more room in the buffer. */
10004 buf_p->resize (buf_p->size () + repeat);
10005 buf = buf_p->data ();
10006 }
10007
10008 memset (&buf[bc], buf[bc - 1], repeat);
10009 bc += repeat;
10010 continue;
10011 }
10012
10013 buf[bc] = '\0';
10014 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10015 return -1;
10016 }
10017 default:
10018 if (bc >= buf_p->size () - 1)
10019 {
10020 /* Make some more room in the buffer. */
10021 buf_p->resize (buf_p->size () * 2);
10022 buf = buf_p->data ();
10023 }
10024
10025 buf[bc++] = c;
10026 csum += c;
10027 continue;
10028 }
10029 }
10030 }
10031
10032 /* Set this to the maximum number of seconds to wait instead of waiting forever
10033 in target_wait(). If this timer times out, then it generates an error and
10034 the command is aborted. This replaces most of the need for timeouts in the
10035 GDB test suite, and makes it possible to distinguish between a hung target
10036 and one with slow communications. */
10037
10038 static int watchdog = 0;
10039 static void
10040 show_watchdog (struct ui_file *file, int from_tty,
10041 struct cmd_list_element *c, const char *value)
10042 {
10043 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10044 }
10045
10046 /* Read a packet from the remote machine, with error checking, and
10047 store it in *BUF. Resize *BUF if necessary to hold the result. If
10048 FOREVER, wait forever rather than timing out; this is used (in
10049 synchronous mode) to wait for a target that is is executing user
10050 code to stop. If FOREVER == 0, this function is allowed to time
10051 out gracefully and return an indication of this to the caller.
10052 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
10053 consider receiving a notification enough reason to return to the
10054 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
10055 holds a notification or not (a regular packet). */
10056
10057 int
10058 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
10059 int forever, int expecting_notif,
10060 int *is_notif)
10061 {
10062 struct remote_state *rs = get_remote_state ();
10063 int c;
10064 int tries;
10065 int timeout;
10066 int val = -1;
10067
10068 strcpy (buf->data (), "timeout");
10069
10070 if (forever)
10071 timeout = watchdog > 0 ? watchdog : -1;
10072 else if (expecting_notif)
10073 timeout = 0; /* There should already be a char in the buffer. If
10074 not, bail out. */
10075 else
10076 timeout = remote_timeout;
10077
10078 #define MAX_TRIES 3
10079
10080 /* Process any number of notifications, and then return when
10081 we get a packet. */
10082 for (;;)
10083 {
10084 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10085 times. */
10086 for (tries = 1; tries <= MAX_TRIES; tries++)
10087 {
10088 /* This can loop forever if the remote side sends us
10089 characters continuously, but if it pauses, we'll get
10090 SERIAL_TIMEOUT from readchar because of timeout. Then
10091 we'll count that as a retry.
10092
10093 Note that even when forever is set, we will only wait
10094 forever prior to the start of a packet. After that, we
10095 expect characters to arrive at a brisk pace. They should
10096 show up within remote_timeout intervals. */
10097 do
10098 c = readchar (timeout);
10099 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10100
10101 if (c == SERIAL_TIMEOUT)
10102 {
10103 if (expecting_notif)
10104 return -1; /* Don't complain, it's normal to not get
10105 anything in this case. */
10106
10107 if (forever) /* Watchdog went off? Kill the target. */
10108 {
10109 remote_unpush_target (this);
10110 throw_error (TARGET_CLOSE_ERROR,
10111 _("Watchdog timeout has expired. "
10112 "Target detached."));
10113 }
10114
10115 remote_debug_printf ("Timed out.");
10116 }
10117 else
10118 {
10119 /* We've found the start of a packet or notification.
10120 Now collect the data. */
10121 val = read_frame (buf);
10122 if (val >= 0)
10123 break;
10124 }
10125
10126 remote_serial_write ("-", 1);
10127 }
10128
10129 if (tries > MAX_TRIES)
10130 {
10131 /* We have tried hard enough, and just can't receive the
10132 packet/notification. Give up. */
10133 gdb_printf (_("Ignoring packet error, continuing...\n"));
10134
10135 /* Skip the ack char if we're in no-ack mode. */
10136 if (!rs->noack_mode)
10137 remote_serial_write ("+", 1);
10138 return -1;
10139 }
10140
10141 /* If we got an ordinary packet, return that to our caller. */
10142 if (c == '$')
10143 {
10144 if (remote_debug)
10145 {
10146 int max_chars;
10147
10148 if (remote_packet_max_chars < 0)
10149 max_chars = val;
10150 else
10151 max_chars = remote_packet_max_chars;
10152
10153 std::string str
10154 = escape_buffer (buf->data (),
10155 std::min (val, max_chars));
10156
10157 if (val > max_chars)
10158 remote_debug_printf_nofunc
10159 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10160 val - max_chars);
10161 else
10162 remote_debug_printf_nofunc ("Packet received: %s",
10163 str.c_str ());
10164 }
10165
10166 /* Skip the ack char if we're in no-ack mode. */
10167 if (!rs->noack_mode)
10168 remote_serial_write ("+", 1);
10169 if (is_notif != NULL)
10170 *is_notif = 0;
10171 return val;
10172 }
10173
10174 /* If we got a notification, handle it, and go back to looking
10175 for a packet. */
10176 else
10177 {
10178 gdb_assert (c == '%');
10179
10180 remote_debug_printf_nofunc
10181 (" Notification received: %s",
10182 escape_buffer (buf->data (), val).c_str ());
10183
10184 if (is_notif != NULL)
10185 *is_notif = 1;
10186
10187 handle_notification (rs->notif_state, buf->data ());
10188
10189 /* Notifications require no acknowledgement. */
10190
10191 if (expecting_notif)
10192 return val;
10193 }
10194 }
10195 }
10196
10197 /* Read a packet from the remote machine, with error checking, and
10198 store it in *BUF. Resize *BUF if necessary to hold the result. If
10199 FOREVER, wait forever rather than timing out; this is used (in
10200 synchronous mode) to wait for a target that is is executing user
10201 code to stop. */
10202
10203 int
10204 remote_target::getpkt (gdb::char_vector *buf, int forever)
10205 {
10206 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10207 }
10208
10209 int
10210 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10211 int *is_notif)
10212 {
10213 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10214 }
10215
10216 /* Kill any new fork children of inferior INF that haven't been
10217 processed by follow_fork. */
10218
10219 void
10220 remote_target::kill_new_fork_children (inferior *inf)
10221 {
10222 remote_state *rs = get_remote_state ();
10223 const notif_client *notif = &notif_client_stop;
10224
10225 /* Kill the fork child threads of any threads in inferior INF that are stopped
10226 at a fork event. */
10227 for (thread_info *thread : inf->non_exited_threads ())
10228 {
10229 const target_waitstatus *ws = thread_pending_fork_status (thread);
10230
10231 if (ws == nullptr)
10232 continue;
10233
10234 int child_pid = ws->child_ptid ().pid ();
10235 int res = remote_vkill (child_pid);
10236
10237 if (res != 0)
10238 error (_("Can't kill fork child process %d"), child_pid);
10239 }
10240
10241 /* Check for any pending fork events (not reported or processed yet)
10242 in inferior INF and kill those fork child threads as well. */
10243 remote_notif_get_pending_events (notif);
10244 for (auto &event : rs->stop_reply_queue)
10245 {
10246 if (event->ptid.pid () != inf->pid)
10247 continue;
10248
10249 if (!is_fork_status (event->ws.kind ()))
10250 continue;
10251
10252 int child_pid = event->ws.child_ptid ().pid ();
10253 int res = remote_vkill (child_pid);
10254
10255 if (res != 0)
10256 error (_("Can't kill fork child process %d"), child_pid);
10257 }
10258 }
10259
10260 \f
10261 /* Target hook to kill the current inferior. */
10262
10263 void
10264 remote_target::kill ()
10265 {
10266 int res = -1;
10267 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10268
10269 gdb_assert (inf != nullptr);
10270
10271 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10272 {
10273 /* If we're stopped while forking and we haven't followed yet,
10274 kill the child task. We need to do this before killing the
10275 parent task because if this is a vfork then the parent will
10276 be sleeping. */
10277 kill_new_fork_children (inf);
10278
10279 res = remote_vkill (inf->pid);
10280 if (res == 0)
10281 {
10282 target_mourn_inferior (inferior_ptid);
10283 return;
10284 }
10285 }
10286
10287 /* If we are in 'target remote' mode and we are killing the only
10288 inferior, then we will tell gdbserver to exit and unpush the
10289 target. */
10290 if (res == -1 && !m_features.remote_multi_process_p ()
10291 && number_of_live_inferiors (this) == 1)
10292 {
10293 remote_kill_k ();
10294
10295 /* We've killed the remote end, we get to mourn it. If we are
10296 not in extended mode, mourning the inferior also unpushes
10297 remote_ops from the target stack, which closes the remote
10298 connection. */
10299 target_mourn_inferior (inferior_ptid);
10300
10301 return;
10302 }
10303
10304 error (_("Can't kill process"));
10305 }
10306
10307 /* Send a kill request to the target using the 'vKill' packet. */
10308
10309 int
10310 remote_target::remote_vkill (int pid)
10311 {
10312 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10313 return -1;
10314
10315 remote_state *rs = get_remote_state ();
10316
10317 /* Tell the remote target to detach. */
10318 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10319 putpkt (rs->buf);
10320 getpkt (&rs->buf, 0);
10321
10322 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10323 {
10324 case PACKET_OK:
10325 return 0;
10326 case PACKET_ERROR:
10327 return 1;
10328 case PACKET_UNKNOWN:
10329 return -1;
10330 default:
10331 internal_error (_("Bad result from packet_ok"));
10332 }
10333 }
10334
10335 /* Send a kill request to the target using the 'k' packet. */
10336
10337 void
10338 remote_target::remote_kill_k ()
10339 {
10340 /* Catch errors so the user can quit from gdb even when we
10341 aren't on speaking terms with the remote system. */
10342 try
10343 {
10344 putpkt ("k");
10345 }
10346 catch (const gdb_exception_error &ex)
10347 {
10348 if (ex.error == TARGET_CLOSE_ERROR)
10349 {
10350 /* If we got an (EOF) error that caused the target
10351 to go away, then we're done, that's what we wanted.
10352 "k" is susceptible to cause a premature EOF, given
10353 that the remote server isn't actually required to
10354 reply to "k", and it can happen that it doesn't
10355 even get to reply ACK to the "k". */
10356 return;
10357 }
10358
10359 /* Otherwise, something went wrong. We didn't actually kill
10360 the target. Just propagate the exception, and let the
10361 user or higher layers decide what to do. */
10362 throw;
10363 }
10364 }
10365
10366 void
10367 remote_target::mourn_inferior ()
10368 {
10369 struct remote_state *rs = get_remote_state ();
10370
10371 /* We're no longer interested in notification events of an inferior
10372 that exited or was killed/detached. */
10373 discard_pending_stop_replies (current_inferior ());
10374
10375 /* In 'target remote' mode with one inferior, we close the connection. */
10376 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10377 {
10378 remote_unpush_target (this);
10379 return;
10380 }
10381
10382 /* In case we got here due to an error, but we're going to stay
10383 connected. */
10384 rs->waiting_for_stop_reply = 0;
10385
10386 /* If the current general thread belonged to the process we just
10387 detached from or has exited, the remote side current general
10388 thread becomes undefined. Considering a case like this:
10389
10390 - We just got here due to a detach.
10391 - The process that we're detaching from happens to immediately
10392 report a global breakpoint being hit in non-stop mode, in the
10393 same thread we had selected before.
10394 - GDB attaches to this process again.
10395 - This event happens to be the next event we handle.
10396
10397 GDB would consider that the current general thread didn't need to
10398 be set on the stub side (with Hg), since for all it knew,
10399 GENERAL_THREAD hadn't changed.
10400
10401 Notice that although in all-stop mode, the remote server always
10402 sets the current thread to the thread reporting the stop event,
10403 that doesn't happen in non-stop mode; in non-stop, the stub *must
10404 not* change the current thread when reporting a breakpoint hit,
10405 due to the decoupling of event reporting and event handling.
10406
10407 To keep things simple, we always invalidate our notion of the
10408 current thread. */
10409 record_currthread (rs, minus_one_ptid);
10410
10411 /* Call common code to mark the inferior as not running. */
10412 generic_mourn_inferior ();
10413 }
10414
10415 bool
10416 extended_remote_target::supports_disable_randomization ()
10417 {
10418 return (m_features.packet_support (PACKET_QDisableRandomization)
10419 == PACKET_ENABLE);
10420 }
10421
10422 void
10423 remote_target::extended_remote_disable_randomization (int val)
10424 {
10425 struct remote_state *rs = get_remote_state ();
10426 char *reply;
10427
10428 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10429 "QDisableRandomization:%x", val);
10430 putpkt (rs->buf);
10431 reply = remote_get_noisy_reply ();
10432 if (*reply == '\0')
10433 error (_("Target does not support QDisableRandomization."));
10434 if (strcmp (reply, "OK") != 0)
10435 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10436 }
10437
10438 int
10439 remote_target::extended_remote_run (const std::string &args)
10440 {
10441 struct remote_state *rs = get_remote_state ();
10442 int len;
10443 const char *remote_exec_file = get_remote_exec_file ();
10444
10445 /* If the user has disabled vRun support, or we have detected that
10446 support is not available, do not try it. */
10447 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10448 return -1;
10449
10450 strcpy (rs->buf.data (), "vRun;");
10451 len = strlen (rs->buf.data ());
10452
10453 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10454 error (_("Remote file name too long for run packet"));
10455 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10456 strlen (remote_exec_file));
10457
10458 if (!args.empty ())
10459 {
10460 int i;
10461
10462 gdb_argv argv (args.c_str ());
10463 for (i = 0; argv[i] != NULL; i++)
10464 {
10465 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10466 error (_("Argument list too long for run packet"));
10467 rs->buf[len++] = ';';
10468 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10469 strlen (argv[i]));
10470 }
10471 }
10472
10473 rs->buf[len++] = '\0';
10474
10475 putpkt (rs->buf);
10476 getpkt (&rs->buf, 0);
10477
10478 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10479 {
10480 case PACKET_OK:
10481 /* We have a wait response. All is well. */
10482 return 0;
10483 case PACKET_UNKNOWN:
10484 return -1;
10485 case PACKET_ERROR:
10486 if (remote_exec_file[0] == '\0')
10487 error (_("Running the default executable on the remote target failed; "
10488 "try \"set remote exec-file\"?"));
10489 else
10490 error (_("Running \"%s\" on the remote target failed"),
10491 remote_exec_file);
10492 default:
10493 gdb_assert_not_reached ("bad switch");
10494 }
10495 }
10496
10497 /* Helper function to send set/unset environment packets. ACTION is
10498 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10499 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10500 sent. */
10501
10502 void
10503 remote_target::send_environment_packet (const char *action,
10504 const char *packet,
10505 const char *value)
10506 {
10507 remote_state *rs = get_remote_state ();
10508
10509 /* Convert the environment variable to an hex string, which
10510 is the best format to be transmitted over the wire. */
10511 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10512 strlen (value));
10513
10514 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10515 "%s:%s", packet, encoded_value.c_str ());
10516
10517 putpkt (rs->buf);
10518 getpkt (&rs->buf, 0);
10519 if (strcmp (rs->buf.data (), "OK") != 0)
10520 warning (_("Unable to %s environment variable '%s' on remote."),
10521 action, value);
10522 }
10523
10524 /* Helper function to handle the QEnvironment* packets. */
10525
10526 void
10527 remote_target::extended_remote_environment_support ()
10528 {
10529 remote_state *rs = get_remote_state ();
10530
10531 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10532 {
10533 putpkt ("QEnvironmentReset");
10534 getpkt (&rs->buf, 0);
10535 if (strcmp (rs->buf.data (), "OK") != 0)
10536 warning (_("Unable to reset environment on remote."));
10537 }
10538
10539 gdb_environ *e = &current_inferior ()->environment;
10540
10541 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10542 != PACKET_DISABLE)
10543 {
10544 for (const std::string &el : e->user_set_env ())
10545 send_environment_packet ("set", "QEnvironmentHexEncoded",
10546 el.c_str ());
10547 }
10548
10549
10550 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10551 for (const std::string &el : e->user_unset_env ())
10552 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10553 }
10554
10555 /* Helper function to set the current working directory for the
10556 inferior in the remote target. */
10557
10558 void
10559 remote_target::extended_remote_set_inferior_cwd ()
10560 {
10561 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10562 {
10563 const std::string &inferior_cwd = current_inferior ()->cwd ();
10564 remote_state *rs = get_remote_state ();
10565
10566 if (!inferior_cwd.empty ())
10567 {
10568 std::string hexpath
10569 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10570 inferior_cwd.size ());
10571
10572 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10573 "QSetWorkingDir:%s", hexpath.c_str ());
10574 }
10575 else
10576 {
10577 /* An empty inferior_cwd means that the user wants us to
10578 reset the remote server's inferior's cwd. */
10579 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10580 "QSetWorkingDir:");
10581 }
10582
10583 putpkt (rs->buf);
10584 getpkt (&rs->buf, 0);
10585 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10586 error (_("\
10587 Remote replied unexpectedly while setting the inferior's working\n\
10588 directory: %s"),
10589 rs->buf.data ());
10590
10591 }
10592 }
10593
10594 /* In the extended protocol we want to be able to do things like
10595 "run" and have them basically work as expected. So we need
10596 a special create_inferior function. We support changing the
10597 executable file and the command line arguments, but not the
10598 environment. */
10599
10600 void
10601 extended_remote_target::create_inferior (const char *exec_file,
10602 const std::string &args,
10603 char **env, int from_tty)
10604 {
10605 int run_worked;
10606 char *stop_reply;
10607 struct remote_state *rs = get_remote_state ();
10608 const char *remote_exec_file = get_remote_exec_file ();
10609
10610 /* If running asynchronously, register the target file descriptor
10611 with the event loop. */
10612 if (target_can_async_p ())
10613 target_async (true);
10614
10615 /* Disable address space randomization if requested (and supported). */
10616 if (supports_disable_randomization ())
10617 extended_remote_disable_randomization (disable_randomization);
10618
10619 /* If startup-with-shell is on, we inform gdbserver to start the
10620 remote inferior using a shell. */
10621 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10622 {
10623 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10624 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10625 putpkt (rs->buf);
10626 getpkt (&rs->buf, 0);
10627 if (strcmp (rs->buf.data (), "OK") != 0)
10628 error (_("\
10629 Remote replied unexpectedly while setting startup-with-shell: %s"),
10630 rs->buf.data ());
10631 }
10632
10633 extended_remote_environment_support ();
10634
10635 extended_remote_set_inferior_cwd ();
10636
10637 /* Now restart the remote server. */
10638 run_worked = extended_remote_run (args) != -1;
10639 if (!run_worked)
10640 {
10641 /* vRun was not supported. Fail if we need it to do what the
10642 user requested. */
10643 if (remote_exec_file[0])
10644 error (_("Remote target does not support \"set remote exec-file\""));
10645 if (!args.empty ())
10646 error (_("Remote target does not support \"set args\" or run ARGS"));
10647
10648 /* Fall back to "R". */
10649 extended_remote_restart ();
10650 }
10651
10652 /* vRun's success return is a stop reply. */
10653 stop_reply = run_worked ? rs->buf.data () : NULL;
10654 add_current_inferior_and_thread (stop_reply);
10655
10656 /* Get updated offsets, if the stub uses qOffsets. */
10657 get_offsets ();
10658 }
10659 \f
10660
10661 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10662 the list of conditions (in agent expression bytecode format), if any, the
10663 target needs to evaluate. The output is placed into the packet buffer
10664 started from BUF and ended at BUF_END. */
10665
10666 static int
10667 remote_add_target_side_condition (struct gdbarch *gdbarch,
10668 struct bp_target_info *bp_tgt, char *buf,
10669 char *buf_end)
10670 {
10671 if (bp_tgt->conditions.empty ())
10672 return 0;
10673
10674 buf += strlen (buf);
10675 xsnprintf (buf, buf_end - buf, "%s", ";");
10676 buf++;
10677
10678 /* Send conditions to the target. */
10679 for (agent_expr *aexpr : bp_tgt->conditions)
10680 {
10681 xsnprintf (buf, buf_end - buf, "X%x,", (int) aexpr->buf.size ());
10682 buf += strlen (buf);
10683 for (int i = 0; i < aexpr->buf.size (); ++i)
10684 buf = pack_hex_byte (buf, aexpr->buf[i]);
10685 *buf = '\0';
10686 }
10687 return 0;
10688 }
10689
10690 static void
10691 remote_add_target_side_commands (struct gdbarch *gdbarch,
10692 struct bp_target_info *bp_tgt, char *buf)
10693 {
10694 if (bp_tgt->tcommands.empty ())
10695 return;
10696
10697 buf += strlen (buf);
10698
10699 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10700 buf += strlen (buf);
10701
10702 /* Concatenate all the agent expressions that are commands into the
10703 cmds parameter. */
10704 for (agent_expr *aexpr : bp_tgt->tcommands)
10705 {
10706 sprintf (buf, "X%x,", (int) aexpr->buf.size ());
10707 buf += strlen (buf);
10708 for (int i = 0; i < aexpr->buf.size (); ++i)
10709 buf = pack_hex_byte (buf, aexpr->buf[i]);
10710 *buf = '\0';
10711 }
10712 }
10713
10714 /* Insert a breakpoint. On targets that have software breakpoint
10715 support, we ask the remote target to do the work; on targets
10716 which don't, we insert a traditional memory breakpoint. */
10717
10718 int
10719 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10720 struct bp_target_info *bp_tgt)
10721 {
10722 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10723 If it succeeds, then set the support to PACKET_ENABLE. If it
10724 fails, and the user has explicitly requested the Z support then
10725 report an error, otherwise, mark it disabled and go on. */
10726
10727 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10728 {
10729 CORE_ADDR addr = bp_tgt->reqstd_address;
10730 struct remote_state *rs;
10731 char *p, *endbuf;
10732
10733 /* Make sure the remote is pointing at the right process, if
10734 necessary. */
10735 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10736 set_general_process ();
10737
10738 rs = get_remote_state ();
10739 p = rs->buf.data ();
10740 endbuf = p + get_remote_packet_size ();
10741
10742 *(p++) = 'Z';
10743 *(p++) = '0';
10744 *(p++) = ',';
10745 addr = (ULONGEST) remote_address_masked (addr);
10746 p += hexnumstr (p, addr);
10747 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10748
10749 if (supports_evaluation_of_breakpoint_conditions ())
10750 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10751
10752 if (can_run_breakpoint_commands ())
10753 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10754
10755 putpkt (rs->buf);
10756 getpkt (&rs->buf, 0);
10757
10758 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10759 {
10760 case PACKET_ERROR:
10761 return -1;
10762 case PACKET_OK:
10763 return 0;
10764 case PACKET_UNKNOWN:
10765 break;
10766 }
10767 }
10768
10769 /* If this breakpoint has target-side commands but this stub doesn't
10770 support Z0 packets, throw error. */
10771 if (!bp_tgt->tcommands.empty ())
10772 throw_error (NOT_SUPPORTED_ERROR, _("\
10773 Target doesn't support breakpoints that have target side commands."));
10774
10775 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10776 }
10777
10778 int
10779 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10780 struct bp_target_info *bp_tgt,
10781 enum remove_bp_reason reason)
10782 {
10783 CORE_ADDR addr = bp_tgt->placed_address;
10784 struct remote_state *rs = get_remote_state ();
10785
10786 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10787 {
10788 char *p = rs->buf.data ();
10789 char *endbuf = p + get_remote_packet_size ();
10790
10791 /* Make sure the remote is pointing at the right process, if
10792 necessary. */
10793 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10794 set_general_process ();
10795
10796 *(p++) = 'z';
10797 *(p++) = '0';
10798 *(p++) = ',';
10799
10800 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10801 p += hexnumstr (p, addr);
10802 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10803
10804 putpkt (rs->buf);
10805 getpkt (&rs->buf, 0);
10806
10807 return (rs->buf[0] == 'E');
10808 }
10809
10810 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10811 }
10812
10813 static enum Z_packet_type
10814 watchpoint_to_Z_packet (int type)
10815 {
10816 switch (type)
10817 {
10818 case hw_write:
10819 return Z_PACKET_WRITE_WP;
10820 break;
10821 case hw_read:
10822 return Z_PACKET_READ_WP;
10823 break;
10824 case hw_access:
10825 return Z_PACKET_ACCESS_WP;
10826 break;
10827 default:
10828 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10829 }
10830 }
10831
10832 int
10833 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10834 enum target_hw_bp_type type, struct expression *cond)
10835 {
10836 struct remote_state *rs = get_remote_state ();
10837 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10838 char *p;
10839 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10840
10841 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10842 + to_underlying (packet))) == PACKET_DISABLE)
10843 return 1;
10844
10845 /* Make sure the remote is pointing at the right process, if
10846 necessary. */
10847 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10848 set_general_process ();
10849
10850 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10851 p = strchr (rs->buf.data (), '\0');
10852 addr = remote_address_masked (addr);
10853 p += hexnumstr (p, (ULONGEST) addr);
10854 xsnprintf (p, endbuf - p, ",%x", len);
10855
10856 putpkt (rs->buf);
10857 getpkt (&rs->buf, 0);
10858
10859 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10860 + to_underlying (packet))))
10861 {
10862 case PACKET_ERROR:
10863 return -1;
10864 case PACKET_UNKNOWN:
10865 return 1;
10866 case PACKET_OK:
10867 return 0;
10868 }
10869 internal_error (_("remote_insert_watchpoint: reached end of function"));
10870 }
10871
10872 bool
10873 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10874 CORE_ADDR start, int length)
10875 {
10876 CORE_ADDR diff = remote_address_masked (addr - start);
10877
10878 return diff < length;
10879 }
10880
10881
10882 int
10883 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10884 enum target_hw_bp_type type, struct expression *cond)
10885 {
10886 struct remote_state *rs = get_remote_state ();
10887 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10888 char *p;
10889 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10890
10891 if (m_features.packet_support ((to_underlying (PACKET_Z0)
10892 + to_underlying (packet))) == PACKET_DISABLE)
10893 return -1;
10894
10895 /* Make sure the remote is pointing at the right process, if
10896 necessary. */
10897 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10898 set_general_process ();
10899
10900 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10901 p = strchr (rs->buf.data (), '\0');
10902 addr = remote_address_masked (addr);
10903 p += hexnumstr (p, (ULONGEST) addr);
10904 xsnprintf (p, endbuf - p, ",%x", len);
10905 putpkt (rs->buf);
10906 getpkt (&rs->buf, 0);
10907
10908 switch (m_features.packet_ok (rs->buf, (to_underlying (PACKET_Z0)
10909 + to_underlying (packet))))
10910 {
10911 case PACKET_ERROR:
10912 case PACKET_UNKNOWN:
10913 return -1;
10914 case PACKET_OK:
10915 return 0;
10916 }
10917 internal_error (_("remote_remove_watchpoint: reached end of function"));
10918 }
10919
10920
10921 static int remote_hw_watchpoint_limit = -1;
10922 static int remote_hw_watchpoint_length_limit = -1;
10923 static int remote_hw_breakpoint_limit = -1;
10924
10925 int
10926 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10927 {
10928 if (remote_hw_watchpoint_length_limit == 0)
10929 return 0;
10930 else if (remote_hw_watchpoint_length_limit < 0)
10931 return 1;
10932 else if (len <= remote_hw_watchpoint_length_limit)
10933 return 1;
10934 else
10935 return 0;
10936 }
10937
10938 int
10939 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10940 {
10941 if (type == bp_hardware_breakpoint)
10942 {
10943 if (remote_hw_breakpoint_limit == 0)
10944 return 0;
10945 else if (remote_hw_breakpoint_limit < 0)
10946 return 1;
10947 else if (cnt <= remote_hw_breakpoint_limit)
10948 return 1;
10949 }
10950 else
10951 {
10952 if (remote_hw_watchpoint_limit == 0)
10953 return 0;
10954 else if (remote_hw_watchpoint_limit < 0)
10955 return 1;
10956 else if (ot)
10957 return -1;
10958 else if (cnt <= remote_hw_watchpoint_limit)
10959 return 1;
10960 }
10961 return -1;
10962 }
10963
10964 /* The to_stopped_by_sw_breakpoint method of target remote. */
10965
10966 bool
10967 remote_target::stopped_by_sw_breakpoint ()
10968 {
10969 struct thread_info *thread = inferior_thread ();
10970
10971 return (thread->priv != NULL
10972 && (get_remote_thread_info (thread)->stop_reason
10973 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10974 }
10975
10976 /* The to_supports_stopped_by_sw_breakpoint method of target
10977 remote. */
10978
10979 bool
10980 remote_target::supports_stopped_by_sw_breakpoint ()
10981 {
10982 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10983 }
10984
10985 /* The to_stopped_by_hw_breakpoint method of target remote. */
10986
10987 bool
10988 remote_target::stopped_by_hw_breakpoint ()
10989 {
10990 struct thread_info *thread = inferior_thread ();
10991
10992 return (thread->priv != NULL
10993 && (get_remote_thread_info (thread)->stop_reason
10994 == TARGET_STOPPED_BY_HW_BREAKPOINT));
10995 }
10996
10997 /* The to_supports_stopped_by_hw_breakpoint method of target
10998 remote. */
10999
11000 bool
11001 remote_target::supports_stopped_by_hw_breakpoint ()
11002 {
11003 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11004 }
11005
11006 bool
11007 remote_target::stopped_by_watchpoint ()
11008 {
11009 struct thread_info *thread = inferior_thread ();
11010
11011 return (thread->priv != NULL
11012 && (get_remote_thread_info (thread)->stop_reason
11013 == TARGET_STOPPED_BY_WATCHPOINT));
11014 }
11015
11016 bool
11017 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11018 {
11019 struct thread_info *thread = inferior_thread ();
11020
11021 if (thread->priv != NULL
11022 && (get_remote_thread_info (thread)->stop_reason
11023 == TARGET_STOPPED_BY_WATCHPOINT))
11024 {
11025 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11026 return true;
11027 }
11028
11029 return false;
11030 }
11031
11032
11033 int
11034 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11035 struct bp_target_info *bp_tgt)
11036 {
11037 CORE_ADDR addr = bp_tgt->reqstd_address;
11038 struct remote_state *rs;
11039 char *p, *endbuf;
11040 char *message;
11041
11042 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11043 return -1;
11044
11045 /* Make sure the remote is pointing at the right process, if
11046 necessary. */
11047 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11048 set_general_process ();
11049
11050 rs = get_remote_state ();
11051 p = rs->buf.data ();
11052 endbuf = p + get_remote_packet_size ();
11053
11054 *(p++) = 'Z';
11055 *(p++) = '1';
11056 *(p++) = ',';
11057
11058 addr = remote_address_masked (addr);
11059 p += hexnumstr (p, (ULONGEST) addr);
11060 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11061
11062 if (supports_evaluation_of_breakpoint_conditions ())
11063 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11064
11065 if (can_run_breakpoint_commands ())
11066 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11067
11068 putpkt (rs->buf);
11069 getpkt (&rs->buf, 0);
11070
11071 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11072 {
11073 case PACKET_ERROR:
11074 if (rs->buf[1] == '.')
11075 {
11076 message = strchr (&rs->buf[2], '.');
11077 if (message)
11078 error (_("Remote failure reply: %s"), message + 1);
11079 }
11080 return -1;
11081 case PACKET_UNKNOWN:
11082 return -1;
11083 case PACKET_OK:
11084 return 0;
11085 }
11086 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11087 }
11088
11089
11090 int
11091 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11092 struct bp_target_info *bp_tgt)
11093 {
11094 CORE_ADDR addr;
11095 struct remote_state *rs = get_remote_state ();
11096 char *p = rs->buf.data ();
11097 char *endbuf = p + get_remote_packet_size ();
11098
11099 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11100 return -1;
11101
11102 /* Make sure the remote is pointing at the right process, if
11103 necessary. */
11104 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11105 set_general_process ();
11106
11107 *(p++) = 'z';
11108 *(p++) = '1';
11109 *(p++) = ',';
11110
11111 addr = remote_address_masked (bp_tgt->placed_address);
11112 p += hexnumstr (p, (ULONGEST) addr);
11113 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11114
11115 putpkt (rs->buf);
11116 getpkt (&rs->buf, 0);
11117
11118 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11119 {
11120 case PACKET_ERROR:
11121 case PACKET_UNKNOWN:
11122 return -1;
11123 case PACKET_OK:
11124 return 0;
11125 }
11126 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11127 }
11128
11129 /* Verify memory using the "qCRC:" request. */
11130
11131 int
11132 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11133 {
11134 struct remote_state *rs = get_remote_state ();
11135 unsigned long host_crc, target_crc;
11136 char *tmp;
11137
11138 /* It doesn't make sense to use qCRC if the remote target is
11139 connected but not running. */
11140 if (target_has_execution ()
11141 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11142 {
11143 enum packet_result result;
11144
11145 /* Make sure the remote is pointing at the right process. */
11146 set_general_process ();
11147
11148 /* FIXME: assumes lma can fit into long. */
11149 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11150 (long) lma, (long) size);
11151 putpkt (rs->buf);
11152
11153 /* Be clever; compute the host_crc before waiting for target
11154 reply. */
11155 host_crc = xcrc32 (data, size, 0xffffffff);
11156
11157 getpkt (&rs->buf, 0);
11158
11159 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11160 if (result == PACKET_ERROR)
11161 return -1;
11162 else if (result == PACKET_OK)
11163 {
11164 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11165 target_crc = target_crc * 16 + fromhex (*tmp);
11166
11167 return (host_crc == target_crc);
11168 }
11169 }
11170
11171 return simple_verify_memory (this, data, lma, size);
11172 }
11173
11174 /* compare-sections command
11175
11176 With no arguments, compares each loadable section in the exec bfd
11177 with the same memory range on the target, and reports mismatches.
11178 Useful for verifying the image on the target against the exec file. */
11179
11180 static void
11181 compare_sections_command (const char *args, int from_tty)
11182 {
11183 asection *s;
11184 const char *sectname;
11185 bfd_size_type size;
11186 bfd_vma lma;
11187 int matched = 0;
11188 int mismatched = 0;
11189 int res;
11190 int read_only = 0;
11191
11192 if (!current_program_space->exec_bfd ())
11193 error (_("command cannot be used without an exec file"));
11194
11195 if (args != NULL && strcmp (args, "-r") == 0)
11196 {
11197 read_only = 1;
11198 args = NULL;
11199 }
11200
11201 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11202 {
11203 if (!(s->flags & SEC_LOAD))
11204 continue; /* Skip non-loadable section. */
11205
11206 if (read_only && (s->flags & SEC_READONLY) == 0)
11207 continue; /* Skip writeable sections */
11208
11209 size = bfd_section_size (s);
11210 if (size == 0)
11211 continue; /* Skip zero-length section. */
11212
11213 sectname = bfd_section_name (s);
11214 if (args && strcmp (args, sectname) != 0)
11215 continue; /* Not the section selected by user. */
11216
11217 matched = 1; /* Do this section. */
11218 lma = s->lma;
11219
11220 gdb::byte_vector sectdata (size);
11221 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11222 sectdata.data (), 0, size);
11223
11224 res = target_verify_memory (sectdata.data (), lma, size);
11225
11226 if (res == -1)
11227 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11228 paddress (target_gdbarch (), lma),
11229 paddress (target_gdbarch (), lma + size));
11230
11231 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11232 paddress (target_gdbarch (), lma),
11233 paddress (target_gdbarch (), lma + size));
11234 if (res)
11235 gdb_printf ("matched.\n");
11236 else
11237 {
11238 gdb_printf ("MIS-MATCHED!\n");
11239 mismatched++;
11240 }
11241 }
11242 if (mismatched > 0)
11243 warning (_("One or more sections of the target image does "
11244 "not match the loaded file"));
11245 if (args && !matched)
11246 gdb_printf (_("No loaded section named '%s'.\n"), args);
11247 }
11248
11249 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11250 into remote target. The number of bytes written to the remote
11251 target is returned, or -1 for error. */
11252
11253 target_xfer_status
11254 remote_target::remote_write_qxfer (const char *object_name,
11255 const char *annex, const gdb_byte *writebuf,
11256 ULONGEST offset, LONGEST len,
11257 ULONGEST *xfered_len,
11258 const unsigned int which_packet)
11259 {
11260 int i, buf_len;
11261 ULONGEST n;
11262 struct remote_state *rs = get_remote_state ();
11263 int max_size = get_memory_write_packet_size ();
11264
11265 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11266 return TARGET_XFER_E_IO;
11267
11268 /* Insert header. */
11269 i = snprintf (rs->buf.data (), max_size,
11270 "qXfer:%s:write:%s:%s:",
11271 object_name, annex ? annex : "",
11272 phex_nz (offset, sizeof offset));
11273 max_size -= (i + 1);
11274
11275 /* Escape as much data as fits into rs->buf. */
11276 buf_len = remote_escape_output
11277 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11278
11279 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11280 || getpkt (&rs->buf, 0) < 0
11281 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11282 return TARGET_XFER_E_IO;
11283
11284 unpack_varlen_hex (rs->buf.data (), &n);
11285
11286 *xfered_len = n;
11287 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11288 }
11289
11290 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11291 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11292 number of bytes read is returned, or 0 for EOF, or -1 for error.
11293 The number of bytes read may be less than LEN without indicating an
11294 EOF. PACKET is checked and updated to indicate whether the remote
11295 target supports this object. */
11296
11297 target_xfer_status
11298 remote_target::remote_read_qxfer (const char *object_name,
11299 const char *annex,
11300 gdb_byte *readbuf, ULONGEST offset,
11301 LONGEST len,
11302 ULONGEST *xfered_len,
11303 const unsigned int which_packet)
11304 {
11305 struct remote_state *rs = get_remote_state ();
11306 LONGEST i, n, packet_len;
11307
11308 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11309 return TARGET_XFER_E_IO;
11310
11311 /* Check whether we've cached an end-of-object packet that matches
11312 this request. */
11313 if (rs->finished_object)
11314 {
11315 if (strcmp (object_name, rs->finished_object) == 0
11316 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11317 && offset == rs->finished_offset)
11318 return TARGET_XFER_EOF;
11319
11320
11321 /* Otherwise, we're now reading something different. Discard
11322 the cache. */
11323 xfree (rs->finished_object);
11324 xfree (rs->finished_annex);
11325 rs->finished_object = NULL;
11326 rs->finished_annex = NULL;
11327 }
11328
11329 /* Request only enough to fit in a single packet. The actual data
11330 may not, since we don't know how much of it will need to be escaped;
11331 the target is free to respond with slightly less data. We subtract
11332 five to account for the response type and the protocol frame. */
11333 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11334 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11335 "qXfer:%s:read:%s:%s,%s",
11336 object_name, annex ? annex : "",
11337 phex_nz (offset, sizeof offset),
11338 phex_nz (n, sizeof n));
11339 i = putpkt (rs->buf);
11340 if (i < 0)
11341 return TARGET_XFER_E_IO;
11342
11343 rs->buf[0] = '\0';
11344 packet_len = getpkt (&rs->buf, 0);
11345 if (packet_len < 0
11346 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11347 return TARGET_XFER_E_IO;
11348
11349 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11350 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11351
11352 /* 'm' means there is (or at least might be) more data after this
11353 batch. That does not make sense unless there's at least one byte
11354 of data in this reply. */
11355 if (rs->buf[0] == 'm' && packet_len == 1)
11356 error (_("Remote qXfer reply contained no data."));
11357
11358 /* Got some data. */
11359 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11360 packet_len - 1, readbuf, n);
11361
11362 /* 'l' is an EOF marker, possibly including a final block of data,
11363 or possibly empty. If we have the final block of a non-empty
11364 object, record this fact to bypass a subsequent partial read. */
11365 if (rs->buf[0] == 'l' && offset + i > 0)
11366 {
11367 rs->finished_object = xstrdup (object_name);
11368 rs->finished_annex = xstrdup (annex ? annex : "");
11369 rs->finished_offset = offset + i;
11370 }
11371
11372 if (i == 0)
11373 return TARGET_XFER_EOF;
11374 else
11375 {
11376 *xfered_len = i;
11377 return TARGET_XFER_OK;
11378 }
11379 }
11380
11381 enum target_xfer_status
11382 remote_target::xfer_partial (enum target_object object,
11383 const char *annex, gdb_byte *readbuf,
11384 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11385 ULONGEST *xfered_len)
11386 {
11387 struct remote_state *rs;
11388 int i;
11389 char *p2;
11390 char query_type;
11391 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11392
11393 set_remote_traceframe ();
11394 set_general_thread (inferior_ptid);
11395
11396 rs = get_remote_state ();
11397
11398 /* Handle memory using the standard memory routines. */
11399 if (object == TARGET_OBJECT_MEMORY)
11400 {
11401 /* If the remote target is connected but not running, we should
11402 pass this request down to a lower stratum (e.g. the executable
11403 file). */
11404 if (!target_has_execution ())
11405 return TARGET_XFER_EOF;
11406
11407 if (writebuf != NULL)
11408 return remote_write_bytes (offset, writebuf, len, unit_size,
11409 xfered_len);
11410 else
11411 return remote_read_bytes (offset, readbuf, len, unit_size,
11412 xfered_len);
11413 }
11414
11415 /* Handle extra signal info using qxfer packets. */
11416 if (object == TARGET_OBJECT_SIGNAL_INFO)
11417 {
11418 if (readbuf)
11419 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11420 xfered_len, PACKET_qXfer_siginfo_read);
11421 else
11422 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11423 xfered_len, PACKET_qXfer_siginfo_write);
11424 }
11425
11426 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11427 {
11428 if (readbuf)
11429 return remote_read_qxfer ("statictrace", annex,
11430 readbuf, offset, len, xfered_len,
11431 PACKET_qXfer_statictrace_read);
11432 else
11433 return TARGET_XFER_E_IO;
11434 }
11435
11436 /* Only handle flash writes. */
11437 if (writebuf != NULL)
11438 {
11439 switch (object)
11440 {
11441 case TARGET_OBJECT_FLASH:
11442 return remote_flash_write (offset, len, xfered_len,
11443 writebuf);
11444
11445 default:
11446 return TARGET_XFER_E_IO;
11447 }
11448 }
11449
11450 /* Map pre-existing objects onto letters. DO NOT do this for new
11451 objects!!! Instead specify new query packets. */
11452 switch (object)
11453 {
11454 case TARGET_OBJECT_AVR:
11455 query_type = 'R';
11456 break;
11457
11458 case TARGET_OBJECT_AUXV:
11459 gdb_assert (annex == NULL);
11460 return remote_read_qxfer
11461 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11462
11463 case TARGET_OBJECT_AVAILABLE_FEATURES:
11464 return remote_read_qxfer
11465 ("features", annex, readbuf, offset, len, xfered_len,
11466 PACKET_qXfer_features);
11467
11468 case TARGET_OBJECT_LIBRARIES:
11469 return remote_read_qxfer
11470 ("libraries", annex, readbuf, offset, len, xfered_len,
11471 PACKET_qXfer_libraries);
11472
11473 case TARGET_OBJECT_LIBRARIES_SVR4:
11474 return remote_read_qxfer
11475 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11476 PACKET_qXfer_libraries_svr4);
11477
11478 case TARGET_OBJECT_MEMORY_MAP:
11479 gdb_assert (annex == NULL);
11480 return remote_read_qxfer
11481 ("memory-map", annex, readbuf, offset, len, xfered_len,
11482 PACKET_qXfer_memory_map);
11483
11484 case TARGET_OBJECT_OSDATA:
11485 /* Should only get here if we're connected. */
11486 gdb_assert (rs->remote_desc);
11487 return remote_read_qxfer
11488 ("osdata", annex, readbuf, offset, len, xfered_len,
11489 PACKET_qXfer_osdata);
11490
11491 case TARGET_OBJECT_THREADS:
11492 gdb_assert (annex == NULL);
11493 return remote_read_qxfer
11494 ("threads", annex, readbuf, offset, len, xfered_len,
11495 PACKET_qXfer_threads);
11496
11497 case TARGET_OBJECT_TRACEFRAME_INFO:
11498 gdb_assert (annex == NULL);
11499 return remote_read_qxfer
11500 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11501 PACKET_qXfer_traceframe_info);
11502
11503 case TARGET_OBJECT_FDPIC:
11504 return remote_read_qxfer
11505 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11506
11507 case TARGET_OBJECT_OPENVMS_UIB:
11508 return remote_read_qxfer
11509 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11510
11511 case TARGET_OBJECT_BTRACE:
11512 return remote_read_qxfer
11513 ("btrace", annex, readbuf, offset, len, xfered_len,
11514 PACKET_qXfer_btrace);
11515
11516 case TARGET_OBJECT_BTRACE_CONF:
11517 return remote_read_qxfer
11518 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11519 PACKET_qXfer_btrace_conf);
11520
11521 case TARGET_OBJECT_EXEC_FILE:
11522 return remote_read_qxfer
11523 ("exec-file", annex, readbuf, offset, len, xfered_len,
11524 PACKET_qXfer_exec_file);
11525
11526 default:
11527 return TARGET_XFER_E_IO;
11528 }
11529
11530 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11531 large enough let the caller deal with it. */
11532 if (len < get_remote_packet_size ())
11533 return TARGET_XFER_E_IO;
11534 len = get_remote_packet_size ();
11535
11536 /* Except for querying the minimum buffer size, target must be open. */
11537 if (!rs->remote_desc)
11538 error (_("remote query is only available after target open"));
11539
11540 gdb_assert (annex != NULL);
11541 gdb_assert (readbuf != NULL);
11542
11543 p2 = rs->buf.data ();
11544 *p2++ = 'q';
11545 *p2++ = query_type;
11546
11547 /* We used one buffer char for the remote protocol q command and
11548 another for the query type. As the remote protocol encapsulation
11549 uses 4 chars plus one extra in case we are debugging
11550 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11551 string. */
11552 i = 0;
11553 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11554 {
11555 /* Bad caller may have sent forbidden characters. */
11556 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11557 *p2++ = annex[i];
11558 i++;
11559 }
11560 *p2 = '\0';
11561 gdb_assert (annex[i] == '\0');
11562
11563 i = putpkt (rs->buf);
11564 if (i < 0)
11565 return TARGET_XFER_E_IO;
11566
11567 getpkt (&rs->buf, 0);
11568 strcpy ((char *) readbuf, rs->buf.data ());
11569
11570 *xfered_len = strlen ((char *) readbuf);
11571 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11572 }
11573
11574 /* Implementation of to_get_memory_xfer_limit. */
11575
11576 ULONGEST
11577 remote_target::get_memory_xfer_limit ()
11578 {
11579 return get_memory_write_packet_size ();
11580 }
11581
11582 int
11583 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11584 const gdb_byte *pattern, ULONGEST pattern_len,
11585 CORE_ADDR *found_addrp)
11586 {
11587 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11588 struct remote_state *rs = get_remote_state ();
11589 int max_size = get_memory_write_packet_size ();
11590
11591 /* Number of packet bytes used to encode the pattern;
11592 this could be more than PATTERN_LEN due to escape characters. */
11593 int escaped_pattern_len;
11594 /* Amount of pattern that was encodable in the packet. */
11595 int used_pattern_len;
11596 int i;
11597 int found;
11598 ULONGEST found_addr;
11599
11600 auto read_memory = [this] (CORE_ADDR addr, gdb_byte *result, size_t len)
11601 {
11602 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11603 == len);
11604 };
11605
11606 /* Don't go to the target if we don't have to. This is done before
11607 checking packet_support to avoid the possibility that a success for this
11608 edge case means the facility works in general. */
11609 if (pattern_len > search_space_len)
11610 return 0;
11611 if (pattern_len == 0)
11612 {
11613 *found_addrp = start_addr;
11614 return 1;
11615 }
11616
11617 /* If we already know the packet isn't supported, fall back to the simple
11618 way of searching memory. */
11619
11620 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11621 {
11622 /* Target doesn't provided special support, fall back and use the
11623 standard support (copy memory and do the search here). */
11624 return simple_search_memory (read_memory, start_addr, search_space_len,
11625 pattern, pattern_len, found_addrp);
11626 }
11627
11628 /* Make sure the remote is pointing at the right process. */
11629 set_general_process ();
11630
11631 /* Insert header. */
11632 i = snprintf (rs->buf.data (), max_size,
11633 "qSearch:memory:%s;%s;",
11634 phex_nz (start_addr, addr_size),
11635 phex_nz (search_space_len, sizeof (search_space_len)));
11636 max_size -= (i + 1);
11637
11638 /* Escape as much data as fits into rs->buf. */
11639 escaped_pattern_len =
11640 remote_escape_output (pattern, pattern_len, 1,
11641 (gdb_byte *) rs->buf.data () + i,
11642 &used_pattern_len, max_size);
11643
11644 /* Bail if the pattern is too large. */
11645 if (used_pattern_len != pattern_len)
11646 error (_("Pattern is too large to transmit to remote target."));
11647
11648 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11649 || getpkt (&rs->buf, 0) < 0
11650 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11651 {
11652 /* The request may not have worked because the command is not
11653 supported. If so, fall back to the simple way. */
11654 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11655 {
11656 return simple_search_memory (read_memory, start_addr, search_space_len,
11657 pattern, pattern_len, found_addrp);
11658 }
11659 return -1;
11660 }
11661
11662 if (rs->buf[0] == '0')
11663 found = 0;
11664 else if (rs->buf[0] == '1')
11665 {
11666 found = 1;
11667 if (rs->buf[1] != ',')
11668 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11669 unpack_varlen_hex (&rs->buf[2], &found_addr);
11670 *found_addrp = found_addr;
11671 }
11672 else
11673 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11674
11675 return found;
11676 }
11677
11678 void
11679 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11680 {
11681 struct remote_state *rs = get_remote_state ();
11682 char *p = rs->buf.data ();
11683
11684 if (!rs->remote_desc)
11685 error (_("remote rcmd is only available after target open"));
11686
11687 /* Send a NULL command across as an empty command. */
11688 if (command == NULL)
11689 command = "";
11690
11691 /* The query prefix. */
11692 strcpy (rs->buf.data (), "qRcmd,");
11693 p = strchr (rs->buf.data (), '\0');
11694
11695 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11696 > get_remote_packet_size ())
11697 error (_("\"monitor\" command ``%s'' is too long."), command);
11698
11699 /* Encode the actual command. */
11700 bin2hex ((const gdb_byte *) command, p, strlen (command));
11701
11702 if (putpkt (rs->buf) < 0)
11703 error (_("Communication problem with target."));
11704
11705 /* get/display the response */
11706 while (1)
11707 {
11708 char *buf;
11709
11710 /* XXX - see also remote_get_noisy_reply(). */
11711 QUIT; /* Allow user to bail out with ^C. */
11712 rs->buf[0] = '\0';
11713 if (getpkt (&rs->buf, 0) == -1)
11714 {
11715 /* Timeout. Continue to (try to) read responses.
11716 This is better than stopping with an error, assuming the stub
11717 is still executing the (long) monitor command.
11718 If needed, the user can interrupt gdb using C-c, obtaining
11719 an effect similar to stop on timeout. */
11720 continue;
11721 }
11722 buf = rs->buf.data ();
11723 if (buf[0] == '\0')
11724 error (_("Target does not support this command."));
11725 if (buf[0] == 'O' && buf[1] != 'K')
11726 {
11727 remote_console_output (buf + 1); /* 'O' message from stub. */
11728 continue;
11729 }
11730 if (strcmp (buf, "OK") == 0)
11731 break;
11732 if (strlen (buf) == 3 && buf[0] == 'E'
11733 && isxdigit (buf[1]) && isxdigit (buf[2]))
11734 {
11735 error (_("Protocol error with Rcmd"));
11736 }
11737 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11738 {
11739 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11740
11741 gdb_putc (c, outbuf);
11742 }
11743 break;
11744 }
11745 }
11746
11747 std::vector<mem_region>
11748 remote_target::memory_map ()
11749 {
11750 std::vector<mem_region> result;
11751 gdb::optional<gdb::char_vector> text
11752 = target_read_stralloc (current_inferior ()->top_target (),
11753 TARGET_OBJECT_MEMORY_MAP, NULL);
11754
11755 if (text)
11756 result = parse_memory_map (text->data ());
11757
11758 return result;
11759 }
11760
11761 /* Set of callbacks used to implement the 'maint packet' command. */
11762
11763 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11764 {
11765 /* Called before the packet is sent. BUF is the packet content before
11766 the protocol specific prefix, suffix, and escaping is added. */
11767
11768 void sending (gdb::array_view<const char> &buf) override
11769 {
11770 gdb_puts ("sending: ");
11771 print_packet (buf);
11772 gdb_puts ("\n");
11773 }
11774
11775 /* Called with BUF, the reply from the remote target. */
11776
11777 void received (gdb::array_view<const char> &buf) override
11778 {
11779 gdb_puts ("received: \"");
11780 print_packet (buf);
11781 gdb_puts ("\"\n");
11782 }
11783
11784 private:
11785
11786 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11787 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11788
11789 static void
11790 print_packet (gdb::array_view<const char> &buf)
11791 {
11792 string_file stb;
11793
11794 for (int i = 0; i < buf.size (); ++i)
11795 {
11796 gdb_byte c = buf[i];
11797 if (isprint (c))
11798 gdb_putc (c, &stb);
11799 else
11800 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11801 }
11802
11803 gdb_puts (stb.string ().c_str ());
11804 }
11805 };
11806
11807 /* See remote.h. */
11808
11809 void
11810 send_remote_packet (gdb::array_view<const char> &buf,
11811 send_remote_packet_callbacks *callbacks)
11812 {
11813 if (buf.size () == 0 || buf.data ()[0] == '\0')
11814 error (_("a remote packet must not be empty"));
11815
11816 remote_target *remote = get_current_remote_target ();
11817 if (remote == nullptr)
11818 error (_("packets can only be sent to a remote target"));
11819
11820 callbacks->sending (buf);
11821
11822 remote->putpkt_binary (buf.data (), buf.size ());
11823 remote_state *rs = remote->get_remote_state ();
11824 int bytes = remote->getpkt (&rs->buf, 0);
11825
11826 if (bytes < 0)
11827 error (_("error while fetching packet from remote target"));
11828
11829 gdb::array_view<const char> view (&rs->buf[0], bytes);
11830 callbacks->received (view);
11831 }
11832
11833 /* Entry point for the 'maint packet' command. */
11834
11835 static void
11836 cli_packet_command (const char *args, int from_tty)
11837 {
11838 cli_packet_command_callbacks cb;
11839 gdb::array_view<const char> view
11840 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11841 send_remote_packet (view, &cb);
11842 }
11843
11844 #if 0
11845 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11846
11847 static void display_thread_info (struct gdb_ext_thread_info *info);
11848
11849 static void threadset_test_cmd (char *cmd, int tty);
11850
11851 static void threadalive_test (char *cmd, int tty);
11852
11853 static void threadlist_test_cmd (char *cmd, int tty);
11854
11855 int get_and_display_threadinfo (threadref *ref);
11856
11857 static void threadinfo_test_cmd (char *cmd, int tty);
11858
11859 static int thread_display_step (threadref *ref, void *context);
11860
11861 static void threadlist_update_test_cmd (char *cmd, int tty);
11862
11863 static void init_remote_threadtests (void);
11864
11865 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11866
11867 static void
11868 threadset_test_cmd (const char *cmd, int tty)
11869 {
11870 int sample_thread = SAMPLE_THREAD;
11871
11872 gdb_printf (_("Remote threadset test\n"));
11873 set_general_thread (sample_thread);
11874 }
11875
11876
11877 static void
11878 threadalive_test (const char *cmd, int tty)
11879 {
11880 int sample_thread = SAMPLE_THREAD;
11881 int pid = inferior_ptid.pid ();
11882 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11883
11884 if (remote_thread_alive (ptid))
11885 gdb_printf ("PASS: Thread alive test\n");
11886 else
11887 gdb_printf ("FAIL: Thread alive test\n");
11888 }
11889
11890 void output_threadid (char *title, threadref *ref);
11891
11892 void
11893 output_threadid (char *title, threadref *ref)
11894 {
11895 char hexid[20];
11896
11897 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11898 hexid[16] = 0;
11899 gdb_printf ("%s %s\n", title, (&hexid[0]));
11900 }
11901
11902 static void
11903 threadlist_test_cmd (const char *cmd, int tty)
11904 {
11905 int startflag = 1;
11906 threadref nextthread;
11907 int done, result_count;
11908 threadref threadlist[3];
11909
11910 gdb_printf ("Remote Threadlist test\n");
11911 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11912 &result_count, &threadlist[0]))
11913 gdb_printf ("FAIL: threadlist test\n");
11914 else
11915 {
11916 threadref *scan = threadlist;
11917 threadref *limit = scan + result_count;
11918
11919 while (scan < limit)
11920 output_threadid (" thread ", scan++);
11921 }
11922 }
11923
11924 void
11925 display_thread_info (struct gdb_ext_thread_info *info)
11926 {
11927 output_threadid ("Threadid: ", &info->threadid);
11928 gdb_printf ("Name: %s\n ", info->shortname);
11929 gdb_printf ("State: %s\n", info->display);
11930 gdb_printf ("other: %s\n\n", info->more_display);
11931 }
11932
11933 int
11934 get_and_display_threadinfo (threadref *ref)
11935 {
11936 int result;
11937 int set;
11938 struct gdb_ext_thread_info threadinfo;
11939
11940 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11941 | TAG_MOREDISPLAY | TAG_DISPLAY;
11942 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11943 display_thread_info (&threadinfo);
11944 return result;
11945 }
11946
11947 static void
11948 threadinfo_test_cmd (const char *cmd, int tty)
11949 {
11950 int athread = SAMPLE_THREAD;
11951 threadref thread;
11952 int set;
11953
11954 int_to_threadref (&thread, athread);
11955 gdb_printf ("Remote Threadinfo test\n");
11956 if (!get_and_display_threadinfo (&thread))
11957 gdb_printf ("FAIL cannot get thread info\n");
11958 }
11959
11960 static int
11961 thread_display_step (threadref *ref, void *context)
11962 {
11963 /* output_threadid(" threadstep ",ref); *//* simple test */
11964 return get_and_display_threadinfo (ref);
11965 }
11966
11967 static void
11968 threadlist_update_test_cmd (const char *cmd, int tty)
11969 {
11970 gdb_printf ("Remote Threadlist update test\n");
11971 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11972 }
11973
11974 static void
11975 init_remote_threadtests (void)
11976 {
11977 add_com ("tlist", class_obscure, threadlist_test_cmd,
11978 _("Fetch and print the remote list of "
11979 "thread identifiers, one pkt only."));
11980 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11981 _("Fetch and display info about one thread."));
11982 add_com ("tset", class_obscure, threadset_test_cmd,
11983 _("Test setting to a different thread."));
11984 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11985 _("Iterate through updating all remote thread info."));
11986 add_com ("talive", class_obscure, threadalive_test,
11987 _("Remote thread alive test."));
11988 }
11989
11990 #endif /* 0 */
11991
11992 /* Convert a thread ID to a string. */
11993
11994 std::string
11995 remote_target::pid_to_str (ptid_t ptid)
11996 {
11997 if (ptid == null_ptid)
11998 return normal_pid_to_str (ptid);
11999 else if (ptid.is_pid ())
12000 {
12001 /* Printing an inferior target id. */
12002
12003 /* When multi-process extensions are off, there's no way in the
12004 remote protocol to know the remote process id, if there's any
12005 at all. There's one exception --- when we're connected with
12006 target extended-remote, and we manually attached to a process
12007 with "attach PID". We don't record anywhere a flag that
12008 allows us to distinguish that case from the case of
12009 connecting with extended-remote and the stub already being
12010 attached to a process, and reporting yes to qAttached, hence
12011 no smart special casing here. */
12012 if (!m_features.remote_multi_process_p ())
12013 return "Remote target";
12014
12015 return normal_pid_to_str (ptid);
12016 }
12017 else
12018 {
12019 if (magic_null_ptid == ptid)
12020 return "Thread <main>";
12021 else if (m_features.remote_multi_process_p ())
12022 if (ptid.lwp () == 0)
12023 return normal_pid_to_str (ptid);
12024 else
12025 return string_printf ("Thread %d.%ld",
12026 ptid.pid (), ptid.lwp ());
12027 else
12028 return string_printf ("Thread %ld", ptid.lwp ());
12029 }
12030 }
12031
12032 /* Get the address of the thread local variable in OBJFILE which is
12033 stored at OFFSET within the thread local storage for thread PTID. */
12034
12035 CORE_ADDR
12036 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12037 CORE_ADDR offset)
12038 {
12039 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12040 {
12041 struct remote_state *rs = get_remote_state ();
12042 char *p = rs->buf.data ();
12043 char *endp = p + get_remote_packet_size ();
12044 enum packet_result result;
12045
12046 strcpy (p, "qGetTLSAddr:");
12047 p += strlen (p);
12048 p = write_ptid (p, endp, ptid);
12049 *p++ = ',';
12050 p += hexnumstr (p, offset);
12051 *p++ = ',';
12052 p += hexnumstr (p, lm);
12053 *p++ = '\0';
12054
12055 putpkt (rs->buf);
12056 getpkt (&rs->buf, 0);
12057 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12058 if (result == PACKET_OK)
12059 {
12060 ULONGEST addr;
12061
12062 unpack_varlen_hex (rs->buf.data (), &addr);
12063 return addr;
12064 }
12065 else if (result == PACKET_UNKNOWN)
12066 throw_error (TLS_GENERIC_ERROR,
12067 _("Remote target doesn't support qGetTLSAddr packet"));
12068 else
12069 throw_error (TLS_GENERIC_ERROR,
12070 _("Remote target failed to process qGetTLSAddr request"));
12071 }
12072 else
12073 throw_error (TLS_GENERIC_ERROR,
12074 _("TLS not supported or disabled on this target"));
12075 /* Not reached. */
12076 return 0;
12077 }
12078
12079 /* Provide thread local base, i.e. Thread Information Block address.
12080 Returns 1 if ptid is found and thread_local_base is non zero. */
12081
12082 bool
12083 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12084 {
12085 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12086 {
12087 struct remote_state *rs = get_remote_state ();
12088 char *p = rs->buf.data ();
12089 char *endp = p + get_remote_packet_size ();
12090 enum packet_result result;
12091
12092 strcpy (p, "qGetTIBAddr:");
12093 p += strlen (p);
12094 p = write_ptid (p, endp, ptid);
12095 *p++ = '\0';
12096
12097 putpkt (rs->buf);
12098 getpkt (&rs->buf, 0);
12099 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12100 if (result == PACKET_OK)
12101 {
12102 ULONGEST val;
12103 unpack_varlen_hex (rs->buf.data (), &val);
12104 if (addr)
12105 *addr = (CORE_ADDR) val;
12106 return true;
12107 }
12108 else if (result == PACKET_UNKNOWN)
12109 error (_("Remote target doesn't support qGetTIBAddr packet"));
12110 else
12111 error (_("Remote target failed to process qGetTIBAddr request"));
12112 }
12113 else
12114 error (_("qGetTIBAddr not supported or disabled on this target"));
12115 /* Not reached. */
12116 return false;
12117 }
12118
12119 /* Support for inferring a target description based on the current
12120 architecture and the size of a 'g' packet. While the 'g' packet
12121 can have any size (since optional registers can be left off the
12122 end), some sizes are easily recognizable given knowledge of the
12123 approximate architecture. */
12124
12125 struct remote_g_packet_guess
12126 {
12127 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12128 : bytes (bytes_),
12129 tdesc (tdesc_)
12130 {
12131 }
12132
12133 int bytes;
12134 const struct target_desc *tdesc;
12135 };
12136
12137 struct remote_g_packet_data
12138 {
12139 std::vector<remote_g_packet_guess> guesses;
12140 };
12141
12142 static const registry<gdbarch>::key<struct remote_g_packet_data>
12143 remote_g_packet_data_handle;
12144
12145 static struct remote_g_packet_data *
12146 get_g_packet_data (struct gdbarch *gdbarch)
12147 {
12148 struct remote_g_packet_data *data
12149 = remote_g_packet_data_handle.get (gdbarch);
12150 if (data == nullptr)
12151 data = remote_g_packet_data_handle.emplace (gdbarch);
12152 return data;
12153 }
12154
12155 void
12156 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12157 const struct target_desc *tdesc)
12158 {
12159 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12160
12161 gdb_assert (tdesc != NULL);
12162
12163 for (const remote_g_packet_guess &guess : data->guesses)
12164 if (guess.bytes == bytes)
12165 internal_error (_("Duplicate g packet description added for size %d"),
12166 bytes);
12167
12168 data->guesses.emplace_back (bytes, tdesc);
12169 }
12170
12171 /* Return true if remote_read_description would do anything on this target
12172 and architecture, false otherwise. */
12173
12174 static bool
12175 remote_read_description_p (struct target_ops *target)
12176 {
12177 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12178
12179 return !data->guesses.empty ();
12180 }
12181
12182 const struct target_desc *
12183 remote_target::read_description ()
12184 {
12185 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12186
12187 /* Do not try this during initial connection, when we do not know
12188 whether there is a running but stopped thread. */
12189 if (!target_has_execution () || inferior_ptid == null_ptid)
12190 return beneath ()->read_description ();
12191
12192 if (!data->guesses.empty ())
12193 {
12194 int bytes = send_g_packet ();
12195
12196 for (const remote_g_packet_guess &guess : data->guesses)
12197 if (guess.bytes == bytes)
12198 return guess.tdesc;
12199
12200 /* We discard the g packet. A minor optimization would be to
12201 hold on to it, and fill the register cache once we have selected
12202 an architecture, but it's too tricky to do safely. */
12203 }
12204
12205 return beneath ()->read_description ();
12206 }
12207
12208 /* Remote file transfer support. This is host-initiated I/O, not
12209 target-initiated; for target-initiated, see remote-fileio.c. */
12210
12211 /* If *LEFT is at least the length of STRING, copy STRING to
12212 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12213 decrease *LEFT. Otherwise raise an error. */
12214
12215 static void
12216 remote_buffer_add_string (char **buffer, int *left, const char *string)
12217 {
12218 int len = strlen (string);
12219
12220 if (len > *left)
12221 error (_("Packet too long for target."));
12222
12223 memcpy (*buffer, string, len);
12224 *buffer += len;
12225 *left -= len;
12226
12227 /* NUL-terminate the buffer as a convenience, if there is
12228 room. */
12229 if (*left)
12230 **buffer = '\0';
12231 }
12232
12233 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12234 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12235 decrease *LEFT. Otherwise raise an error. */
12236
12237 static void
12238 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12239 int len)
12240 {
12241 if (2 * len > *left)
12242 error (_("Packet too long for target."));
12243
12244 bin2hex (bytes, *buffer, len);
12245 *buffer += 2 * len;
12246 *left -= 2 * len;
12247
12248 /* NUL-terminate the buffer as a convenience, if there is
12249 room. */
12250 if (*left)
12251 **buffer = '\0';
12252 }
12253
12254 /* If *LEFT is large enough, convert VALUE to hex and add it to
12255 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12256 decrease *LEFT. Otherwise raise an error. */
12257
12258 static void
12259 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12260 {
12261 int len = hexnumlen (value);
12262
12263 if (len > *left)
12264 error (_("Packet too long for target."));
12265
12266 hexnumstr (*buffer, value);
12267 *buffer += len;
12268 *left -= len;
12269
12270 /* NUL-terminate the buffer as a convenience, if there is
12271 room. */
12272 if (*left)
12273 **buffer = '\0';
12274 }
12275
12276 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12277 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12278 was included, and *ATTACHMENT to point to the start of the annex
12279 if any. The length of the packet isn't needed here; there may
12280 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12281
12282 Return 0 if the packet could be parsed, -1 if it could not. If
12283 -1 is returned, the other variables may not be initialized. */
12284
12285 static int
12286 remote_hostio_parse_result (const char *buffer, int *retcode,
12287 fileio_error *remote_errno, const char **attachment)
12288 {
12289 char *p, *p2;
12290
12291 *remote_errno = FILEIO_SUCCESS;
12292 *attachment = NULL;
12293
12294 if (buffer[0] != 'F')
12295 return -1;
12296
12297 errno = 0;
12298 *retcode = strtol (&buffer[1], &p, 16);
12299 if (errno != 0 || p == &buffer[1])
12300 return -1;
12301
12302 /* Check for ",errno". */
12303 if (*p == ',')
12304 {
12305 errno = 0;
12306 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12307 if (errno != 0 || p + 1 == p2)
12308 return -1;
12309 p = p2;
12310 }
12311
12312 /* Check for ";attachment". If there is no attachment, the
12313 packet should end here. */
12314 if (*p == ';')
12315 {
12316 *attachment = p + 1;
12317 return 0;
12318 }
12319 else if (*p == '\0')
12320 return 0;
12321 else
12322 return -1;
12323 }
12324
12325 /* Send a prepared I/O packet to the target and read its response.
12326 The prepared packet is in the global RS->BUF before this function
12327 is called, and the answer is there when we return.
12328
12329 COMMAND_BYTES is the length of the request to send, which may include
12330 binary data. WHICH_PACKET is the packet configuration to check
12331 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12332 is set to the error number and -1 is returned. Otherwise the value
12333 returned by the function is returned.
12334
12335 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12336 attachment is expected; an error will be reported if there's a
12337 mismatch. If one is found, *ATTACHMENT will be set to point into
12338 the packet buffer and *ATTACHMENT_LEN will be set to the
12339 attachment's length. */
12340
12341 int
12342 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12343 fileio_error *remote_errno, const char **attachment,
12344 int *attachment_len)
12345 {
12346 struct remote_state *rs = get_remote_state ();
12347 int ret, bytes_read;
12348 const char *attachment_tmp;
12349
12350 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12351 {
12352 *remote_errno = FILEIO_ENOSYS;
12353 return -1;
12354 }
12355
12356 putpkt_binary (rs->buf.data (), command_bytes);
12357 bytes_read = getpkt (&rs->buf, 0);
12358
12359 /* If it timed out, something is wrong. Don't try to parse the
12360 buffer. */
12361 if (bytes_read < 0)
12362 {
12363 *remote_errno = FILEIO_EINVAL;
12364 return -1;
12365 }
12366
12367 switch (m_features.packet_ok (rs->buf, which_packet))
12368 {
12369 case PACKET_ERROR:
12370 *remote_errno = FILEIO_EINVAL;
12371 return -1;
12372 case PACKET_UNKNOWN:
12373 *remote_errno = FILEIO_ENOSYS;
12374 return -1;
12375 case PACKET_OK:
12376 break;
12377 }
12378
12379 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12380 &attachment_tmp))
12381 {
12382 *remote_errno = FILEIO_EINVAL;
12383 return -1;
12384 }
12385
12386 /* Make sure we saw an attachment if and only if we expected one. */
12387 if ((attachment_tmp == NULL && attachment != NULL)
12388 || (attachment_tmp != NULL && attachment == NULL))
12389 {
12390 *remote_errno = FILEIO_EINVAL;
12391 return -1;
12392 }
12393
12394 /* If an attachment was found, it must point into the packet buffer;
12395 work out how many bytes there were. */
12396 if (attachment_tmp != NULL)
12397 {
12398 *attachment = attachment_tmp;
12399 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12400 }
12401
12402 return ret;
12403 }
12404
12405 /* See declaration.h. */
12406
12407 void
12408 readahead_cache::invalidate ()
12409 {
12410 this->fd = -1;
12411 }
12412
12413 /* See declaration.h. */
12414
12415 void
12416 readahead_cache::invalidate_fd (int fd)
12417 {
12418 if (this->fd == fd)
12419 this->fd = -1;
12420 }
12421
12422 /* Set the filesystem remote_hostio functions that take FILENAME
12423 arguments will use. Return 0 on success, or -1 if an error
12424 occurs (and set *REMOTE_ERRNO). */
12425
12426 int
12427 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12428 fileio_error *remote_errno)
12429 {
12430 struct remote_state *rs = get_remote_state ();
12431 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12432 char *p = rs->buf.data ();
12433 int left = get_remote_packet_size () - 1;
12434 char arg[9];
12435 int ret;
12436
12437 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12438 return 0;
12439
12440 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12441 return 0;
12442
12443 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12444
12445 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12446 remote_buffer_add_string (&p, &left, arg);
12447
12448 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12449 remote_errno, NULL, NULL);
12450
12451 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12452 return 0;
12453
12454 if (ret == 0)
12455 rs->fs_pid = required_pid;
12456
12457 return ret;
12458 }
12459
12460 /* Implementation of to_fileio_open. */
12461
12462 int
12463 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12464 int flags, int mode, int warn_if_slow,
12465 fileio_error *remote_errno)
12466 {
12467 struct remote_state *rs = get_remote_state ();
12468 char *p = rs->buf.data ();
12469 int left = get_remote_packet_size () - 1;
12470
12471 if (warn_if_slow)
12472 {
12473 static int warning_issued = 0;
12474
12475 gdb_printf (_("Reading %s from remote target...\n"),
12476 filename);
12477
12478 if (!warning_issued)
12479 {
12480 warning (_("File transfers from remote targets can be slow."
12481 " Use \"set sysroot\" to access files locally"
12482 " instead."));
12483 warning_issued = 1;
12484 }
12485 }
12486
12487 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12488 return -1;
12489
12490 remote_buffer_add_string (&p, &left, "vFile:open:");
12491
12492 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12493 strlen (filename));
12494 remote_buffer_add_string (&p, &left, ",");
12495
12496 remote_buffer_add_int (&p, &left, flags);
12497 remote_buffer_add_string (&p, &left, ",");
12498
12499 remote_buffer_add_int (&p, &left, mode);
12500
12501 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12502 remote_errno, NULL, NULL);
12503 }
12504
12505 int
12506 remote_target::fileio_open (struct inferior *inf, const char *filename,
12507 int flags, int mode, int warn_if_slow,
12508 fileio_error *remote_errno)
12509 {
12510 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12511 remote_errno);
12512 }
12513
12514 /* Implementation of to_fileio_pwrite. */
12515
12516 int
12517 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12518 ULONGEST offset, fileio_error *remote_errno)
12519 {
12520 struct remote_state *rs = get_remote_state ();
12521 char *p = rs->buf.data ();
12522 int left = get_remote_packet_size ();
12523 int out_len;
12524
12525 rs->readahead_cache.invalidate_fd (fd);
12526
12527 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12528
12529 remote_buffer_add_int (&p, &left, fd);
12530 remote_buffer_add_string (&p, &left, ",");
12531
12532 remote_buffer_add_int (&p, &left, offset);
12533 remote_buffer_add_string (&p, &left, ",");
12534
12535 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12536 (get_remote_packet_size ()
12537 - (p - rs->buf.data ())));
12538
12539 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12540 remote_errno, NULL, NULL);
12541 }
12542
12543 int
12544 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12545 ULONGEST offset, fileio_error *remote_errno)
12546 {
12547 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12548 }
12549
12550 /* Helper for the implementation of to_fileio_pread. Read the file
12551 from the remote side with vFile:pread. */
12552
12553 int
12554 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12555 ULONGEST offset, fileio_error *remote_errno)
12556 {
12557 struct remote_state *rs = get_remote_state ();
12558 char *p = rs->buf.data ();
12559 const char *attachment;
12560 int left = get_remote_packet_size ();
12561 int ret, attachment_len;
12562 int read_len;
12563
12564 remote_buffer_add_string (&p, &left, "vFile:pread:");
12565
12566 remote_buffer_add_int (&p, &left, fd);
12567 remote_buffer_add_string (&p, &left, ",");
12568
12569 remote_buffer_add_int (&p, &left, len);
12570 remote_buffer_add_string (&p, &left, ",");
12571
12572 remote_buffer_add_int (&p, &left, offset);
12573
12574 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12575 remote_errno, &attachment,
12576 &attachment_len);
12577
12578 if (ret < 0)
12579 return ret;
12580
12581 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12582 read_buf, len);
12583 if (read_len != ret)
12584 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12585
12586 return ret;
12587 }
12588
12589 /* See declaration.h. */
12590
12591 int
12592 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12593 ULONGEST offset)
12594 {
12595 if (this->fd == fd
12596 && this->offset <= offset
12597 && offset < this->offset + this->buf.size ())
12598 {
12599 ULONGEST max = this->offset + this->buf.size ();
12600
12601 if (offset + len > max)
12602 len = max - offset;
12603
12604 memcpy (read_buf, &this->buf[offset - this->offset], len);
12605 return len;
12606 }
12607
12608 return 0;
12609 }
12610
12611 /* Implementation of to_fileio_pread. */
12612
12613 int
12614 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12615 ULONGEST offset, fileio_error *remote_errno)
12616 {
12617 int ret;
12618 struct remote_state *rs = get_remote_state ();
12619 readahead_cache *cache = &rs->readahead_cache;
12620
12621 ret = cache->pread (fd, read_buf, len, offset);
12622 if (ret > 0)
12623 {
12624 cache->hit_count++;
12625
12626 remote_debug_printf ("readahead cache hit %s",
12627 pulongest (cache->hit_count));
12628 return ret;
12629 }
12630
12631 cache->miss_count++;
12632
12633 remote_debug_printf ("readahead cache miss %s",
12634 pulongest (cache->miss_count));
12635
12636 cache->fd = fd;
12637 cache->offset = offset;
12638 cache->buf.resize (get_remote_packet_size ());
12639
12640 ret = remote_hostio_pread_vFile (cache->fd, &cache->buf[0],
12641 cache->buf.size (),
12642 cache->offset, remote_errno);
12643 if (ret <= 0)
12644 {
12645 cache->invalidate_fd (fd);
12646 return ret;
12647 }
12648
12649 cache->buf.resize (ret);
12650 return cache->pread (fd, read_buf, len, offset);
12651 }
12652
12653 int
12654 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12655 ULONGEST offset, fileio_error *remote_errno)
12656 {
12657 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12658 }
12659
12660 /* Implementation of to_fileio_close. */
12661
12662 int
12663 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12664 {
12665 struct remote_state *rs = get_remote_state ();
12666 char *p = rs->buf.data ();
12667 int left = get_remote_packet_size () - 1;
12668
12669 rs->readahead_cache.invalidate_fd (fd);
12670
12671 remote_buffer_add_string (&p, &left, "vFile:close:");
12672
12673 remote_buffer_add_int (&p, &left, fd);
12674
12675 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12676 remote_errno, NULL, NULL);
12677 }
12678
12679 int
12680 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12681 {
12682 return remote_hostio_close (fd, remote_errno);
12683 }
12684
12685 /* Implementation of to_fileio_unlink. */
12686
12687 int
12688 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12689 fileio_error *remote_errno)
12690 {
12691 struct remote_state *rs = get_remote_state ();
12692 char *p = rs->buf.data ();
12693 int left = get_remote_packet_size () - 1;
12694
12695 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12696 return -1;
12697
12698 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12699
12700 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12701 strlen (filename));
12702
12703 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12704 remote_errno, NULL, NULL);
12705 }
12706
12707 int
12708 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12709 fileio_error *remote_errno)
12710 {
12711 return remote_hostio_unlink (inf, filename, remote_errno);
12712 }
12713
12714 /* Implementation of to_fileio_readlink. */
12715
12716 gdb::optional<std::string>
12717 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12718 fileio_error *remote_errno)
12719 {
12720 struct remote_state *rs = get_remote_state ();
12721 char *p = rs->buf.data ();
12722 const char *attachment;
12723 int left = get_remote_packet_size ();
12724 int len, attachment_len;
12725 int read_len;
12726
12727 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12728 return {};
12729
12730 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12731
12732 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12733 strlen (filename));
12734
12735 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12736 remote_errno, &attachment,
12737 &attachment_len);
12738
12739 if (len < 0)
12740 return {};
12741
12742 std::string ret (len, '\0');
12743
12744 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12745 (gdb_byte *) &ret[0], len);
12746 if (read_len != len)
12747 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12748
12749 return ret;
12750 }
12751
12752 /* Implementation of to_fileio_fstat. */
12753
12754 int
12755 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12756 {
12757 struct remote_state *rs = get_remote_state ();
12758 char *p = rs->buf.data ();
12759 int left = get_remote_packet_size ();
12760 int attachment_len, ret;
12761 const char *attachment;
12762 struct fio_stat fst;
12763 int read_len;
12764
12765 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12766
12767 remote_buffer_add_int (&p, &left, fd);
12768
12769 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12770 remote_errno, &attachment,
12771 &attachment_len);
12772 if (ret < 0)
12773 {
12774 if (*remote_errno != FILEIO_ENOSYS)
12775 return ret;
12776
12777 /* Strictly we should return -1, ENOSYS here, but when
12778 "set sysroot remote:" was implemented in August 2008
12779 BFD's need for a stat function was sidestepped with
12780 this hack. This was not remedied until March 2015
12781 so we retain the previous behavior to avoid breaking
12782 compatibility.
12783
12784 Note that the memset is a March 2015 addition; older
12785 GDBs set st_size *and nothing else* so the structure
12786 would have garbage in all other fields. This might
12787 break something but retaining the previous behavior
12788 here would be just too wrong. */
12789
12790 memset (st, 0, sizeof (struct stat));
12791 st->st_size = INT_MAX;
12792 return 0;
12793 }
12794
12795 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12796 (gdb_byte *) &fst, sizeof (fst));
12797
12798 if (read_len != ret)
12799 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12800
12801 if (read_len != sizeof (fst))
12802 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12803 read_len, (int) sizeof (fst));
12804
12805 remote_fileio_to_host_stat (&fst, st);
12806
12807 return 0;
12808 }
12809
12810 /* Implementation of to_filesystem_is_local. */
12811
12812 bool
12813 remote_target::filesystem_is_local ()
12814 {
12815 /* Valgrind GDB presents itself as a remote target but works
12816 on the local filesystem: it does not implement remote get
12817 and users are not expected to set a sysroot. To handle
12818 this case we treat the remote filesystem as local if the
12819 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12820 does not support vFile:open. */
12821 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12822 {
12823 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12824
12825 if (ps == PACKET_SUPPORT_UNKNOWN)
12826 {
12827 int fd;
12828 fileio_error remote_errno;
12829
12830 /* Try opening a file to probe support. The supplied
12831 filename is irrelevant, we only care about whether
12832 the stub recognizes the packet or not. */
12833 fd = remote_hostio_open (NULL, "just probing",
12834 FILEIO_O_RDONLY, 0700, 0,
12835 &remote_errno);
12836
12837 if (fd >= 0)
12838 remote_hostio_close (fd, &remote_errno);
12839
12840 ps = m_features.packet_support (PACKET_vFile_open);
12841 }
12842
12843 if (ps == PACKET_DISABLE)
12844 {
12845 static int warning_issued = 0;
12846
12847 if (!warning_issued)
12848 {
12849 warning (_("remote target does not support file"
12850 " transfer, attempting to access files"
12851 " from local filesystem."));
12852 warning_issued = 1;
12853 }
12854
12855 return true;
12856 }
12857 }
12858
12859 return false;
12860 }
12861
12862 static char *
12863 remote_hostio_error (fileio_error errnum)
12864 {
12865 int host_error = fileio_error_to_host (errnum);
12866
12867 if (host_error == -1)
12868 error (_("Unknown remote I/O error %d"), errnum);
12869 else
12870 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12871 }
12872
12873 /* A RAII wrapper around a remote file descriptor. */
12874
12875 class scoped_remote_fd
12876 {
12877 public:
12878 scoped_remote_fd (remote_target *remote, int fd)
12879 : m_remote (remote), m_fd (fd)
12880 {
12881 }
12882
12883 ~scoped_remote_fd ()
12884 {
12885 if (m_fd != -1)
12886 {
12887 try
12888 {
12889 fileio_error remote_errno;
12890 m_remote->remote_hostio_close (m_fd, &remote_errno);
12891 }
12892 catch (...)
12893 {
12894 /* Swallow exception before it escapes the dtor. If
12895 something goes wrong, likely the connection is gone,
12896 and there's nothing else that can be done. */
12897 }
12898 }
12899 }
12900
12901 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12902
12903 /* Release ownership of the file descriptor, and return it. */
12904 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12905 {
12906 int fd = m_fd;
12907 m_fd = -1;
12908 return fd;
12909 }
12910
12911 /* Return the owned file descriptor. */
12912 int get () const noexcept
12913 {
12914 return m_fd;
12915 }
12916
12917 private:
12918 /* The remote target. */
12919 remote_target *m_remote;
12920
12921 /* The owned remote I/O file descriptor. */
12922 int m_fd;
12923 };
12924
12925 void
12926 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12927 {
12928 remote_target *remote = get_current_remote_target ();
12929
12930 if (remote == nullptr)
12931 error (_("command can only be used with remote target"));
12932
12933 remote->remote_file_put (local_file, remote_file, from_tty);
12934 }
12935
12936 void
12937 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12938 int from_tty)
12939 {
12940 int retcode, bytes, io_size;
12941 fileio_error remote_errno;
12942 int bytes_in_buffer;
12943 int saw_eof;
12944 ULONGEST offset;
12945
12946 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12947 if (file == NULL)
12948 perror_with_name (local_file);
12949
12950 scoped_remote_fd fd
12951 (this, remote_hostio_open (NULL,
12952 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12953 | FILEIO_O_TRUNC),
12954 0700, 0, &remote_errno));
12955 if (fd.get () == -1)
12956 remote_hostio_error (remote_errno);
12957
12958 /* Send up to this many bytes at once. They won't all fit in the
12959 remote packet limit, so we'll transfer slightly fewer. */
12960 io_size = get_remote_packet_size ();
12961 gdb::byte_vector buffer (io_size);
12962
12963 bytes_in_buffer = 0;
12964 saw_eof = 0;
12965 offset = 0;
12966 while (bytes_in_buffer || !saw_eof)
12967 {
12968 if (!saw_eof)
12969 {
12970 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12971 io_size - bytes_in_buffer,
12972 file.get ());
12973 if (bytes == 0)
12974 {
12975 if (ferror (file.get ()))
12976 error (_("Error reading %s."), local_file);
12977 else
12978 {
12979 /* EOF. Unless there is something still in the
12980 buffer from the last iteration, we are done. */
12981 saw_eof = 1;
12982 if (bytes_in_buffer == 0)
12983 break;
12984 }
12985 }
12986 }
12987 else
12988 bytes = 0;
12989
12990 bytes += bytes_in_buffer;
12991 bytes_in_buffer = 0;
12992
12993 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12994 offset, &remote_errno);
12995
12996 if (retcode < 0)
12997 remote_hostio_error (remote_errno);
12998 else if (retcode == 0)
12999 error (_("Remote write of %d bytes returned 0!"), bytes);
13000 else if (retcode < bytes)
13001 {
13002 /* Short write. Save the rest of the read data for the next
13003 write. */
13004 bytes_in_buffer = bytes - retcode;
13005 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13006 }
13007
13008 offset += retcode;
13009 }
13010
13011 if (remote_hostio_close (fd.release (), &remote_errno))
13012 remote_hostio_error (remote_errno);
13013
13014 if (from_tty)
13015 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13016 }
13017
13018 void
13019 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13020 {
13021 remote_target *remote = get_current_remote_target ();
13022
13023 if (remote == nullptr)
13024 error (_("command can only be used with remote target"));
13025
13026 remote->remote_file_get (remote_file, local_file, from_tty);
13027 }
13028
13029 void
13030 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13031 int from_tty)
13032 {
13033 fileio_error remote_errno;
13034 int bytes, io_size;
13035 ULONGEST offset;
13036
13037 scoped_remote_fd fd
13038 (this, remote_hostio_open (NULL,
13039 remote_file, FILEIO_O_RDONLY, 0, 0,
13040 &remote_errno));
13041 if (fd.get () == -1)
13042 remote_hostio_error (remote_errno);
13043
13044 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13045 if (file == NULL)
13046 perror_with_name (local_file);
13047
13048 /* Send up to this many bytes at once. They won't all fit in the
13049 remote packet limit, so we'll transfer slightly fewer. */
13050 io_size = get_remote_packet_size ();
13051 gdb::byte_vector buffer (io_size);
13052
13053 offset = 0;
13054 while (1)
13055 {
13056 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13057 &remote_errno);
13058 if (bytes == 0)
13059 /* Success, but no bytes, means end-of-file. */
13060 break;
13061 if (bytes == -1)
13062 remote_hostio_error (remote_errno);
13063
13064 offset += bytes;
13065
13066 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13067 if (bytes == 0)
13068 perror_with_name (local_file);
13069 }
13070
13071 if (remote_hostio_close (fd.release (), &remote_errno))
13072 remote_hostio_error (remote_errno);
13073
13074 if (from_tty)
13075 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13076 }
13077
13078 void
13079 remote_file_delete (const char *remote_file, int from_tty)
13080 {
13081 remote_target *remote = get_current_remote_target ();
13082
13083 if (remote == nullptr)
13084 error (_("command can only be used with remote target"));
13085
13086 remote->remote_file_delete (remote_file, from_tty);
13087 }
13088
13089 void
13090 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13091 {
13092 int retcode;
13093 fileio_error remote_errno;
13094
13095 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13096 if (retcode == -1)
13097 remote_hostio_error (remote_errno);
13098
13099 if (from_tty)
13100 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13101 }
13102
13103 static void
13104 remote_put_command (const char *args, int from_tty)
13105 {
13106 if (args == NULL)
13107 error_no_arg (_("file to put"));
13108
13109 gdb_argv argv (args);
13110 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13111 error (_("Invalid parameters to remote put"));
13112
13113 remote_file_put (argv[0], argv[1], from_tty);
13114 }
13115
13116 static void
13117 remote_get_command (const char *args, int from_tty)
13118 {
13119 if (args == NULL)
13120 error_no_arg (_("file to get"));
13121
13122 gdb_argv argv (args);
13123 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13124 error (_("Invalid parameters to remote get"));
13125
13126 remote_file_get (argv[0], argv[1], from_tty);
13127 }
13128
13129 static void
13130 remote_delete_command (const char *args, int from_tty)
13131 {
13132 if (args == NULL)
13133 error_no_arg (_("file to delete"));
13134
13135 gdb_argv argv (args);
13136 if (argv[0] == NULL || argv[1] != NULL)
13137 error (_("Invalid parameters to remote delete"));
13138
13139 remote_file_delete (argv[0], from_tty);
13140 }
13141
13142 bool
13143 remote_target::can_execute_reverse ()
13144 {
13145 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13146 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13147 return true;
13148 else
13149 return false;
13150 }
13151
13152 bool
13153 remote_target::supports_non_stop ()
13154 {
13155 return true;
13156 }
13157
13158 bool
13159 remote_target::supports_disable_randomization ()
13160 {
13161 /* Only supported in extended mode. */
13162 return false;
13163 }
13164
13165 bool
13166 remote_target::supports_multi_process ()
13167 {
13168 return m_features.remote_multi_process_p ();
13169 }
13170
13171 int
13172 remote_target::remote_supports_cond_tracepoints ()
13173 {
13174 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13175 == PACKET_ENABLE);
13176 }
13177
13178 bool
13179 remote_target::supports_evaluation_of_breakpoint_conditions ()
13180 {
13181 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13182 == PACKET_ENABLE);
13183 }
13184
13185 int
13186 remote_target::remote_supports_fast_tracepoints ()
13187 {
13188 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13189 }
13190
13191 int
13192 remote_target::remote_supports_static_tracepoints ()
13193 {
13194 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13195 }
13196
13197 int
13198 remote_target::remote_supports_install_in_trace ()
13199 {
13200 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13201 }
13202
13203 bool
13204 remote_target::supports_enable_disable_tracepoint ()
13205 {
13206 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13207 == PACKET_ENABLE);
13208 }
13209
13210 bool
13211 remote_target::supports_string_tracing ()
13212 {
13213 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13214 }
13215
13216 bool
13217 remote_target::can_run_breakpoint_commands ()
13218 {
13219 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13220 }
13221
13222 void
13223 remote_target::trace_init ()
13224 {
13225 struct remote_state *rs = get_remote_state ();
13226
13227 putpkt ("QTinit");
13228 remote_get_noisy_reply ();
13229 if (strcmp (rs->buf.data (), "OK") != 0)
13230 error (_("Target does not support this command."));
13231 }
13232
13233 /* Recursive routine to walk through command list including loops, and
13234 download packets for each command. */
13235
13236 void
13237 remote_target::remote_download_command_source (int num, ULONGEST addr,
13238 struct command_line *cmds)
13239 {
13240 struct remote_state *rs = get_remote_state ();
13241 struct command_line *cmd;
13242
13243 for (cmd = cmds; cmd; cmd = cmd->next)
13244 {
13245 QUIT; /* Allow user to bail out with ^C. */
13246 strcpy (rs->buf.data (), "QTDPsrc:");
13247 encode_source_string (num, addr, "cmd", cmd->line,
13248 rs->buf.data () + strlen (rs->buf.data ()),
13249 rs->buf.size () - strlen (rs->buf.data ()));
13250 putpkt (rs->buf);
13251 remote_get_noisy_reply ();
13252 if (strcmp (rs->buf.data (), "OK"))
13253 warning (_("Target does not support source download."));
13254
13255 if (cmd->control_type == while_control
13256 || cmd->control_type == while_stepping_control)
13257 {
13258 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13259
13260 QUIT; /* Allow user to bail out with ^C. */
13261 strcpy (rs->buf.data (), "QTDPsrc:");
13262 encode_source_string (num, addr, "cmd", "end",
13263 rs->buf.data () + strlen (rs->buf.data ()),
13264 rs->buf.size () - strlen (rs->buf.data ()));
13265 putpkt (rs->buf);
13266 remote_get_noisy_reply ();
13267 if (strcmp (rs->buf.data (), "OK"))
13268 warning (_("Target does not support source download."));
13269 }
13270 }
13271 }
13272
13273 void
13274 remote_target::download_tracepoint (struct bp_location *loc)
13275 {
13276 CORE_ADDR tpaddr;
13277 char addrbuf[40];
13278 std::vector<std::string> tdp_actions;
13279 std::vector<std::string> stepping_actions;
13280 char *pkt;
13281 struct breakpoint *b = loc->owner;
13282 struct tracepoint *t = (struct tracepoint *) b;
13283 struct remote_state *rs = get_remote_state ();
13284 int ret;
13285 const char *err_msg = _("Tracepoint packet too large for target.");
13286 size_t size_left;
13287
13288 /* We use a buffer other than rs->buf because we'll build strings
13289 across multiple statements, and other statements in between could
13290 modify rs->buf. */
13291 gdb::char_vector buf (get_remote_packet_size ());
13292
13293 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13294
13295 tpaddr = loc->address;
13296 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13297 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13298 b->number, addrbuf, /* address */
13299 (b->enable_state == bp_enabled ? 'E' : 'D'),
13300 t->step_count, t->pass_count);
13301
13302 if (ret < 0 || ret >= buf.size ())
13303 error ("%s", err_msg);
13304
13305 /* Fast tracepoints are mostly handled by the target, but we can
13306 tell the target how big of an instruction block should be moved
13307 around. */
13308 if (b->type == bp_fast_tracepoint)
13309 {
13310 /* Only test for support at download time; we may not know
13311 target capabilities at definition time. */
13312 if (remote_supports_fast_tracepoints ())
13313 {
13314 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13315 NULL))
13316 {
13317 size_left = buf.size () - strlen (buf.data ());
13318 ret = snprintf (buf.data () + strlen (buf.data ()),
13319 size_left, ":F%x",
13320 gdb_insn_length (loc->gdbarch, tpaddr));
13321
13322 if (ret < 0 || ret >= size_left)
13323 error ("%s", err_msg);
13324 }
13325 else
13326 /* If it passed validation at definition but fails now,
13327 something is very wrong. */
13328 internal_error (_("Fast tracepoint not valid during download"));
13329 }
13330 else
13331 /* Fast tracepoints are functionally identical to regular
13332 tracepoints, so don't take lack of support as a reason to
13333 give up on the trace run. */
13334 warning (_("Target does not support fast tracepoints, "
13335 "downloading %d as regular tracepoint"), b->number);
13336 }
13337 else if (b->type == bp_static_tracepoint
13338 || b->type == bp_static_marker_tracepoint)
13339 {
13340 /* Only test for support at download time; we may not know
13341 target capabilities at definition time. */
13342 if (remote_supports_static_tracepoints ())
13343 {
13344 struct static_tracepoint_marker marker;
13345
13346 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13347 {
13348 size_left = buf.size () - strlen (buf.data ());
13349 ret = snprintf (buf.data () + strlen (buf.data ()),
13350 size_left, ":S");
13351
13352 if (ret < 0 || ret >= size_left)
13353 error ("%s", err_msg);
13354 }
13355 else
13356 error (_("Static tracepoint not valid during download"));
13357 }
13358 else
13359 /* Fast tracepoints are functionally identical to regular
13360 tracepoints, so don't take lack of support as a reason
13361 to give up on the trace run. */
13362 error (_("Target does not support static tracepoints"));
13363 }
13364 /* If the tracepoint has a conditional, make it into an agent
13365 expression and append to the definition. */
13366 if (loc->cond)
13367 {
13368 /* Only test support at download time, we may not know target
13369 capabilities at definition time. */
13370 if (remote_supports_cond_tracepoints ())
13371 {
13372 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13373 loc->cond.get ());
13374
13375 size_left = buf.size () - strlen (buf.data ());
13376
13377 ret = snprintf (buf.data () + strlen (buf.data ()),
13378 size_left, ":X%x,", (int) aexpr->buf.size ());
13379
13380 if (ret < 0 || ret >= size_left)
13381 error ("%s", err_msg);
13382
13383 size_left = buf.size () - strlen (buf.data ());
13384
13385 /* Two bytes to encode each aexpr byte, plus the terminating
13386 null byte. */
13387 if (aexpr->buf.size () * 2 + 1 > size_left)
13388 error ("%s", err_msg);
13389
13390 pkt = buf.data () + strlen (buf.data ());
13391
13392 for (int ndx = 0; ndx < aexpr->buf.size (); ++ndx)
13393 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13394 *pkt = '\0';
13395 }
13396 else
13397 warning (_("Target does not support conditional tracepoints, "
13398 "ignoring tp %d cond"), b->number);
13399 }
13400
13401 if (b->commands || !default_collect.empty ())
13402 {
13403 size_left = buf.size () - strlen (buf.data ());
13404
13405 ret = snprintf (buf.data () + strlen (buf.data ()),
13406 size_left, "-");
13407
13408 if (ret < 0 || ret >= size_left)
13409 error ("%s", err_msg);
13410 }
13411
13412 putpkt (buf.data ());
13413 remote_get_noisy_reply ();
13414 if (strcmp (rs->buf.data (), "OK"))
13415 error (_("Target does not support tracepoints."));
13416
13417 /* do_single_steps (t); */
13418 for (auto action_it = tdp_actions.begin ();
13419 action_it != tdp_actions.end (); action_it++)
13420 {
13421 QUIT; /* Allow user to bail out with ^C. */
13422
13423 bool has_more = ((action_it + 1) != tdp_actions.end ()
13424 || !stepping_actions.empty ());
13425
13426 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13427 b->number, addrbuf, /* address */
13428 action_it->c_str (),
13429 has_more ? '-' : 0);
13430
13431 if (ret < 0 || ret >= buf.size ())
13432 error ("%s", err_msg);
13433
13434 putpkt (buf.data ());
13435 remote_get_noisy_reply ();
13436 if (strcmp (rs->buf.data (), "OK"))
13437 error (_("Error on target while setting tracepoints."));
13438 }
13439
13440 for (auto action_it = stepping_actions.begin ();
13441 action_it != stepping_actions.end (); action_it++)
13442 {
13443 QUIT; /* Allow user to bail out with ^C. */
13444
13445 bool is_first = action_it == stepping_actions.begin ();
13446 bool has_more = (action_it + 1) != stepping_actions.end ();
13447
13448 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13449 b->number, addrbuf, /* address */
13450 is_first ? "S" : "",
13451 action_it->c_str (),
13452 has_more ? "-" : "");
13453
13454 if (ret < 0 || ret >= buf.size ())
13455 error ("%s", err_msg);
13456
13457 putpkt (buf.data ());
13458 remote_get_noisy_reply ();
13459 if (strcmp (rs->buf.data (), "OK"))
13460 error (_("Error on target while setting tracepoints."));
13461 }
13462
13463 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13464 {
13465 if (b->locspec != nullptr)
13466 {
13467 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13468
13469 if (ret < 0 || ret >= buf.size ())
13470 error ("%s", err_msg);
13471
13472 const char *str = b->locspec->to_string ();
13473 encode_source_string (b->number, loc->address, "at", str,
13474 buf.data () + strlen (buf.data ()),
13475 buf.size () - strlen (buf.data ()));
13476 putpkt (buf.data ());
13477 remote_get_noisy_reply ();
13478 if (strcmp (rs->buf.data (), "OK"))
13479 warning (_("Target does not support source download."));
13480 }
13481 if (b->cond_string)
13482 {
13483 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13484
13485 if (ret < 0 || ret >= buf.size ())
13486 error ("%s", err_msg);
13487
13488 encode_source_string (b->number, loc->address,
13489 "cond", b->cond_string.get (),
13490 buf.data () + strlen (buf.data ()),
13491 buf.size () - strlen (buf.data ()));
13492 putpkt (buf.data ());
13493 remote_get_noisy_reply ();
13494 if (strcmp (rs->buf.data (), "OK"))
13495 warning (_("Target does not support source download."));
13496 }
13497 remote_download_command_source (b->number, loc->address,
13498 breakpoint_commands (b));
13499 }
13500 }
13501
13502 bool
13503 remote_target::can_download_tracepoint ()
13504 {
13505 struct remote_state *rs = get_remote_state ();
13506 struct trace_status *ts;
13507 int status;
13508
13509 /* Don't try to install tracepoints until we've relocated our
13510 symbols, and fetched and merged the target's tracepoint list with
13511 ours. */
13512 if (rs->starting_up)
13513 return false;
13514
13515 ts = current_trace_status ();
13516 status = get_trace_status (ts);
13517
13518 if (status == -1 || !ts->running_known || !ts->running)
13519 return false;
13520
13521 /* If we are in a tracing experiment, but remote stub doesn't support
13522 installing tracepoint in trace, we have to return. */
13523 if (!remote_supports_install_in_trace ())
13524 return false;
13525
13526 return true;
13527 }
13528
13529
13530 void
13531 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13532 {
13533 struct remote_state *rs = get_remote_state ();
13534 char *p;
13535
13536 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13537 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13538 tsv.builtin);
13539 p = rs->buf.data () + strlen (rs->buf.data ());
13540 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13541 >= get_remote_packet_size ())
13542 error (_("Trace state variable name too long for tsv definition packet"));
13543 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13544 *p++ = '\0';
13545 putpkt (rs->buf);
13546 remote_get_noisy_reply ();
13547 if (rs->buf[0] == '\0')
13548 error (_("Target does not support this command."));
13549 if (strcmp (rs->buf.data (), "OK") != 0)
13550 error (_("Error on target while downloading trace state variable."));
13551 }
13552
13553 void
13554 remote_target::enable_tracepoint (struct bp_location *location)
13555 {
13556 struct remote_state *rs = get_remote_state ();
13557
13558 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13559 location->owner->number,
13560 phex (location->address, sizeof (CORE_ADDR)));
13561 putpkt (rs->buf);
13562 remote_get_noisy_reply ();
13563 if (rs->buf[0] == '\0')
13564 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13565 if (strcmp (rs->buf.data (), "OK") != 0)
13566 error (_("Error on target while enabling tracepoint."));
13567 }
13568
13569 void
13570 remote_target::disable_tracepoint (struct bp_location *location)
13571 {
13572 struct remote_state *rs = get_remote_state ();
13573
13574 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13575 location->owner->number,
13576 phex (location->address, sizeof (CORE_ADDR)));
13577 putpkt (rs->buf);
13578 remote_get_noisy_reply ();
13579 if (rs->buf[0] == '\0')
13580 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13581 if (strcmp (rs->buf.data (), "OK") != 0)
13582 error (_("Error on target while disabling tracepoint."));
13583 }
13584
13585 void
13586 remote_target::trace_set_readonly_regions ()
13587 {
13588 asection *s;
13589 bfd_size_type size;
13590 bfd_vma vma;
13591 int anysecs = 0;
13592 int offset = 0;
13593 bfd *abfd = current_program_space->exec_bfd ();
13594
13595 if (!abfd)
13596 return; /* No information to give. */
13597
13598 struct remote_state *rs = get_remote_state ();
13599
13600 strcpy (rs->buf.data (), "QTro");
13601 offset = strlen (rs->buf.data ());
13602 for (s = abfd->sections; s; s = s->next)
13603 {
13604 char tmp1[40], tmp2[40];
13605 int sec_length;
13606
13607 if ((s->flags & SEC_LOAD) == 0
13608 /* || (s->flags & SEC_CODE) == 0 */
13609 || (s->flags & SEC_READONLY) == 0)
13610 continue;
13611
13612 anysecs = 1;
13613 vma = bfd_section_vma (s);
13614 size = bfd_section_size (s);
13615 bfd_sprintf_vma (abfd, tmp1, vma);
13616 bfd_sprintf_vma (abfd, tmp2, vma + size);
13617 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13618 if (offset + sec_length + 1 > rs->buf.size ())
13619 {
13620 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13621 != PACKET_ENABLE)
13622 warning (_("\
13623 Too many sections for read-only sections definition packet."));
13624 break;
13625 }
13626 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13627 tmp1, tmp2);
13628 offset += sec_length;
13629 }
13630 if (anysecs)
13631 {
13632 putpkt (rs->buf);
13633 getpkt (&rs->buf, 0);
13634 }
13635 }
13636
13637 void
13638 remote_target::trace_start ()
13639 {
13640 struct remote_state *rs = get_remote_state ();
13641
13642 putpkt ("QTStart");
13643 remote_get_noisy_reply ();
13644 if (rs->buf[0] == '\0')
13645 error (_("Target does not support this command."));
13646 if (strcmp (rs->buf.data (), "OK") != 0)
13647 error (_("Bogus reply from target: %s"), rs->buf.data ());
13648 }
13649
13650 int
13651 remote_target::get_trace_status (struct trace_status *ts)
13652 {
13653 /* Initialize it just to avoid a GCC false warning. */
13654 char *p = NULL;
13655 enum packet_result result;
13656 struct remote_state *rs = get_remote_state ();
13657
13658 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13659 return -1;
13660
13661 /* FIXME we need to get register block size some other way. */
13662 trace_regblock_size
13663 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13664
13665 putpkt ("qTStatus");
13666
13667 try
13668 {
13669 p = remote_get_noisy_reply ();
13670 }
13671 catch (const gdb_exception_error &ex)
13672 {
13673 if (ex.error != TARGET_CLOSE_ERROR)
13674 {
13675 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13676 return -1;
13677 }
13678 throw;
13679 }
13680
13681 result = m_features.packet_ok (p, PACKET_qTStatus);
13682
13683 /* If the remote target doesn't do tracing, flag it. */
13684 if (result == PACKET_UNKNOWN)
13685 return -1;
13686
13687 /* We're working with a live target. */
13688 ts->filename = NULL;
13689
13690 if (*p++ != 'T')
13691 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13692
13693 /* Function 'parse_trace_status' sets default value of each field of
13694 'ts' at first, so we don't have to do it here. */
13695 parse_trace_status (p, ts);
13696
13697 return ts->running;
13698 }
13699
13700 void
13701 remote_target::get_tracepoint_status (struct breakpoint *bp,
13702 struct uploaded_tp *utp)
13703 {
13704 struct remote_state *rs = get_remote_state ();
13705 char *reply;
13706 struct tracepoint *tp = (struct tracepoint *) bp;
13707 size_t size = get_remote_packet_size ();
13708
13709 if (tp)
13710 {
13711 tp->hit_count = 0;
13712 tp->traceframe_usage = 0;
13713 for (bp_location &loc : tp->locations ())
13714 {
13715 /* If the tracepoint was never downloaded, don't go asking for
13716 any status. */
13717 if (tp->number_on_target == 0)
13718 continue;
13719 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13720 phex_nz (loc.address, 0));
13721 putpkt (rs->buf);
13722 reply = remote_get_noisy_reply ();
13723 if (reply && *reply)
13724 {
13725 if (*reply == 'V')
13726 parse_tracepoint_status (reply + 1, bp, utp);
13727 }
13728 }
13729 }
13730 else if (utp)
13731 {
13732 utp->hit_count = 0;
13733 utp->traceframe_usage = 0;
13734 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13735 phex_nz (utp->addr, 0));
13736 putpkt (rs->buf);
13737 reply = remote_get_noisy_reply ();
13738 if (reply && *reply)
13739 {
13740 if (*reply == 'V')
13741 parse_tracepoint_status (reply + 1, bp, utp);
13742 }
13743 }
13744 }
13745
13746 void
13747 remote_target::trace_stop ()
13748 {
13749 struct remote_state *rs = get_remote_state ();
13750
13751 putpkt ("QTStop");
13752 remote_get_noisy_reply ();
13753 if (rs->buf[0] == '\0')
13754 error (_("Target does not support this command."));
13755 if (strcmp (rs->buf.data (), "OK") != 0)
13756 error (_("Bogus reply from target: %s"), rs->buf.data ());
13757 }
13758
13759 int
13760 remote_target::trace_find (enum trace_find_type type, int num,
13761 CORE_ADDR addr1, CORE_ADDR addr2,
13762 int *tpp)
13763 {
13764 struct remote_state *rs = get_remote_state ();
13765 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13766 char *p, *reply;
13767 int target_frameno = -1, target_tracept = -1;
13768
13769 /* Lookups other than by absolute frame number depend on the current
13770 trace selected, so make sure it is correct on the remote end
13771 first. */
13772 if (type != tfind_number)
13773 set_remote_traceframe ();
13774
13775 p = rs->buf.data ();
13776 strcpy (p, "QTFrame:");
13777 p = strchr (p, '\0');
13778 switch (type)
13779 {
13780 case tfind_number:
13781 xsnprintf (p, endbuf - p, "%x", num);
13782 break;
13783 case tfind_pc:
13784 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13785 break;
13786 case tfind_tp:
13787 xsnprintf (p, endbuf - p, "tdp:%x", num);
13788 break;
13789 case tfind_range:
13790 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13791 phex_nz (addr2, 0));
13792 break;
13793 case tfind_outside:
13794 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13795 phex_nz (addr2, 0));
13796 break;
13797 default:
13798 error (_("Unknown trace find type %d"), type);
13799 }
13800
13801 putpkt (rs->buf);
13802 reply = remote_get_noisy_reply ();
13803 if (*reply == '\0')
13804 error (_("Target does not support this command."));
13805
13806 while (reply && *reply)
13807 switch (*reply)
13808 {
13809 case 'F':
13810 p = ++reply;
13811 target_frameno = (int) strtol (p, &reply, 16);
13812 if (reply == p)
13813 error (_("Unable to parse trace frame number"));
13814 /* Don't update our remote traceframe number cache on failure
13815 to select a remote traceframe. */
13816 if (target_frameno == -1)
13817 return -1;
13818 break;
13819 case 'T':
13820 p = ++reply;
13821 target_tracept = (int) strtol (p, &reply, 16);
13822 if (reply == p)
13823 error (_("Unable to parse tracepoint number"));
13824 break;
13825 case 'O': /* "OK"? */
13826 if (reply[1] == 'K' && reply[2] == '\0')
13827 reply += 2;
13828 else
13829 error (_("Bogus reply from target: %s"), reply);
13830 break;
13831 default:
13832 error (_("Bogus reply from target: %s"), reply);
13833 }
13834 if (tpp)
13835 *tpp = target_tracept;
13836
13837 rs->remote_traceframe_number = target_frameno;
13838 return target_frameno;
13839 }
13840
13841 bool
13842 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13843 {
13844 struct remote_state *rs = get_remote_state ();
13845 char *reply;
13846 ULONGEST uval;
13847
13848 set_remote_traceframe ();
13849
13850 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13851 putpkt (rs->buf);
13852 reply = remote_get_noisy_reply ();
13853 if (reply && *reply)
13854 {
13855 if (*reply == 'V')
13856 {
13857 unpack_varlen_hex (reply + 1, &uval);
13858 *val = (LONGEST) uval;
13859 return true;
13860 }
13861 }
13862 return false;
13863 }
13864
13865 int
13866 remote_target::save_trace_data (const char *filename)
13867 {
13868 struct remote_state *rs = get_remote_state ();
13869 char *p, *reply;
13870
13871 p = rs->buf.data ();
13872 strcpy (p, "QTSave:");
13873 p += strlen (p);
13874 if ((p - rs->buf.data ()) + strlen (filename) * 2
13875 >= get_remote_packet_size ())
13876 error (_("Remote file name too long for trace save packet"));
13877 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13878 *p++ = '\0';
13879 putpkt (rs->buf);
13880 reply = remote_get_noisy_reply ();
13881 if (*reply == '\0')
13882 error (_("Target does not support this command."));
13883 if (strcmp (reply, "OK") != 0)
13884 error (_("Bogus reply from target: %s"), reply);
13885 return 0;
13886 }
13887
13888 /* This is basically a memory transfer, but needs to be its own packet
13889 because we don't know how the target actually organizes its trace
13890 memory, plus we want to be able to ask for as much as possible, but
13891 not be unhappy if we don't get as much as we ask for. */
13892
13893 LONGEST
13894 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13895 {
13896 struct remote_state *rs = get_remote_state ();
13897 char *reply;
13898 char *p;
13899 int rslt;
13900
13901 p = rs->buf.data ();
13902 strcpy (p, "qTBuffer:");
13903 p += strlen (p);
13904 p += hexnumstr (p, offset);
13905 *p++ = ',';
13906 p += hexnumstr (p, len);
13907 *p++ = '\0';
13908
13909 putpkt (rs->buf);
13910 reply = remote_get_noisy_reply ();
13911 if (reply && *reply)
13912 {
13913 /* 'l' by itself means we're at the end of the buffer and
13914 there is nothing more to get. */
13915 if (*reply == 'l')
13916 return 0;
13917
13918 /* Convert the reply into binary. Limit the number of bytes to
13919 convert according to our passed-in buffer size, rather than
13920 what was returned in the packet; if the target is
13921 unexpectedly generous and gives us a bigger reply than we
13922 asked for, we don't want to crash. */
13923 rslt = hex2bin (reply, buf, len);
13924 return rslt;
13925 }
13926
13927 /* Something went wrong, flag as an error. */
13928 return -1;
13929 }
13930
13931 void
13932 remote_target::set_disconnected_tracing (int val)
13933 {
13934 struct remote_state *rs = get_remote_state ();
13935
13936 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13937 == PACKET_ENABLE)
13938 {
13939 char *reply;
13940
13941 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13942 "QTDisconnected:%x", val);
13943 putpkt (rs->buf);
13944 reply = remote_get_noisy_reply ();
13945 if (*reply == '\0')
13946 error (_("Target does not support this command."));
13947 if (strcmp (reply, "OK") != 0)
13948 error (_("Bogus reply from target: %s"), reply);
13949 }
13950 else if (val)
13951 warning (_("Target does not support disconnected tracing."));
13952 }
13953
13954 int
13955 remote_target::core_of_thread (ptid_t ptid)
13956 {
13957 thread_info *info = this->find_thread (ptid);
13958
13959 if (info != NULL && info->priv != NULL)
13960 return get_remote_thread_info (info)->core;
13961
13962 return -1;
13963 }
13964
13965 void
13966 remote_target::set_circular_trace_buffer (int val)
13967 {
13968 struct remote_state *rs = get_remote_state ();
13969 char *reply;
13970
13971 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13972 "QTBuffer:circular:%x", val);
13973 putpkt (rs->buf);
13974 reply = remote_get_noisy_reply ();
13975 if (*reply == '\0')
13976 error (_("Target does not support this command."));
13977 if (strcmp (reply, "OK") != 0)
13978 error (_("Bogus reply from target: %s"), reply);
13979 }
13980
13981 traceframe_info_up
13982 remote_target::traceframe_info ()
13983 {
13984 gdb::optional<gdb::char_vector> text
13985 = target_read_stralloc (current_inferior ()->top_target (),
13986 TARGET_OBJECT_TRACEFRAME_INFO,
13987 NULL);
13988 if (text)
13989 return parse_traceframe_info (text->data ());
13990
13991 return NULL;
13992 }
13993
13994 /* Handle the qTMinFTPILen packet. Returns the minimum length of
13995 instruction on which a fast tracepoint may be placed. Returns -1
13996 if the packet is not supported, and 0 if the minimum instruction
13997 length is unknown. */
13998
13999 int
14000 remote_target::get_min_fast_tracepoint_insn_len ()
14001 {
14002 struct remote_state *rs = get_remote_state ();
14003 char *reply;
14004
14005 /* If we're not debugging a process yet, the IPA can't be
14006 loaded. */
14007 if (!target_has_execution ())
14008 return 0;
14009
14010 /* Make sure the remote is pointing at the right process. */
14011 set_general_process ();
14012
14013 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14014 putpkt (rs->buf);
14015 reply = remote_get_noisy_reply ();
14016 if (*reply == '\0')
14017 return -1;
14018 else
14019 {
14020 ULONGEST min_insn_len;
14021
14022 unpack_varlen_hex (reply, &min_insn_len);
14023
14024 return (int) min_insn_len;
14025 }
14026 }
14027
14028 void
14029 remote_target::set_trace_buffer_size (LONGEST val)
14030 {
14031 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14032 {
14033 struct remote_state *rs = get_remote_state ();
14034 char *buf = rs->buf.data ();
14035 char *endbuf = buf + get_remote_packet_size ();
14036 enum packet_result result;
14037
14038 gdb_assert (val >= 0 || val == -1);
14039 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14040 /* Send -1 as literal "-1" to avoid host size dependency. */
14041 if (val < 0)
14042 {
14043 *buf++ = '-';
14044 buf += hexnumstr (buf, (ULONGEST) -val);
14045 }
14046 else
14047 buf += hexnumstr (buf, (ULONGEST) val);
14048
14049 putpkt (rs->buf);
14050 remote_get_noisy_reply ();
14051 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14052
14053 if (result != PACKET_OK)
14054 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14055 }
14056 }
14057
14058 bool
14059 remote_target::set_trace_notes (const char *user, const char *notes,
14060 const char *stop_notes)
14061 {
14062 struct remote_state *rs = get_remote_state ();
14063 char *reply;
14064 char *buf = rs->buf.data ();
14065 char *endbuf = buf + get_remote_packet_size ();
14066 int nbytes;
14067
14068 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14069 if (user)
14070 {
14071 buf += xsnprintf (buf, endbuf - buf, "user:");
14072 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14073 buf += 2 * nbytes;
14074 *buf++ = ';';
14075 }
14076 if (notes)
14077 {
14078 buf += xsnprintf (buf, endbuf - buf, "notes:");
14079 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14080 buf += 2 * nbytes;
14081 *buf++ = ';';
14082 }
14083 if (stop_notes)
14084 {
14085 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14086 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14087 buf += 2 * nbytes;
14088 *buf++ = ';';
14089 }
14090 /* Ensure the buffer is terminated. */
14091 *buf = '\0';
14092
14093 putpkt (rs->buf);
14094 reply = remote_get_noisy_reply ();
14095 if (*reply == '\0')
14096 return false;
14097
14098 if (strcmp (reply, "OK") != 0)
14099 error (_("Bogus reply from target: %s"), reply);
14100
14101 return true;
14102 }
14103
14104 bool
14105 remote_target::use_agent (bool use)
14106 {
14107 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14108 {
14109 struct remote_state *rs = get_remote_state ();
14110
14111 /* If the stub supports QAgent. */
14112 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14113 putpkt (rs->buf);
14114 getpkt (&rs->buf, 0);
14115
14116 if (strcmp (rs->buf.data (), "OK") == 0)
14117 {
14118 ::use_agent = use;
14119 return true;
14120 }
14121 }
14122
14123 return false;
14124 }
14125
14126 bool
14127 remote_target::can_use_agent ()
14128 {
14129 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14130 }
14131
14132 struct btrace_target_info
14133 {
14134 /* The ptid of the traced thread. */
14135 ptid_t ptid;
14136
14137 /* The obtained branch trace configuration. */
14138 struct btrace_config conf;
14139 };
14140
14141 /* Reset our idea of our target's btrace configuration. */
14142
14143 static void
14144 remote_btrace_reset (remote_state *rs)
14145 {
14146 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14147 }
14148
14149 /* Synchronize the configuration with the target. */
14150
14151 void
14152 remote_target::btrace_sync_conf (const btrace_config *conf)
14153 {
14154 struct remote_state *rs;
14155 char *buf, *pos, *endbuf;
14156
14157 rs = get_remote_state ();
14158 buf = rs->buf.data ();
14159 endbuf = buf + get_remote_packet_size ();
14160
14161 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14162 && conf->bts.size != rs->btrace_config.bts.size)
14163 {
14164 pos = buf;
14165 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14166 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14167 conf->bts.size);
14168
14169 putpkt (buf);
14170 getpkt (&rs->buf, 0);
14171
14172 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14173 == PACKET_ERROR)
14174 {
14175 if (buf[0] == 'E' && buf[1] == '.')
14176 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14177 else
14178 error (_("Failed to configure the BTS buffer size."));
14179 }
14180
14181 rs->btrace_config.bts.size = conf->bts.size;
14182 }
14183
14184 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14185 && conf->pt.size != rs->btrace_config.pt.size)
14186 {
14187 pos = buf;
14188 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14189 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14190 conf->pt.size);
14191
14192 putpkt (buf);
14193 getpkt (&rs->buf, 0);
14194
14195 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14196 == PACKET_ERROR)
14197 {
14198 if (buf[0] == 'E' && buf[1] == '.')
14199 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14200 else
14201 error (_("Failed to configure the trace buffer size."));
14202 }
14203
14204 rs->btrace_config.pt.size = conf->pt.size;
14205 }
14206 }
14207
14208 /* Read TP's btrace configuration from the target and store it into CONF. */
14209
14210 static void
14211 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14212 {
14213 /* target_read_stralloc relies on INFERIOR_PTID. */
14214 scoped_restore_current_thread restore_thread;
14215 switch_to_thread (tp);
14216
14217 gdb::optional<gdb::char_vector> xml
14218 = target_read_stralloc (current_inferior ()->top_target (),
14219 TARGET_OBJECT_BTRACE_CONF, "");
14220 if (xml)
14221 parse_xml_btrace_conf (conf, xml->data ());
14222 }
14223
14224 /* Maybe reopen target btrace. */
14225
14226 void
14227 remote_target::remote_btrace_maybe_reopen ()
14228 {
14229 struct remote_state *rs = get_remote_state ();
14230 int btrace_target_pushed = 0;
14231 #if !defined (HAVE_LIBIPT)
14232 int warned = 0;
14233 #endif
14234
14235 /* Don't bother walking the entirety of the remote thread list when
14236 we know the feature isn't supported by the remote. */
14237 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14238 return;
14239
14240 for (thread_info *tp : all_non_exited_threads (this))
14241 {
14242 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14243 btrace_read_config (tp, &rs->btrace_config);
14244
14245 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14246 continue;
14247
14248 #if !defined (HAVE_LIBIPT)
14249 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14250 {
14251 if (!warned)
14252 {
14253 warned = 1;
14254 warning (_("Target is recording using Intel Processor Trace "
14255 "but support was disabled at compile time."));
14256 }
14257
14258 continue;
14259 }
14260 #endif /* !defined (HAVE_LIBIPT) */
14261
14262 /* Push target, once, but before anything else happens. This way our
14263 changes to the threads will be cleaned up by unpushing the target
14264 in case btrace_read_config () throws. */
14265 if (!btrace_target_pushed)
14266 {
14267 btrace_target_pushed = 1;
14268 record_btrace_push_target ();
14269 gdb_printf (_("Target is recording using %s.\n"),
14270 btrace_format_string (rs->btrace_config.format));
14271 }
14272
14273 tp->btrace.target = XCNEW (struct btrace_target_info);
14274 tp->btrace.target->ptid = tp->ptid;
14275 tp->btrace.target->conf = rs->btrace_config;
14276 }
14277 }
14278
14279 /* Enable branch tracing. */
14280
14281 struct btrace_target_info *
14282 remote_target::enable_btrace (thread_info *tp,
14283 const struct btrace_config *conf)
14284 {
14285 struct btrace_target_info *tinfo = NULL;
14286 struct packet_config *packet = NULL;
14287 struct remote_state *rs = get_remote_state ();
14288 char *buf = rs->buf.data ();
14289 char *endbuf = buf + get_remote_packet_size ();
14290
14291 unsigned int which_packet;
14292 switch (conf->format)
14293 {
14294 case BTRACE_FORMAT_BTS:
14295 which_packet = PACKET_Qbtrace_bts;
14296 break;
14297 case BTRACE_FORMAT_PT:
14298 which_packet = PACKET_Qbtrace_pt;
14299 break;
14300 default:
14301 internal_error (_("Bad branch btrace format: %u."),
14302 (unsigned int) conf->format);
14303 }
14304
14305 packet = &m_features.m_protocol_packets[which_packet];
14306 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14307 error (_("Target does not support branch tracing."));
14308
14309 btrace_sync_conf (conf);
14310
14311 ptid_t ptid = tp->ptid;
14312 set_general_thread (ptid);
14313
14314 buf += xsnprintf (buf, endbuf - buf, "%s",
14315 packets_descriptions[which_packet].name);
14316 putpkt (rs->buf);
14317 getpkt (&rs->buf, 0);
14318
14319 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14320 {
14321 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14322 error (_("Could not enable branch tracing for %s: %s"),
14323 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14324 else
14325 error (_("Could not enable branch tracing for %s."),
14326 target_pid_to_str (ptid).c_str ());
14327 }
14328
14329 tinfo = XCNEW (struct btrace_target_info);
14330 tinfo->ptid = ptid;
14331
14332 /* If we fail to read the configuration, we lose some information, but the
14333 tracing itself is not impacted. */
14334 try
14335 {
14336 btrace_read_config (tp, &tinfo->conf);
14337 }
14338 catch (const gdb_exception_error &err)
14339 {
14340 if (err.message != NULL)
14341 warning ("%s", err.what ());
14342 }
14343
14344 return tinfo;
14345 }
14346
14347 /* Disable branch tracing. */
14348
14349 void
14350 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14351 {
14352 struct remote_state *rs = get_remote_state ();
14353 char *buf = rs->buf.data ();
14354 char *endbuf = buf + get_remote_packet_size ();
14355
14356 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14357 error (_("Target does not support branch tracing."));
14358
14359 set_general_thread (tinfo->ptid);
14360
14361 buf += xsnprintf (buf, endbuf - buf, "%s",
14362 packets_descriptions[PACKET_Qbtrace_off].name);
14363 putpkt (rs->buf);
14364 getpkt (&rs->buf, 0);
14365
14366 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14367 {
14368 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14369 error (_("Could not disable branch tracing for %s: %s"),
14370 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14371 else
14372 error (_("Could not disable branch tracing for %s."),
14373 target_pid_to_str (tinfo->ptid).c_str ());
14374 }
14375
14376 xfree (tinfo);
14377 }
14378
14379 /* Teardown branch tracing. */
14380
14381 void
14382 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14383 {
14384 /* We must not talk to the target during teardown. */
14385 xfree (tinfo);
14386 }
14387
14388 /* Read the branch trace. */
14389
14390 enum btrace_error
14391 remote_target::read_btrace (struct btrace_data *btrace,
14392 struct btrace_target_info *tinfo,
14393 enum btrace_read_type type)
14394 {
14395 const char *annex;
14396
14397 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14398 error (_("Target does not support branch tracing."));
14399
14400 #if !defined(HAVE_LIBEXPAT)
14401 error (_("Cannot process branch tracing result. XML parsing not supported."));
14402 #endif
14403
14404 switch (type)
14405 {
14406 case BTRACE_READ_ALL:
14407 annex = "all";
14408 break;
14409 case BTRACE_READ_NEW:
14410 annex = "new";
14411 break;
14412 case BTRACE_READ_DELTA:
14413 annex = "delta";
14414 break;
14415 default:
14416 internal_error (_("Bad branch tracing read type: %u."),
14417 (unsigned int) type);
14418 }
14419
14420 gdb::optional<gdb::char_vector> xml
14421 = target_read_stralloc (current_inferior ()->top_target (),
14422 TARGET_OBJECT_BTRACE, annex);
14423 if (!xml)
14424 return BTRACE_ERR_UNKNOWN;
14425
14426 parse_xml_btrace (btrace, xml->data ());
14427
14428 return BTRACE_ERR_NONE;
14429 }
14430
14431 const struct btrace_config *
14432 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14433 {
14434 return &tinfo->conf;
14435 }
14436
14437 bool
14438 remote_target::augmented_libraries_svr4_read ()
14439 {
14440 return
14441 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14442 == PACKET_ENABLE);
14443 }
14444
14445 /* Implementation of to_load. */
14446
14447 void
14448 remote_target::load (const char *name, int from_tty)
14449 {
14450 generic_load (name, from_tty);
14451 }
14452
14453 /* Accepts an integer PID; returns a string representing a file that
14454 can be opened on the remote side to get the symbols for the child
14455 process. Returns NULL if the operation is not supported. */
14456
14457 const char *
14458 remote_target::pid_to_exec_file (int pid)
14459 {
14460 static gdb::optional<gdb::char_vector> filename;
14461 char *annex = NULL;
14462
14463 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14464 return NULL;
14465
14466 inferior *inf = find_inferior_pid (this, pid);
14467 if (inf == NULL)
14468 internal_error (_("not currently attached to process %d"), pid);
14469
14470 if (!inf->fake_pid_p)
14471 {
14472 const int annex_size = 9;
14473
14474 annex = (char *) alloca (annex_size);
14475 xsnprintf (annex, annex_size, "%x", pid);
14476 }
14477
14478 filename = target_read_stralloc (current_inferior ()->top_target (),
14479 TARGET_OBJECT_EXEC_FILE, annex);
14480
14481 return filename ? filename->data () : nullptr;
14482 }
14483
14484 /* Implement the to_can_do_single_step target_ops method. */
14485
14486 int
14487 remote_target::can_do_single_step ()
14488 {
14489 /* We can only tell whether target supports single step or not by
14490 supported s and S vCont actions if the stub supports vContSupported
14491 feature. If the stub doesn't support vContSupported feature,
14492 we have conservatively to think target doesn't supports single
14493 step. */
14494 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14495 {
14496 struct remote_state *rs = get_remote_state ();
14497
14498 return rs->supports_vCont.s && rs->supports_vCont.S;
14499 }
14500 else
14501 return 0;
14502 }
14503
14504 /* Implementation of the to_execution_direction method for the remote
14505 target. */
14506
14507 enum exec_direction_kind
14508 remote_target::execution_direction ()
14509 {
14510 struct remote_state *rs = get_remote_state ();
14511
14512 return rs->last_resume_exec_dir;
14513 }
14514
14515 /* Return pointer to the thread_info struct which corresponds to
14516 THREAD_HANDLE (having length HANDLE_LEN). */
14517
14518 thread_info *
14519 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14520 int handle_len,
14521 inferior *inf)
14522 {
14523 for (thread_info *tp : all_non_exited_threads (this))
14524 {
14525 remote_thread_info *priv = get_remote_thread_info (tp);
14526
14527 if (tp->inf == inf && priv != NULL)
14528 {
14529 if (handle_len != priv->thread_handle.size ())
14530 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14531 handle_len, priv->thread_handle.size ());
14532 if (memcmp (thread_handle, priv->thread_handle.data (),
14533 handle_len) == 0)
14534 return tp;
14535 }
14536 }
14537
14538 return NULL;
14539 }
14540
14541 gdb::array_view<const gdb_byte>
14542 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14543 {
14544 remote_thread_info *priv = get_remote_thread_info (tp);
14545 return priv->thread_handle;
14546 }
14547
14548 bool
14549 remote_target::can_async_p ()
14550 {
14551 /* This flag should be checked in the common target.c code. */
14552 gdb_assert (target_async_permitted);
14553
14554 /* We're async whenever the serial device can. */
14555 struct remote_state *rs = get_remote_state ();
14556 return serial_can_async_p (rs->remote_desc);
14557 }
14558
14559 bool
14560 remote_target::is_async_p ()
14561 {
14562 /* We're async whenever the serial device is. */
14563 struct remote_state *rs = get_remote_state ();
14564 return serial_is_async_p (rs->remote_desc);
14565 }
14566
14567 /* Pass the SERIAL event on and up to the client. One day this code
14568 will be able to delay notifying the client of an event until the
14569 point where an entire packet has been received. */
14570
14571 static serial_event_ftype remote_async_serial_handler;
14572
14573 static void
14574 remote_async_serial_handler (struct serial *scb, void *context)
14575 {
14576 /* Don't propogate error information up to the client. Instead let
14577 the client find out about the error by querying the target. */
14578 inferior_event_handler (INF_REG_EVENT);
14579 }
14580
14581 static void
14582 remote_async_inferior_event_handler (gdb_client_data data)
14583 {
14584 inferior_event_handler (INF_REG_EVENT);
14585 }
14586
14587 int
14588 remote_target::async_wait_fd ()
14589 {
14590 struct remote_state *rs = get_remote_state ();
14591 return rs->remote_desc->fd;
14592 }
14593
14594 void
14595 remote_target::async (bool enable)
14596 {
14597 struct remote_state *rs = get_remote_state ();
14598
14599 if (enable)
14600 {
14601 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14602
14603 /* If there are pending events in the stop reply queue tell the
14604 event loop to process them. */
14605 if (!rs->stop_reply_queue.empty ())
14606 mark_async_event_handler (rs->remote_async_inferior_event_token);
14607 /* For simplicity, below we clear the pending events token
14608 without remembering whether it is marked, so here we always
14609 mark it. If there's actually no pending notification to
14610 process, this ends up being a no-op (other than a spurious
14611 event-loop wakeup). */
14612 if (target_is_non_stop_p ())
14613 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14614 }
14615 else
14616 {
14617 serial_async (rs->remote_desc, NULL, NULL);
14618 /* If the core is disabling async, it doesn't want to be
14619 disturbed with target events. Clear all async event sources
14620 too. */
14621 clear_async_event_handler (rs->remote_async_inferior_event_token);
14622 if (target_is_non_stop_p ())
14623 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14624 }
14625 }
14626
14627 /* Implementation of the to_thread_events method. */
14628
14629 void
14630 remote_target::thread_events (int enable)
14631 {
14632 struct remote_state *rs = get_remote_state ();
14633 size_t size = get_remote_packet_size ();
14634
14635 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14636 return;
14637
14638 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14639 putpkt (rs->buf);
14640 getpkt (&rs->buf, 0);
14641
14642 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
14643 {
14644 case PACKET_OK:
14645 if (strcmp (rs->buf.data (), "OK") != 0)
14646 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14647 break;
14648 case PACKET_ERROR:
14649 warning (_("Remote failure reply: %s"), rs->buf.data ());
14650 break;
14651 case PACKET_UNKNOWN:
14652 break;
14653 }
14654 }
14655
14656 static void
14657 show_remote_cmd (const char *args, int from_tty)
14658 {
14659 /* We can't just use cmd_show_list here, because we want to skip
14660 the redundant "show remote Z-packet" and the legacy aliases. */
14661 struct cmd_list_element *list = remote_show_cmdlist;
14662 struct ui_out *uiout = current_uiout;
14663
14664 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14665 for (; list != NULL; list = list->next)
14666 if (strcmp (list->name, "Z-packet") == 0)
14667 continue;
14668 else if (list->type == not_set_cmd)
14669 /* Alias commands are exactly like the original, except they
14670 don't have the normal type. */
14671 continue;
14672 else
14673 {
14674 ui_out_emit_tuple option_emitter (uiout, "option");
14675
14676 uiout->field_string ("name", list->name);
14677 uiout->text (": ");
14678 if (list->type == show_cmd)
14679 do_show_command (NULL, from_tty, list);
14680 else
14681 cmd_func (list, NULL, from_tty);
14682 }
14683 }
14684
14685
14686 /* Function to be called whenever a new objfile (shlib) is detected. */
14687 static void
14688 remote_new_objfile (struct objfile *objfile)
14689 {
14690 /* The objfile change happened in that program space. */
14691 program_space *pspace = current_program_space;
14692
14693 /* The affected program space is possibly shared by multiple inferiors.
14694 Consider sending a qSymbol packet for each of the inferiors using that
14695 program space. */
14696 for (inferior *inf : all_inferiors ())
14697 {
14698 if (inf->pspace != pspace)
14699 continue;
14700
14701 /* Check whether the inferior's process target is a remote target. */
14702 remote_target *remote = as_remote_target (inf->process_target ());
14703 if (remote == nullptr)
14704 continue;
14705
14706 /* When we are attaching or handling a fork child and the shared library
14707 subsystem reads the list of loaded libraries, we receive new objfile
14708 events in between each found library. The libraries are read in an
14709 undefined order, so if we gave the remote side a chance to look up
14710 symbols between each objfile, we might give it an inconsistent picture
14711 of the inferior. It could appear that a library A appears loaded but
14712 a library B does not, even though library A requires library B. That
14713 would present a state that couldn't normally exist in the inferior.
14714
14715 So, skip these events, we'll give the remote a chance to look up
14716 symbols once all the loaded libraries and their symbols are known to
14717 GDB. */
14718 if (inf->in_initial_library_scan)
14719 continue;
14720
14721 if (!remote->has_execution (inf))
14722 continue;
14723
14724 /* Need to switch to a specific thread, because remote_check_symbols will
14725 set the general thread using INFERIOR_PTID.
14726
14727 It's possible to have inferiors with no thread here, because we are
14728 called very early in the connection process, while the inferior is
14729 being set up, before threads are added. Just skip it, start_remote_1
14730 also calls remote_check_symbols when it's done setting things up. */
14731 thread_info *thread = any_thread_of_inferior (inf);
14732 if (thread != nullptr)
14733 {
14734 scoped_restore_current_thread restore_thread;
14735 switch_to_thread (thread);
14736 remote->remote_check_symbols ();
14737 }
14738 }
14739 }
14740
14741 /* Pull all the tracepoints defined on the target and create local
14742 data structures representing them. We don't want to create real
14743 tracepoints yet, we don't want to mess up the user's existing
14744 collection. */
14745
14746 int
14747 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14748 {
14749 struct remote_state *rs = get_remote_state ();
14750 char *p;
14751
14752 /* Ask for a first packet of tracepoint definition. */
14753 putpkt ("qTfP");
14754 getpkt (&rs->buf, 0);
14755 p = rs->buf.data ();
14756 while (*p && *p != 'l')
14757 {
14758 parse_tracepoint_definition (p, utpp);
14759 /* Ask for another packet of tracepoint definition. */
14760 putpkt ("qTsP");
14761 getpkt (&rs->buf, 0);
14762 p = rs->buf.data ();
14763 }
14764 return 0;
14765 }
14766
14767 int
14768 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14769 {
14770 struct remote_state *rs = get_remote_state ();
14771 char *p;
14772
14773 /* Ask for a first packet of variable definition. */
14774 putpkt ("qTfV");
14775 getpkt (&rs->buf, 0);
14776 p = rs->buf.data ();
14777 while (*p && *p != 'l')
14778 {
14779 parse_tsv_definition (p, utsvp);
14780 /* Ask for another packet of variable definition. */
14781 putpkt ("qTsV");
14782 getpkt (&rs->buf, 0);
14783 p = rs->buf.data ();
14784 }
14785 return 0;
14786 }
14787
14788 /* The "set/show range-stepping" show hook. */
14789
14790 static void
14791 show_range_stepping (struct ui_file *file, int from_tty,
14792 struct cmd_list_element *c,
14793 const char *value)
14794 {
14795 gdb_printf (file,
14796 _("Debugger's willingness to use range stepping "
14797 "is %s.\n"), value);
14798 }
14799
14800 /* Return true if the vCont;r action is supported by the remote
14801 stub. */
14802
14803 bool
14804 remote_target::vcont_r_supported ()
14805 {
14806 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
14807 && get_remote_state ()->supports_vCont.r);
14808 }
14809
14810 /* The "set/show range-stepping" set hook. */
14811
14812 static void
14813 set_range_stepping (const char *ignore_args, int from_tty,
14814 struct cmd_list_element *c)
14815 {
14816 /* When enabling, check whether range stepping is actually supported
14817 by the target, and warn if not. */
14818 if (use_range_stepping)
14819 {
14820 remote_target *remote = get_current_remote_target ();
14821 if (remote == NULL
14822 || !remote->vcont_r_supported ())
14823 warning (_("Range stepping is not supported by the current target"));
14824 }
14825 }
14826
14827 static void
14828 show_remote_debug (struct ui_file *file, int from_tty,
14829 struct cmd_list_element *c, const char *value)
14830 {
14831 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14832 value);
14833 }
14834
14835 static void
14836 show_remote_timeout (struct ui_file *file, int from_tty,
14837 struct cmd_list_element *c, const char *value)
14838 {
14839 gdb_printf (file,
14840 _("Timeout limit to wait for target to respond is %s.\n"),
14841 value);
14842 }
14843
14844 /* Implement the "supports_memory_tagging" target_ops method. */
14845
14846 bool
14847 remote_target::supports_memory_tagging ()
14848 {
14849 return m_features.remote_memory_tagging_p ();
14850 }
14851
14852 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14853
14854 static void
14855 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14856 size_t len, int type)
14857 {
14858 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14859
14860 std::string request = string_printf ("qMemTags:%s,%s:%s",
14861 phex_nz (address, addr_size),
14862 phex_nz (len, sizeof (len)),
14863 phex_nz (type, sizeof (type)));
14864
14865 strcpy (packet.data (), request.c_str ());
14866 }
14867
14868 /* Parse the qMemTags packet reply into TAGS.
14869
14870 Return true if successful, false otherwise. */
14871
14872 static bool
14873 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14874 gdb::byte_vector &tags)
14875 {
14876 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14877 return false;
14878
14879 /* Copy the tag data. */
14880 tags = hex2bin (reply.data () + 1);
14881
14882 return true;
14883 }
14884
14885 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14886
14887 static void
14888 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14889 size_t len, int type,
14890 const gdb::byte_vector &tags)
14891 {
14892 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14893
14894 /* Put together the main packet, address and length. */
14895 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14896 phex_nz (address, addr_size),
14897 phex_nz (len, sizeof (len)),
14898 phex_nz (type, sizeof (type)));
14899 request += bin2hex (tags.data (), tags.size ());
14900
14901 /* Check if we have exceeded the maximum packet size. */
14902 if (packet.size () < request.length ())
14903 error (_("Contents too big for packet QMemTags."));
14904
14905 strcpy (packet.data (), request.c_str ());
14906 }
14907
14908 /* Implement the "fetch_memtags" target_ops method. */
14909
14910 bool
14911 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14912 gdb::byte_vector &tags, int type)
14913 {
14914 /* Make sure the qMemTags packet is supported. */
14915 if (!m_features.remote_memory_tagging_p ())
14916 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14917
14918 struct remote_state *rs = get_remote_state ();
14919
14920 create_fetch_memtags_request (rs->buf, address, len, type);
14921
14922 putpkt (rs->buf);
14923 getpkt (&rs->buf, 0);
14924
14925 return parse_fetch_memtags_reply (rs->buf, tags);
14926 }
14927
14928 /* Implement the "store_memtags" target_ops method. */
14929
14930 bool
14931 remote_target::store_memtags (CORE_ADDR address, size_t len,
14932 const gdb::byte_vector &tags, int type)
14933 {
14934 /* Make sure the QMemTags packet is supported. */
14935 if (!m_features.remote_memory_tagging_p ())
14936 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14937
14938 struct remote_state *rs = get_remote_state ();
14939
14940 create_store_memtags_request (rs->buf, address, len, type, tags);
14941
14942 putpkt (rs->buf);
14943 getpkt (&rs->buf, 0);
14944
14945 /* Verify if the request was successful. */
14946 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14947 }
14948
14949 /* Return true if remote target T is non-stop. */
14950
14951 bool
14952 remote_target_is_non_stop_p (remote_target *t)
14953 {
14954 scoped_restore_current_thread restore_thread;
14955 switch_to_target_no_thread (t);
14956
14957 return target_is_non_stop_p ();
14958 }
14959
14960 #if GDB_SELF_TEST
14961
14962 namespace selftests {
14963
14964 static void
14965 test_memory_tagging_functions ()
14966 {
14967 remote_target remote;
14968
14969 struct packet_config *config
14970 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
14971
14972 scoped_restore restore_memtag_support_
14973 = make_scoped_restore (&config->support);
14974
14975 /* Test memory tagging packet support. */
14976 config->support = PACKET_SUPPORT_UNKNOWN;
14977 SELF_CHECK (remote.supports_memory_tagging () == false);
14978 config->support = PACKET_DISABLE;
14979 SELF_CHECK (remote.supports_memory_tagging () == false);
14980 config->support = PACKET_ENABLE;
14981 SELF_CHECK (remote.supports_memory_tagging () == true);
14982
14983 /* Setup testing. */
14984 gdb::char_vector packet;
14985 gdb::byte_vector tags, bv;
14986 std::string expected, reply;
14987 packet.resize (32000);
14988
14989 /* Test creating a qMemTags request. */
14990
14991 expected = "qMemTags:0,0:0";
14992 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
14993 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14994
14995 expected = "qMemTags:deadbeef,10:1";
14996 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
14997 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
14998
14999 /* Test parsing a qMemTags reply. */
15000
15001 /* Error reply, tags vector unmodified. */
15002 reply = "E00";
15003 strcpy (packet.data (), reply.c_str ());
15004 tags.resize (0);
15005 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15006 SELF_CHECK (tags.size () == 0);
15007
15008 /* Valid reply, tags vector updated. */
15009 tags.resize (0);
15010 bv.resize (0);
15011
15012 for (int i = 0; i < 5; i++)
15013 bv.push_back (i);
15014
15015 reply = "m" + bin2hex (bv.data (), bv.size ());
15016 strcpy (packet.data (), reply.c_str ());
15017
15018 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15019 SELF_CHECK (tags.size () == 5);
15020
15021 for (int i = 0; i < 5; i++)
15022 SELF_CHECK (tags[i] == i);
15023
15024 /* Test creating a QMemTags request. */
15025
15026 /* Empty tag data. */
15027 tags.resize (0);
15028 expected = "QMemTags:0,0:0:";
15029 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15030 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15031 expected.length ()) == 0);
15032
15033 /* Non-empty tag data. */
15034 tags.resize (0);
15035 for (int i = 0; i < 5; i++)
15036 tags.push_back (i);
15037 expected = "QMemTags:deadbeef,ff:1:0001020304";
15038 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15039 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15040 expected.length ()) == 0);
15041 }
15042
15043 } // namespace selftests
15044 #endif /* GDB_SELF_TEST */
15045
15046 void _initialize_remote ();
15047 void
15048 _initialize_remote ()
15049 {
15050 add_target (remote_target_info, remote_target::open);
15051 add_target (extended_remote_target_info, extended_remote_target::open);
15052
15053 /* Hook into new objfile notification. */
15054 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15055
15056 #if 0
15057 init_remote_threadtests ();
15058 #endif
15059
15060 /* set/show remote ... */
15061
15062 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15063 Remote protocol specific variables.\n\
15064 Configure various remote-protocol specific variables such as\n\
15065 the packets being used."),
15066 &remote_set_cmdlist,
15067 0 /* allow-unknown */, &setlist);
15068 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15069 Remote protocol specific variables.\n\
15070 Configure various remote-protocol specific variables such as\n\
15071 the packets being used."),
15072 &remote_show_cmdlist,
15073 0 /* allow-unknown */, &showlist);
15074
15075 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15076 Compare section data on target to the exec file.\n\
15077 Argument is a single section name (default: all loaded sections).\n\
15078 To compare only read-only loaded sections, specify the -r option."),
15079 &cmdlist);
15080
15081 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15082 Send an arbitrary packet to a remote target.\n\
15083 maintenance packet TEXT\n\
15084 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15085 this command sends the string TEXT to the inferior, and displays the\n\
15086 response packet. GDB supplies the initial `$' character, and the\n\
15087 terminating `#' character and checksum."),
15088 &maintenancelist);
15089
15090 set_show_commands remotebreak_cmds
15091 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15092 Set whether to send break if interrupted."), _("\
15093 Show whether to send break if interrupted."), _("\
15094 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15095 set_remotebreak, show_remotebreak,
15096 &setlist, &showlist);
15097 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15098 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15099
15100 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15101 interrupt_sequence_modes, &interrupt_sequence_mode,
15102 _("\
15103 Set interrupt sequence to remote target."), _("\
15104 Show interrupt sequence to remote target."), _("\
15105 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15106 NULL, show_interrupt_sequence,
15107 &remote_set_cmdlist,
15108 &remote_show_cmdlist);
15109
15110 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15111 &interrupt_on_connect, _("\
15112 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15113 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15114 If set, interrupt sequence is sent to remote target."),
15115 NULL, NULL,
15116 &remote_set_cmdlist, &remote_show_cmdlist);
15117
15118 /* Install commands for configuring memory read/write packets. */
15119
15120 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15121 Set the maximum number of bytes per memory write packet (deprecated)."),
15122 &setlist);
15123 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15124 Show the maximum number of bytes per memory write packet (deprecated)."),
15125 &showlist);
15126 add_cmd ("memory-write-packet-size", no_class,
15127 set_memory_write_packet_size, _("\
15128 Set the maximum number of bytes per memory-write packet.\n\
15129 Specify the number of bytes in a packet or 0 (zero) for the\n\
15130 default packet size. The actual limit is further reduced\n\
15131 dependent on the target. Specify \"fixed\" to disable the\n\
15132 further restriction and \"limit\" to enable that restriction."),
15133 &remote_set_cmdlist);
15134 add_cmd ("memory-read-packet-size", no_class,
15135 set_memory_read_packet_size, _("\
15136 Set the maximum number of bytes per memory-read packet.\n\
15137 Specify the number of bytes in a packet or 0 (zero) for the\n\
15138 default packet size. The actual limit is further reduced\n\
15139 dependent on the target. Specify \"fixed\" to disable the\n\
15140 further restriction and \"limit\" to enable that restriction."),
15141 &remote_set_cmdlist);
15142 add_cmd ("memory-write-packet-size", no_class,
15143 show_memory_write_packet_size,
15144 _("Show the maximum number of bytes per memory-write packet."),
15145 &remote_show_cmdlist);
15146 add_cmd ("memory-read-packet-size", no_class,
15147 show_memory_read_packet_size,
15148 _("Show the maximum number of bytes per memory-read packet."),
15149 &remote_show_cmdlist);
15150
15151 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15152 &remote_hw_watchpoint_limit, _("\
15153 Set the maximum number of target hardware watchpoints."), _("\
15154 Show the maximum number of target hardware watchpoints."), _("\
15155 Specify \"unlimited\" for unlimited hardware watchpoints."),
15156 NULL, show_hardware_watchpoint_limit,
15157 &remote_set_cmdlist,
15158 &remote_show_cmdlist);
15159 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15160 no_class,
15161 &remote_hw_watchpoint_length_limit, _("\
15162 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15163 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15164 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15165 NULL, show_hardware_watchpoint_length_limit,
15166 &remote_set_cmdlist, &remote_show_cmdlist);
15167 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15168 &remote_hw_breakpoint_limit, _("\
15169 Set the maximum number of target hardware breakpoints."), _("\
15170 Show the maximum number of target hardware breakpoints."), _("\
15171 Specify \"unlimited\" for unlimited hardware breakpoints."),
15172 NULL, show_hardware_breakpoint_limit,
15173 &remote_set_cmdlist, &remote_show_cmdlist);
15174
15175 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15176 &remote_address_size, _("\
15177 Set the maximum size of the address (in bits) in a memory packet."), _("\
15178 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15179 NULL,
15180 NULL, /* FIXME: i18n: */
15181 &setlist, &showlist);
15182
15183 init_all_packet_configs ();
15184
15185 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15186
15187 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15188
15189 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15190 0);
15191
15192 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15193 "catch-syscalls", 0);
15194
15195 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15196 "program-signals", 0);
15197
15198 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15199 "set-working-dir", 0);
15200
15201 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15202 "startup-with-shell", 0);
15203
15204 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15205 "environment-hex-encoded", 0);
15206
15207 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15208 "environment-reset", 0);
15209
15210 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15211 "environment-unset", 0);
15212
15213 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15214
15215 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15216
15217 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15218
15219 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15220
15221 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15222
15223 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15224
15225 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15226
15227 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15228
15229 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15230 "read-aux-vector", 0);
15231
15232 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15233 "pid-to-exec-file", 0);
15234
15235 add_packet_config_cmd (PACKET_qXfer_features,
15236 "qXfer:features:read", "target-features", 0);
15237
15238 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15239 "library-info", 0);
15240
15241 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15242 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15243
15244 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15245 "memory-map", 0);
15246
15247 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15248
15249 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15250 0);
15251
15252 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15253 "read-siginfo-object", 0);
15254
15255 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15256 "write-siginfo-object", 0);
15257
15258 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15259 "qXfer:traceframe-info:read", "traceframe-info", 0);
15260
15261 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15262 "unwind-info-block", 0);
15263
15264 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15265 "get-thread-local-storage-address", 0);
15266
15267 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15268 "get-thread-information-block-address", 0);
15269
15270 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15271
15272 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15273
15274 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15275 0);
15276
15277 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15278 "search-memory", 0);
15279
15280 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15281
15282 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15283
15284 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15285
15286 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15287
15288 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15289 0);
15290
15291 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15292
15293 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15294 0);
15295
15296 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15297 "hostio-readlink", 0);
15298
15299 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15300
15301 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15302
15303 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15304
15305 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15306
15307 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15308
15309 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15310
15311 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15312 "ConditionalTracepoints", "conditional-tracepoints",
15313 0);
15314
15315 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15316 "ConditionalBreakpoints", "conditional-breakpoints",
15317 0);
15318
15319 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15320 "breakpoint-commands", 0);
15321
15322 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15323 "fast-tracepoints", 0);
15324
15325 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15326 "TracepointSource", 0);
15327
15328 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15329
15330 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15331 "static-tracepoints", 0);
15332
15333 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15334 "install-in-trace", 0);
15335
15336 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15337 "qXfer:statictrace:read", "read-sdata-object", 0);
15338
15339 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15340 "read-fdpic-loadmap", 0);
15341
15342 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15343 "disable-randomization", 0);
15344
15345 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15346
15347 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15348 "trace-buffer-size", 0);
15349
15350 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15351 0);
15352
15353 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15354 0);
15355
15356 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15357 0);
15358
15359 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15360
15361 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15362 "read-btrace-conf", 0);
15363
15364 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15365 "btrace-conf-bts-size", 0);
15366
15367 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15368 "multiprocess-feature", 0);
15369
15370 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15371 "swbreak-feature", 0);
15372
15373 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15374 "hwbreak-feature", 0);
15375
15376 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15377 "fork-event-feature", 0);
15378
15379 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15380 "vfork-event-feature", 0);
15381
15382 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15383 "btrace-conf-pt-size", 0);
15384
15385 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15386 "verbose-resume-supported", 0);
15387
15388 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15389 "exec-event-feature", 0);
15390
15391 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15392
15393 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15394 0);
15395
15396 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15397 "no-resumed-stop-reply", 0);
15398
15399 add_packet_config_cmd (PACKET_memory_tagging_feature,
15400 "memory-tagging-feature", "memory-tagging-feature", 0);
15401
15402 /* Assert that we've registered "set remote foo-packet" commands
15403 for all packet configs. */
15404 {
15405 int i;
15406
15407 for (i = 0; i < PACKET_MAX; i++)
15408 {
15409 /* Ideally all configs would have a command associated. Some
15410 still don't though. */
15411 int excepted;
15412
15413 switch (i)
15414 {
15415 case PACKET_QNonStop:
15416 case PACKET_EnableDisableTracepoints_feature:
15417 case PACKET_tracenz_feature:
15418 case PACKET_DisconnectedTracing_feature:
15419 case PACKET_augmented_libraries_svr4_read_feature:
15420 case PACKET_qCRC:
15421 /* Additions to this list need to be well justified:
15422 pre-existing packets are OK; new packets are not. */
15423 excepted = 1;
15424 break;
15425 default:
15426 excepted = 0;
15427 break;
15428 }
15429
15430 /* This catches both forgetting to add a config command, and
15431 forgetting to remove a packet from the exception list. */
15432 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15433 }
15434 }
15435
15436 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15437 Z sub-packet has its own set and show commands, but users may
15438 have sets to this variable in their .gdbinit files (or in their
15439 documentation). */
15440 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15441 &remote_Z_packet_detect, _("\
15442 Set use of remote protocol `Z' packets."), _("\
15443 Show use of remote protocol `Z' packets."), _("\
15444 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15445 packets."),
15446 set_remote_protocol_Z_packet_cmd,
15447 show_remote_protocol_Z_packet_cmd,
15448 /* FIXME: i18n: Use of remote protocol
15449 `Z' packets is %s. */
15450 &remote_set_cmdlist, &remote_show_cmdlist);
15451
15452 add_basic_prefix_cmd ("remote", class_files, _("\
15453 Manipulate files on the remote system.\n\
15454 Transfer files to and from the remote target system."),
15455 &remote_cmdlist,
15456 0 /* allow-unknown */, &cmdlist);
15457
15458 add_cmd ("put", class_files, remote_put_command,
15459 _("Copy a local file to the remote system."),
15460 &remote_cmdlist);
15461
15462 add_cmd ("get", class_files, remote_get_command,
15463 _("Copy a remote file to the local system."),
15464 &remote_cmdlist);
15465
15466 add_cmd ("delete", class_files, remote_delete_command,
15467 _("Delete a remote file."),
15468 &remote_cmdlist);
15469
15470 add_setshow_string_noescape_cmd ("exec-file", class_files,
15471 &remote_exec_file_var, _("\
15472 Set the remote pathname for \"run\"."), _("\
15473 Show the remote pathname for \"run\"."), NULL,
15474 set_remote_exec_file,
15475 show_remote_exec_file,
15476 &remote_set_cmdlist,
15477 &remote_show_cmdlist);
15478
15479 add_setshow_boolean_cmd ("range-stepping", class_run,
15480 &use_range_stepping, _("\
15481 Enable or disable range stepping."), _("\
15482 Show whether target-assisted range stepping is enabled."), _("\
15483 If on, and the target supports it, when stepping a source line, GDB\n\
15484 tells the target to step the corresponding range of addresses itself instead\n\
15485 of issuing multiple single-steps. This speeds up source level\n\
15486 stepping. If off, GDB always issues single-steps, even if range\n\
15487 stepping is supported by the target. The default is on."),
15488 set_range_stepping,
15489 show_range_stepping,
15490 &setlist,
15491 &showlist);
15492
15493 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15494 Set watchdog timer."), _("\
15495 Show watchdog timer."), _("\
15496 When non-zero, this timeout is used instead of waiting forever for a target\n\
15497 to finish a low-level step or continue operation. If the specified amount\n\
15498 of time passes without a response from the target, an error occurs."),
15499 NULL,
15500 show_watchdog,
15501 &setlist, &showlist);
15502
15503 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15504 &remote_packet_max_chars, _("\
15505 Set the maximum number of characters to display for each remote packet."), _("\
15506 Show the maximum number of characters to display for each remote packet."), _("\
15507 Specify \"unlimited\" to display all the characters."),
15508 NULL, show_remote_packet_max_chars,
15509 &setdebuglist, &showdebuglist);
15510
15511 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15512 _("Set debugging of remote protocol."),
15513 _("Show debugging of remote protocol."),
15514 _("\
15515 When enabled, each packet sent or received with the remote target\n\
15516 is displayed."),
15517 NULL,
15518 show_remote_debug,
15519 &setdebuglist, &showdebuglist);
15520
15521 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15522 &remote_timeout, _("\
15523 Set timeout limit to wait for target to respond."), _("\
15524 Show timeout limit to wait for target to respond."), _("\
15525 This value is used to set the time limit for gdb to wait for a response\n\
15526 from the target."),
15527 NULL,
15528 show_remote_timeout,
15529 &setlist, &showlist);
15530
15531 /* Eventually initialize fileio. See fileio.c */
15532 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15533
15534 #if GDB_SELF_TEST
15535 selftests::register_test ("remote_memory_tagging",
15536 selftests::test_memory_tagging_functions);
15537 #endif
15538 }