]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
ba7a7520cb44701405946ac35d3e065f4b4a7b4e
[thirdparty/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 *buf = nullptr;
358 /* The buffer's size. We try to read as much as fits into a packet
359 at a time. */
360 size_t bufsize = 0;
361
362 /* Cache hit and miss counters. */
363 ULONGEST hit_count = 0;
364 ULONGEST miss_count = 0;
365 };
366
367 /* Description of the remote protocol for a given architecture. */
368
369 struct packet_reg
370 {
371 long offset; /* Offset into G packet. */
372 long regnum; /* GDB's internal register number. */
373 LONGEST pnum; /* Remote protocol register number. */
374 int in_g_packet; /* Always part of G packet. */
375 /* long size in bytes; == register_size (target_gdbarch (), regnum);
376 at present. */
377 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
378 at present. */
379 };
380
381 struct remote_arch_state
382 {
383 explicit remote_arch_state (struct gdbarch *gdbarch);
384
385 /* Description of the remote protocol registers. */
386 long sizeof_g_packet;
387
388 /* Description of the remote protocol registers indexed by REGNUM
389 (making an array gdbarch_num_regs in size). */
390 std::unique_ptr<packet_reg[]> regs;
391
392 /* This is the size (in chars) of the first response to the ``g''
393 packet. It is used as a heuristic when determining the maximum
394 size of memory-read and memory-write packets. A target will
395 typically only reserve a buffer large enough to hold the ``g''
396 packet. The size does not include packet overhead (headers and
397 trailers). */
398 long actual_register_packet_size;
399
400 /* This is the maximum size (in chars) of a non read/write packet.
401 It is also used as a cap on the size of read/write packets. */
402 long remote_packet_size;
403 };
404
405 /* Description of the remote protocol state for the currently
406 connected target. This is per-target state, and independent of the
407 selected architecture. */
408
409 class remote_state
410 {
411 public:
412
413 remote_state ();
414 ~remote_state ();
415
416 /* Get the remote arch state for GDBARCH. */
417 struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
418
419 public: /* data */
420
421 /* A buffer to use for incoming packets, and its current size. The
422 buffer is grown dynamically for larger incoming packets.
423 Outgoing packets may also be constructed in this buffer.
424 The size of the buffer is always at least REMOTE_PACKET_SIZE;
425 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
426 packets. */
427 gdb::char_vector buf;
428
429 /* True if we're going through initial connection setup (finding out
430 about the remote side's threads, relocating symbols, etc.). */
431 bool starting_up = false;
432
433 /* If we negotiated packet size explicitly (and thus can bypass
434 heuristics for the largest packet size that will not overflow
435 a buffer in the stub), this will be set to that packet size.
436 Otherwise zero, meaning to use the guessed size. */
437 long explicit_packet_size = 0;
438
439 /* True, if in no ack mode. That is, neither GDB nor the stub will
440 expect acks from each other. The connection is assumed to be
441 reliable. */
442 bool noack_mode = false;
443
444 /* True if we're connected in extended remote mode. */
445 bool extended = false;
446
447 /* True if we resumed the target and we're waiting for the target to
448 stop. In the mean time, we can't start another command/query.
449 The remote server wouldn't be ready to process it, so we'd
450 timeout waiting for a reply that would never come and eventually
451 we'd close the connection. This can happen in asynchronous mode
452 because we allow GDB commands while the target is running. */
453 bool waiting_for_stop_reply = false;
454
455 /* The status of the stub support for the various vCont actions. */
456 vCont_action_support supports_vCont;
457
458 /* True if the user has pressed Ctrl-C, but the target hasn't
459 responded to that. */
460 bool ctrlc_pending_p = false;
461
462 /* True if we saw a Ctrl-C while reading or writing from/to the
463 remote descriptor. At that point it is not safe to send a remote
464 interrupt packet, so we instead remember we saw the Ctrl-C and
465 process it once we're done with sending/receiving the current
466 packet, which should be shortly. If however that takes too long,
467 and the user presses Ctrl-C again, we offer to disconnect. */
468 bool got_ctrlc_during_io = false;
469
470 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
471 remote_open knows that we don't have a file open when the program
472 starts. */
473 struct serial *remote_desc = nullptr;
474
475 /* These are the threads which we last sent to the remote system. The
476 TID member will be -1 for all or -2 for not sent yet. */
477 ptid_t general_thread = null_ptid;
478 ptid_t continue_thread = null_ptid;
479
480 /* This is the traceframe which we last selected on the remote system.
481 It will be -1 if no traceframe is selected. */
482 int remote_traceframe_number = -1;
483
484 char *last_pass_packet = nullptr;
485
486 /* The last QProgramSignals packet sent to the target. We bypass
487 sending a new program signals list down to the target if the new
488 packet is exactly the same as the last we sent. IOW, we only let
489 the target know about program signals list changes. */
490 char *last_program_signals_packet = nullptr;
491
492 gdb_signal last_sent_signal = GDB_SIGNAL_0;
493
494 bool last_sent_step = false;
495
496 /* The execution direction of the last resume we got. */
497 exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
498
499 char *finished_object = nullptr;
500 char *finished_annex = nullptr;
501 ULONGEST finished_offset = 0;
502
503 /* Should we try the 'ThreadInfo' query packet?
504
505 This variable (NOT available to the user: auto-detect only!)
506 determines whether GDB will use the new, simpler "ThreadInfo"
507 query or the older, more complex syntax for thread queries.
508 This is an auto-detect variable (set to true at each connect,
509 and set to false when the target fails to recognize it). */
510 bool use_threadinfo_query = false;
511 bool use_threadextra_query = false;
512
513 threadref echo_nextthread {};
514 threadref nextthread {};
515 threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
516
517 /* The state of remote notification. */
518 struct remote_notif_state *notif_state = nullptr;
519
520 /* The branch trace configuration. */
521 struct btrace_config btrace_config {};
522
523 /* The argument to the last "vFile:setfs:" packet we sent, used
524 to avoid sending repeated unnecessary "vFile:setfs:" packets.
525 Initialized to -1 to indicate that no "vFile:setfs:" packet
526 has yet been sent. */
527 int fs_pid = -1;
528
529 /* A readahead cache for vFile:pread. Often, reading a binary
530 involves a sequence of small reads. E.g., when parsing an ELF
531 file. A readahead cache helps mostly the case of remote
532 debugging on a connection with higher latency, due to the
533 request/reply nature of the RSP. We only cache data for a single
534 file descriptor at a time. */
535 struct readahead_cache readahead_cache;
536
537 /* The list of already fetched and acknowledged stop events. This
538 queue is used for notification Stop, and other notifications
539 don't need queue for their events, because the notification
540 events of Stop can't be consumed immediately, so that events
541 should be queued first, and be consumed by remote_wait_{ns,as}
542 one per time. Other notifications can consume their events
543 immediately, so queue is not needed for them. */
544 std::vector<stop_reply_up> stop_reply_queue;
545
546 /* Asynchronous signal handle registered as event loop source for
547 when we have pending events ready to be passed to the core. */
548 struct async_event_handler *remote_async_inferior_event_token = nullptr;
549
550 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
551 ``forever'' still use the normal timeout mechanism. This is
552 currently used by the ASYNC code to guarentee that target reads
553 during the initial connect always time-out. Once getpkt has been
554 modified to return a timeout indication and, in turn
555 remote_wait()/wait_for_inferior() have gained a timeout parameter
556 this can go away. */
557 int wait_forever_enabled_p = 1;
558
559 private:
560 /* Mapping of remote protocol data for each gdbarch. Usually there
561 is only one entry here, though we may see more with stubs that
562 support multi-process. */
563 std::unordered_map<struct gdbarch *, remote_arch_state>
564 m_arch_states;
565 };
566
567 static const target_info remote_target_info = {
568 "remote",
569 N_("Remote target using gdb-specific protocol"),
570 remote_doc
571 };
572
573 /* Description of a remote packet. */
574
575 struct packet_description
576 {
577 /* Name of the packet used for gdb output. */
578 const char *name;
579
580 /* Title of the packet, used by the set/show remote name-packet
581 commands to identify the individual packages and gdb output. */
582 const char *title;
583 };
584
585 /* Configuration of a remote packet. */
586
587 struct packet_config
588 {
589 /* If auto, GDB auto-detects support for this packet or feature,
590 either through qSupported, or by trying the packet and looking
591 at the response. If true, GDB assumes the target supports this
592 packet. If false, the packet is disabled. Configs that don't
593 have an associated command always have this set to auto. */
594 enum auto_boolean detect;
595
596 /* Does the target support this packet? */
597 enum packet_support support;
598 };
599
600 /* User configurable variables for the number of characters in a
601 memory read/write packet. MIN (rsa->remote_packet_size,
602 rsa->sizeof_g_packet) is the default. Some targets need smaller
603 values (fifo overruns, et.al.) and some users need larger values
604 (speed up transfers). The variables ``preferred_*'' (the user
605 request), ``current_*'' (what was actually set) and ``forced_*''
606 (Positive - a soft limit, negative - a hard limit). */
607
608 struct memory_packet_config
609 {
610 const char *name;
611 long size;
612 int fixed_p;
613 };
614
615 /* These global variables contain the default configuration for every new
616 remote_feature object. */
617 static memory_packet_config memory_read_packet_config =
618 {
619 "memory-read-packet-size",
620 };
621 static memory_packet_config memory_write_packet_config =
622 {
623 "memory-write-packet-size",
624 };
625
626 /* This global array contains packet descriptions (name and title). */
627 static packet_description packets_descriptions[PACKET_MAX];
628 /* This global array contains the default configuration for every new
629 per-remote target array. */
630 static packet_config remote_protocol_packets[PACKET_MAX];
631
632 /* Description of a remote target's features. It stores the configuration
633 and provides functions to determine supported features of the target. */
634
635 struct remote_features
636 {
637 remote_features ()
638 {
639 m_memory_read_packet_config = memory_read_packet_config;
640 m_memory_write_packet_config = memory_write_packet_config;
641
642 std::copy (std::begin (remote_protocol_packets),
643 std::end (remote_protocol_packets),
644 std::begin (m_protocol_packets));
645 }
646 ~remote_features () = default;
647
648 DISABLE_COPY_AND_ASSIGN (remote_features);
649
650 /* Returns whether a given packet defined by its enum value is supported. */
651 enum packet_support packet_support (int) const;
652
653 /* Returns the packet's corresponding "set remote foo-packet" command
654 state. See struct packet_config for more details. */
655 enum auto_boolean packet_set_cmd_state (int packet) const
656 { return m_protocol_packets[packet].detect; }
657
658 /* Returns true if the multi-process extensions are in effect. */
659 int remote_multi_process_p () const
660 { return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE; }
661
662 /* Returns true if fork events are supported. */
663 int remote_fork_event_p () const
664 { return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE; }
665
666 /* Returns true if vfork events are supported. */
667 int remote_vfork_event_p () const
668 { return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE; }
669
670 /* Returns true if exec events are supported. */
671 int remote_exec_event_p () const
672 { return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE; }
673
674 /* Returns true if memory tagging is supported, false otherwise. */
675 bool remote_memory_tagging_p () const
676 { return packet_support (PACKET_memory_tagging_feature) == PACKET_ENABLE; }
677
678 /* Reset all packets back to "unknown support". Called when opening a
679 new connection to a remote target. */
680 void reset_all_packet_configs_support ();
681
682 /* Check result value in BUF for packet WHICH_PACKET and update the packet's
683 support configuration accordingly. */
684 packet_result packet_ok (const char *buf, const int which_packet);
685 packet_result packet_ok (const gdb::char_vector &buf, const int which_packet);
686
687 /* Configuration of a remote target's memory read packet. */
688 memory_packet_config m_memory_read_packet_config;
689 /* Configuration of a remote target's memory write packet. */
690 memory_packet_config m_memory_write_packet_config;
691
692 /* The per-remote target array which stores a remote's packet
693 configurations. */
694 packet_config m_protocol_packets[PACKET_MAX];
695 };
696
697 class remote_target : public process_stratum_target
698 {
699 public:
700 remote_target () = default;
701 ~remote_target () override;
702
703 const target_info &info () const override
704 { return remote_target_info; }
705
706 const char *connection_string () override;
707
708 thread_control_capabilities get_thread_control_capabilities () override
709 { return tc_schedlock; }
710
711 /* Open a remote connection. */
712 static void open (const char *, int);
713
714 void close () override;
715
716 void detach (inferior *, int) override;
717 void disconnect (const char *, int) override;
718
719 void commit_resumed () override;
720 void resume (ptid_t, int, enum gdb_signal) override;
721 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
722 bool has_pending_events () override;
723
724 void fetch_registers (struct regcache *, int) override;
725 void store_registers (struct regcache *, int) override;
726 void prepare_to_store (struct regcache *) override;
727
728 int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
729
730 int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
731 enum remove_bp_reason) override;
732
733
734 bool stopped_by_sw_breakpoint () override;
735 bool supports_stopped_by_sw_breakpoint () override;
736
737 bool stopped_by_hw_breakpoint () override;
738
739 bool supports_stopped_by_hw_breakpoint () override;
740
741 bool stopped_by_watchpoint () override;
742
743 bool stopped_data_address (CORE_ADDR *) override;
744
745 bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
746
747 int can_use_hw_breakpoint (enum bptype, int, int) override;
748
749 int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
750
751 int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
752
753 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
754
755 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
756 struct expression *) override;
757
758 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
759 struct expression *) override;
760
761 void kill () override;
762
763 void load (const char *, int) override;
764
765 void mourn_inferior () override;
766
767 void pass_signals (gdb::array_view<const unsigned char>) override;
768
769 int set_syscall_catchpoint (int, bool, int,
770 gdb::array_view<const int>) override;
771
772 void program_signals (gdb::array_view<const unsigned char>) override;
773
774 bool thread_alive (ptid_t ptid) override;
775
776 const char *thread_name (struct thread_info *) override;
777
778 void update_thread_list () override;
779
780 std::string pid_to_str (ptid_t) override;
781
782 const char *extra_thread_info (struct thread_info *) override;
783
784 ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
785
786 thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
787 int handle_len,
788 inferior *inf) override;
789
790 gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
791 override;
792
793 void stop (ptid_t) override;
794
795 void interrupt () override;
796
797 void pass_ctrlc () override;
798
799 enum target_xfer_status xfer_partial (enum target_object object,
800 const char *annex,
801 gdb_byte *readbuf,
802 const gdb_byte *writebuf,
803 ULONGEST offset, ULONGEST len,
804 ULONGEST *xfered_len) override;
805
806 ULONGEST get_memory_xfer_limit () override;
807
808 void rcmd (const char *command, struct ui_file *output) override;
809
810 const char *pid_to_exec_file (int pid) override;
811
812 void log_command (const char *cmd) override
813 {
814 serial_log_command (this, cmd);
815 }
816
817 CORE_ADDR get_thread_local_address (ptid_t ptid,
818 CORE_ADDR load_module_addr,
819 CORE_ADDR offset) override;
820
821 bool can_execute_reverse () override;
822
823 std::vector<mem_region> memory_map () override;
824
825 void flash_erase (ULONGEST address, LONGEST length) override;
826
827 void flash_done () override;
828
829 const struct target_desc *read_description () override;
830
831 int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
832 const gdb_byte *pattern, ULONGEST pattern_len,
833 CORE_ADDR *found_addrp) override;
834
835 bool can_async_p () override;
836
837 bool is_async_p () override;
838
839 void async (bool) override;
840
841 int async_wait_fd () override;
842
843 void thread_events (int) override;
844
845 int can_do_single_step () override;
846
847 void terminal_inferior () override;
848
849 void terminal_ours () override;
850
851 bool supports_non_stop () override;
852
853 bool supports_multi_process () override;
854
855 bool supports_disable_randomization () override;
856
857 bool filesystem_is_local () override;
858
859
860 int fileio_open (struct inferior *inf, const char *filename,
861 int flags, int mode, int warn_if_slow,
862 fileio_error *target_errno) override;
863
864 int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
865 ULONGEST offset, fileio_error *target_errno) override;
866
867 int fileio_pread (int fd, gdb_byte *read_buf, int len,
868 ULONGEST offset, fileio_error *target_errno) override;
869
870 int fileio_fstat (int fd, struct stat *sb, fileio_error *target_errno) override;
871
872 int fileio_close (int fd, fileio_error *target_errno) override;
873
874 int fileio_unlink (struct inferior *inf,
875 const char *filename,
876 fileio_error *target_errno) override;
877
878 gdb::optional<std::string>
879 fileio_readlink (struct inferior *inf,
880 const char *filename,
881 fileio_error *target_errno) override;
882
883 bool supports_enable_disable_tracepoint () override;
884
885 bool supports_string_tracing () override;
886
887 int remote_supports_cond_tracepoints ();
888
889 bool supports_evaluation_of_breakpoint_conditions () override;
890
891 int remote_supports_fast_tracepoints ();
892
893 int remote_supports_static_tracepoints ();
894
895 int remote_supports_install_in_trace ();
896
897 bool can_run_breakpoint_commands () override;
898
899 void trace_init () override;
900
901 void download_tracepoint (struct bp_location *location) override;
902
903 bool can_download_tracepoint () override;
904
905 void download_trace_state_variable (const trace_state_variable &tsv) override;
906
907 void enable_tracepoint (struct bp_location *location) override;
908
909 void disable_tracepoint (struct bp_location *location) override;
910
911 void trace_set_readonly_regions () override;
912
913 void trace_start () override;
914
915 int get_trace_status (struct trace_status *ts) override;
916
917 void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
918 override;
919
920 void trace_stop () override;
921
922 int trace_find (enum trace_find_type type, int num,
923 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
924
925 bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
926
927 int save_trace_data (const char *filename) override;
928
929 int upload_tracepoints (struct uploaded_tp **utpp) override;
930
931 int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
932
933 LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
934
935 int get_min_fast_tracepoint_insn_len () override;
936
937 void set_disconnected_tracing (int val) override;
938
939 void set_circular_trace_buffer (int val) override;
940
941 void set_trace_buffer_size (LONGEST val) override;
942
943 bool set_trace_notes (const char *user, const char *notes,
944 const char *stopnotes) override;
945
946 int core_of_thread (ptid_t ptid) override;
947
948 int verify_memory (const gdb_byte *data,
949 CORE_ADDR memaddr, ULONGEST size) override;
950
951
952 bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
953
954 void set_permissions () override;
955
956 bool static_tracepoint_marker_at (CORE_ADDR,
957 struct static_tracepoint_marker *marker)
958 override;
959
960 std::vector<static_tracepoint_marker>
961 static_tracepoint_markers_by_strid (const char *id) override;
962
963 traceframe_info_up traceframe_info () override;
964
965 bool use_agent (bool use) override;
966 bool can_use_agent () override;
967
968 struct btrace_target_info *
969 enable_btrace (thread_info *tp, const struct btrace_config *conf) override;
970
971 void disable_btrace (struct btrace_target_info *tinfo) override;
972
973 void teardown_btrace (struct btrace_target_info *tinfo) override;
974
975 enum btrace_error read_btrace (struct btrace_data *data,
976 struct btrace_target_info *btinfo,
977 enum btrace_read_type type) override;
978
979 const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
980 bool augmented_libraries_svr4_read () override;
981 void follow_fork (inferior *, ptid_t, target_waitkind, bool, bool) override;
982 void follow_exec (inferior *, ptid_t, const char *) override;
983 int insert_fork_catchpoint (int) override;
984 int remove_fork_catchpoint (int) override;
985 int insert_vfork_catchpoint (int) override;
986 int remove_vfork_catchpoint (int) override;
987 int insert_exec_catchpoint (int) override;
988 int remove_exec_catchpoint (int) override;
989 enum exec_direction_kind execution_direction () override;
990
991 bool supports_memory_tagging () override;
992
993 bool fetch_memtags (CORE_ADDR address, size_t len,
994 gdb::byte_vector &tags, int type) override;
995
996 bool store_memtags (CORE_ADDR address, size_t len,
997 const gdb::byte_vector &tags, int type) override;
998
999 public: /* Remote specific methods. */
1000
1001 void remote_download_command_source (int num, ULONGEST addr,
1002 struct command_line *cmds);
1003
1004 void remote_file_put (const char *local_file, const char *remote_file,
1005 int from_tty);
1006 void remote_file_get (const char *remote_file, const char *local_file,
1007 int from_tty);
1008 void remote_file_delete (const char *remote_file, int from_tty);
1009
1010 int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
1011 ULONGEST offset, fileio_error *remote_errno);
1012 int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
1013 ULONGEST offset, fileio_error *remote_errno);
1014 int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
1015 ULONGEST offset, fileio_error *remote_errno);
1016
1017 int remote_hostio_send_command (int command_bytes, int which_packet,
1018 fileio_error *remote_errno, const char **attachment,
1019 int *attachment_len);
1020 int remote_hostio_set_filesystem (struct inferior *inf,
1021 fileio_error *remote_errno);
1022 /* We should get rid of this and use fileio_open directly. */
1023 int remote_hostio_open (struct inferior *inf, const char *filename,
1024 int flags, int mode, int warn_if_slow,
1025 fileio_error *remote_errno);
1026 int remote_hostio_close (int fd, fileio_error *remote_errno);
1027
1028 int remote_hostio_unlink (inferior *inf, const char *filename,
1029 fileio_error *remote_errno);
1030
1031 struct remote_state *get_remote_state ();
1032
1033 long get_remote_packet_size (void);
1034 long get_memory_packet_size (struct memory_packet_config *config);
1035
1036 long get_memory_write_packet_size ();
1037 long get_memory_read_packet_size ();
1038
1039 char *append_pending_thread_resumptions (char *p, char *endp,
1040 ptid_t ptid);
1041 static void open_1 (const char *name, int from_tty, int extended_p);
1042 void start_remote (int from_tty, int extended_p);
1043 void remote_detach_1 (struct inferior *inf, int from_tty);
1044
1045 char *append_resumption (char *p, char *endp,
1046 ptid_t ptid, int step, gdb_signal siggnal);
1047 int remote_resume_with_vcont (ptid_t scope_ptid, int step,
1048 gdb_signal siggnal);
1049
1050 thread_info *add_current_inferior_and_thread (const char *wait_status);
1051
1052 ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
1053 target_wait_flags options);
1054 ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
1055 target_wait_flags options);
1056
1057 ptid_t process_stop_reply (struct stop_reply *stop_reply,
1058 target_waitstatus *status);
1059
1060 ptid_t select_thread_for_ambiguous_stop_reply
1061 (const struct target_waitstatus &status);
1062
1063 void remote_notice_new_inferior (ptid_t currthread, bool executing);
1064
1065 void print_one_stopped_thread (thread_info *thread);
1066 void process_initial_stop_replies (int from_tty);
1067
1068 thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing,
1069 bool silent_p);
1070
1071 void btrace_sync_conf (const btrace_config *conf);
1072
1073 void remote_btrace_maybe_reopen ();
1074
1075 void remove_new_fork_children (threads_listing_context *context);
1076 void kill_new_fork_children (inferior *inf);
1077 void discard_pending_stop_replies (struct inferior *inf);
1078 int stop_reply_queue_length ();
1079
1080 void check_pending_events_prevent_wildcard_vcont
1081 (bool *may_global_wildcard_vcont);
1082
1083 void discard_pending_stop_replies_in_queue ();
1084 struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
1085 struct stop_reply *queued_stop_reply (ptid_t ptid);
1086 int peek_stop_reply (ptid_t ptid);
1087 void remote_parse_stop_reply (const char *buf, stop_reply *event);
1088
1089 void remote_stop_ns (ptid_t ptid);
1090 void remote_interrupt_as ();
1091 void remote_interrupt_ns ();
1092
1093 char *remote_get_noisy_reply ();
1094 int remote_query_attached (int pid);
1095 inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
1096 int try_open_exec);
1097
1098 ptid_t remote_current_thread (ptid_t oldpid);
1099 ptid_t get_current_thread (const char *wait_status);
1100
1101 void set_thread (ptid_t ptid, int gen);
1102 void set_general_thread (ptid_t ptid);
1103 void set_continue_thread (ptid_t ptid);
1104 void set_general_process ();
1105
1106 char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
1107
1108 int remote_unpack_thread_info_response (const char *pkt, threadref *expectedref,
1109 gdb_ext_thread_info *info);
1110 int remote_get_threadinfo (threadref *threadid, int fieldset,
1111 gdb_ext_thread_info *info);
1112
1113 int parse_threadlist_response (const char *pkt, int result_limit,
1114 threadref *original_echo,
1115 threadref *resultlist,
1116 int *doneflag);
1117 int remote_get_threadlist (int startflag, threadref *nextthread,
1118 int result_limit, int *done, int *result_count,
1119 threadref *threadlist);
1120
1121 int remote_threadlist_iterator (rmt_thread_action stepfunction,
1122 void *context, int looplimit);
1123
1124 int remote_get_threads_with_ql (threads_listing_context *context);
1125 int remote_get_threads_with_qxfer (threads_listing_context *context);
1126 int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
1127
1128 void extended_remote_restart ();
1129
1130 void get_offsets ();
1131
1132 void remote_check_symbols ();
1133
1134 void remote_supported_packet (const struct protocol_feature *feature,
1135 enum packet_support support,
1136 const char *argument);
1137
1138 void remote_query_supported ();
1139
1140 void remote_packet_size (const protocol_feature *feature,
1141 packet_support support, const char *value);
1142
1143 void remote_serial_quit_handler ();
1144
1145 void remote_detach_pid (int pid);
1146
1147 void remote_vcont_probe ();
1148
1149 void remote_resume_with_hc (ptid_t ptid, int step,
1150 gdb_signal siggnal);
1151
1152 void send_interrupt_sequence ();
1153 void interrupt_query ();
1154
1155 void remote_notif_get_pending_events (const notif_client *nc);
1156
1157 int fetch_register_using_p (struct regcache *regcache,
1158 packet_reg *reg);
1159 int send_g_packet ();
1160 void process_g_packet (struct regcache *regcache);
1161 void fetch_registers_using_g (struct regcache *regcache);
1162 int store_register_using_P (const struct regcache *regcache,
1163 packet_reg *reg);
1164 void store_registers_using_G (const struct regcache *regcache);
1165
1166 void set_remote_traceframe ();
1167
1168 void check_binary_download (CORE_ADDR addr);
1169
1170 target_xfer_status remote_write_bytes_aux (const char *header,
1171 CORE_ADDR memaddr,
1172 const gdb_byte *myaddr,
1173 ULONGEST len_units,
1174 int unit_size,
1175 ULONGEST *xfered_len_units,
1176 char packet_format,
1177 int use_length);
1178
1179 target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
1180 const gdb_byte *myaddr, ULONGEST len,
1181 int unit_size, ULONGEST *xfered_len);
1182
1183 target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
1184 ULONGEST len_units,
1185 int unit_size, ULONGEST *xfered_len_units);
1186
1187 target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
1188 ULONGEST memaddr,
1189 ULONGEST len,
1190 int unit_size,
1191 ULONGEST *xfered_len);
1192
1193 target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
1194 gdb_byte *myaddr, ULONGEST len,
1195 int unit_size,
1196 ULONGEST *xfered_len);
1197
1198 packet_result remote_send_printf (const char *format, ...)
1199 ATTRIBUTE_PRINTF (2, 3);
1200
1201 target_xfer_status remote_flash_write (ULONGEST address,
1202 ULONGEST length, ULONGEST *xfered_len,
1203 const gdb_byte *data);
1204
1205 int readchar (int timeout);
1206
1207 void remote_serial_write (const char *str, int len);
1208
1209 int putpkt (const char *buf);
1210 int putpkt_binary (const char *buf, int cnt);
1211
1212 int putpkt (const gdb::char_vector &buf)
1213 {
1214 return putpkt (buf.data ());
1215 }
1216
1217 void skip_frame ();
1218 long read_frame (gdb::char_vector *buf_p);
1219 void getpkt (gdb::char_vector *buf, int forever);
1220 int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
1221 int expecting_notif, int *is_notif);
1222 int getpkt_sane (gdb::char_vector *buf, int forever);
1223 int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
1224 int *is_notif);
1225 int remote_vkill (int pid);
1226 void remote_kill_k ();
1227
1228 void extended_remote_disable_randomization (int val);
1229 int extended_remote_run (const std::string &args);
1230
1231 void send_environment_packet (const char *action,
1232 const char *packet,
1233 const char *value);
1234
1235 void extended_remote_environment_support ();
1236 void extended_remote_set_inferior_cwd ();
1237
1238 target_xfer_status remote_write_qxfer (const char *object_name,
1239 const char *annex,
1240 const gdb_byte *writebuf,
1241 ULONGEST offset, LONGEST len,
1242 ULONGEST *xfered_len,
1243 const unsigned int which_packet);
1244
1245 target_xfer_status remote_read_qxfer (const char *object_name,
1246 const char *annex,
1247 gdb_byte *readbuf, ULONGEST offset,
1248 LONGEST len,
1249 ULONGEST *xfered_len,
1250 const unsigned int which_packet);
1251
1252 void push_stop_reply (struct stop_reply *new_event);
1253
1254 bool vcont_r_supported ();
1255
1256 remote_features m_features;
1257
1258 private:
1259
1260 bool start_remote_1 (int from_tty, int extended_p);
1261
1262 /* The remote state. Don't reference this directly. Use the
1263 get_remote_state method instead. */
1264 remote_state m_remote_state;
1265 };
1266
1267 static const target_info extended_remote_target_info = {
1268 "extended-remote",
1269 N_("Extended remote target using gdb-specific protocol"),
1270 remote_doc
1271 };
1272
1273 /* Set up the extended remote target by extending the standard remote
1274 target and adding to it. */
1275
1276 class extended_remote_target final : public remote_target
1277 {
1278 public:
1279 const target_info &info () const override
1280 { return extended_remote_target_info; }
1281
1282 /* Open an extended-remote connection. */
1283 static void open (const char *, int);
1284
1285 bool can_create_inferior () override { return true; }
1286 void create_inferior (const char *, const std::string &,
1287 char **, int) override;
1288
1289 void detach (inferior *, int) override;
1290
1291 bool can_attach () override { return true; }
1292 void attach (const char *, int) override;
1293
1294 void post_attach (int) override;
1295 bool supports_disable_randomization () override;
1296 };
1297
1298 struct stop_reply : public notif_event
1299 {
1300 ~stop_reply ();
1301
1302 /* The identifier of the thread about this event */
1303 ptid_t ptid;
1304
1305 /* The remote state this event is associated with. When the remote
1306 connection, represented by a remote_state object, is closed,
1307 all the associated stop_reply events should be released. */
1308 struct remote_state *rs;
1309
1310 struct target_waitstatus ws;
1311
1312 /* The architecture associated with the expedited registers. */
1313 gdbarch *arch;
1314
1315 /* Expedited registers. This makes remote debugging a bit more
1316 efficient for those targets that provide critical registers as
1317 part of their normal status mechanism (as another roundtrip to
1318 fetch them is avoided). */
1319 std::vector<cached_reg_t> regcache;
1320
1321 enum target_stop_reason stop_reason;
1322
1323 CORE_ADDR watch_data_address;
1324
1325 int core;
1326 };
1327
1328 /* Return TARGET as a remote_target if it is one, else nullptr. */
1329
1330 static remote_target *
1331 as_remote_target (process_stratum_target *target)
1332 {
1333 return dynamic_cast<remote_target *> (target);
1334 }
1335
1336 /* See remote.h. */
1337
1338 bool
1339 is_remote_target (process_stratum_target *target)
1340 {
1341 return as_remote_target (target) != nullptr;
1342 }
1343
1344 /* Per-program-space data key. */
1345 static const registry<program_space>::key<char, gdb::xfree_deleter<char>>
1346 remote_pspace_data;
1347
1348 /* The variable registered as the control variable used by the
1349 remote exec-file commands. While the remote exec-file setting is
1350 per-program-space, the set/show machinery uses this as the
1351 location of the remote exec-file value. */
1352 static std::string remote_exec_file_var;
1353
1354 /* The size to align memory write packets, when practical. The protocol
1355 does not guarantee any alignment, and gdb will generate short
1356 writes and unaligned writes, but even as a best-effort attempt this
1357 can improve bulk transfers. For instance, if a write is misaligned
1358 relative to the target's data bus, the stub may need to make an extra
1359 round trip fetching data from the target. This doesn't make a
1360 huge difference, but it's easy to do, so we try to be helpful.
1361
1362 The alignment chosen is arbitrary; usually data bus width is
1363 important here, not the possibly larger cache line size. */
1364 enum { REMOTE_ALIGN_WRITES = 16 };
1365
1366 /* Prototypes for local functions. */
1367
1368 static int hexnumlen (ULONGEST num);
1369
1370 static int stubhex (int ch);
1371
1372 static int hexnumstr (char *, ULONGEST);
1373
1374 static int hexnumnstr (char *, ULONGEST, int);
1375
1376 static CORE_ADDR remote_address_masked (CORE_ADDR);
1377
1378 static int stub_unpack_int (const char *buff, int fieldlength);
1379
1380 static void set_remote_protocol_packet_cmd (const char *args, int from_tty,
1381 cmd_list_element *c);
1382
1383 static void show_packet_config_cmd (ui_file *file,
1384 const unsigned int which_packet,
1385 remote_target *remote);
1386
1387 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1388 int from_tty,
1389 struct cmd_list_element *c,
1390 const char *value);
1391
1392 static ptid_t read_ptid (const char *buf, const char **obuf);
1393
1394 static void remote_async_inferior_event_handler (gdb_client_data);
1395
1396 static bool remote_read_description_p (struct target_ops *target);
1397
1398 static void remote_console_output (const char *msg);
1399
1400 static void remote_btrace_reset (remote_state *rs);
1401
1402 static void remote_unpush_and_throw (remote_target *target);
1403
1404 /* For "remote". */
1405
1406 static struct cmd_list_element *remote_cmdlist;
1407
1408 /* For "set remote" and "show remote". */
1409
1410 static struct cmd_list_element *remote_set_cmdlist;
1411 static struct cmd_list_element *remote_show_cmdlist;
1412
1413 /* Controls whether GDB is willing to use range stepping. */
1414
1415 static bool use_range_stepping = true;
1416
1417 /* From the remote target's point of view, each thread is in one of these three
1418 states. */
1419 enum class resume_state
1420 {
1421 /* Not resumed - we haven't been asked to resume this thread. */
1422 NOT_RESUMED,
1423
1424 /* We have been asked to resume this thread, but haven't sent a vCont action
1425 for it yet. We'll need to consider it next time commit_resume is
1426 called. */
1427 RESUMED_PENDING_VCONT,
1428
1429 /* We have been asked to resume this thread, and we have sent a vCont action
1430 for it. */
1431 RESUMED,
1432 };
1433
1434 /* Information about a thread's pending vCont-resume. Used when a thread is in
1435 the remote_resume_state::RESUMED_PENDING_VCONT state. remote_target::resume
1436 stores this information which is then picked up by
1437 remote_target::commit_resume to know which is the proper action for this
1438 thread to include in the vCont packet. */
1439 struct resumed_pending_vcont_info
1440 {
1441 /* True if the last resume call for this thread was a step request, false
1442 if a continue request. */
1443 bool step;
1444
1445 /* The signal specified in the last resume call for this thread. */
1446 gdb_signal sig;
1447 };
1448
1449 /* Private data that we'll store in (struct thread_info)->priv. */
1450 struct remote_thread_info : public private_thread_info
1451 {
1452 std::string extra;
1453 std::string name;
1454 int core = -1;
1455
1456 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1457 sequence of bytes. */
1458 gdb::byte_vector thread_handle;
1459
1460 /* Whether the target stopped for a breakpoint/watchpoint. */
1461 enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1462
1463 /* This is set to the data address of the access causing the target
1464 to stop for a watchpoint. */
1465 CORE_ADDR watch_data_address = 0;
1466
1467 /* Get the thread's resume state. */
1468 enum resume_state get_resume_state () const
1469 {
1470 return m_resume_state;
1471 }
1472
1473 /* Put the thread in the NOT_RESUMED state. */
1474 void set_not_resumed ()
1475 {
1476 m_resume_state = resume_state::NOT_RESUMED;
1477 }
1478
1479 /* Put the thread in the RESUMED_PENDING_VCONT state. */
1480 void set_resumed_pending_vcont (bool step, gdb_signal sig)
1481 {
1482 m_resume_state = resume_state::RESUMED_PENDING_VCONT;
1483 m_resumed_pending_vcont_info.step = step;
1484 m_resumed_pending_vcont_info.sig = sig;
1485 }
1486
1487 /* Get the information this thread's pending vCont-resumption.
1488
1489 Must only be called if the thread is in the RESUMED_PENDING_VCONT resume
1490 state. */
1491 const struct resumed_pending_vcont_info &resumed_pending_vcont_info () const
1492 {
1493 gdb_assert (m_resume_state == resume_state::RESUMED_PENDING_VCONT);
1494
1495 return m_resumed_pending_vcont_info;
1496 }
1497
1498 /* Put the thread in the VCONT_RESUMED state. */
1499 void set_resumed ()
1500 {
1501 m_resume_state = resume_state::RESUMED;
1502 }
1503
1504 private:
1505 /* Resume state for this thread. This is used to implement vCont action
1506 coalescing (only when the target operates in non-stop mode).
1507
1508 remote_target::resume moves the thread to the RESUMED_PENDING_VCONT state,
1509 which notes that this thread must be considered in the next commit_resume
1510 call.
1511
1512 remote_target::commit_resume sends a vCont packet with actions for the
1513 threads in the RESUMED_PENDING_VCONT state and moves them to the
1514 VCONT_RESUMED state.
1515
1516 When reporting a stop to the core for a thread, that thread is moved back
1517 to the NOT_RESUMED state. */
1518 enum resume_state m_resume_state = resume_state::NOT_RESUMED;
1519
1520 /* Extra info used if the thread is in the RESUMED_PENDING_VCONT state. */
1521 struct resumed_pending_vcont_info m_resumed_pending_vcont_info;
1522 };
1523
1524 remote_state::remote_state ()
1525 : buf (400)
1526 {
1527 }
1528
1529 remote_state::~remote_state ()
1530 {
1531 xfree (this->last_pass_packet);
1532 xfree (this->last_program_signals_packet);
1533 xfree (this->finished_object);
1534 xfree (this->finished_annex);
1535 }
1536
1537 /* Utility: generate error from an incoming stub packet. */
1538 static void
1539 trace_error (char *buf)
1540 {
1541 if (*buf++ != 'E')
1542 return; /* not an error msg */
1543 switch (*buf)
1544 {
1545 case '1': /* malformed packet error */
1546 if (*++buf == '0') /* general case: */
1547 error (_("remote.c: error in outgoing packet."));
1548 else
1549 error (_("remote.c: error in outgoing packet at field #%ld."),
1550 strtol (buf, NULL, 16));
1551 default:
1552 error (_("Target returns error code '%s'."), buf);
1553 }
1554 }
1555
1556 /* Utility: wait for reply from stub, while accepting "O" packets. */
1557
1558 char *
1559 remote_target::remote_get_noisy_reply ()
1560 {
1561 struct remote_state *rs = get_remote_state ();
1562
1563 do /* Loop on reply from remote stub. */
1564 {
1565 char *buf;
1566
1567 QUIT; /* Allow user to bail out with ^C. */
1568 getpkt (&rs->buf, 0);
1569 buf = rs->buf.data ();
1570 if (buf[0] == 'E')
1571 trace_error (buf);
1572 else if (startswith (buf, "qRelocInsn:"))
1573 {
1574 ULONGEST ul;
1575 CORE_ADDR from, to, org_to;
1576 const char *p, *pp;
1577 int adjusted_size = 0;
1578 int relocated = 0;
1579
1580 p = buf + strlen ("qRelocInsn:");
1581 pp = unpack_varlen_hex (p, &ul);
1582 if (*pp != ';')
1583 error (_("invalid qRelocInsn packet: %s"), buf);
1584 from = ul;
1585
1586 p = pp + 1;
1587 unpack_varlen_hex (p, &ul);
1588 to = ul;
1589
1590 org_to = to;
1591
1592 try
1593 {
1594 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1595 relocated = 1;
1596 }
1597 catch (const gdb_exception &ex)
1598 {
1599 if (ex.error == MEMORY_ERROR)
1600 {
1601 /* Propagate memory errors silently back to the
1602 target. The stub may have limited the range of
1603 addresses we can write to, for example. */
1604 }
1605 else
1606 {
1607 /* Something unexpectedly bad happened. Be verbose
1608 so we can tell what, and propagate the error back
1609 to the stub, so it doesn't get stuck waiting for
1610 a response. */
1611 exception_fprintf (gdb_stderr, ex,
1612 _("warning: relocating instruction: "));
1613 }
1614 putpkt ("E01");
1615 }
1616
1617 if (relocated)
1618 {
1619 adjusted_size = to - org_to;
1620
1621 xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1622 putpkt (buf);
1623 }
1624 }
1625 else if (buf[0] == 'O' && buf[1] != 'K')
1626 remote_console_output (buf + 1); /* 'O' message from stub */
1627 else
1628 return buf; /* Here's the actual reply. */
1629 }
1630 while (1);
1631 }
1632
1633 struct remote_arch_state *
1634 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1635 {
1636 remote_arch_state *rsa;
1637
1638 auto it = this->m_arch_states.find (gdbarch);
1639 if (it == this->m_arch_states.end ())
1640 {
1641 auto p = this->m_arch_states.emplace (std::piecewise_construct,
1642 std::forward_as_tuple (gdbarch),
1643 std::forward_as_tuple (gdbarch));
1644 rsa = &p.first->second;
1645
1646 /* Make sure that the packet buffer is plenty big enough for
1647 this architecture. */
1648 if (this->buf.size () < rsa->remote_packet_size)
1649 this->buf.resize (2 * rsa->remote_packet_size);
1650 }
1651 else
1652 rsa = &it->second;
1653
1654 return rsa;
1655 }
1656
1657 /* Fetch the global remote target state. */
1658
1659 remote_state *
1660 remote_target::get_remote_state ()
1661 {
1662 /* Make sure that the remote architecture state has been
1663 initialized, because doing so might reallocate rs->buf. Any
1664 function which calls getpkt also needs to be mindful of changes
1665 to rs->buf, but this call limits the number of places which run
1666 into trouble. */
1667 m_remote_state.get_remote_arch_state (target_gdbarch ());
1668
1669 return &m_remote_state;
1670 }
1671
1672 /* Fetch the remote exec-file from the current program space. */
1673
1674 static const char *
1675 get_remote_exec_file (void)
1676 {
1677 char *remote_exec_file;
1678
1679 remote_exec_file = remote_pspace_data.get (current_program_space);
1680 if (remote_exec_file == NULL)
1681 return "";
1682
1683 return remote_exec_file;
1684 }
1685
1686 /* Set the remote exec file for PSPACE. */
1687
1688 static void
1689 set_pspace_remote_exec_file (struct program_space *pspace,
1690 const char *remote_exec_file)
1691 {
1692 char *old_file = remote_pspace_data.get (pspace);
1693
1694 xfree (old_file);
1695 remote_pspace_data.set (pspace, xstrdup (remote_exec_file));
1696 }
1697
1698 /* The "set/show remote exec-file" set command hook. */
1699
1700 static void
1701 set_remote_exec_file (const char *ignored, int from_tty,
1702 struct cmd_list_element *c)
1703 {
1704 set_pspace_remote_exec_file (current_program_space,
1705 remote_exec_file_var.c_str ());
1706 }
1707
1708 /* The "set/show remote exec-file" show command hook. */
1709
1710 static void
1711 show_remote_exec_file (struct ui_file *file, int from_tty,
1712 struct cmd_list_element *cmd, const char *value)
1713 {
1714 gdb_printf (file, "%s\n", get_remote_exec_file ());
1715 }
1716
1717 static int
1718 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1719 {
1720 int regnum, num_remote_regs, offset;
1721 struct packet_reg **remote_regs;
1722
1723 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1724 {
1725 struct packet_reg *r = &regs[regnum];
1726
1727 if (register_size (gdbarch, regnum) == 0)
1728 /* Do not try to fetch zero-sized (placeholder) registers. */
1729 r->pnum = -1;
1730 else
1731 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1732
1733 r->regnum = regnum;
1734 }
1735
1736 /* Define the g/G packet format as the contents of each register
1737 with a remote protocol number, in order of ascending protocol
1738 number. */
1739
1740 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1741 for (num_remote_regs = 0, regnum = 0;
1742 regnum < gdbarch_num_regs (gdbarch);
1743 regnum++)
1744 if (regs[regnum].pnum != -1)
1745 remote_regs[num_remote_regs++] = &regs[regnum];
1746
1747 std::sort (remote_regs, remote_regs + num_remote_regs,
1748 [] (const packet_reg *a, const packet_reg *b)
1749 { return a->pnum < b->pnum; });
1750
1751 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1752 {
1753 remote_regs[regnum]->in_g_packet = 1;
1754 remote_regs[regnum]->offset = offset;
1755 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1756 }
1757
1758 return offset;
1759 }
1760
1761 /* Given the architecture described by GDBARCH, return the remote
1762 protocol register's number and the register's offset in the g/G
1763 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1764 If the target does not have a mapping for REGNUM, return false,
1765 otherwise, return true. */
1766
1767 int
1768 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1769 int *pnum, int *poffset)
1770 {
1771 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1772
1773 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1774
1775 map_regcache_remote_table (gdbarch, regs.data ());
1776
1777 *pnum = regs[regnum].pnum;
1778 *poffset = regs[regnum].offset;
1779
1780 return *pnum != -1;
1781 }
1782
1783 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1784 {
1785 /* Use the architecture to build a regnum<->pnum table, which will be
1786 1:1 unless a feature set specifies otherwise. */
1787 this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1788
1789 /* Record the maximum possible size of the g packet - it may turn out
1790 to be smaller. */
1791 this->sizeof_g_packet
1792 = map_regcache_remote_table (gdbarch, this->regs.get ());
1793
1794 /* Default maximum number of characters in a packet body. Many
1795 remote stubs have a hardwired buffer size of 400 bytes
1796 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
1797 as the maximum packet-size to ensure that the packet and an extra
1798 NUL character can always fit in the buffer. This stops GDB
1799 trashing stubs that try to squeeze an extra NUL into what is
1800 already a full buffer (As of 1999-12-04 that was most stubs). */
1801 this->remote_packet_size = 400 - 1;
1802
1803 /* This one is filled in when a ``g'' packet is received. */
1804 this->actual_register_packet_size = 0;
1805
1806 /* Should rsa->sizeof_g_packet needs more space than the
1807 default, adjust the size accordingly. Remember that each byte is
1808 encoded as two characters. 32 is the overhead for the packet
1809 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
1810 (``$NN:G...#NN'') is a better guess, the below has been padded a
1811 little. */
1812 if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1813 this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1814 }
1815
1816 /* Get a pointer to the current remote target. If not connected to a
1817 remote target, return NULL. */
1818
1819 static remote_target *
1820 get_current_remote_target ()
1821 {
1822 target_ops *proc_target = current_inferior ()->process_target ();
1823 return dynamic_cast<remote_target *> (proc_target);
1824 }
1825
1826 /* Return the current allowed size of a remote packet. This is
1827 inferred from the current architecture, and should be used to
1828 limit the length of outgoing packets. */
1829 long
1830 remote_target::get_remote_packet_size ()
1831 {
1832 struct remote_state *rs = get_remote_state ();
1833 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1834
1835 if (rs->explicit_packet_size)
1836 return rs->explicit_packet_size;
1837
1838 return rsa->remote_packet_size;
1839 }
1840
1841 static struct packet_reg *
1842 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1843 long regnum)
1844 {
1845 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1846 return NULL;
1847 else
1848 {
1849 struct packet_reg *r = &rsa->regs[regnum];
1850
1851 gdb_assert (r->regnum == regnum);
1852 return r;
1853 }
1854 }
1855
1856 static struct packet_reg *
1857 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1858 LONGEST pnum)
1859 {
1860 int i;
1861
1862 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1863 {
1864 struct packet_reg *r = &rsa->regs[i];
1865
1866 if (r->pnum == pnum)
1867 return r;
1868 }
1869 return NULL;
1870 }
1871
1872 /* Allow the user to specify what sequence to send to the remote
1873 when he requests a program interruption: Although ^C is usually
1874 what remote systems expect (this is the default, here), it is
1875 sometimes preferable to send a break. On other systems such
1876 as the Linux kernel, a break followed by g, which is Magic SysRq g
1877 is required in order to interrupt the execution. */
1878 const char interrupt_sequence_control_c[] = "Ctrl-C";
1879 const char interrupt_sequence_break[] = "BREAK";
1880 const char interrupt_sequence_break_g[] = "BREAK-g";
1881 static const char *const interrupt_sequence_modes[] =
1882 {
1883 interrupt_sequence_control_c,
1884 interrupt_sequence_break,
1885 interrupt_sequence_break_g,
1886 NULL
1887 };
1888 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1889
1890 static void
1891 show_interrupt_sequence (struct ui_file *file, int from_tty,
1892 struct cmd_list_element *c,
1893 const char *value)
1894 {
1895 if (interrupt_sequence_mode == interrupt_sequence_control_c)
1896 gdb_printf (file,
1897 _("Send the ASCII ETX character (Ctrl-c) "
1898 "to the remote target to interrupt the "
1899 "execution of the program.\n"));
1900 else if (interrupt_sequence_mode == interrupt_sequence_break)
1901 gdb_printf (file,
1902 _("send a break signal to the remote target "
1903 "to interrupt the execution of the program.\n"));
1904 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1905 gdb_printf (file,
1906 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1907 "the remote target to interrupt the execution "
1908 "of Linux kernel.\n"));
1909 else
1910 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
1911 interrupt_sequence_mode);
1912 }
1913
1914 /* This boolean variable specifies whether interrupt_sequence is sent
1915 to the remote target when gdb connects to it.
1916 This is mostly needed when you debug the Linux kernel: The Linux kernel
1917 expects BREAK g which is Magic SysRq g for connecting gdb. */
1918 static bool interrupt_on_connect = false;
1919
1920 /* This variable is used to implement the "set/show remotebreak" commands.
1921 Since these commands are now deprecated in favor of "set/show remote
1922 interrupt-sequence", it no longer has any effect on the code. */
1923 static bool remote_break;
1924
1925 static void
1926 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1927 {
1928 if (remote_break)
1929 interrupt_sequence_mode = interrupt_sequence_break;
1930 else
1931 interrupt_sequence_mode = interrupt_sequence_control_c;
1932 }
1933
1934 static void
1935 show_remotebreak (struct ui_file *file, int from_tty,
1936 struct cmd_list_element *c,
1937 const char *value)
1938 {
1939 }
1940
1941 /* This variable sets the number of bits in an address that are to be
1942 sent in a memory ("M" or "m") packet. Normally, after stripping
1943 leading zeros, the entire address would be sent. This variable
1944 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1945 initial implementation of remote.c restricted the address sent in
1946 memory packets to ``host::sizeof long'' bytes - (typically 32
1947 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1948 address was never sent. Since fixing this bug may cause a break in
1949 some remote targets this variable is principally provided to
1950 facilitate backward compatibility. */
1951
1952 static unsigned int remote_address_size;
1953
1954 \f
1955 /* The default max memory-write-packet-size, when the setting is
1956 "fixed". The 16k is historical. (It came from older GDB's using
1957 alloca for buffers and the knowledge (folklore?) that some hosts
1958 don't cope very well with large alloca calls.) */
1959 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1960
1961 /* The minimum remote packet size for memory transfers. Ensures we
1962 can write at least one byte. */
1963 #define MIN_MEMORY_PACKET_SIZE 20
1964
1965 /* Get the memory packet size, assuming it is fixed. */
1966
1967 static long
1968 get_fixed_memory_packet_size (struct memory_packet_config *config)
1969 {
1970 gdb_assert (config->fixed_p);
1971
1972 if (config->size <= 0)
1973 return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1974 else
1975 return config->size;
1976 }
1977
1978 /* Compute the current size of a read/write packet. Since this makes
1979 use of ``actual_register_packet_size'' the computation is dynamic. */
1980
1981 long
1982 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1983 {
1984 struct remote_state *rs = get_remote_state ();
1985 remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1986
1987 long what_they_get;
1988 if (config->fixed_p)
1989 what_they_get = get_fixed_memory_packet_size (config);
1990 else
1991 {
1992 what_they_get = get_remote_packet_size ();
1993 /* Limit the packet to the size specified by the user. */
1994 if (config->size > 0
1995 && what_they_get > config->size)
1996 what_they_get = config->size;
1997
1998 /* Limit it to the size of the targets ``g'' response unless we have
1999 permission from the stub to use a larger packet size. */
2000 if (rs->explicit_packet_size == 0
2001 && rsa->actual_register_packet_size > 0
2002 && what_they_get > rsa->actual_register_packet_size)
2003 what_they_get = rsa->actual_register_packet_size;
2004 }
2005 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
2006 what_they_get = MIN_MEMORY_PACKET_SIZE;
2007
2008 /* Make sure there is room in the global buffer for this packet
2009 (including its trailing NUL byte). */
2010 if (rs->buf.size () < what_they_get + 1)
2011 rs->buf.resize (2 * what_they_get);
2012
2013 return what_they_get;
2014 }
2015
2016 /* Update the size of a read/write packet. If they user wants
2017 something really big then do a sanity check. */
2018
2019 static void
2020 set_memory_packet_size (const char *args, struct memory_packet_config *config,
2021 bool target_connected)
2022 {
2023 int fixed_p = config->fixed_p;
2024 long size = config->size;
2025
2026 if (args == NULL)
2027 error (_("Argument required (integer, \"fixed\" or \"limit\")."));
2028 else if (strcmp (args, "hard") == 0
2029 || strcmp (args, "fixed") == 0)
2030 fixed_p = 1;
2031 else if (strcmp (args, "soft") == 0
2032 || strcmp (args, "limit") == 0)
2033 fixed_p = 0;
2034 else
2035 {
2036 char *end;
2037
2038 size = strtoul (args, &end, 0);
2039 if (args == end)
2040 error (_("Invalid %s (bad syntax)."), config->name);
2041
2042 /* Instead of explicitly capping the size of a packet to or
2043 disallowing it, the user is allowed to set the size to
2044 something arbitrarily large. */
2045 }
2046
2047 /* Extra checks? */
2048 if (fixed_p && !config->fixed_p)
2049 {
2050 /* So that the query shows the correct value. */
2051 long query_size = (size <= 0
2052 ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
2053 : size);
2054
2055 if (target_connected
2056 && !query (_("The target may not be able to correctly handle a %s\n"
2057 "of %ld bytes. Change the packet size? "),
2058 config->name, query_size))
2059 error (_("Packet size not changed."));
2060 else if (!target_connected
2061 && !query (_("Future remote targets may not be able to "
2062 "correctly handle a %s\nof %ld bytes. Change the "
2063 "packet size for future remote targets? "),
2064 config->name, query_size))
2065 error (_("Packet size not changed."));
2066 }
2067 /* Update the config. */
2068 config->fixed_p = fixed_p;
2069 config->size = size;
2070
2071 const char *target_type = get_target_type_name (target_connected);
2072 gdb_printf (_("The %s %s is set to \"%s\".\n"), config->name, target_type,
2073 args);
2074
2075 }
2076
2077 /* Show the memory-read or write-packet size configuration CONFIG of the
2078 target REMOTE. If REMOTE is nullptr, the default configuration for future
2079 remote targets should be passed in CONFIG. */
2080
2081 static void
2082 show_memory_packet_size (memory_packet_config *config, remote_target *remote)
2083 {
2084 const char *target_type = get_target_type_name (remote != nullptr);
2085
2086 if (config->size == 0)
2087 gdb_printf (_("The %s %s is 0 (default). "), config->name, target_type);
2088 else
2089 gdb_printf (_("The %s %s is %ld. "), config->name, target_type,
2090 config->size);
2091
2092 if (config->fixed_p)
2093 gdb_printf (_("Packets are fixed at %ld bytes.\n"),
2094 get_fixed_memory_packet_size (config));
2095 else
2096 {
2097 if (remote != nullptr)
2098 gdb_printf (_("Packets are limited to %ld bytes.\n"),
2099 remote->get_memory_packet_size (config));
2100 else
2101 gdb_puts ("The actual limit will be further reduced "
2102 "dependent on the target.\n");
2103 }
2104 }
2105
2106 /* Configure the memory-write-packet size of the currently selected target. If
2107 no target is available, the default configuration for future remote targets
2108 is configured. */
2109
2110 static void
2111 set_memory_write_packet_size (const char *args, int from_tty)
2112 {
2113 remote_target *remote = get_current_remote_target ();
2114 if (remote != nullptr)
2115 {
2116 set_memory_packet_size
2117 (args, &remote->m_features.m_memory_write_packet_config, true);
2118 }
2119 else
2120 {
2121 memory_packet_config* config = &memory_write_packet_config;
2122 set_memory_packet_size (args, config, false);
2123 }
2124 }
2125
2126 /* Display the memory-write-packet size of the currently selected target. If
2127 no target is available, the default configuration for future remote targets
2128 is shown. */
2129
2130 static void
2131 show_memory_write_packet_size (const char *args, int from_tty)
2132 {
2133 remote_target *remote = get_current_remote_target ();
2134 if (remote != nullptr)
2135 show_memory_packet_size (&remote->m_features.m_memory_write_packet_config,
2136 remote);
2137 else
2138 show_memory_packet_size (&memory_write_packet_config, nullptr);
2139 }
2140
2141 /* Show the number of hardware watchpoints that can be used. */
2142
2143 static void
2144 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
2145 struct cmd_list_element *c,
2146 const char *value)
2147 {
2148 gdb_printf (file, _("The maximum number of target hardware "
2149 "watchpoints is %s.\n"), value);
2150 }
2151
2152 /* Show the length limit (in bytes) for hardware watchpoints. */
2153
2154 static void
2155 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
2156 struct cmd_list_element *c,
2157 const char *value)
2158 {
2159 gdb_printf (file, _("The maximum length (in bytes) of a target "
2160 "hardware watchpoint is %s.\n"), value);
2161 }
2162
2163 /* Show the number of hardware breakpoints that can be used. */
2164
2165 static void
2166 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
2167 struct cmd_list_element *c,
2168 const char *value)
2169 {
2170 gdb_printf (file, _("The maximum number of target hardware "
2171 "breakpoints is %s.\n"), value);
2172 }
2173
2174 /* Controls the maximum number of characters to display in the debug output
2175 for each remote packet. The remaining characters are omitted. */
2176
2177 static int remote_packet_max_chars = 512;
2178
2179 /* Show the maximum number of characters to display for each remote packet
2180 when remote debugging is enabled. */
2181
2182 static void
2183 show_remote_packet_max_chars (struct ui_file *file, int from_tty,
2184 struct cmd_list_element *c,
2185 const char *value)
2186 {
2187 gdb_printf (file, _("Number of remote packet characters to "
2188 "display is %s.\n"), value);
2189 }
2190
2191 long
2192 remote_target::get_memory_write_packet_size ()
2193 {
2194 return get_memory_packet_size (&m_features.m_memory_write_packet_config);
2195 }
2196
2197 /* Configure the memory-read-packet size of the currently selected target. If
2198 no target is available, the default configuration for future remote targets
2199 is adapted. */
2200
2201 static void
2202 set_memory_read_packet_size (const char *args, int from_tty)
2203 {
2204 remote_target *remote = get_current_remote_target ();
2205 if (remote != nullptr)
2206 set_memory_packet_size
2207 (args, &remote->m_features.m_memory_read_packet_config, true);
2208 else
2209 {
2210 memory_packet_config* config = &memory_read_packet_config;
2211 set_memory_packet_size (args, config, false);
2212 }
2213
2214 }
2215
2216 /* Display the memory-read-packet size of the currently selected target. If
2217 no target is available, the default configuration for future remote targets
2218 is shown. */
2219
2220 static void
2221 show_memory_read_packet_size (const char *args, int from_tty)
2222 {
2223 remote_target *remote = get_current_remote_target ();
2224 if (remote != nullptr)
2225 show_memory_packet_size (&remote->m_features.m_memory_read_packet_config,
2226 remote);
2227 else
2228 show_memory_packet_size (&memory_read_packet_config, nullptr);
2229 }
2230
2231 long
2232 remote_target::get_memory_read_packet_size ()
2233 {
2234 long size = get_memory_packet_size (&m_features.m_memory_read_packet_config);
2235
2236 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
2237 extra buffer size argument before the memory read size can be
2238 increased beyond this. */
2239 if (size > get_remote_packet_size ())
2240 size = get_remote_packet_size ();
2241 return size;
2242 }
2243
2244 static enum packet_support packet_config_support (const packet_config *config);
2245
2246
2247 static void
2248 set_remote_protocol_packet_cmd (const char *args, int from_tty,
2249 cmd_list_element *c)
2250 {
2251 remote_target *remote = get_current_remote_target ();
2252 gdb_assert (c->var.has_value ());
2253
2254 auto *default_config = static_cast<packet_config *> (c->context ());
2255 const int packet_idx = std::distance (remote_protocol_packets,
2256 default_config);
2257
2258 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2259 {
2260 const char *name = packets_descriptions[packet_idx].name;
2261 const auto_boolean value = c->var->get<auto_boolean> ();
2262 const char *support = get_packet_support_name (value);
2263 const char *target_type = get_target_type_name (remote != nullptr);
2264
2265 if (remote != nullptr)
2266 remote->m_features.m_protocol_packets[packet_idx].detect = value;
2267 else
2268 remote_protocol_packets[packet_idx].detect = value;
2269
2270 gdb_printf (_("Support for the '%s' packet %s is set to \"%s\".\n"), name,
2271 target_type, support);
2272 return;
2273 }
2274
2275 internal_error (_("Could not find config for %s"), c->name);
2276 }
2277
2278 static void
2279 show_packet_config_cmd (ui_file *file, const unsigned int which_packet,
2280 remote_target *remote)
2281 {
2282 const char *support = "internal-error";
2283 const char *target_type = get_target_type_name (remote != nullptr);
2284
2285 packet_config *config;
2286 if (remote != nullptr)
2287 config = &remote->m_features.m_protocol_packets[which_packet];
2288 else
2289 config = &remote_protocol_packets[which_packet];
2290
2291 switch (packet_config_support (config))
2292 {
2293 case PACKET_ENABLE:
2294 support = "enabled";
2295 break;
2296 case PACKET_DISABLE:
2297 support = "disabled";
2298 break;
2299 case PACKET_SUPPORT_UNKNOWN:
2300 support = "unknown";
2301 break;
2302 }
2303 switch (config->detect)
2304 {
2305 case AUTO_BOOLEAN_AUTO:
2306 gdb_printf (file,
2307 _("Support for the '%s' packet %s is \"auto\", "
2308 "currently %s.\n"),
2309 packets_descriptions[which_packet].name, target_type,
2310 support);
2311 break;
2312 case AUTO_BOOLEAN_TRUE:
2313 case AUTO_BOOLEAN_FALSE:
2314 gdb_printf (file,
2315 _("Support for the '%s' packet %s is \"%s\".\n"),
2316 packets_descriptions[which_packet].name, target_type,
2317 get_packet_support_name (config->detect));
2318 break;
2319 }
2320 }
2321
2322 static void
2323 add_packet_config_cmd (const unsigned int which_packet, const char *name,
2324 const char *title, int legacy)
2325 {
2326 packets_descriptions[which_packet].name = name;
2327 packets_descriptions[which_packet].title = title;
2328
2329 packet_config *config = &remote_protocol_packets[which_packet];
2330
2331 gdb::unique_xmalloc_ptr<char> set_doc
2332 = xstrprintf ("Set use of remote protocol `%s' (%s) packet.",
2333 name, title);
2334 gdb::unique_xmalloc_ptr<char> show_doc
2335 = xstrprintf ("Show current use of remote protocol `%s' (%s) packet.",
2336 name, title);
2337 /* set/show TITLE-packet {auto,on,off} */
2338 gdb::unique_xmalloc_ptr<char> cmd_name = xstrprintf ("%s-packet", title);
2339 set_show_commands cmds
2340 = add_setshow_auto_boolean_cmd (cmd_name.release (), class_obscure,
2341 &config->detect, set_doc.get (),
2342 show_doc.get (), NULL, /* help_doc */
2343 set_remote_protocol_packet_cmd,
2344 show_remote_protocol_packet_cmd,
2345 &remote_set_cmdlist, &remote_show_cmdlist);
2346 cmds.show->set_context (config);
2347 cmds.set->set_context (config);
2348
2349 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
2350 if (legacy)
2351 {
2352 /* It's not clear who should take ownership of the LEGACY_NAME string
2353 created below, so, for now, place the string into a static vector
2354 which ensures the strings is released when GDB exits. */
2355 static std::vector<gdb::unique_xmalloc_ptr<char>> legacy_names;
2356 gdb::unique_xmalloc_ptr<char> legacy_name
2357 = xstrprintf ("%s-packet", name);
2358 add_alias_cmd (legacy_name.get (), cmds.set, class_obscure, 0,
2359 &remote_set_cmdlist);
2360 add_alias_cmd (legacy_name.get (), cmds.show, class_obscure, 0,
2361 &remote_show_cmdlist);
2362 legacy_names.emplace_back (std::move (legacy_name));
2363 }
2364 }
2365
2366 static enum packet_result
2367 packet_check_result (const char *buf)
2368 {
2369 if (buf[0] != '\0')
2370 {
2371 /* The stub recognized the packet request. Check that the
2372 operation succeeded. */
2373 if (buf[0] == 'E'
2374 && isxdigit (buf[1]) && isxdigit (buf[2])
2375 && buf[3] == '\0')
2376 /* "Enn" - definitely an error. */
2377 return PACKET_ERROR;
2378
2379 /* Always treat "E." as an error. This will be used for
2380 more verbose error messages, such as E.memtypes. */
2381 if (buf[0] == 'E' && buf[1] == '.')
2382 return PACKET_ERROR;
2383
2384 /* The packet may or may not be OK. Just assume it is. */
2385 return PACKET_OK;
2386 }
2387 else
2388 /* The stub does not support the packet. */
2389 return PACKET_UNKNOWN;
2390 }
2391
2392 static enum packet_result
2393 packet_check_result (const gdb::char_vector &buf)
2394 {
2395 return packet_check_result (buf.data ());
2396 }
2397
2398 packet_result
2399 remote_features::packet_ok (const char *buf, const int which_packet)
2400 {
2401 packet_config *config = &m_protocol_packets[which_packet];
2402 packet_description *descr = &packets_descriptions[which_packet];
2403
2404 enum packet_result result;
2405
2406 if (config->detect != AUTO_BOOLEAN_TRUE
2407 && config->support == PACKET_DISABLE)
2408 internal_error (_("packet_ok: attempt to use a disabled packet"));
2409
2410 result = packet_check_result (buf);
2411 switch (result)
2412 {
2413 case PACKET_OK:
2414 case PACKET_ERROR:
2415 /* The stub recognized the packet request. */
2416 if (config->support == PACKET_SUPPORT_UNKNOWN)
2417 {
2418 remote_debug_printf ("Packet %s (%s) is supported",
2419 descr->name, descr->title);
2420 config->support = PACKET_ENABLE;
2421 }
2422 break;
2423 case PACKET_UNKNOWN:
2424 /* The stub does not support the packet. */
2425 if (config->detect == AUTO_BOOLEAN_AUTO
2426 && config->support == PACKET_ENABLE)
2427 {
2428 /* If the stub previously indicated that the packet was
2429 supported then there is a protocol error. */
2430 error (_("Protocol error: %s (%s) conflicting enabled responses."),
2431 descr->name, descr->title);
2432 }
2433 else if (config->detect == AUTO_BOOLEAN_TRUE)
2434 {
2435 /* The user set it wrong. */
2436 error (_("Enabled packet %s (%s) not recognized by stub"),
2437 descr->name, descr->title);
2438 }
2439
2440 remote_debug_printf ("Packet %s (%s) is NOT supported", descr->name,
2441 descr->title);
2442 config->support = PACKET_DISABLE;
2443 break;
2444 }
2445
2446 return result;
2447 }
2448
2449 packet_result
2450 remote_features::packet_ok (const gdb::char_vector &buf, const int which_packet)
2451 {
2452 return packet_ok (buf.data (), which_packet);
2453 }
2454
2455 /* Returns whether a given packet or feature is supported. This takes
2456 into account the state of the corresponding "set remote foo-packet"
2457 command, which may be used to bypass auto-detection. */
2458
2459 static enum packet_support
2460 packet_config_support (const packet_config *config)
2461 {
2462 switch (config->detect)
2463 {
2464 case AUTO_BOOLEAN_TRUE:
2465 return PACKET_ENABLE;
2466 case AUTO_BOOLEAN_FALSE:
2467 return PACKET_DISABLE;
2468 case AUTO_BOOLEAN_AUTO:
2469 return config->support;
2470 default:
2471 gdb_assert_not_reached ("bad switch");
2472 }
2473 }
2474
2475 packet_support
2476 remote_features::packet_support (int packet) const
2477 {
2478 const packet_config *config = &m_protocol_packets[packet];
2479 return packet_config_support (config);
2480 }
2481
2482 static void
2483 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2484 struct cmd_list_element *c,
2485 const char *value)
2486 {
2487 remote_target *remote = get_current_remote_target ();
2488 gdb_assert (c->var.has_value ());
2489
2490 auto *default_config = static_cast<packet_config *> (c->context ());
2491 const int packet_idx = std::distance (remote_protocol_packets,
2492 default_config);
2493
2494 if (packet_idx >= 0 && packet_idx < PACKET_MAX)
2495 {
2496 show_packet_config_cmd (file, packet_idx, remote);
2497 return;
2498 }
2499 internal_error (_("Could not find config for %s"), c->name);
2500 }
2501
2502 /* Should we try one of the 'Z' requests? */
2503
2504 enum Z_packet_type
2505 {
2506 Z_PACKET_SOFTWARE_BP,
2507 Z_PACKET_HARDWARE_BP,
2508 Z_PACKET_WRITE_WP,
2509 Z_PACKET_READ_WP,
2510 Z_PACKET_ACCESS_WP,
2511 NR_Z_PACKET_TYPES
2512 };
2513
2514 /* For compatibility with older distributions. Provide a ``set remote
2515 Z-packet ...'' command that updates all the Z packet types. */
2516
2517 static enum auto_boolean remote_Z_packet_detect;
2518
2519 static void
2520 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2521 struct cmd_list_element *c)
2522 {
2523 remote_target *remote = get_current_remote_target ();
2524 int i;
2525
2526 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2527 {
2528 if (remote != nullptr)
2529 remote->m_features.m_protocol_packets[PACKET_Z0 + i].detect
2530 = remote_Z_packet_detect;
2531 else
2532 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2533 }
2534
2535 const char *support = get_packet_support_name (remote_Z_packet_detect);
2536 const char *target_type = get_target_type_name (remote != nullptr);
2537 gdb_printf (_("Use of Z packets %s is set to \"%s\".\n"), target_type,
2538 support);
2539
2540 }
2541
2542 static void
2543 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2544 struct cmd_list_element *c,
2545 const char *value)
2546 {
2547 remote_target *remote = get_current_remote_target ();
2548 int i;
2549
2550 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2551 show_packet_config_cmd (file, PACKET_Z0 + i, remote);
2552 }
2553
2554 /* Insert fork catchpoint target routine. If fork events are enabled
2555 then return success, nothing more to do. */
2556
2557 int
2558 remote_target::insert_fork_catchpoint (int pid)
2559 {
2560 return !m_features.remote_fork_event_p ();
2561 }
2562
2563 /* Remove fork catchpoint target routine. Nothing to do, just
2564 return success. */
2565
2566 int
2567 remote_target::remove_fork_catchpoint (int pid)
2568 {
2569 return 0;
2570 }
2571
2572 /* Insert vfork catchpoint target routine. If vfork events are enabled
2573 then return success, nothing more to do. */
2574
2575 int
2576 remote_target::insert_vfork_catchpoint (int pid)
2577 {
2578 return !m_features.remote_vfork_event_p ();
2579 }
2580
2581 /* Remove vfork catchpoint target routine. Nothing to do, just
2582 return success. */
2583
2584 int
2585 remote_target::remove_vfork_catchpoint (int pid)
2586 {
2587 return 0;
2588 }
2589
2590 /* Insert exec catchpoint target routine. If exec events are
2591 enabled, just return success. */
2592
2593 int
2594 remote_target::insert_exec_catchpoint (int pid)
2595 {
2596 return !m_features.remote_exec_event_p ();
2597 }
2598
2599 /* Remove exec catchpoint target routine. Nothing to do, just
2600 return success. */
2601
2602 int
2603 remote_target::remove_exec_catchpoint (int pid)
2604 {
2605 return 0;
2606 }
2607
2608 \f
2609
2610 /* Take advantage of the fact that the TID field is not used, to tag
2611 special ptids with it set to != 0. */
2612 static const ptid_t magic_null_ptid (42000, -1, 1);
2613 static const ptid_t not_sent_ptid (42000, -2, 1);
2614 static const ptid_t any_thread_ptid (42000, 0, 1);
2615
2616 /* Find out if the stub attached to PID (and hence GDB should offer to
2617 detach instead of killing it when bailing out). */
2618
2619 int
2620 remote_target::remote_query_attached (int pid)
2621 {
2622 struct remote_state *rs = get_remote_state ();
2623 size_t size = get_remote_packet_size ();
2624
2625 if (m_features.packet_support (PACKET_qAttached) == PACKET_DISABLE)
2626 return 0;
2627
2628 if (m_features.remote_multi_process_p ())
2629 xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2630 else
2631 xsnprintf (rs->buf.data (), size, "qAttached");
2632
2633 putpkt (rs->buf);
2634 getpkt (&rs->buf, 0);
2635
2636 switch (m_features.packet_ok (rs->buf, PACKET_qAttached))
2637 {
2638 case PACKET_OK:
2639 if (strcmp (rs->buf.data (), "1") == 0)
2640 return 1;
2641 break;
2642 case PACKET_ERROR:
2643 warning (_("Remote failure reply: %s"), rs->buf.data ());
2644 break;
2645 case PACKET_UNKNOWN:
2646 break;
2647 }
2648
2649 return 0;
2650 }
2651
2652 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
2653 has been invented by GDB, instead of reported by the target. Since
2654 we can be connected to a remote system before before knowing about
2655 any inferior, mark the target with execution when we find the first
2656 inferior. If ATTACHED is 1, then we had just attached to this
2657 inferior. If it is 0, then we just created this inferior. If it
2658 is -1, then try querying the remote stub to find out if it had
2659 attached to the inferior or not. If TRY_OPEN_EXEC is true then
2660 attempt to open this inferior's executable as the main executable
2661 if no main executable is open already. */
2662
2663 inferior *
2664 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2665 int try_open_exec)
2666 {
2667 struct inferior *inf;
2668
2669 /* Check whether this process we're learning about is to be
2670 considered attached, or if is to be considered to have been
2671 spawned by the stub. */
2672 if (attached == -1)
2673 attached = remote_query_attached (pid);
2674
2675 if (gdbarch_has_global_solist (target_gdbarch ()))
2676 {
2677 /* If the target shares code across all inferiors, then every
2678 attach adds a new inferior. */
2679 inf = add_inferior (pid);
2680
2681 /* ... and every inferior is bound to the same program space.
2682 However, each inferior may still have its own address
2683 space. */
2684 inf->aspace = maybe_new_address_space ();
2685 inf->pspace = current_program_space;
2686 }
2687 else
2688 {
2689 /* In the traditional debugging scenario, there's a 1-1 match
2690 between program/address spaces. We simply bind the inferior
2691 to the program space's address space. */
2692 inf = current_inferior ();
2693
2694 /* However, if the current inferior is already bound to a
2695 process, find some other empty inferior. */
2696 if (inf->pid != 0)
2697 {
2698 inf = nullptr;
2699 for (inferior *it : all_inferiors ())
2700 if (it->pid == 0)
2701 {
2702 inf = it;
2703 break;
2704 }
2705 }
2706 if (inf == nullptr)
2707 {
2708 /* Since all inferiors were already bound to a process, add
2709 a new inferior. */
2710 inf = add_inferior_with_spaces ();
2711 }
2712 switch_to_inferior_no_thread (inf);
2713 inf->push_target (this);
2714 inferior_appeared (inf, pid);
2715 }
2716
2717 inf->attach_flag = attached;
2718 inf->fake_pid_p = fake_pid_p;
2719
2720 /* If no main executable is currently open then attempt to
2721 open the file that was executed to create this inferior. */
2722 if (try_open_exec && get_exec_file (0) == NULL)
2723 exec_file_locate_attach (pid, 0, 1);
2724
2725 /* Check for exec file mismatch, and let the user solve it. */
2726 validate_exec_file (1);
2727
2728 return inf;
2729 }
2730
2731 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2732 static remote_thread_info *get_remote_thread_info (remote_target *target,
2733 ptid_t ptid);
2734
2735 /* Add thread PTID to GDB's thread list. Tag it as executing/running
2736 according to EXECUTING and RUNNING respectively. If SILENT_P (or the
2737 remote_state::starting_up flag) is true then the new thread is added
2738 silently, otherwise the new thread will be announced to the user. */
2739
2740 thread_info *
2741 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing,
2742 bool silent_p)
2743 {
2744 struct remote_state *rs = get_remote_state ();
2745 struct thread_info *thread;
2746
2747 /* GDB historically didn't pull threads in the initial connection
2748 setup. If the remote target doesn't even have a concept of
2749 threads (e.g., a bare-metal target), even if internally we
2750 consider that a single-threaded target, mentioning a new thread
2751 might be confusing to the user. Be silent then, preserving the
2752 age old behavior. */
2753 if (rs->starting_up || silent_p)
2754 thread = add_thread_silent (this, ptid);
2755 else
2756 thread = add_thread (this, ptid);
2757
2758 /* We start by assuming threads are resumed. That state then gets updated
2759 when we process a matching stop reply. */
2760 get_remote_thread_info (thread)->set_resumed ();
2761
2762 set_executing (this, ptid, executing);
2763 set_running (this, ptid, running);
2764
2765 return thread;
2766 }
2767
2768 /* Come here when we learn about a thread id from the remote target.
2769 It may be the first time we hear about such thread, so take the
2770 opportunity to add it to GDB's thread list. In case this is the
2771 first time we're noticing its corresponding inferior, add it to
2772 GDB's inferior list as well. EXECUTING indicates whether the
2773 thread is (internally) executing or stopped. */
2774
2775 void
2776 remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
2777 {
2778 /* In non-stop mode, we assume new found threads are (externally)
2779 running until proven otherwise with a stop reply. In all-stop,
2780 we can only get here if all threads are stopped. */
2781 bool running = target_is_non_stop_p ();
2782
2783 /* If this is a new thread, add it to GDB's thread list.
2784 If we leave it up to WFI to do this, bad things will happen. */
2785
2786 thread_info *tp = find_thread_ptid (this, currthread);
2787 if (tp != NULL && tp->state == THREAD_EXITED)
2788 {
2789 /* We're seeing an event on a thread id we knew had exited.
2790 This has to be a new thread reusing the old id. Add it. */
2791 remote_add_thread (currthread, running, executing, false);
2792 return;
2793 }
2794
2795 if (!in_thread_list (this, currthread))
2796 {
2797 struct inferior *inf = NULL;
2798 int pid = currthread.pid ();
2799
2800 if (inferior_ptid.is_pid ()
2801 && pid == inferior_ptid.pid ())
2802 {
2803 /* inferior_ptid has no thread member yet. This can happen
2804 with the vAttach -> remote_wait,"TAAthread:" path if the
2805 stub doesn't support qC. This is the first stop reported
2806 after an attach, so this is the main thread. Update the
2807 ptid in the thread list. */
2808 if (in_thread_list (this, ptid_t (pid)))
2809 thread_change_ptid (this, inferior_ptid, currthread);
2810 else
2811 {
2812 thread_info *thr
2813 = remote_add_thread (currthread, running, executing, false);
2814 switch_to_thread (thr);
2815 }
2816 return;
2817 }
2818
2819 if (magic_null_ptid == inferior_ptid)
2820 {
2821 /* inferior_ptid is not set yet. This can happen with the
2822 vRun -> remote_wait,"TAAthread:" path if the stub
2823 doesn't support qC. This is the first stop reported
2824 after an attach, so this is the main thread. Update the
2825 ptid in the thread list. */
2826 thread_change_ptid (this, inferior_ptid, currthread);
2827 return;
2828 }
2829
2830 /* When connecting to a target remote, or to a target
2831 extended-remote which already was debugging an inferior, we
2832 may not know about it yet. Add it before adding its child
2833 thread, so notifications are emitted in a sensible order. */
2834 if (find_inferior_pid (this, currthread.pid ()) == NULL)
2835 {
2836 bool fake_pid_p = !m_features.remote_multi_process_p ();
2837
2838 inf = remote_add_inferior (fake_pid_p,
2839 currthread.pid (), -1, 1);
2840 }
2841
2842 /* This is really a new thread. Add it. */
2843 thread_info *new_thr
2844 = remote_add_thread (currthread, running, executing, false);
2845
2846 /* If we found a new inferior, let the common code do whatever
2847 it needs to with it (e.g., read shared libraries, insert
2848 breakpoints), unless we're just setting up an all-stop
2849 connection. */
2850 if (inf != NULL)
2851 {
2852 struct remote_state *rs = get_remote_state ();
2853
2854 if (!rs->starting_up)
2855 notice_new_inferior (new_thr, executing, 0);
2856 }
2857 }
2858 }
2859
2860 /* Return THREAD's private thread data, creating it if necessary. */
2861
2862 static remote_thread_info *
2863 get_remote_thread_info (thread_info *thread)
2864 {
2865 gdb_assert (thread != NULL);
2866
2867 if (thread->priv == NULL)
2868 thread->priv.reset (new remote_thread_info);
2869
2870 return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
2871 }
2872
2873 /* Return PTID's private thread data, creating it if necessary. */
2874
2875 static remote_thread_info *
2876 get_remote_thread_info (remote_target *target, ptid_t ptid)
2877 {
2878 thread_info *thr = find_thread_ptid (target, ptid);
2879 return get_remote_thread_info (thr);
2880 }
2881
2882 /* Call this function as a result of
2883 1) A halt indication (T packet) containing a thread id
2884 2) A direct query of currthread
2885 3) Successful execution of set thread */
2886
2887 static void
2888 record_currthread (struct remote_state *rs, ptid_t currthread)
2889 {
2890 rs->general_thread = currthread;
2891 }
2892
2893 /* If 'QPassSignals' is supported, tell the remote stub what signals
2894 it can simply pass through to the inferior without reporting. */
2895
2896 void
2897 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2898 {
2899 if (m_features.packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2900 {
2901 char *pass_packet, *p;
2902 int count = 0;
2903 struct remote_state *rs = get_remote_state ();
2904
2905 gdb_assert (pass_signals.size () < 256);
2906 for (size_t i = 0; i < pass_signals.size (); i++)
2907 {
2908 if (pass_signals[i])
2909 count++;
2910 }
2911 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2912 strcpy (pass_packet, "QPassSignals:");
2913 p = pass_packet + strlen (pass_packet);
2914 for (size_t i = 0; i < pass_signals.size (); i++)
2915 {
2916 if (pass_signals[i])
2917 {
2918 if (i >= 16)
2919 *p++ = tohex (i >> 4);
2920 *p++ = tohex (i & 15);
2921 if (count)
2922 *p++ = ';';
2923 else
2924 break;
2925 count--;
2926 }
2927 }
2928 *p = 0;
2929 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2930 {
2931 putpkt (pass_packet);
2932 getpkt (&rs->buf, 0);
2933 m_features.packet_ok (rs->buf, PACKET_QPassSignals);
2934 xfree (rs->last_pass_packet);
2935 rs->last_pass_packet = pass_packet;
2936 }
2937 else
2938 xfree (pass_packet);
2939 }
2940 }
2941
2942 /* If 'QCatchSyscalls' is supported, tell the remote stub
2943 to report syscalls to GDB. */
2944
2945 int
2946 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2947 gdb::array_view<const int> syscall_counts)
2948 {
2949 const char *catch_packet;
2950 enum packet_result result;
2951 int n_sysno = 0;
2952
2953 if (m_features.packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2954 {
2955 /* Not supported. */
2956 return 1;
2957 }
2958
2959 if (needed && any_count == 0)
2960 {
2961 /* Count how many syscalls are to be caught. */
2962 for (size_t i = 0; i < syscall_counts.size (); i++)
2963 {
2964 if (syscall_counts[i] != 0)
2965 n_sysno++;
2966 }
2967 }
2968
2969 remote_debug_printf ("pid %d needed %d any_count %d n_sysno %d",
2970 pid, needed, any_count, n_sysno);
2971
2972 std::string built_packet;
2973 if (needed)
2974 {
2975 /* Prepare a packet with the sysno list, assuming max 8+1
2976 characters for a sysno. If the resulting packet size is too
2977 big, fallback on the non-selective packet. */
2978 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2979 built_packet.reserve (maxpktsz);
2980 built_packet = "QCatchSyscalls:1";
2981 if (any_count == 0)
2982 {
2983 /* Add in each syscall to be caught. */
2984 for (size_t i = 0; i < syscall_counts.size (); i++)
2985 {
2986 if (syscall_counts[i] != 0)
2987 string_appendf (built_packet, ";%zx", i);
2988 }
2989 }
2990 if (built_packet.size () > get_remote_packet_size ())
2991 {
2992 /* catch_packet too big. Fallback to less efficient
2993 non selective mode, with GDB doing the filtering. */
2994 catch_packet = "QCatchSyscalls:1";
2995 }
2996 else
2997 catch_packet = built_packet.c_str ();
2998 }
2999 else
3000 catch_packet = "QCatchSyscalls:0";
3001
3002 struct remote_state *rs = get_remote_state ();
3003
3004 putpkt (catch_packet);
3005 getpkt (&rs->buf, 0);
3006 result = m_features.packet_ok (rs->buf, PACKET_QCatchSyscalls);
3007 if (result == PACKET_OK)
3008 return 0;
3009 else
3010 return -1;
3011 }
3012
3013 /* If 'QProgramSignals' is supported, tell the remote stub what
3014 signals it should pass through to the inferior when detaching. */
3015
3016 void
3017 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
3018 {
3019 if (m_features.packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
3020 {
3021 char *packet, *p;
3022 int count = 0;
3023 struct remote_state *rs = get_remote_state ();
3024
3025 gdb_assert (signals.size () < 256);
3026 for (size_t i = 0; i < signals.size (); i++)
3027 {
3028 if (signals[i])
3029 count++;
3030 }
3031 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
3032 strcpy (packet, "QProgramSignals:");
3033 p = packet + strlen (packet);
3034 for (size_t i = 0; i < signals.size (); i++)
3035 {
3036 if (signal_pass_state (i))
3037 {
3038 if (i >= 16)
3039 *p++ = tohex (i >> 4);
3040 *p++ = tohex (i & 15);
3041 if (count)
3042 *p++ = ';';
3043 else
3044 break;
3045 count--;
3046 }
3047 }
3048 *p = 0;
3049 if (!rs->last_program_signals_packet
3050 || strcmp (rs->last_program_signals_packet, packet) != 0)
3051 {
3052 putpkt (packet);
3053 getpkt (&rs->buf, 0);
3054 m_features.packet_ok (rs->buf, PACKET_QProgramSignals);
3055 xfree (rs->last_program_signals_packet);
3056 rs->last_program_signals_packet = packet;
3057 }
3058 else
3059 xfree (packet);
3060 }
3061 }
3062
3063 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
3064 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
3065 thread. If GEN is set, set the general thread, if not, then set
3066 the step/continue thread. */
3067 void
3068 remote_target::set_thread (ptid_t ptid, int gen)
3069 {
3070 struct remote_state *rs = get_remote_state ();
3071 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
3072 char *buf = rs->buf.data ();
3073 char *endbuf = buf + get_remote_packet_size ();
3074
3075 if (state == ptid)
3076 return;
3077
3078 *buf++ = 'H';
3079 *buf++ = gen ? 'g' : 'c';
3080 if (ptid == magic_null_ptid)
3081 xsnprintf (buf, endbuf - buf, "0");
3082 else if (ptid == any_thread_ptid)
3083 xsnprintf (buf, endbuf - buf, "0");
3084 else if (ptid == minus_one_ptid)
3085 xsnprintf (buf, endbuf - buf, "-1");
3086 else
3087 write_ptid (buf, endbuf, ptid);
3088 putpkt (rs->buf);
3089 getpkt (&rs->buf, 0);
3090 if (gen)
3091 rs->general_thread = ptid;
3092 else
3093 rs->continue_thread = ptid;
3094 }
3095
3096 void
3097 remote_target::set_general_thread (ptid_t ptid)
3098 {
3099 set_thread (ptid, 1);
3100 }
3101
3102 void
3103 remote_target::set_continue_thread (ptid_t ptid)
3104 {
3105 set_thread (ptid, 0);
3106 }
3107
3108 /* Change the remote current process. Which thread within the process
3109 ends up selected isn't important, as long as it is the same process
3110 as what INFERIOR_PTID points to.
3111
3112 This comes from that fact that there is no explicit notion of
3113 "selected process" in the protocol. The selected process for
3114 general operations is the process the selected general thread
3115 belongs to. */
3116
3117 void
3118 remote_target::set_general_process ()
3119 {
3120 /* If the remote can't handle multiple processes, don't bother. */
3121 if (!m_features.remote_multi_process_p ())
3122 return;
3123
3124 remote_state *rs = get_remote_state ();
3125
3126 /* We only need to change the remote current thread if it's pointing
3127 at some other process. */
3128 if (rs->general_thread.pid () != inferior_ptid.pid ())
3129 set_general_thread (inferior_ptid);
3130 }
3131
3132 \f
3133 /* Return nonzero if this is the main thread that we made up ourselves
3134 to model non-threaded targets as single-threaded. */
3135
3136 static int
3137 remote_thread_always_alive (ptid_t ptid)
3138 {
3139 if (ptid == magic_null_ptid)
3140 /* The main thread is always alive. */
3141 return 1;
3142
3143 if (ptid.pid () != 0 && ptid.lwp () == 0)
3144 /* The main thread is always alive. This can happen after a
3145 vAttach, if the remote side doesn't support
3146 multi-threading. */
3147 return 1;
3148
3149 return 0;
3150 }
3151
3152 /* Return nonzero if the thread PTID is still alive on the remote
3153 system. */
3154
3155 bool
3156 remote_target::thread_alive (ptid_t ptid)
3157 {
3158 struct remote_state *rs = get_remote_state ();
3159 char *p, *endp;
3160
3161 /* Check if this is a thread that we made up ourselves to model
3162 non-threaded targets as single-threaded. */
3163 if (remote_thread_always_alive (ptid))
3164 return 1;
3165
3166 p = rs->buf.data ();
3167 endp = p + get_remote_packet_size ();
3168
3169 *p++ = 'T';
3170 write_ptid (p, endp, ptid);
3171
3172 putpkt (rs->buf);
3173 getpkt (&rs->buf, 0);
3174 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
3175 }
3176
3177 /* Return a pointer to a thread name if we know it and NULL otherwise.
3178 The thread_info object owns the memory for the name. */
3179
3180 const char *
3181 remote_target::thread_name (struct thread_info *info)
3182 {
3183 if (info->priv != NULL)
3184 {
3185 const std::string &name = get_remote_thread_info (info)->name;
3186 return !name.empty () ? name.c_str () : NULL;
3187 }
3188
3189 return NULL;
3190 }
3191
3192 /* About these extended threadlist and threadinfo packets. They are
3193 variable length packets but, the fields within them are often fixed
3194 length. They are redundant enough to send over UDP as is the
3195 remote protocol in general. There is a matching unit test module
3196 in libstub. */
3197
3198 /* WARNING: This threadref data structure comes from the remote O.S.,
3199 libstub protocol encoding, and remote.c. It is not particularly
3200 changable. */
3201
3202 /* Right now, the internal structure is int. We want it to be bigger.
3203 Plan to fix this. */
3204
3205 typedef int gdb_threadref; /* Internal GDB thread reference. */
3206
3207 /* gdb_ext_thread_info is an internal GDB data structure which is
3208 equivalent to the reply of the remote threadinfo packet. */
3209
3210 struct gdb_ext_thread_info
3211 {
3212 threadref threadid; /* External form of thread reference. */
3213 int active; /* Has state interesting to GDB?
3214 regs, stack. */
3215 char display[256]; /* Brief state display, name,
3216 blocked/suspended. */
3217 char shortname[32]; /* To be used to name threads. */
3218 char more_display[256]; /* Long info, statistics, queue depth,
3219 whatever. */
3220 };
3221
3222 /* The volume of remote transfers can be limited by submitting
3223 a mask containing bits specifying the desired information.
3224 Use a union of these values as the 'selection' parameter to
3225 get_thread_info. FIXME: Make these TAG names more thread specific. */
3226
3227 #define TAG_THREADID 1
3228 #define TAG_EXISTS 2
3229 #define TAG_DISPLAY 4
3230 #define TAG_THREADNAME 8
3231 #define TAG_MOREDISPLAY 16
3232
3233 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
3234
3235 static const char *unpack_nibble (const char *buf, int *val);
3236
3237 static const char *unpack_byte (const char *buf, int *value);
3238
3239 static char *pack_int (char *buf, int value);
3240
3241 static const char *unpack_int (const char *buf, int *value);
3242
3243 static const char *unpack_string (const char *src, char *dest, int length);
3244
3245 static char *pack_threadid (char *pkt, threadref *id);
3246
3247 static const char *unpack_threadid (const char *inbuf, threadref *id);
3248
3249 void int_to_threadref (threadref *id, int value);
3250
3251 static int threadref_to_int (threadref *ref);
3252
3253 static void copy_threadref (threadref *dest, threadref *src);
3254
3255 static int threadmatch (threadref *dest, threadref *src);
3256
3257 static char *pack_threadinfo_request (char *pkt, int mode,
3258 threadref *id);
3259
3260 static char *pack_threadlist_request (char *pkt, int startflag,
3261 int threadcount,
3262 threadref *nextthread);
3263
3264 static int remote_newthread_step (threadref *ref, void *context);
3265
3266
3267 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
3268 buffer we're allowed to write to. Returns
3269 BUF+CHARACTERS_WRITTEN. */
3270
3271 char *
3272 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
3273 {
3274 int pid, tid;
3275
3276 if (m_features.remote_multi_process_p ())
3277 {
3278 pid = ptid.pid ();
3279 if (pid < 0)
3280 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
3281 else
3282 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
3283 }
3284 tid = ptid.lwp ();
3285 if (tid < 0)
3286 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
3287 else
3288 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
3289
3290 return buf;
3291 }
3292
3293 /* Extract a PTID from BUF. If non-null, OBUF is set to one past the
3294 last parsed char. Returns null_ptid if no thread id is found, and
3295 throws an error if the thread id has an invalid format. */
3296
3297 static ptid_t
3298 read_ptid (const char *buf, const char **obuf)
3299 {
3300 const char *p = buf;
3301 const char *pp;
3302 ULONGEST pid = 0, tid = 0;
3303
3304 if (*p == 'p')
3305 {
3306 /* Multi-process ptid. */
3307 pp = unpack_varlen_hex (p + 1, &pid);
3308 if (*pp != '.')
3309 error (_("invalid remote ptid: %s"), p);
3310
3311 p = pp;
3312 pp = unpack_varlen_hex (p + 1, &tid);
3313 if (obuf)
3314 *obuf = pp;
3315 return ptid_t (pid, tid);
3316 }
3317
3318 /* No multi-process. Just a tid. */
3319 pp = unpack_varlen_hex (p, &tid);
3320
3321 /* Return null_ptid when no thread id is found. */
3322 if (p == pp)
3323 {
3324 if (obuf)
3325 *obuf = pp;
3326 return null_ptid;
3327 }
3328
3329 /* Since the stub is not sending a process id, default to what's
3330 current_inferior, unless it doesn't have a PID yet. If so,
3331 then since there's no way to know the pid of the reported
3332 threads, use the magic number. */
3333 inferior *inf = current_inferior ();
3334 if (inf->pid == 0)
3335 pid = magic_null_ptid.pid ();
3336 else
3337 pid = inf->pid;
3338
3339 if (obuf)
3340 *obuf = pp;
3341 return ptid_t (pid, tid);
3342 }
3343
3344 static int
3345 stubhex (int ch)
3346 {
3347 if (ch >= 'a' && ch <= 'f')
3348 return ch - 'a' + 10;
3349 if (ch >= '0' && ch <= '9')
3350 return ch - '0';
3351 if (ch >= 'A' && ch <= 'F')
3352 return ch - 'A' + 10;
3353 return -1;
3354 }
3355
3356 static int
3357 stub_unpack_int (const char *buff, int fieldlength)
3358 {
3359 int nibble;
3360 int retval = 0;
3361
3362 while (fieldlength)
3363 {
3364 nibble = stubhex (*buff++);
3365 retval |= nibble;
3366 fieldlength--;
3367 if (fieldlength)
3368 retval = retval << 4;
3369 }
3370 return retval;
3371 }
3372
3373 static const char *
3374 unpack_nibble (const char *buf, int *val)
3375 {
3376 *val = fromhex (*buf++);
3377 return buf;
3378 }
3379
3380 static const char *
3381 unpack_byte (const char *buf, int *value)
3382 {
3383 *value = stub_unpack_int (buf, 2);
3384 return buf + 2;
3385 }
3386
3387 static char *
3388 pack_int (char *buf, int value)
3389 {
3390 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3391 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3392 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3393 buf = pack_hex_byte (buf, (value & 0xff));
3394 return buf;
3395 }
3396
3397 static const char *
3398 unpack_int (const char *buf, int *value)
3399 {
3400 *value = stub_unpack_int (buf, 8);
3401 return buf + 8;
3402 }
3403
3404 #if 0 /* Currently unused, uncomment when needed. */
3405 static char *pack_string (char *pkt, char *string);
3406
3407 static char *
3408 pack_string (char *pkt, char *string)
3409 {
3410 char ch;
3411 int len;
3412
3413 len = strlen (string);
3414 if (len > 200)
3415 len = 200; /* Bigger than most GDB packets, junk??? */
3416 pkt = pack_hex_byte (pkt, len);
3417 while (len-- > 0)
3418 {
3419 ch = *string++;
3420 if ((ch == '\0') || (ch == '#'))
3421 ch = '*'; /* Protect encapsulation. */
3422 *pkt++ = ch;
3423 }
3424 return pkt;
3425 }
3426 #endif /* 0 (unused) */
3427
3428 static const char *
3429 unpack_string (const char *src, char *dest, int length)
3430 {
3431 while (length--)
3432 *dest++ = *src++;
3433 *dest = '\0';
3434 return src;
3435 }
3436
3437 static char *
3438 pack_threadid (char *pkt, threadref *id)
3439 {
3440 char *limit;
3441 unsigned char *altid;
3442
3443 altid = (unsigned char *) id;
3444 limit = pkt + BUF_THREAD_ID_SIZE;
3445 while (pkt < limit)
3446 pkt = pack_hex_byte (pkt, *altid++);
3447 return pkt;
3448 }
3449
3450
3451 static const char *
3452 unpack_threadid (const char *inbuf, threadref *id)
3453 {
3454 char *altref;
3455 const char *limit = inbuf + BUF_THREAD_ID_SIZE;
3456 int x, y;
3457
3458 altref = (char *) id;
3459
3460 while (inbuf < limit)
3461 {
3462 x = stubhex (*inbuf++);
3463 y = stubhex (*inbuf++);
3464 *altref++ = (x << 4) | y;
3465 }
3466 return inbuf;
3467 }
3468
3469 /* Externally, threadrefs are 64 bits but internally, they are still
3470 ints. This is due to a mismatch of specifications. We would like
3471 to use 64bit thread references internally. This is an adapter
3472 function. */
3473
3474 void
3475 int_to_threadref (threadref *id, int value)
3476 {
3477 unsigned char *scan;
3478
3479 scan = (unsigned char *) id;
3480 {
3481 int i = 4;
3482 while (i--)
3483 *scan++ = 0;
3484 }
3485 *scan++ = (value >> 24) & 0xff;
3486 *scan++ = (value >> 16) & 0xff;
3487 *scan++ = (value >> 8) & 0xff;
3488 *scan++ = (value & 0xff);
3489 }
3490
3491 static int
3492 threadref_to_int (threadref *ref)
3493 {
3494 int i, value = 0;
3495 unsigned char *scan;
3496
3497 scan = *ref;
3498 scan += 4;
3499 i = 4;
3500 while (i-- > 0)
3501 value = (value << 8) | ((*scan++) & 0xff);
3502 return value;
3503 }
3504
3505 static void
3506 copy_threadref (threadref *dest, threadref *src)
3507 {
3508 int i;
3509 unsigned char *csrc, *cdest;
3510
3511 csrc = (unsigned char *) src;
3512 cdest = (unsigned char *) dest;
3513 i = 8;
3514 while (i--)
3515 *cdest++ = *csrc++;
3516 }
3517
3518 static int
3519 threadmatch (threadref *dest, threadref *src)
3520 {
3521 /* Things are broken right now, so just assume we got a match. */
3522 #if 0
3523 unsigned char *srcp, *destp;
3524 int i, result;
3525 srcp = (char *) src;
3526 destp = (char *) dest;
3527
3528 result = 1;
3529 while (i-- > 0)
3530 result &= (*srcp++ == *destp++) ? 1 : 0;
3531 return result;
3532 #endif
3533 return 1;
3534 }
3535
3536 /*
3537 threadid:1, # always request threadid
3538 context_exists:2,
3539 display:4,
3540 unique_name:8,
3541 more_display:16
3542 */
3543
3544 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
3545
3546 static char *
3547 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3548 {
3549 *pkt++ = 'q'; /* Info Query */
3550 *pkt++ = 'P'; /* process or thread info */
3551 pkt = pack_int (pkt, mode); /* mode */
3552 pkt = pack_threadid (pkt, id); /* threadid */
3553 *pkt = '\0'; /* terminate */
3554 return pkt;
3555 }
3556
3557 /* These values tag the fields in a thread info response packet. */
3558 /* Tagging the fields allows us to request specific fields and to
3559 add more fields as time goes by. */
3560
3561 #define TAG_THREADID 1 /* Echo the thread identifier. */
3562 #define TAG_EXISTS 2 /* Is this process defined enough to
3563 fetch registers and its stack? */
3564 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
3565 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
3566 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
3567 the process. */
3568
3569 int
3570 remote_target::remote_unpack_thread_info_response (const char *pkt,
3571 threadref *expectedref,
3572 gdb_ext_thread_info *info)
3573 {
3574 struct remote_state *rs = get_remote_state ();
3575 int mask, length;
3576 int tag;
3577 threadref ref;
3578 const char *limit = pkt + rs->buf.size (); /* Plausible parsing limit. */
3579 int retval = 1;
3580
3581 /* info->threadid = 0; FIXME: implement zero_threadref. */
3582 info->active = 0;
3583 info->display[0] = '\0';
3584 info->shortname[0] = '\0';
3585 info->more_display[0] = '\0';
3586
3587 /* Assume the characters indicating the packet type have been
3588 stripped. */
3589 pkt = unpack_int (pkt, &mask); /* arg mask */
3590 pkt = unpack_threadid (pkt, &ref);
3591
3592 if (mask == 0)
3593 warning (_("Incomplete response to threadinfo request."));
3594 if (!threadmatch (&ref, expectedref))
3595 { /* This is an answer to a different request. */
3596 warning (_("ERROR RMT Thread info mismatch."));
3597 return 0;
3598 }
3599 copy_threadref (&info->threadid, &ref);
3600
3601 /* Loop on tagged fields , try to bail if something goes wrong. */
3602
3603 /* Packets are terminated with nulls. */
3604 while ((pkt < limit) && mask && *pkt)
3605 {
3606 pkt = unpack_int (pkt, &tag); /* tag */
3607 pkt = unpack_byte (pkt, &length); /* length */
3608 if (!(tag & mask)) /* Tags out of synch with mask. */
3609 {
3610 warning (_("ERROR RMT: threadinfo tag mismatch."));
3611 retval = 0;
3612 break;
3613 }
3614 if (tag == TAG_THREADID)
3615 {
3616 if (length != 16)
3617 {
3618 warning (_("ERROR RMT: length of threadid is not 16."));
3619 retval = 0;
3620 break;
3621 }
3622 pkt = unpack_threadid (pkt, &ref);
3623 mask = mask & ~TAG_THREADID;
3624 continue;
3625 }
3626 if (tag == TAG_EXISTS)
3627 {
3628 info->active = stub_unpack_int (pkt, length);
3629 pkt += length;
3630 mask = mask & ~(TAG_EXISTS);
3631 if (length > 8)
3632 {
3633 warning (_("ERROR RMT: 'exists' length too long."));
3634 retval = 0;
3635 break;
3636 }
3637 continue;
3638 }
3639 if (tag == TAG_THREADNAME)
3640 {
3641 pkt = unpack_string (pkt, &info->shortname[0], length);
3642 mask = mask & ~TAG_THREADNAME;
3643 continue;
3644 }
3645 if (tag == TAG_DISPLAY)
3646 {
3647 pkt = unpack_string (pkt, &info->display[0], length);
3648 mask = mask & ~TAG_DISPLAY;
3649 continue;
3650 }
3651 if (tag == TAG_MOREDISPLAY)
3652 {
3653 pkt = unpack_string (pkt, &info->more_display[0], length);
3654 mask = mask & ~TAG_MOREDISPLAY;
3655 continue;
3656 }
3657 warning (_("ERROR RMT: unknown thread info tag."));
3658 break; /* Not a tag we know about. */
3659 }
3660 return retval;
3661 }
3662
3663 int
3664 remote_target::remote_get_threadinfo (threadref *threadid,
3665 int fieldset,
3666 gdb_ext_thread_info *info)
3667 {
3668 struct remote_state *rs = get_remote_state ();
3669 int result;
3670
3671 pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3672 putpkt (rs->buf);
3673 getpkt (&rs->buf, 0);
3674
3675 if (rs->buf[0] == '\0')
3676 return 0;
3677
3678 result = remote_unpack_thread_info_response (&rs->buf[2],
3679 threadid, info);
3680 return result;
3681 }
3682
3683 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
3684
3685 static char *
3686 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3687 threadref *nextthread)
3688 {
3689 *pkt++ = 'q'; /* info query packet */
3690 *pkt++ = 'L'; /* Process LIST or threadLIST request */
3691 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
3692 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
3693 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
3694 *pkt = '\0';
3695 return pkt;
3696 }
3697
3698 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3699
3700 int
3701 remote_target::parse_threadlist_response (const char *pkt, int result_limit,
3702 threadref *original_echo,
3703 threadref *resultlist,
3704 int *doneflag)
3705 {
3706 struct remote_state *rs = get_remote_state ();
3707 int count, resultcount, done;
3708
3709 resultcount = 0;
3710 /* Assume the 'q' and 'M chars have been stripped. */
3711 const char *limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3712 /* done parse past here */
3713 pkt = unpack_byte (pkt, &count); /* count field */
3714 pkt = unpack_nibble (pkt, &done);
3715 /* The first threadid is the argument threadid. */
3716 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
3717 while ((count-- > 0) && (pkt < limit))
3718 {
3719 pkt = unpack_threadid (pkt, resultlist++);
3720 if (resultcount++ >= result_limit)
3721 break;
3722 }
3723 if (doneflag)
3724 *doneflag = done;
3725 return resultcount;
3726 }
3727
3728 /* Fetch the next batch of threads from the remote. Returns -1 if the
3729 qL packet is not supported, 0 on error and 1 on success. */
3730
3731 int
3732 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3733 int result_limit, int *done, int *result_count,
3734 threadref *threadlist)
3735 {
3736 struct remote_state *rs = get_remote_state ();
3737 int result = 1;
3738
3739 /* Truncate result limit to be smaller than the packet size. */
3740 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3741 >= get_remote_packet_size ())
3742 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3743
3744 pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3745 nextthread);
3746 putpkt (rs->buf);
3747 getpkt (&rs->buf, 0);
3748 if (rs->buf[0] == '\0')
3749 {
3750 /* Packet not supported. */
3751 return -1;
3752 }
3753
3754 *result_count =
3755 parse_threadlist_response (&rs->buf[2], result_limit,
3756 &rs->echo_nextthread, threadlist, done);
3757
3758 if (!threadmatch (&rs->echo_nextthread, nextthread))
3759 {
3760 /* FIXME: This is a good reason to drop the packet. */
3761 /* Possibly, there is a duplicate response. */
3762 /* Possibilities :
3763 retransmit immediatly - race conditions
3764 retransmit after timeout - yes
3765 exit
3766 wait for packet, then exit
3767 */
3768 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3769 return 0; /* I choose simply exiting. */
3770 }
3771 if (*result_count <= 0)
3772 {
3773 if (*done != 1)
3774 {
3775 warning (_("RMT ERROR : failed to get remote thread list."));
3776 result = 0;
3777 }
3778 return result; /* break; */
3779 }
3780 if (*result_count > result_limit)
3781 {
3782 *result_count = 0;
3783 warning (_("RMT ERROR: threadlist response longer than requested."));
3784 return 0;
3785 }
3786 return result;
3787 }
3788
3789 /* Fetch the list of remote threads, with the qL packet, and call
3790 STEPFUNCTION for each thread found. Stops iterating and returns 1
3791 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
3792 STEPFUNCTION returns false. If the packet is not supported,
3793 returns -1. */
3794
3795 int
3796 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3797 void *context, int looplimit)
3798 {
3799 struct remote_state *rs = get_remote_state ();
3800 int done, i, result_count;
3801 int startflag = 1;
3802 int result = 1;
3803 int loopcount = 0;
3804
3805 done = 0;
3806 while (!done)
3807 {
3808 if (loopcount++ > looplimit)
3809 {
3810 result = 0;
3811 warning (_("Remote fetch threadlist -infinite loop-."));
3812 break;
3813 }
3814 result = remote_get_threadlist (startflag, &rs->nextthread,
3815 MAXTHREADLISTRESULTS,
3816 &done, &result_count,
3817 rs->resultthreadlist);
3818 if (result <= 0)
3819 break;
3820 /* Clear for later iterations. */
3821 startflag = 0;
3822 /* Setup to resume next batch of thread references, set nextthread. */
3823 if (result_count >= 1)
3824 copy_threadref (&rs->nextthread,
3825 &rs->resultthreadlist[result_count - 1]);
3826 i = 0;
3827 while (result_count--)
3828 {
3829 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3830 {
3831 result = 0;
3832 break;
3833 }
3834 }
3835 }
3836 return result;
3837 }
3838
3839 /* A thread found on the remote target. */
3840
3841 struct thread_item
3842 {
3843 explicit thread_item (ptid_t ptid_)
3844 : ptid (ptid_)
3845 {}
3846
3847 thread_item (thread_item &&other) = default;
3848 thread_item &operator= (thread_item &&other) = default;
3849
3850 DISABLE_COPY_AND_ASSIGN (thread_item);
3851
3852 /* The thread's PTID. */
3853 ptid_t ptid;
3854
3855 /* The thread's extra info. */
3856 std::string extra;
3857
3858 /* The thread's name. */
3859 std::string name;
3860
3861 /* The core the thread was running on. -1 if not known. */
3862 int core = -1;
3863
3864 /* The thread handle associated with the thread. */
3865 gdb::byte_vector thread_handle;
3866 };
3867
3868 /* Context passed around to the various methods listing remote
3869 threads. As new threads are found, they're added to the ITEMS
3870 vector. */
3871
3872 struct threads_listing_context
3873 {
3874 /* Return true if this object contains an entry for a thread with ptid
3875 PTID. */
3876
3877 bool contains_thread (ptid_t ptid) const
3878 {
3879 auto match_ptid = [&] (const thread_item &item)
3880 {
3881 return item.ptid == ptid;
3882 };
3883
3884 auto it = std::find_if (this->items.begin (),
3885 this->items.end (),
3886 match_ptid);
3887
3888 return it != this->items.end ();
3889 }
3890
3891 /* Remove the thread with ptid PTID. */
3892
3893 void remove_thread (ptid_t ptid)
3894 {
3895 auto match_ptid = [&] (const thread_item &item)
3896 {
3897 return item.ptid == ptid;
3898 };
3899
3900 auto it = std::remove_if (this->items.begin (),
3901 this->items.end (),
3902 match_ptid);
3903
3904 if (it != this->items.end ())
3905 this->items.erase (it);
3906 }
3907
3908 /* The threads found on the remote target. */
3909 std::vector<thread_item> items;
3910 };
3911
3912 static int
3913 remote_newthread_step (threadref *ref, void *data)
3914 {
3915 struct threads_listing_context *context
3916 = (struct threads_listing_context *) data;
3917 int pid = inferior_ptid.pid ();
3918 int lwp = threadref_to_int (ref);
3919 ptid_t ptid (pid, lwp);
3920
3921 context->items.emplace_back (ptid);
3922
3923 return 1; /* continue iterator */
3924 }
3925
3926 #define CRAZY_MAX_THREADS 1000
3927
3928 ptid_t
3929 remote_target::remote_current_thread (ptid_t oldpid)
3930 {
3931 struct remote_state *rs = get_remote_state ();
3932
3933 putpkt ("qC");
3934 getpkt (&rs->buf, 0);
3935 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3936 {
3937 const char *obuf;
3938 ptid_t result;
3939
3940 result = read_ptid (&rs->buf[2], &obuf);
3941 if (*obuf != '\0')
3942 remote_debug_printf ("warning: garbage in qC reply");
3943
3944 return result;
3945 }
3946 else
3947 return oldpid;
3948 }
3949
3950 /* List remote threads using the deprecated qL packet. */
3951
3952 int
3953 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3954 {
3955 if (remote_threadlist_iterator (remote_newthread_step, context,
3956 CRAZY_MAX_THREADS) >= 0)
3957 return 1;
3958
3959 return 0;
3960 }
3961
3962 #if defined(HAVE_LIBEXPAT)
3963
3964 static void
3965 start_thread (struct gdb_xml_parser *parser,
3966 const struct gdb_xml_element *element,
3967 void *user_data,
3968 std::vector<gdb_xml_value> &attributes)
3969 {
3970 struct threads_listing_context *data
3971 = (struct threads_listing_context *) user_data;
3972 struct gdb_xml_value *attr;
3973
3974 char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3975 ptid_t ptid = read_ptid (id, NULL);
3976
3977 data->items.emplace_back (ptid);
3978 thread_item &item = data->items.back ();
3979
3980 attr = xml_find_attribute (attributes, "core");
3981 if (attr != NULL)
3982 item.core = *(ULONGEST *) attr->value.get ();
3983
3984 attr = xml_find_attribute (attributes, "name");
3985 if (attr != NULL)
3986 item.name = (const char *) attr->value.get ();
3987
3988 attr = xml_find_attribute (attributes, "handle");
3989 if (attr != NULL)
3990 item.thread_handle = hex2bin ((const char *) attr->value.get ());
3991 }
3992
3993 static void
3994 end_thread (struct gdb_xml_parser *parser,
3995 const struct gdb_xml_element *element,
3996 void *user_data, const char *body_text)
3997 {
3998 struct threads_listing_context *data
3999 = (struct threads_listing_context *) user_data;
4000
4001 if (body_text != NULL && *body_text != '\0')
4002 data->items.back ().extra = body_text;
4003 }
4004
4005 const struct gdb_xml_attribute thread_attributes[] = {
4006 { "id", GDB_XML_AF_NONE, NULL, NULL },
4007 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
4008 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
4009 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
4010 { NULL, GDB_XML_AF_NONE, NULL, NULL }
4011 };
4012
4013 const struct gdb_xml_element thread_children[] = {
4014 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4015 };
4016
4017 const struct gdb_xml_element threads_children[] = {
4018 { "thread", thread_attributes, thread_children,
4019 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
4020 start_thread, end_thread },
4021 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4022 };
4023
4024 const struct gdb_xml_element threads_elements[] = {
4025 { "threads", NULL, threads_children,
4026 GDB_XML_EF_NONE, NULL, NULL },
4027 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
4028 };
4029
4030 #endif
4031
4032 /* List remote threads using qXfer:threads:read. */
4033
4034 int
4035 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
4036 {
4037 #if defined(HAVE_LIBEXPAT)
4038 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4039 {
4040 gdb::optional<gdb::char_vector> xml
4041 = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
4042
4043 if (xml && (*xml)[0] != '\0')
4044 {
4045 gdb_xml_parse_quick (_("threads"), "threads.dtd",
4046 threads_elements, xml->data (), context);
4047 }
4048
4049 return 1;
4050 }
4051 #endif
4052
4053 return 0;
4054 }
4055
4056 /* List remote threads using qfThreadInfo/qsThreadInfo. */
4057
4058 int
4059 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
4060 {
4061 struct remote_state *rs = get_remote_state ();
4062
4063 if (rs->use_threadinfo_query)
4064 {
4065 const char *bufp;
4066
4067 putpkt ("qfThreadInfo");
4068 getpkt (&rs->buf, 0);
4069 bufp = rs->buf.data ();
4070 if (bufp[0] != '\0') /* q packet recognized */
4071 {
4072 while (*bufp++ == 'm') /* reply contains one or more TID */
4073 {
4074 do
4075 {
4076 ptid_t ptid = read_ptid (bufp, &bufp);
4077 context->items.emplace_back (ptid);
4078 }
4079 while (*bufp++ == ','); /* comma-separated list */
4080 putpkt ("qsThreadInfo");
4081 getpkt (&rs->buf, 0);
4082 bufp = rs->buf.data ();
4083 }
4084 return 1;
4085 }
4086 else
4087 {
4088 /* Packet not recognized. */
4089 rs->use_threadinfo_query = 0;
4090 }
4091 }
4092
4093 return 0;
4094 }
4095
4096 /* Return true if INF only has one non-exited thread. */
4097
4098 static bool
4099 has_single_non_exited_thread (inferior *inf)
4100 {
4101 int count = 0;
4102 for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
4103 if (++count > 1)
4104 break;
4105 return count == 1;
4106 }
4107
4108 /* Implement the to_update_thread_list function for the remote
4109 targets. */
4110
4111 void
4112 remote_target::update_thread_list ()
4113 {
4114 struct threads_listing_context context;
4115 int got_list = 0;
4116
4117 /* We have a few different mechanisms to fetch the thread list. Try
4118 them all, starting with the most preferred one first, falling
4119 back to older methods. */
4120 if (remote_get_threads_with_qxfer (&context)
4121 || remote_get_threads_with_qthreadinfo (&context)
4122 || remote_get_threads_with_ql (&context))
4123 {
4124 got_list = 1;
4125
4126 if (context.items.empty ()
4127 && remote_thread_always_alive (inferior_ptid))
4128 {
4129 /* Some targets don't really support threads, but still
4130 reply an (empty) thread list in response to the thread
4131 listing packets, instead of replying "packet not
4132 supported". Exit early so we don't delete the main
4133 thread. */
4134 return;
4135 }
4136
4137 /* CONTEXT now holds the current thread list on the remote
4138 target end. Delete GDB-side threads no longer found on the
4139 target. */
4140 for (thread_info *tp : all_threads_safe ())
4141 {
4142 if (tp->inf->process_target () != this)
4143 continue;
4144
4145 if (!context.contains_thread (tp->ptid))
4146 {
4147 /* Do not remove the thread if it is the last thread in
4148 the inferior. This situation happens when we have a
4149 pending exit process status to process. Otherwise we
4150 may end up with a seemingly live inferior (i.e. pid
4151 != 0) that has no threads. */
4152 if (has_single_non_exited_thread (tp->inf))
4153 continue;
4154
4155 /* Not found. */
4156 delete_thread (tp);
4157 }
4158 }
4159
4160 /* Remove any unreported fork child threads from CONTEXT so
4161 that we don't interfere with follow fork, which is where
4162 creation of such threads is handled. */
4163 remove_new_fork_children (&context);
4164
4165 /* And now add threads we don't know about yet to our list. */
4166 for (thread_item &item : context.items)
4167 {
4168 if (item.ptid != null_ptid)
4169 {
4170 /* In non-stop mode, we assume new found threads are
4171 executing until proven otherwise with a stop reply.
4172 In all-stop, we can only get here if all threads are
4173 stopped. */
4174 bool executing = target_is_non_stop_p ();
4175
4176 remote_notice_new_inferior (item.ptid, executing);
4177
4178 thread_info *tp = find_thread_ptid (this, item.ptid);
4179 remote_thread_info *info = get_remote_thread_info (tp);
4180 info->core = item.core;
4181 info->extra = std::move (item.extra);
4182 info->name = std::move (item.name);
4183 info->thread_handle = std::move (item.thread_handle);
4184 }
4185 }
4186 }
4187
4188 if (!got_list)
4189 {
4190 /* If no thread listing method is supported, then query whether
4191 each known thread is alive, one by one, with the T packet.
4192 If the target doesn't support threads at all, then this is a
4193 no-op. See remote_thread_alive. */
4194 prune_threads ();
4195 }
4196 }
4197
4198 /*
4199 * Collect a descriptive string about the given thread.
4200 * The target may say anything it wants to about the thread
4201 * (typically info about its blocked / runnable state, name, etc.).
4202 * This string will appear in the info threads display.
4203 *
4204 * Optional: targets are not required to implement this function.
4205 */
4206
4207 const char *
4208 remote_target::extra_thread_info (thread_info *tp)
4209 {
4210 struct remote_state *rs = get_remote_state ();
4211 int set;
4212 threadref id;
4213 struct gdb_ext_thread_info threadinfo;
4214
4215 if (rs->remote_desc == 0) /* paranoia */
4216 internal_error (_("remote_threads_extra_info"));
4217
4218 if (tp->ptid == magic_null_ptid
4219 || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
4220 /* This is the main thread which was added by GDB. The remote
4221 server doesn't know about it. */
4222 return NULL;
4223
4224 std::string &extra = get_remote_thread_info (tp)->extra;
4225
4226 /* If already have cached info, use it. */
4227 if (!extra.empty ())
4228 return extra.c_str ();
4229
4230 if (m_features.packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
4231 {
4232 /* If we're using qXfer:threads:read, then the extra info is
4233 included in the XML. So if we didn't have anything cached,
4234 it's because there's really no extra info. */
4235 return NULL;
4236 }
4237
4238 if (rs->use_threadextra_query)
4239 {
4240 char *b = rs->buf.data ();
4241 char *endb = b + get_remote_packet_size ();
4242
4243 xsnprintf (b, endb - b, "qThreadExtraInfo,");
4244 b += strlen (b);
4245 write_ptid (b, endb, tp->ptid);
4246
4247 putpkt (rs->buf);
4248 getpkt (&rs->buf, 0);
4249 if (rs->buf[0] != 0)
4250 {
4251 extra.resize (strlen (rs->buf.data ()) / 2);
4252 hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
4253 return extra.c_str ();
4254 }
4255 }
4256
4257 /* If the above query fails, fall back to the old method. */
4258 rs->use_threadextra_query = 0;
4259 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4260 | TAG_MOREDISPLAY | TAG_DISPLAY;
4261 int_to_threadref (&id, tp->ptid.lwp ());
4262 if (remote_get_threadinfo (&id, set, &threadinfo))
4263 if (threadinfo.active)
4264 {
4265 if (*threadinfo.shortname)
4266 string_appendf (extra, " Name: %s", threadinfo.shortname);
4267 if (*threadinfo.display)
4268 {
4269 if (!extra.empty ())
4270 extra += ',';
4271 string_appendf (extra, " State: %s", threadinfo.display);
4272 }
4273 if (*threadinfo.more_display)
4274 {
4275 if (!extra.empty ())
4276 extra += ',';
4277 string_appendf (extra, " Priority: %s", threadinfo.more_display);
4278 }
4279 return extra.c_str ();
4280 }
4281 return NULL;
4282 }
4283 \f
4284
4285 bool
4286 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
4287 struct static_tracepoint_marker *marker)
4288 {
4289 struct remote_state *rs = get_remote_state ();
4290 char *p = rs->buf.data ();
4291
4292 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
4293 p += strlen (p);
4294 p += hexnumstr (p, addr);
4295 putpkt (rs->buf);
4296 getpkt (&rs->buf, 0);
4297 p = rs->buf.data ();
4298
4299 if (*p == 'E')
4300 error (_("Remote failure reply: %s"), p);
4301
4302 if (*p++ == 'm')
4303 {
4304 parse_static_tracepoint_marker_definition (p, NULL, marker);
4305 return true;
4306 }
4307
4308 return false;
4309 }
4310
4311 std::vector<static_tracepoint_marker>
4312 remote_target::static_tracepoint_markers_by_strid (const char *strid)
4313 {
4314 struct remote_state *rs = get_remote_state ();
4315 std::vector<static_tracepoint_marker> markers;
4316 const char *p;
4317 static_tracepoint_marker marker;
4318
4319 /* Ask for a first packet of static tracepoint marker
4320 definition. */
4321 putpkt ("qTfSTM");
4322 getpkt (&rs->buf, 0);
4323 p = rs->buf.data ();
4324 if (*p == 'E')
4325 error (_("Remote failure reply: %s"), p);
4326
4327 while (*p++ == 'm')
4328 {
4329 do
4330 {
4331 parse_static_tracepoint_marker_definition (p, &p, &marker);
4332
4333 if (strid == NULL || marker.str_id == strid)
4334 markers.push_back (std::move (marker));
4335 }
4336 while (*p++ == ','); /* comma-separated list */
4337 /* Ask for another packet of static tracepoint definition. */
4338 putpkt ("qTsSTM");
4339 getpkt (&rs->buf, 0);
4340 p = rs->buf.data ();
4341 }
4342
4343 return markers;
4344 }
4345
4346 \f
4347 /* Implement the to_get_ada_task_ptid function for the remote targets. */
4348
4349 ptid_t
4350 remote_target::get_ada_task_ptid (long lwp, ULONGEST thread)
4351 {
4352 return ptid_t (inferior_ptid.pid (), lwp);
4353 }
4354 \f
4355
4356 /* Restart the remote side; this is an extended protocol operation. */
4357
4358 void
4359 remote_target::extended_remote_restart ()
4360 {
4361 struct remote_state *rs = get_remote_state ();
4362
4363 /* Send the restart command; for reasons I don't understand the
4364 remote side really expects a number after the "R". */
4365 xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4366 putpkt (rs->buf);
4367
4368 remote_fileio_reset ();
4369 }
4370 \f
4371 /* Clean up connection to a remote debugger. */
4372
4373 void
4374 remote_target::close ()
4375 {
4376 /* Make sure we leave stdin registered in the event loop. */
4377 terminal_ours ();
4378
4379 trace_reset_local_state ();
4380
4381 delete this;
4382 }
4383
4384 remote_target::~remote_target ()
4385 {
4386 struct remote_state *rs = get_remote_state ();
4387
4388 /* Check for NULL because we may get here with a partially
4389 constructed target/connection. */
4390 if (rs->remote_desc == nullptr)
4391 return;
4392
4393 serial_close (rs->remote_desc);
4394
4395 /* We are destroying the remote target, so we should discard
4396 everything of this target. */
4397 discard_pending_stop_replies_in_queue ();
4398
4399 if (rs->remote_async_inferior_event_token)
4400 delete_async_event_handler (&rs->remote_async_inferior_event_token);
4401
4402 delete rs->notif_state;
4403 }
4404
4405 /* Query the remote side for the text, data and bss offsets. */
4406
4407 void
4408 remote_target::get_offsets ()
4409 {
4410 struct remote_state *rs = get_remote_state ();
4411 char *buf;
4412 char *ptr;
4413 int lose, num_segments = 0, do_sections, do_segments;
4414 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4415
4416 if (current_program_space->symfile_object_file == NULL)
4417 return;
4418
4419 putpkt ("qOffsets");
4420 getpkt (&rs->buf, 0);
4421 buf = rs->buf.data ();
4422
4423 if (buf[0] == '\000')
4424 return; /* Return silently. Stub doesn't support
4425 this command. */
4426 if (buf[0] == 'E')
4427 {
4428 warning (_("Remote failure reply: %s"), buf);
4429 return;
4430 }
4431
4432 /* Pick up each field in turn. This used to be done with scanf, but
4433 scanf will make trouble if CORE_ADDR size doesn't match
4434 conversion directives correctly. The following code will work
4435 with any size of CORE_ADDR. */
4436 text_addr = data_addr = bss_addr = 0;
4437 ptr = buf;
4438 lose = 0;
4439
4440 if (startswith (ptr, "Text="))
4441 {
4442 ptr += 5;
4443 /* Don't use strtol, could lose on big values. */
4444 while (*ptr && *ptr != ';')
4445 text_addr = (text_addr << 4) + fromhex (*ptr++);
4446
4447 if (startswith (ptr, ";Data="))
4448 {
4449 ptr += 6;
4450 while (*ptr && *ptr != ';')
4451 data_addr = (data_addr << 4) + fromhex (*ptr++);
4452 }
4453 else
4454 lose = 1;
4455
4456 if (!lose && startswith (ptr, ";Bss="))
4457 {
4458 ptr += 5;
4459 while (*ptr && *ptr != ';')
4460 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4461
4462 if (bss_addr != data_addr)
4463 warning (_("Target reported unsupported offsets: %s"), buf);
4464 }
4465 else
4466 lose = 1;
4467 }
4468 else if (startswith (ptr, "TextSeg="))
4469 {
4470 ptr += 8;
4471 /* Don't use strtol, could lose on big values. */
4472 while (*ptr && *ptr != ';')
4473 text_addr = (text_addr << 4) + fromhex (*ptr++);
4474 num_segments = 1;
4475
4476 if (startswith (ptr, ";DataSeg="))
4477 {
4478 ptr += 9;
4479 while (*ptr && *ptr != ';')
4480 data_addr = (data_addr << 4) + fromhex (*ptr++);
4481 num_segments++;
4482 }
4483 }
4484 else
4485 lose = 1;
4486
4487 if (lose)
4488 error (_("Malformed response to offset query, %s"), buf);
4489 else if (*ptr != '\0')
4490 warning (_("Target reported unsupported offsets: %s"), buf);
4491
4492 objfile *objf = current_program_space->symfile_object_file;
4493 section_offsets offs = objf->section_offsets;
4494
4495 symfile_segment_data_up data = get_symfile_segment_data (objf->obfd.get ());
4496 do_segments = (data != NULL);
4497 do_sections = num_segments == 0;
4498
4499 if (num_segments > 0)
4500 {
4501 segments[0] = text_addr;
4502 segments[1] = data_addr;
4503 }
4504 /* If we have two segments, we can still try to relocate everything
4505 by assuming that the .text and .data offsets apply to the whole
4506 text and data segments. Convert the offsets given in the packet
4507 to base addresses for symfile_map_offsets_to_segments. */
4508 else if (data != nullptr && data->segments.size () == 2)
4509 {
4510 segments[0] = data->segments[0].base + text_addr;
4511 segments[1] = data->segments[1].base + data_addr;
4512 num_segments = 2;
4513 }
4514 /* If the object file has only one segment, assume that it is text
4515 rather than data; main programs with no writable data are rare,
4516 but programs with no code are useless. Of course the code might
4517 have ended up in the data segment... to detect that we would need
4518 the permissions here. */
4519 else if (data && data->segments.size () == 1)
4520 {
4521 segments[0] = data->segments[0].base + text_addr;
4522 num_segments = 1;
4523 }
4524 /* There's no way to relocate by segment. */
4525 else
4526 do_segments = 0;
4527
4528 if (do_segments)
4529 {
4530 int ret = symfile_map_offsets_to_segments (objf->obfd.get (),
4531 data.get (), offs,
4532 num_segments, segments);
4533
4534 if (ret == 0 && !do_sections)
4535 error (_("Can not handle qOffsets TextSeg "
4536 "response with this symbol file"));
4537
4538 if (ret > 0)
4539 do_sections = 0;
4540 }
4541
4542 if (do_sections)
4543 {
4544 offs[SECT_OFF_TEXT (objf)] = text_addr;
4545
4546 /* This is a temporary kludge to force data and bss to use the
4547 same offsets because that's what nlmconv does now. The real
4548 solution requires changes to the stub and remote.c that I
4549 don't have time to do right now. */
4550
4551 offs[SECT_OFF_DATA (objf)] = data_addr;
4552 offs[SECT_OFF_BSS (objf)] = data_addr;
4553 }
4554
4555 objfile_relocate (objf, offs);
4556 }
4557
4558 /* Send interrupt_sequence to remote target. */
4559
4560 void
4561 remote_target::send_interrupt_sequence ()
4562 {
4563 struct remote_state *rs = get_remote_state ();
4564
4565 if (interrupt_sequence_mode == interrupt_sequence_control_c)
4566 remote_serial_write ("\x03", 1);
4567 else if (interrupt_sequence_mode == interrupt_sequence_break)
4568 serial_send_break (rs->remote_desc);
4569 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4570 {
4571 serial_send_break (rs->remote_desc);
4572 remote_serial_write ("g", 1);
4573 }
4574 else
4575 internal_error (_("Invalid value for interrupt_sequence_mode: %s."),
4576 interrupt_sequence_mode);
4577 }
4578
4579
4580 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4581 and extract the PTID. Returns NULL_PTID if not found. */
4582
4583 static ptid_t
4584 stop_reply_extract_thread (const char *stop_reply)
4585 {
4586 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4587 {
4588 const char *p;
4589
4590 /* Txx r:val ; r:val (...) */
4591 p = &stop_reply[3];
4592
4593 /* Look for "register" named "thread". */
4594 while (*p != '\0')
4595 {
4596 const char *p1;
4597
4598 p1 = strchr (p, ':');
4599 if (p1 == NULL)
4600 return null_ptid;
4601
4602 if (strncmp (p, "thread", p1 - p) == 0)
4603 return read_ptid (++p1, &p);
4604
4605 p1 = strchr (p, ';');
4606 if (p1 == NULL)
4607 return null_ptid;
4608 p1++;
4609
4610 p = p1;
4611 }
4612 }
4613
4614 return null_ptid;
4615 }
4616
4617 /* Determine the remote side's current thread. If we have a stop
4618 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4619 "thread" register we can extract the current thread from. If not,
4620 ask the remote which is the current thread with qC. The former
4621 method avoids a roundtrip. */
4622
4623 ptid_t
4624 remote_target::get_current_thread (const char *wait_status)
4625 {
4626 ptid_t ptid = null_ptid;
4627
4628 /* Note we don't use remote_parse_stop_reply as that makes use of
4629 the target architecture, which we haven't yet fully determined at
4630 this point. */
4631 if (wait_status != NULL)
4632 ptid = stop_reply_extract_thread (wait_status);
4633 if (ptid == null_ptid)
4634 ptid = remote_current_thread (inferior_ptid);
4635
4636 return ptid;
4637 }
4638
4639 /* Query the remote target for which is the current thread/process,
4640 add it to our tables, and update INFERIOR_PTID. The caller is
4641 responsible for setting the state such that the remote end is ready
4642 to return the current thread.
4643
4644 This function is called after handling the '?' or 'vRun' packets,
4645 whose response is a stop reply from which we can also try
4646 extracting the thread. If the target doesn't support the explicit
4647 qC query, we infer the current thread from that stop reply, passed
4648 in in WAIT_STATUS, which may be NULL.
4649
4650 The function returns pointer to the main thread of the inferior. */
4651
4652 thread_info *
4653 remote_target::add_current_inferior_and_thread (const char *wait_status)
4654 {
4655 bool fake_pid_p = false;
4656
4657 switch_to_no_thread ();
4658
4659 /* Now, if we have thread information, update the current thread's
4660 ptid. */
4661 ptid_t curr_ptid = get_current_thread (wait_status);
4662
4663 if (curr_ptid != null_ptid)
4664 {
4665 if (!m_features.remote_multi_process_p ())
4666 fake_pid_p = true;
4667 }
4668 else
4669 {
4670 /* Without this, some commands which require an active target
4671 (such as kill) won't work. This variable serves (at least)
4672 double duty as both the pid of the target process (if it has
4673 such), and as a flag indicating that a target is active. */
4674 curr_ptid = magic_null_ptid;
4675 fake_pid_p = true;
4676 }
4677
4678 remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4679
4680 /* Add the main thread and switch to it. Don't try reading
4681 registers yet, since we haven't fetched the target description
4682 yet. */
4683 thread_info *tp = add_thread_silent (this, curr_ptid);
4684 switch_to_thread_no_regs (tp);
4685
4686 return tp;
4687 }
4688
4689 /* Print info about a thread that was found already stopped on
4690 connection. */
4691
4692 void
4693 remote_target::print_one_stopped_thread (thread_info *thread)
4694 {
4695 target_waitstatus ws;
4696
4697 /* If there is a pending waitstatus, use it. If there isn't it's because
4698 the thread's stop was reported with TARGET_WAITKIND_STOPPED / GDB_SIGNAL_0
4699 and process_initial_stop_replies decided it wasn't interesting to save
4700 and report to the core. */
4701 if (thread->has_pending_waitstatus ())
4702 {
4703 ws = thread->pending_waitstatus ();
4704 thread->clear_pending_waitstatus ();
4705 }
4706 else
4707 {
4708 ws.set_stopped (GDB_SIGNAL_0);
4709 }
4710
4711 switch_to_thread (thread);
4712 thread->set_stop_pc (get_frame_pc (get_current_frame ()));
4713 set_current_sal_from_frame (get_current_frame ());
4714
4715 /* For "info program". */
4716 set_last_target_status (this, thread->ptid, ws);
4717
4718 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4719 {
4720 enum gdb_signal sig = ws.sig ();
4721
4722 if (signal_print_state (sig))
4723 gdb::observers::signal_received.notify (sig);
4724 }
4725 gdb::observers::normal_stop.notify (NULL, 1);
4726 }
4727
4728 /* Process all initial stop replies the remote side sent in response
4729 to the ? packet. These indicate threads that were already stopped
4730 on initial connection. We mark these threads as stopped and print
4731 their current frame before giving the user the prompt. */
4732
4733 void
4734 remote_target::process_initial_stop_replies (int from_tty)
4735 {
4736 int pending_stop_replies = stop_reply_queue_length ();
4737 struct thread_info *selected = NULL;
4738 struct thread_info *lowest_stopped = NULL;
4739 struct thread_info *first = NULL;
4740
4741 /* This is only used when the target is non-stop. */
4742 gdb_assert (target_is_non_stop_p ());
4743
4744 /* Consume the initial pending events. */
4745 while (pending_stop_replies-- > 0)
4746 {
4747 ptid_t waiton_ptid = minus_one_ptid;
4748 ptid_t event_ptid;
4749 struct target_waitstatus ws;
4750 int ignore_event = 0;
4751
4752 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4753 if (remote_debug)
4754 print_target_wait_results (waiton_ptid, event_ptid, ws);
4755
4756 switch (ws.kind ())
4757 {
4758 case TARGET_WAITKIND_IGNORE:
4759 case TARGET_WAITKIND_NO_RESUMED:
4760 case TARGET_WAITKIND_SIGNALLED:
4761 case TARGET_WAITKIND_EXITED:
4762 /* We shouldn't see these, but if we do, just ignore. */
4763 remote_debug_printf ("event ignored");
4764 ignore_event = 1;
4765 break;
4766
4767 default:
4768 break;
4769 }
4770
4771 if (ignore_event)
4772 continue;
4773
4774 thread_info *evthread = find_thread_ptid (this, event_ptid);
4775
4776 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4777 {
4778 enum gdb_signal sig = ws.sig ();
4779
4780 /* Stubs traditionally report SIGTRAP as initial signal,
4781 instead of signal 0. Suppress it. */
4782 if (sig == GDB_SIGNAL_TRAP)
4783 sig = GDB_SIGNAL_0;
4784 evthread->set_stop_signal (sig);
4785 ws.set_stopped (sig);
4786 }
4787
4788 if (ws.kind () != TARGET_WAITKIND_STOPPED
4789 || ws.sig () != GDB_SIGNAL_0)
4790 evthread->set_pending_waitstatus (ws);
4791
4792 set_executing (this, event_ptid, false);
4793 set_running (this, event_ptid, false);
4794 get_remote_thread_info (evthread)->set_not_resumed ();
4795 }
4796
4797 /* "Notice" the new inferiors before anything related to
4798 registers/memory. */
4799 for (inferior *inf : all_non_exited_inferiors (this))
4800 {
4801 inf->needs_setup = true;
4802
4803 if (non_stop)
4804 {
4805 thread_info *thread = any_live_thread_of_inferior (inf);
4806 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4807 from_tty);
4808 }
4809 }
4810
4811 /* If all-stop on top of non-stop, pause all threads. Note this
4812 records the threads' stop pc, so must be done after "noticing"
4813 the inferiors. */
4814 if (!non_stop)
4815 {
4816 {
4817 /* At this point, the remote target is not async. It needs to be for
4818 the poll in stop_all_threads to consider events from it, so enable
4819 it temporarily. */
4820 gdb_assert (!this->is_async_p ());
4821 SCOPE_EXIT { target_async (false); };
4822 target_async (true);
4823 stop_all_threads ("remote connect in all-stop");
4824 }
4825
4826 /* If all threads of an inferior were already stopped, we
4827 haven't setup the inferior yet. */
4828 for (inferior *inf : all_non_exited_inferiors (this))
4829 {
4830 if (inf->needs_setup)
4831 {
4832 thread_info *thread = any_live_thread_of_inferior (inf);
4833 switch_to_thread_no_regs (thread);
4834 setup_inferior (0);
4835 }
4836 }
4837 }
4838
4839 /* Now go over all threads that are stopped, and print their current
4840 frame. If all-stop, then if there's a signalled thread, pick
4841 that as current. */
4842 for (thread_info *thread : all_non_exited_threads (this))
4843 {
4844 if (first == NULL)
4845 first = thread;
4846
4847 if (!non_stop)
4848 thread->set_running (false);
4849 else if (thread->state != THREAD_STOPPED)
4850 continue;
4851
4852 if (selected == nullptr && thread->has_pending_waitstatus ())
4853 selected = thread;
4854
4855 if (lowest_stopped == NULL
4856 || thread->inf->num < lowest_stopped->inf->num
4857 || thread->per_inf_num < lowest_stopped->per_inf_num)
4858 lowest_stopped = thread;
4859
4860 if (non_stop)
4861 print_one_stopped_thread (thread);
4862 }
4863
4864 /* In all-stop, we only print the status of one thread, and leave
4865 others with their status pending. */
4866 if (!non_stop)
4867 {
4868 thread_info *thread = selected;
4869 if (thread == NULL)
4870 thread = lowest_stopped;
4871 if (thread == NULL)
4872 thread = first;
4873
4874 print_one_stopped_thread (thread);
4875 }
4876 }
4877
4878 /* Mark a remote_target as starting (by setting the starting_up flag within
4879 its remote_state) for the lifetime of this object. The reference count
4880 on the remote target is temporarily incremented, to prevent the target
4881 being deleted under our feet. */
4882
4883 struct scoped_mark_target_starting
4884 {
4885 /* Constructor, TARGET is the target to be marked as starting, its
4886 reference count will be incremented. */
4887 scoped_mark_target_starting (remote_target *target)
4888 : m_remote_target (remote_target_ref::new_reference (target)),
4889 m_restore_starting_up (set_starting_up_flag (target))
4890 { /* Nothing. */ }
4891
4892 private:
4893
4894 /* Helper function, set the starting_up flag on TARGET and return an
4895 object which, when it goes out of scope, will restore the previous
4896 value of the starting_up flag. */
4897 static scoped_restore_tmpl<bool>
4898 set_starting_up_flag (remote_target *target)
4899 {
4900 remote_state *rs = target->get_remote_state ();
4901 gdb_assert (!rs->starting_up);
4902 return make_scoped_restore (&rs->starting_up, true);
4903 }
4904
4905 /* A gdb::ref_ptr pointer to a remote_target. */
4906 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4907
4908 /* A reference to the target on which we are operating. */
4909 remote_target_ref m_remote_target;
4910
4911 /* An object which restores the previous value of the starting_up flag
4912 when it goes out of scope. */
4913 scoped_restore_tmpl<bool> m_restore_starting_up;
4914 };
4915
4916 /* Helper for remote_target::start_remote, start the remote connection and
4917 sync state. Return true if everything goes OK, otherwise, return false.
4918 This function exists so that the scoped_restore created within it will
4919 expire before we return to remote_target::start_remote. */
4920
4921 bool
4922 remote_target::start_remote_1 (int from_tty, int extended_p)
4923 {
4924 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4925
4926 struct remote_state *rs = get_remote_state ();
4927
4928 /* Signal other parts that we're going through the initial setup,
4929 and so things may not be stable yet. E.g., we don't try to
4930 install tracepoints until we've relocated symbols. Also, a
4931 Ctrl-C before we're connected and synced up can't interrupt the
4932 target. Instead, it offers to drop the (potentially wedged)
4933 connection. */
4934 scoped_mark_target_starting target_is_starting (this);
4935
4936 QUIT;
4937
4938 if (interrupt_on_connect)
4939 send_interrupt_sequence ();
4940
4941 /* Ack any packet which the remote side has already sent. */
4942 remote_serial_write ("+", 1);
4943
4944 /* The first packet we send to the target is the optional "supported
4945 packets" request. If the target can answer this, it will tell us
4946 which later probes to skip. */
4947 remote_query_supported ();
4948
4949 /* Check vCont support and set the remote state's vCont_action_support
4950 attribute. */
4951 remote_vcont_probe ();
4952
4953 /* If the stub wants to get a QAllow, compose one and send it. */
4954 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4955 set_permissions ();
4956
4957 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4958 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4959 as a reply to known packet. For packet "vFile:setfs:" it is an
4960 invalid reply and GDB would return error in
4961 remote_hostio_set_filesystem, making remote files access impossible.
4962 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4963 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4964 {
4965 const char v_mustreplyempty[] = "vMustReplyEmpty";
4966
4967 putpkt (v_mustreplyempty);
4968 getpkt (&rs->buf, 0);
4969 if (strcmp (rs->buf.data (), "OK") == 0)
4970 {
4971 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4972 = PACKET_DISABLE;
4973 }
4974 else if (strcmp (rs->buf.data (), "") != 0)
4975 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4976 rs->buf.data ());
4977 }
4978
4979 /* Next, we possibly activate noack mode.
4980
4981 If the QStartNoAckMode packet configuration is set to AUTO,
4982 enable noack mode if the stub reported a wish for it with
4983 qSupported.
4984
4985 If set to TRUE, then enable noack mode even if the stub didn't
4986 report it in qSupported. If the stub doesn't reply OK, the
4987 session ends with an error.
4988
4989 If FALSE, then don't activate noack mode, regardless of what the
4990 stub claimed should be the default with qSupported. */
4991
4992 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
4993 {
4994 putpkt ("QStartNoAckMode");
4995 getpkt (&rs->buf, 0);
4996 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
4997 rs->noack_mode = 1;
4998 }
4999
5000 if (extended_p)
5001 {
5002 /* Tell the remote that we are using the extended protocol. */
5003 putpkt ("!");
5004 getpkt (&rs->buf, 0);
5005 }
5006
5007 /* Let the target know which signals it is allowed to pass down to
5008 the program. */
5009 update_signals_program_target ();
5010
5011 /* Next, if the target can specify a description, read it. We do
5012 this before anything involving memory or registers. */
5013 target_find_description ();
5014
5015 /* Next, now that we know something about the target, update the
5016 address spaces in the program spaces. */
5017 update_address_spaces ();
5018
5019 /* On OSs where the list of libraries is global to all
5020 processes, we fetch them early. */
5021 if (gdbarch_has_global_solist (target_gdbarch ()))
5022 solib_add (NULL, from_tty, auto_solib_add);
5023
5024 if (target_is_non_stop_p ())
5025 {
5026 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5027 error (_("Non-stop mode requested, but remote "
5028 "does not support non-stop"));
5029
5030 putpkt ("QNonStop:1");
5031 getpkt (&rs->buf, 0);
5032
5033 if (strcmp (rs->buf.data (), "OK") != 0)
5034 error (_("Remote refused setting non-stop mode with: %s"),
5035 rs->buf.data ());
5036
5037 /* Find about threads and processes the stub is already
5038 controlling. We default to adding them in the running state.
5039 The '?' query below will then tell us about which threads are
5040 stopped. */
5041 this->update_thread_list ();
5042 }
5043 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5044 {
5045 /* Don't assume that the stub can operate in all-stop mode.
5046 Request it explicitly. */
5047 putpkt ("QNonStop:0");
5048 getpkt (&rs->buf, 0);
5049
5050 if (strcmp (rs->buf.data (), "OK") != 0)
5051 error (_("Remote refused setting all-stop mode with: %s"),
5052 rs->buf.data ());
5053 }
5054
5055 /* Upload TSVs regardless of whether the target is running or not. The
5056 remote stub, such as GDBserver, may have some predefined or builtin
5057 TSVs, even if the target is not running. */
5058 if (get_trace_status (current_trace_status ()) != -1)
5059 {
5060 struct uploaded_tsv *uploaded_tsvs = NULL;
5061
5062 upload_trace_state_variables (&uploaded_tsvs);
5063 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5064 }
5065
5066 /* Check whether the target is running now. */
5067 putpkt ("?");
5068 getpkt (&rs->buf, 0);
5069
5070 if (!target_is_non_stop_p ())
5071 {
5072 char *wait_status = NULL;
5073
5074 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5075 {
5076 if (!extended_p)
5077 error (_("The target is not running (try extended-remote?)"));
5078 return false;
5079 }
5080 else
5081 {
5082 /* Save the reply for later. */
5083 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5084 strcpy (wait_status, rs->buf.data ());
5085 }
5086
5087 /* Fetch thread list. */
5088 target_update_thread_list ();
5089
5090 /* Let the stub know that we want it to return the thread. */
5091 set_continue_thread (minus_one_ptid);
5092
5093 if (thread_count (this) == 0)
5094 {
5095 /* Target has no concept of threads at all. GDB treats
5096 non-threaded target as single-threaded; add a main
5097 thread. */
5098 thread_info *tp = add_current_inferior_and_thread (wait_status);
5099 get_remote_thread_info (tp)->set_resumed ();
5100 }
5101 else
5102 {
5103 /* We have thread information; select the thread the target
5104 says should be current. If we're reconnecting to a
5105 multi-threaded program, this will ideally be the thread
5106 that last reported an event before GDB disconnected. */
5107 ptid_t curr_thread = get_current_thread (wait_status);
5108 if (curr_thread == null_ptid)
5109 {
5110 /* Odd... The target was able to list threads, but not
5111 tell us which thread was current (no "thread"
5112 register in T stop reply?). Just pick the first
5113 thread in the thread list then. */
5114
5115 remote_debug_printf ("warning: couldn't determine remote "
5116 "current thread; picking first in list.");
5117
5118 for (thread_info *tp : all_non_exited_threads (this,
5119 minus_one_ptid))
5120 {
5121 switch_to_thread (tp);
5122 break;
5123 }
5124 }
5125 else
5126 switch_to_thread (find_thread_ptid (this, curr_thread));
5127 }
5128
5129 /* init_wait_for_inferior should be called before get_offsets in order
5130 to manage `inserted' flag in bp loc in a correct state.
5131 breakpoint_init_inferior, called from init_wait_for_inferior, set
5132 `inserted' flag to 0, while before breakpoint_re_set, called from
5133 start_remote, set `inserted' flag to 1. In the initialization of
5134 inferior, breakpoint_init_inferior should be called first, and then
5135 breakpoint_re_set can be called. If this order is broken, state of
5136 `inserted' flag is wrong, and cause some problems on breakpoint
5137 manipulation. */
5138 init_wait_for_inferior ();
5139
5140 get_offsets (); /* Get text, data & bss offsets. */
5141
5142 /* If we could not find a description using qXfer, and we know
5143 how to do it some other way, try again. This is not
5144 supported for non-stop; it could be, but it is tricky if
5145 there are no stopped threads when we connect. */
5146 if (remote_read_description_p (this)
5147 && gdbarch_target_desc (target_gdbarch ()) == NULL)
5148 {
5149 target_clear_description ();
5150 target_find_description ();
5151 }
5152
5153 /* Use the previously fetched status. */
5154 gdb_assert (wait_status != NULL);
5155 struct notif_event *reply
5156 = remote_notif_parse (this, &notif_client_stop, wait_status);
5157 push_stop_reply ((struct stop_reply *) reply);
5158
5159 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5160 }
5161 else
5162 {
5163 /* Clear WFI global state. Do this before finding about new
5164 threads and inferiors, and setting the current inferior.
5165 Otherwise we would clear the proceed status of the current
5166 inferior when we want its stop_soon state to be preserved
5167 (see notice_new_inferior). */
5168 init_wait_for_inferior ();
5169
5170 /* In non-stop, we will either get an "OK", meaning that there
5171 are no stopped threads at this time; or, a regular stop
5172 reply. In the latter case, there may be more than one thread
5173 stopped --- we pull them all out using the vStopped
5174 mechanism. */
5175 if (strcmp (rs->buf.data (), "OK") != 0)
5176 {
5177 const notif_client *notif = &notif_client_stop;
5178
5179 /* remote_notif_get_pending_replies acks this one, and gets
5180 the rest out. */
5181 rs->notif_state->pending_event[notif_client_stop.id]
5182 = remote_notif_parse (this, notif, rs->buf.data ());
5183 remote_notif_get_pending_events (notif);
5184 }
5185
5186 if (thread_count (this) == 0)
5187 {
5188 if (!extended_p)
5189 error (_("The target is not running (try extended-remote?)"));
5190 return false;
5191 }
5192
5193 /* Report all signals during attach/startup. */
5194 pass_signals ({});
5195
5196 /* If there are already stopped threads, mark them stopped and
5197 report their stops before giving the prompt to the user. */
5198 process_initial_stop_replies (from_tty);
5199
5200 if (target_can_async_p ())
5201 target_async (true);
5202 }
5203
5204 /* Give the target a chance to look up symbols. */
5205 for (inferior *inf : all_inferiors (this))
5206 {
5207 /* The inferiors that exist at this point were created from what
5208 was found already running on the remote side, so we know they
5209 have execution. */
5210 gdb_assert (this->has_execution (inf));
5211
5212 /* No use without a symbol-file. */
5213 if (inf->pspace->symfile_object_file == nullptr)
5214 continue;
5215
5216 /* Need to switch to a specific thread, because remote_check_symbols
5217 uses INFERIOR_PTID to set the general thread. */
5218 scoped_restore_current_thread restore_thread;
5219 thread_info *thread = any_thread_of_inferior (inf);
5220 switch_to_thread (thread);
5221 this->remote_check_symbols ();
5222 }
5223
5224 /* Possibly the target has been engaged in a trace run started
5225 previously; find out where things are at. */
5226 if (get_trace_status (current_trace_status ()) != -1)
5227 {
5228 struct uploaded_tp *uploaded_tps = NULL;
5229
5230 if (current_trace_status ()->running)
5231 gdb_printf (_("Trace is already running on the target.\n"));
5232
5233 upload_tracepoints (&uploaded_tps);
5234
5235 merge_uploaded_tracepoints (&uploaded_tps);
5236 }
5237
5238 /* Possibly the target has been engaged in a btrace record started
5239 previously; find out where things are at. */
5240 remote_btrace_maybe_reopen ();
5241
5242 return true;
5243 }
5244
5245 /* Start the remote connection and sync state. */
5246
5247 void
5248 remote_target::start_remote (int from_tty, int extended_p)
5249 {
5250 if (start_remote_1 (from_tty, extended_p)
5251 && breakpoints_should_be_inserted_now ())
5252 insert_breakpoints ();
5253 }
5254
5255 const char *
5256 remote_target::connection_string ()
5257 {
5258 remote_state *rs = get_remote_state ();
5259
5260 if (rs->remote_desc->name != NULL)
5261 return rs->remote_desc->name;
5262 else
5263 return NULL;
5264 }
5265
5266 /* Open a connection to a remote debugger.
5267 NAME is the filename used for communication. */
5268
5269 void
5270 remote_target::open (const char *name, int from_tty)
5271 {
5272 open_1 (name, from_tty, 0);
5273 }
5274
5275 /* Open a connection to a remote debugger using the extended
5276 remote gdb protocol. NAME is the filename used for communication. */
5277
5278 void
5279 extended_remote_target::open (const char *name, int from_tty)
5280 {
5281 open_1 (name, from_tty, 1 /*extended_p */);
5282 }
5283
5284 void
5285 remote_features::reset_all_packet_configs_support ()
5286 {
5287 int i;
5288
5289 for (i = 0; i < PACKET_MAX; i++)
5290 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5291 }
5292
5293 /* Initialize all packet configs. */
5294
5295 static void
5296 init_all_packet_configs (void)
5297 {
5298 int i;
5299
5300 for (i = 0; i < PACKET_MAX; i++)
5301 {
5302 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5303 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5304 }
5305 }
5306
5307 /* Symbol look-up. */
5308
5309 void
5310 remote_target::remote_check_symbols ()
5311 {
5312 char *tmp;
5313 int end;
5314
5315 /* It doesn't make sense to send a qSymbol packet for an inferior that
5316 doesn't have execution, because the remote side doesn't know about
5317 inferiors without execution. */
5318 gdb_assert (target_has_execution ());
5319
5320 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5321 return;
5322
5323 /* Make sure the remote is pointing at the right process. Note
5324 there's no way to select "no process". */
5325 set_general_process ();
5326
5327 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5328 because we need both at the same time. */
5329 gdb::char_vector msg (get_remote_packet_size ());
5330 gdb::char_vector reply (get_remote_packet_size ());
5331
5332 /* Invite target to request symbol lookups. */
5333
5334 putpkt ("qSymbol::");
5335 getpkt (&reply, 0);
5336 m_features.packet_ok (reply, PACKET_qSymbol);
5337
5338 while (startswith (reply.data (), "qSymbol:"))
5339 {
5340 struct bound_minimal_symbol sym;
5341
5342 tmp = &reply[8];
5343 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5344 strlen (tmp) / 2);
5345 msg[end] = '\0';
5346 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5347 if (sym.minsym == NULL)
5348 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5349 &reply[8]);
5350 else
5351 {
5352 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5353 CORE_ADDR sym_addr = sym.value_address ();
5354
5355 /* If this is a function address, return the start of code
5356 instead of any data function descriptor. */
5357 sym_addr = gdbarch_convert_from_func_ptr_addr
5358 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5359
5360 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5361 phex_nz (sym_addr, addr_size), &reply[8]);
5362 }
5363
5364 putpkt (msg.data ());
5365 getpkt (&reply, 0);
5366 }
5367 }
5368
5369 static struct serial *
5370 remote_serial_open (const char *name)
5371 {
5372 static int udp_warning = 0;
5373
5374 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5375 of in ser-tcp.c, because it is the remote protocol assuming that the
5376 serial connection is reliable and not the serial connection promising
5377 to be. */
5378 if (!udp_warning && startswith (name, "udp:"))
5379 {
5380 warning (_("The remote protocol may be unreliable over UDP.\n"
5381 "Some events may be lost, rendering further debugging "
5382 "impossible."));
5383 udp_warning = 1;
5384 }
5385
5386 return serial_open (name);
5387 }
5388
5389 /* Inform the target of our permission settings. The permission flags
5390 work without this, but if the target knows the settings, it can do
5391 a couple things. First, it can add its own check, to catch cases
5392 that somehow manage to get by the permissions checks in target
5393 methods. Second, if the target is wired to disallow particular
5394 settings (for instance, a system in the field that is not set up to
5395 be able to stop at a breakpoint), it can object to any unavailable
5396 permissions. */
5397
5398 void
5399 remote_target::set_permissions ()
5400 {
5401 struct remote_state *rs = get_remote_state ();
5402
5403 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5404 "WriteReg:%x;WriteMem:%x;"
5405 "InsertBreak:%x;InsertTrace:%x;"
5406 "InsertFastTrace:%x;Stop:%x",
5407 may_write_registers, may_write_memory,
5408 may_insert_breakpoints, may_insert_tracepoints,
5409 may_insert_fast_tracepoints, may_stop);
5410 putpkt (rs->buf);
5411 getpkt (&rs->buf, 0);
5412
5413 /* If the target didn't like the packet, warn the user. Do not try
5414 to undo the user's settings, that would just be maddening. */
5415 if (strcmp (rs->buf.data (), "OK") != 0)
5416 warning (_("Remote refused setting permissions with: %s"),
5417 rs->buf.data ());
5418 }
5419
5420 /* This type describes each known response to the qSupported
5421 packet. */
5422 struct protocol_feature
5423 {
5424 /* The name of this protocol feature. */
5425 const char *name;
5426
5427 /* The default for this protocol feature. */
5428 enum packet_support default_support;
5429
5430 /* The function to call when this feature is reported, or after
5431 qSupported processing if the feature is not supported.
5432 The first argument points to this structure. The second
5433 argument indicates whether the packet requested support be
5434 enabled, disabled, or probed (or the default, if this function
5435 is being called at the end of processing and this feature was
5436 not reported). The third argument may be NULL; if not NULL, it
5437 is a NUL-terminated string taken from the packet following
5438 this feature's name and an equals sign. */
5439 void (*func) (remote_target *remote, const struct protocol_feature *,
5440 enum packet_support, const char *);
5441
5442 /* The corresponding packet for this feature. Only used if
5443 FUNC is remote_supported_packet. */
5444 int packet;
5445 };
5446
5447 static void
5448 remote_supported_packet (remote_target *remote,
5449 const struct protocol_feature *feature,
5450 enum packet_support support,
5451 const char *argument)
5452 {
5453 if (argument)
5454 {
5455 warning (_("Remote qSupported response supplied an unexpected value for"
5456 " \"%s\"."), feature->name);
5457 return;
5458 }
5459
5460 remote->m_features.m_protocol_packets[feature->packet].support = support;
5461 }
5462
5463 void
5464 remote_target::remote_packet_size (const protocol_feature *feature,
5465 enum packet_support support, const char *value)
5466 {
5467 struct remote_state *rs = get_remote_state ();
5468
5469 int packet_size;
5470 char *value_end;
5471
5472 if (support != PACKET_ENABLE)
5473 return;
5474
5475 if (value == NULL || *value == '\0')
5476 {
5477 warning (_("Remote target reported \"%s\" without a size."),
5478 feature->name);
5479 return;
5480 }
5481
5482 errno = 0;
5483 packet_size = strtol (value, &value_end, 16);
5484 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5485 {
5486 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5487 feature->name, value);
5488 return;
5489 }
5490
5491 /* Record the new maximum packet size. */
5492 rs->explicit_packet_size = packet_size;
5493 }
5494
5495 static void
5496 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5497 enum packet_support support, const char *value)
5498 {
5499 remote->remote_packet_size (feature, support, value);
5500 }
5501
5502 static const struct protocol_feature remote_protocol_features[] = {
5503 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5504 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5505 PACKET_qXfer_auxv },
5506 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5507 PACKET_qXfer_exec_file },
5508 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5509 PACKET_qXfer_features },
5510 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5511 PACKET_qXfer_libraries },
5512 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5513 PACKET_qXfer_libraries_svr4 },
5514 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5515 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5516 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5517 PACKET_qXfer_memory_map },
5518 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5519 PACKET_qXfer_osdata },
5520 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5521 PACKET_qXfer_threads },
5522 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5523 PACKET_qXfer_traceframe_info },
5524 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5525 PACKET_QPassSignals },
5526 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5527 PACKET_QCatchSyscalls },
5528 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5529 PACKET_QProgramSignals },
5530 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5531 PACKET_QSetWorkingDir },
5532 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5533 PACKET_QStartupWithShell },
5534 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5535 PACKET_QEnvironmentHexEncoded },
5536 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5537 PACKET_QEnvironmentReset },
5538 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5539 PACKET_QEnvironmentUnset },
5540 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5541 PACKET_QStartNoAckMode },
5542 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5543 PACKET_multiprocess_feature },
5544 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5545 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5546 PACKET_qXfer_siginfo_read },
5547 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5548 PACKET_qXfer_siginfo_write },
5549 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5550 PACKET_ConditionalTracepoints },
5551 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5552 PACKET_ConditionalBreakpoints },
5553 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5554 PACKET_BreakpointCommands },
5555 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5556 PACKET_FastTracepoints },
5557 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5558 PACKET_StaticTracepoints },
5559 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5560 PACKET_InstallInTrace},
5561 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5562 PACKET_DisconnectedTracing_feature },
5563 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5564 PACKET_bc },
5565 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5566 PACKET_bs },
5567 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5568 PACKET_TracepointSource },
5569 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5570 PACKET_QAllow },
5571 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5572 PACKET_EnableDisableTracepoints_feature },
5573 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5574 PACKET_qXfer_fdpic },
5575 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5576 PACKET_qXfer_uib },
5577 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5578 PACKET_QDisableRandomization },
5579 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5580 { "QTBuffer:size", PACKET_DISABLE,
5581 remote_supported_packet, PACKET_QTBuffer_size},
5582 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5583 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5584 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5585 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5586 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5587 PACKET_qXfer_btrace },
5588 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5589 PACKET_qXfer_btrace_conf },
5590 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5591 PACKET_Qbtrace_conf_bts_size },
5592 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5593 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5594 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5595 PACKET_fork_event_feature },
5596 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5597 PACKET_vfork_event_feature },
5598 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5599 PACKET_exec_event_feature },
5600 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5601 PACKET_Qbtrace_conf_pt_size },
5602 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5603 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5604 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5605 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5606 PACKET_memory_tagging_feature },
5607 };
5608
5609 static char *remote_support_xml;
5610
5611 /* Register string appended to "xmlRegisters=" in qSupported query. */
5612
5613 void
5614 register_remote_support_xml (const char *xml)
5615 {
5616 #if defined(HAVE_LIBEXPAT)
5617 if (remote_support_xml == NULL)
5618 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5619 else
5620 {
5621 char *copy = xstrdup (remote_support_xml + 13);
5622 char *saveptr;
5623 char *p = strtok_r (copy, ",", &saveptr);
5624
5625 do
5626 {
5627 if (strcmp (p, xml) == 0)
5628 {
5629 /* already there */
5630 xfree (copy);
5631 return;
5632 }
5633 }
5634 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5635 xfree (copy);
5636
5637 remote_support_xml = reconcat (remote_support_xml,
5638 remote_support_xml, ",", xml,
5639 (char *) NULL);
5640 }
5641 #endif
5642 }
5643
5644 static void
5645 remote_query_supported_append (std::string *msg, const char *append)
5646 {
5647 if (!msg->empty ())
5648 msg->append (";");
5649 msg->append (append);
5650 }
5651
5652 void
5653 remote_target::remote_query_supported ()
5654 {
5655 struct remote_state *rs = get_remote_state ();
5656 char *next;
5657 int i;
5658 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5659
5660 /* The packet support flags are handled differently for this packet
5661 than for most others. We treat an error, a disabled packet, and
5662 an empty response identically: any features which must be reported
5663 to be used will be automatically disabled. An empty buffer
5664 accomplishes this, since that is also the representation for a list
5665 containing no features. */
5666
5667 rs->buf[0] = 0;
5668 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5669 {
5670 std::string q;
5671
5672 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5673 != AUTO_BOOLEAN_FALSE)
5674 remote_query_supported_append (&q, "multiprocess+");
5675
5676 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5677 != AUTO_BOOLEAN_FALSE)
5678 remote_query_supported_append (&q, "swbreak+");
5679
5680 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5681 != AUTO_BOOLEAN_FALSE)
5682 remote_query_supported_append (&q, "hwbreak+");
5683
5684 remote_query_supported_append (&q, "qRelocInsn+");
5685
5686 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5687 != AUTO_BOOLEAN_FALSE)
5688 remote_query_supported_append (&q, "fork-events+");
5689
5690 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5691 != AUTO_BOOLEAN_FALSE)
5692 remote_query_supported_append (&q, "vfork-events+");
5693
5694 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5695 != AUTO_BOOLEAN_FALSE)
5696 remote_query_supported_append (&q, "exec-events+");
5697
5698 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5699 != AUTO_BOOLEAN_FALSE)
5700 remote_query_supported_append (&q, "vContSupported+");
5701
5702 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5703 != AUTO_BOOLEAN_FALSE)
5704 remote_query_supported_append (&q, "QThreadEvents+");
5705
5706 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5707 != AUTO_BOOLEAN_FALSE)
5708 remote_query_supported_append (&q, "no-resumed+");
5709
5710 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5711 != AUTO_BOOLEAN_FALSE)
5712 remote_query_supported_append (&q, "memory-tagging+");
5713
5714 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5715 the qSupported:xmlRegisters=i386 handling. */
5716 if (remote_support_xml != NULL
5717 && (m_features.packet_support (PACKET_qXfer_features)
5718 != PACKET_DISABLE))
5719 remote_query_supported_append (&q, remote_support_xml);
5720
5721 q = "qSupported:" + q;
5722 putpkt (q.c_str ());
5723
5724 getpkt (&rs->buf, 0);
5725
5726 /* If an error occured, warn, but do not return - just reset the
5727 buffer to empty and go on to disable features. */
5728 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5729 {
5730 warning (_("Remote failure reply: %s"), rs->buf.data ());
5731 rs->buf[0] = 0;
5732 }
5733 }
5734
5735 memset (seen, 0, sizeof (seen));
5736
5737 next = rs->buf.data ();
5738 while (*next)
5739 {
5740 enum packet_support is_supported;
5741 char *p, *end, *name_end, *value;
5742
5743 /* First separate out this item from the rest of the packet. If
5744 there's another item after this, we overwrite the separator
5745 (terminated strings are much easier to work with). */
5746 p = next;
5747 end = strchr (p, ';');
5748 if (end == NULL)
5749 {
5750 end = p + strlen (p);
5751 next = end;
5752 }
5753 else
5754 {
5755 *end = '\0';
5756 next = end + 1;
5757
5758 if (end == p)
5759 {
5760 warning (_("empty item in \"qSupported\" response"));
5761 continue;
5762 }
5763 }
5764
5765 name_end = strchr (p, '=');
5766 if (name_end)
5767 {
5768 /* This is a name=value entry. */
5769 is_supported = PACKET_ENABLE;
5770 value = name_end + 1;
5771 *name_end = '\0';
5772 }
5773 else
5774 {
5775 value = NULL;
5776 switch (end[-1])
5777 {
5778 case '+':
5779 is_supported = PACKET_ENABLE;
5780 break;
5781
5782 case '-':
5783 is_supported = PACKET_DISABLE;
5784 break;
5785
5786 case '?':
5787 is_supported = PACKET_SUPPORT_UNKNOWN;
5788 break;
5789
5790 default:
5791 warning (_("unrecognized item \"%s\" "
5792 "in \"qSupported\" response"), p);
5793 continue;
5794 }
5795 end[-1] = '\0';
5796 }
5797
5798 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5799 if (strcmp (remote_protocol_features[i].name, p) == 0)
5800 {
5801 const struct protocol_feature *feature;
5802
5803 seen[i] = 1;
5804 feature = &remote_protocol_features[i];
5805 feature->func (this, feature, is_supported, value);
5806 break;
5807 }
5808 }
5809
5810 /* If we increased the packet size, make sure to increase the global
5811 buffer size also. We delay this until after parsing the entire
5812 qSupported packet, because this is the same buffer we were
5813 parsing. */
5814 if (rs->buf.size () < rs->explicit_packet_size)
5815 rs->buf.resize (rs->explicit_packet_size);
5816
5817 /* Handle the defaults for unmentioned features. */
5818 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5819 if (!seen[i])
5820 {
5821 const struct protocol_feature *feature;
5822
5823 feature = &remote_protocol_features[i];
5824 feature->func (this, feature, feature->default_support, NULL);
5825 }
5826 }
5827
5828 /* Serial QUIT handler for the remote serial descriptor.
5829
5830 Defers handling a Ctrl-C until we're done with the current
5831 command/response packet sequence, unless:
5832
5833 - We're setting up the connection. Don't send a remote interrupt
5834 request, as we're not fully synced yet. Quit immediately
5835 instead.
5836
5837 - The target has been resumed in the foreground
5838 (target_terminal::is_ours is false) with a synchronous resume
5839 packet, and we're blocked waiting for the stop reply, thus a
5840 Ctrl-C should be immediately sent to the target.
5841
5842 - We get a second Ctrl-C while still within the same serial read or
5843 write. In that case the serial is seemingly wedged --- offer to
5844 quit/disconnect.
5845
5846 - We see a second Ctrl-C without target response, after having
5847 previously interrupted the target. In that case the target/stub
5848 is probably wedged --- offer to quit/disconnect.
5849 */
5850
5851 void
5852 remote_target::remote_serial_quit_handler ()
5853 {
5854 struct remote_state *rs = get_remote_state ();
5855
5856 if (check_quit_flag ())
5857 {
5858 /* If we're starting up, we're not fully synced yet. Quit
5859 immediately. */
5860 if (rs->starting_up)
5861 quit ();
5862 else if (rs->got_ctrlc_during_io)
5863 {
5864 if (query (_("The target is not responding to GDB commands.\n"
5865 "Stop debugging it? ")))
5866 remote_unpush_and_throw (this);
5867 }
5868 /* If ^C has already been sent once, offer to disconnect. */
5869 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5870 interrupt_query ();
5871 /* All-stop protocol, and blocked waiting for stop reply. Send
5872 an interrupt request. */
5873 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5874 target_interrupt ();
5875 else
5876 rs->got_ctrlc_during_io = 1;
5877 }
5878 }
5879
5880 /* The remote_target that is current while the quit handler is
5881 overridden with remote_serial_quit_handler. */
5882 static remote_target *curr_quit_handler_target;
5883
5884 static void
5885 remote_serial_quit_handler ()
5886 {
5887 curr_quit_handler_target->remote_serial_quit_handler ();
5888 }
5889
5890 /* Remove the remote target from the target stack of each inferior
5891 that is using it. Upper targets depend on it so remove them
5892 first. */
5893
5894 static void
5895 remote_unpush_target (remote_target *target)
5896 {
5897 /* We have to unpush the target from all inferiors, even those that
5898 aren't running. */
5899 scoped_restore_current_inferior restore_current_inferior;
5900
5901 for (inferior *inf : all_inferiors (target))
5902 {
5903 switch_to_inferior_no_thread (inf);
5904 inf->pop_all_targets_at_and_above (process_stratum);
5905 generic_mourn_inferior ();
5906 }
5907
5908 /* Don't rely on target_close doing this when the target is popped
5909 from the last remote inferior above, because something may be
5910 holding a reference to the target higher up on the stack, meaning
5911 target_close won't be called yet. We lost the connection to the
5912 target, so clear these now, otherwise we may later throw
5913 TARGET_CLOSE_ERROR while trying to tell the remote target to
5914 close the file. */
5915 fileio_handles_invalidate_target (target);
5916 }
5917
5918 static void
5919 remote_unpush_and_throw (remote_target *target)
5920 {
5921 remote_unpush_target (target);
5922 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5923 }
5924
5925 void
5926 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5927 {
5928 remote_target *curr_remote = get_current_remote_target ();
5929
5930 if (name == 0)
5931 error (_("To open a remote debug connection, you need to specify what\n"
5932 "serial device is attached to the remote system\n"
5933 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5934
5935 /* If we're connected to a running target, target_preopen will kill it.
5936 Ask this question first, before target_preopen has a chance to kill
5937 anything. */
5938 if (curr_remote != NULL && !target_has_execution ())
5939 {
5940 if (from_tty
5941 && !query (_("Already connected to a remote target. Disconnect? ")))
5942 error (_("Still connected."));
5943 }
5944
5945 /* Here the possibly existing remote target gets unpushed. */
5946 target_preopen (from_tty);
5947
5948 remote_fileio_reset ();
5949 reopen_exec_file ();
5950 reread_symbols (from_tty);
5951
5952 remote_target *remote
5953 = (extended_p ? new extended_remote_target () : new remote_target ());
5954 target_ops_up target_holder (remote);
5955
5956 remote_state *rs = remote->get_remote_state ();
5957
5958 /* See FIXME above. */
5959 if (!target_async_permitted)
5960 rs->wait_forever_enabled_p = 1;
5961
5962 rs->remote_desc = remote_serial_open (name);
5963 if (!rs->remote_desc)
5964 perror_with_name (name);
5965
5966 if (baud_rate != -1)
5967 {
5968 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5969 {
5970 /* The requested speed could not be set. Error out to
5971 top level after closing remote_desc. Take care to
5972 set remote_desc to NULL to avoid closing remote_desc
5973 more than once. */
5974 serial_close (rs->remote_desc);
5975 rs->remote_desc = NULL;
5976 perror_with_name (name);
5977 }
5978 }
5979
5980 serial_setparity (rs->remote_desc, serial_parity);
5981 serial_raw (rs->remote_desc);
5982
5983 /* If there is something sitting in the buffer we might take it as a
5984 response to a command, which would be bad. */
5985 serial_flush_input (rs->remote_desc);
5986
5987 if (from_tty)
5988 {
5989 gdb_puts ("Remote debugging using ");
5990 gdb_puts (name);
5991 gdb_puts ("\n");
5992 }
5993
5994 /* Switch to using the remote target now. */
5995 current_inferior ()->push_target (std::move (target_holder));
5996
5997 /* Register extra event sources in the event loop. */
5998 rs->remote_async_inferior_event_token
5999 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
6000 "remote");
6001 rs->notif_state = remote_notif_state_allocate (remote);
6002
6003 /* Reset the target state; these things will be queried either by
6004 remote_query_supported or as they are needed. */
6005 remote->m_features.reset_all_packet_configs_support ();
6006 rs->explicit_packet_size = 0;
6007 rs->noack_mode = 0;
6008 rs->extended = extended_p;
6009 rs->waiting_for_stop_reply = 0;
6010 rs->ctrlc_pending_p = 0;
6011 rs->got_ctrlc_during_io = 0;
6012
6013 rs->general_thread = not_sent_ptid;
6014 rs->continue_thread = not_sent_ptid;
6015 rs->remote_traceframe_number = -1;
6016
6017 rs->last_resume_exec_dir = EXEC_FORWARD;
6018
6019 /* Probe for ability to use "ThreadInfo" query, as required. */
6020 rs->use_threadinfo_query = 1;
6021 rs->use_threadextra_query = 1;
6022
6023 rs->readahead_cache.invalidate ();
6024
6025 if (target_async_permitted)
6026 {
6027 /* FIXME: cagney/1999-09-23: During the initial connection it is
6028 assumed that the target is already ready and able to respond to
6029 requests. Unfortunately remote_start_remote() eventually calls
6030 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6031 around this. Eventually a mechanism that allows
6032 wait_for_inferior() to expect/get timeouts will be
6033 implemented. */
6034 rs->wait_forever_enabled_p = 0;
6035 }
6036
6037 /* First delete any symbols previously loaded from shared libraries. */
6038 no_shared_libraries (NULL, 0);
6039
6040 /* Start the remote connection. If error() or QUIT, discard this
6041 target (we'd otherwise be in an inconsistent state) and then
6042 propogate the error on up the exception chain. This ensures that
6043 the caller doesn't stumble along blindly assuming that the
6044 function succeeded. The CLI doesn't have this problem but other
6045 UI's, such as MI do.
6046
6047 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6048 this function should return an error indication letting the
6049 caller restore the previous state. Unfortunately the command
6050 ``target remote'' is directly wired to this function making that
6051 impossible. On a positive note, the CLI side of this problem has
6052 been fixed - the function set_cmd_context() makes it possible for
6053 all the ``target ....'' commands to share a common callback
6054 function. See cli-dump.c. */
6055 {
6056
6057 try
6058 {
6059 remote->start_remote (from_tty, extended_p);
6060 }
6061 catch (const gdb_exception &ex)
6062 {
6063 /* Pop the partially set up target - unless something else did
6064 already before throwing the exception. */
6065 if (ex.error != TARGET_CLOSE_ERROR)
6066 remote_unpush_target (remote);
6067 throw;
6068 }
6069 }
6070
6071 remote_btrace_reset (rs);
6072
6073 if (target_async_permitted)
6074 rs->wait_forever_enabled_p = 1;
6075 }
6076
6077 /* Determine if WS represents a fork status. */
6078
6079 static bool
6080 is_fork_status (target_waitkind kind)
6081 {
6082 return (kind == TARGET_WAITKIND_FORKED
6083 || kind == TARGET_WAITKIND_VFORKED);
6084 }
6085
6086 /* Return THREAD's pending status if it is a pending fork parent, else
6087 return nullptr. */
6088
6089 static const target_waitstatus *
6090 thread_pending_fork_status (struct thread_info *thread)
6091 {
6092 const target_waitstatus &ws
6093 = (thread->has_pending_waitstatus ()
6094 ? thread->pending_waitstatus ()
6095 : thread->pending_follow);
6096
6097 if (!is_fork_status (ws.kind ()))
6098 return nullptr;
6099
6100 return &ws;
6101 }
6102
6103 /* Detach the specified process. */
6104
6105 void
6106 remote_target::remote_detach_pid (int pid)
6107 {
6108 struct remote_state *rs = get_remote_state ();
6109
6110 /* This should not be necessary, but the handling for D;PID in
6111 GDBserver versions prior to 8.2 incorrectly assumes that the
6112 selected process points to the same process we're detaching,
6113 leading to misbehavior (and possibly GDBserver crashing) when it
6114 does not. Since it's easy and cheap, work around it by forcing
6115 GDBserver to select GDB's current process. */
6116 set_general_process ();
6117
6118 if (m_features.remote_multi_process_p ())
6119 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6120 else
6121 strcpy (rs->buf.data (), "D");
6122
6123 putpkt (rs->buf);
6124 getpkt (&rs->buf, 0);
6125
6126 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6127 ;
6128 else if (rs->buf[0] == '\0')
6129 error (_("Remote doesn't know how to detach"));
6130 else
6131 error (_("Can't detach process."));
6132 }
6133
6134 /* This detaches a program to which we previously attached, using
6135 inferior_ptid to identify the process. After this is done, GDB
6136 can be used to debug some other program. We better not have left
6137 any breakpoints in the target program or it'll die when it hits
6138 one. */
6139
6140 void
6141 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6142 {
6143 int pid = inferior_ptid.pid ();
6144 struct remote_state *rs = get_remote_state ();
6145 int is_fork_parent;
6146
6147 if (!target_has_execution ())
6148 error (_("No process to detach from."));
6149
6150 target_announce_detach (from_tty);
6151
6152 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
6153 {
6154 /* If we're in breakpoints-always-inserted mode, or the inferior
6155 is running, we have to remove breakpoints before detaching.
6156 We don't do this in common code instead because not all
6157 targets support removing breakpoints while the target is
6158 running. The remote target / gdbserver does, though. */
6159 remove_breakpoints_inf (current_inferior ());
6160 }
6161
6162 /* Tell the remote target to detach. */
6163 remote_detach_pid (pid);
6164
6165 /* Exit only if this is the only active inferior. */
6166 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6167 gdb_puts (_("Ending remote debugging.\n"));
6168
6169 /* See if any thread of the inferior we are detaching has a pending fork
6170 status. In that case, we must detach from the child resulting from
6171 that fork. */
6172 for (thread_info *thread : inf->non_exited_threads ())
6173 {
6174 const target_waitstatus *ws = thread_pending_fork_status (thread);
6175
6176 if (ws == nullptr)
6177 continue;
6178
6179 remote_detach_pid (ws->child_ptid ().pid ());
6180 }
6181
6182 /* Check also for any pending fork events in the stop reply queue. */
6183 remote_notif_get_pending_events (&notif_client_stop);
6184 for (stop_reply_up &reply : rs->stop_reply_queue)
6185 {
6186 if (reply->ptid.pid () != pid)
6187 continue;
6188
6189 if (!is_fork_status (reply->ws.kind ()))
6190 continue;
6191
6192 remote_detach_pid (reply->ws.child_ptid ().pid ());
6193 }
6194
6195 thread_info *tp = find_thread_ptid (this, inferior_ptid);
6196
6197 /* Check to see if we are detaching a fork parent. Note that if we
6198 are detaching a fork child, tp == NULL. */
6199 is_fork_parent = (tp != NULL
6200 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6201
6202 /* If doing detach-on-fork, we don't mourn, because that will delete
6203 breakpoints that should be available for the followed inferior. */
6204 if (!is_fork_parent)
6205 {
6206 /* Save the pid as a string before mourning, since that will
6207 unpush the remote target, and we need the string after. */
6208 std::string infpid = target_pid_to_str (ptid_t (pid));
6209
6210 target_mourn_inferior (inferior_ptid);
6211 if (print_inferior_events)
6212 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6213 inf->num, infpid.c_str ());
6214 }
6215 else
6216 {
6217 switch_to_no_thread ();
6218 detach_inferior (current_inferior ());
6219 }
6220 }
6221
6222 void
6223 remote_target::detach (inferior *inf, int from_tty)
6224 {
6225 remote_detach_1 (inf, from_tty);
6226 }
6227
6228 void
6229 extended_remote_target::detach (inferior *inf, int from_tty)
6230 {
6231 remote_detach_1 (inf, from_tty);
6232 }
6233
6234 /* Target follow-fork function for remote targets. On entry, and
6235 at return, the current inferior is the fork parent.
6236
6237 Note that although this is currently only used for extended-remote,
6238 it is named remote_follow_fork in anticipation of using it for the
6239 remote target as well. */
6240
6241 void
6242 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6243 target_waitkind fork_kind, bool follow_child,
6244 bool detach_fork)
6245 {
6246 process_stratum_target::follow_fork (child_inf, child_ptid,
6247 fork_kind, follow_child, detach_fork);
6248
6249 if ((fork_kind == TARGET_WAITKIND_FORKED
6250 && m_features.remote_fork_event_p ())
6251 || (fork_kind == TARGET_WAITKIND_VFORKED
6252 && m_features.remote_vfork_event_p ()))
6253 {
6254 /* When following the parent and detaching the child, we detach
6255 the child here. For the case of following the child and
6256 detaching the parent, the detach is done in the target-
6257 independent follow fork code in infrun.c. We can't use
6258 target_detach when detaching an unfollowed child because
6259 the client side doesn't know anything about the child. */
6260 if (detach_fork && !follow_child)
6261 {
6262 /* Detach the fork child. */
6263 remote_detach_pid (child_ptid.pid ());
6264 }
6265 }
6266 }
6267
6268 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6269 in the program space of the new inferior. */
6270
6271 void
6272 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6273 const char *execd_pathname)
6274 {
6275 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6276
6277 /* We know that this is a target file name, so if it has the "target:"
6278 prefix we strip it off before saving it in the program space. */
6279 if (is_target_filename (execd_pathname))
6280 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6281
6282 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6283 }
6284
6285 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6286
6287 void
6288 remote_target::disconnect (const char *args, int from_tty)
6289 {
6290 if (args)
6291 error (_("Argument given to \"disconnect\" when remotely debugging."));
6292
6293 /* Make sure we unpush even the extended remote targets. Calling
6294 target_mourn_inferior won't unpush, and
6295 remote_target::mourn_inferior won't unpush if there is more than
6296 one inferior left. */
6297 remote_unpush_target (this);
6298
6299 if (from_tty)
6300 gdb_puts ("Ending remote debugging.\n");
6301 }
6302
6303 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6304 be chatty about it. */
6305
6306 void
6307 extended_remote_target::attach (const char *args, int from_tty)
6308 {
6309 struct remote_state *rs = get_remote_state ();
6310 int pid;
6311 char *wait_status = NULL;
6312
6313 pid = parse_pid_to_attach (args);
6314
6315 /* Remote PID can be freely equal to getpid, do not check it here the same
6316 way as in other targets. */
6317
6318 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6319 error (_("This target does not support attaching to a process"));
6320
6321 target_announce_attach (from_tty, pid);
6322
6323 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6324 putpkt (rs->buf);
6325 getpkt (&rs->buf, 0);
6326
6327 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6328 {
6329 case PACKET_OK:
6330 if (!target_is_non_stop_p ())
6331 {
6332 /* Save the reply for later. */
6333 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6334 strcpy (wait_status, rs->buf.data ());
6335 }
6336 else if (strcmp (rs->buf.data (), "OK") != 0)
6337 error (_("Attaching to %s failed with: %s"),
6338 target_pid_to_str (ptid_t (pid)).c_str (),
6339 rs->buf.data ());
6340 break;
6341 case PACKET_UNKNOWN:
6342 error (_("This target does not support attaching to a process"));
6343 default:
6344 error (_("Attaching to %s failed"),
6345 target_pid_to_str (ptid_t (pid)).c_str ());
6346 }
6347
6348 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6349
6350 inferior_ptid = ptid_t (pid);
6351
6352 if (target_is_non_stop_p ())
6353 {
6354 /* Get list of threads. */
6355 update_thread_list ();
6356
6357 thread_info *thread = first_thread_of_inferior (current_inferior ());
6358 if (thread != nullptr)
6359 switch_to_thread (thread);
6360
6361 /* Invalidate our notion of the remote current thread. */
6362 record_currthread (rs, minus_one_ptid);
6363 }
6364 else
6365 {
6366 /* Now, if we have thread information, update the main thread's
6367 ptid. */
6368 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6369
6370 /* Add the main thread to the thread list. We add the thread
6371 silently in this case (the final true parameter). */
6372 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6373
6374 switch_to_thread (thr);
6375 }
6376
6377 /* Next, if the target can specify a description, read it. We do
6378 this before anything involving memory or registers. */
6379 target_find_description ();
6380
6381 if (!target_is_non_stop_p ())
6382 {
6383 /* Use the previously fetched status. */
6384 gdb_assert (wait_status != NULL);
6385
6386 struct notif_event *reply
6387 = remote_notif_parse (this, &notif_client_stop, wait_status);
6388
6389 push_stop_reply ((struct stop_reply *) reply);
6390 }
6391 else
6392 {
6393 gdb_assert (wait_status == NULL);
6394
6395 gdb_assert (target_can_async_p ());
6396 }
6397 }
6398
6399 /* Implementation of the to_post_attach method. */
6400
6401 void
6402 extended_remote_target::post_attach (int pid)
6403 {
6404 /* Get text, data & bss offsets. */
6405 get_offsets ();
6406
6407 /* In certain cases GDB might not have had the chance to start
6408 symbol lookup up until now. This could happen if the debugged
6409 binary is not using shared libraries, the vsyscall page is not
6410 present (on Linux) and the binary itself hadn't changed since the
6411 debugging process was started. */
6412 if (current_program_space->symfile_object_file != NULL)
6413 remote_check_symbols();
6414 }
6415
6416 \f
6417 /* Check for the availability of vCont. This function should also check
6418 the response. */
6419
6420 void
6421 remote_target::remote_vcont_probe ()
6422 {
6423 remote_state *rs = get_remote_state ();
6424 char *buf;
6425
6426 strcpy (rs->buf.data (), "vCont?");
6427 putpkt (rs->buf);
6428 getpkt (&rs->buf, 0);
6429 buf = rs->buf.data ();
6430
6431 /* Make sure that the features we assume are supported. */
6432 if (startswith (buf, "vCont"))
6433 {
6434 char *p = &buf[5];
6435 int support_c, support_C;
6436
6437 rs->supports_vCont.s = 0;
6438 rs->supports_vCont.S = 0;
6439 support_c = 0;
6440 support_C = 0;
6441 rs->supports_vCont.t = 0;
6442 rs->supports_vCont.r = 0;
6443 while (p && *p == ';')
6444 {
6445 p++;
6446 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6447 rs->supports_vCont.s = 1;
6448 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6449 rs->supports_vCont.S = 1;
6450 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6451 support_c = 1;
6452 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6453 support_C = 1;
6454 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6455 rs->supports_vCont.t = 1;
6456 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6457 rs->supports_vCont.r = 1;
6458
6459 p = strchr (p, ';');
6460 }
6461
6462 /* If c, and C are not all supported, we can't use vCont. Clearing
6463 BUF will make packet_ok disable the packet. */
6464 if (!support_c || !support_C)
6465 buf[0] = 0;
6466 }
6467
6468 m_features.packet_ok (rs->buf, PACKET_vCont);
6469 }
6470
6471 /* Helper function for building "vCont" resumptions. Write a
6472 resumption to P. ENDP points to one-passed-the-end of the buffer
6473 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6474 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6475 resumed thread should be single-stepped and/or signalled. If PTID
6476 equals minus_one_ptid, then all threads are resumed; if PTID
6477 represents a process, then all threads of the process are
6478 resumed. */
6479
6480 char *
6481 remote_target::append_resumption (char *p, char *endp,
6482 ptid_t ptid, int step, gdb_signal siggnal)
6483 {
6484 struct remote_state *rs = get_remote_state ();
6485
6486 if (step && siggnal != GDB_SIGNAL_0)
6487 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6488 else if (step
6489 /* GDB is willing to range step. */
6490 && use_range_stepping
6491 /* Target supports range stepping. */
6492 && rs->supports_vCont.r
6493 /* We don't currently support range stepping multiple
6494 threads with a wildcard (though the protocol allows it,
6495 so stubs shouldn't make an active effort to forbid
6496 it). */
6497 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6498 {
6499 struct thread_info *tp;
6500
6501 if (ptid == minus_one_ptid)
6502 {
6503 /* If we don't know about the target thread's tid, then
6504 we're resuming magic_null_ptid (see caller). */
6505 tp = find_thread_ptid (this, magic_null_ptid);
6506 }
6507 else
6508 tp = find_thread_ptid (this, ptid);
6509 gdb_assert (tp != NULL);
6510
6511 if (tp->control.may_range_step)
6512 {
6513 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6514
6515 p += xsnprintf (p, endp - p, ";r%s,%s",
6516 phex_nz (tp->control.step_range_start,
6517 addr_size),
6518 phex_nz (tp->control.step_range_end,
6519 addr_size));
6520 }
6521 else
6522 p += xsnprintf (p, endp - p, ";s");
6523 }
6524 else if (step)
6525 p += xsnprintf (p, endp - p, ";s");
6526 else if (siggnal != GDB_SIGNAL_0)
6527 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6528 else
6529 p += xsnprintf (p, endp - p, ";c");
6530
6531 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6532 {
6533 ptid_t nptid;
6534
6535 /* All (-1) threads of process. */
6536 nptid = ptid_t (ptid.pid (), -1);
6537
6538 p += xsnprintf (p, endp - p, ":");
6539 p = write_ptid (p, endp, nptid);
6540 }
6541 else if (ptid != minus_one_ptid)
6542 {
6543 p += xsnprintf (p, endp - p, ":");
6544 p = write_ptid (p, endp, ptid);
6545 }
6546
6547 return p;
6548 }
6549
6550 /* Clear the thread's private info on resume. */
6551
6552 static void
6553 resume_clear_thread_private_info (struct thread_info *thread)
6554 {
6555 if (thread->priv != NULL)
6556 {
6557 remote_thread_info *priv = get_remote_thread_info (thread);
6558
6559 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6560 priv->watch_data_address = 0;
6561 }
6562 }
6563
6564 /* Append a vCont continue-with-signal action for threads that have a
6565 non-zero stop signal. */
6566
6567 char *
6568 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6569 ptid_t ptid)
6570 {
6571 for (thread_info *thread : all_non_exited_threads (this, ptid))
6572 if (inferior_ptid != thread->ptid
6573 && thread->stop_signal () != GDB_SIGNAL_0)
6574 {
6575 p = append_resumption (p, endp, thread->ptid,
6576 0, thread->stop_signal ());
6577 thread->set_stop_signal (GDB_SIGNAL_0);
6578 resume_clear_thread_private_info (thread);
6579 }
6580
6581 return p;
6582 }
6583
6584 /* Set the target running, using the packets that use Hc
6585 (c/s/C/S). */
6586
6587 void
6588 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6589 gdb_signal siggnal)
6590 {
6591 struct remote_state *rs = get_remote_state ();
6592 char *buf;
6593
6594 rs->last_sent_signal = siggnal;
6595 rs->last_sent_step = step;
6596
6597 /* The c/s/C/S resume packets use Hc, so set the continue
6598 thread. */
6599 if (ptid == minus_one_ptid)
6600 set_continue_thread (any_thread_ptid);
6601 else
6602 set_continue_thread (ptid);
6603
6604 for (thread_info *thread : all_non_exited_threads (this))
6605 resume_clear_thread_private_info (thread);
6606
6607 buf = rs->buf.data ();
6608 if (::execution_direction == EXEC_REVERSE)
6609 {
6610 /* We don't pass signals to the target in reverse exec mode. */
6611 if (info_verbose && siggnal != GDB_SIGNAL_0)
6612 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6613 siggnal);
6614
6615 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6616 error (_("Remote reverse-step not supported."));
6617 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6618 error (_("Remote reverse-continue not supported."));
6619
6620 strcpy (buf, step ? "bs" : "bc");
6621 }
6622 else if (siggnal != GDB_SIGNAL_0)
6623 {
6624 buf[0] = step ? 'S' : 'C';
6625 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6626 buf[2] = tohex (((int) siggnal) & 0xf);
6627 buf[3] = '\0';
6628 }
6629 else
6630 strcpy (buf, step ? "s" : "c");
6631
6632 putpkt (buf);
6633 }
6634
6635 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6636 STEP, and SIGGNAL have the same meaning as in target_resume. This
6637 function returns non-zero iff it resumes the inferior.
6638
6639 This function issues a strict subset of all possible vCont commands
6640 at the moment. */
6641
6642 int
6643 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6644 enum gdb_signal siggnal)
6645 {
6646 struct remote_state *rs = get_remote_state ();
6647 char *p;
6648 char *endp;
6649
6650 /* No reverse execution actions defined for vCont. */
6651 if (::execution_direction == EXEC_REVERSE)
6652 return 0;
6653
6654 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6655 return 0;
6656
6657 p = rs->buf.data ();
6658 endp = p + get_remote_packet_size ();
6659
6660 /* If we could generate a wider range of packets, we'd have to worry
6661 about overflowing BUF. Should there be a generic
6662 "multi-part-packet" packet? */
6663
6664 p += xsnprintf (p, endp - p, "vCont");
6665
6666 if (scope_ptid == magic_null_ptid)
6667 {
6668 /* MAGIC_NULL_PTID means that we don't have any active threads,
6669 so we don't have any TID numbers the inferior will
6670 understand. Make sure to only send forms that do not specify
6671 a TID. */
6672 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6673 }
6674 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6675 {
6676 /* Resume all threads (of all processes, or of a single
6677 process), with preference for INFERIOR_PTID. This assumes
6678 inferior_ptid belongs to the set of all threads we are about
6679 to resume. */
6680 if (step || siggnal != GDB_SIGNAL_0)
6681 {
6682 /* Step inferior_ptid, with or without signal. */
6683 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6684 }
6685
6686 /* Also pass down any pending signaled resumption for other
6687 threads not the current. */
6688 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6689
6690 /* And continue others without a signal. */
6691 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6692 }
6693 else
6694 {
6695 /* Scheduler locking; resume only SCOPE_PTID. */
6696 append_resumption (p, endp, scope_ptid, step, siggnal);
6697 }
6698
6699 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6700 putpkt (rs->buf);
6701
6702 if (target_is_non_stop_p ())
6703 {
6704 /* In non-stop, the stub replies to vCont with "OK". The stop
6705 reply will be reported asynchronously by means of a `%Stop'
6706 notification. */
6707 getpkt (&rs->buf, 0);
6708 if (strcmp (rs->buf.data (), "OK") != 0)
6709 error (_("Unexpected vCont reply in non-stop mode: %s"),
6710 rs->buf.data ());
6711 }
6712
6713 return 1;
6714 }
6715
6716 /* Tell the remote machine to resume. */
6717
6718 void
6719 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6720 {
6721 struct remote_state *rs = get_remote_state ();
6722
6723 /* When connected in non-stop mode, the core resumes threads
6724 individually. Resuming remote threads directly in target_resume
6725 would thus result in sending one packet per thread. Instead, to
6726 minimize roundtrip latency, here we just store the resume
6727 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6728 resumption will be done in remote_target::commit_resume, where we'll be
6729 able to do vCont action coalescing. */
6730 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6731 {
6732 remote_thread_info *remote_thr
6733 = get_remote_thread_info (inferior_thread ());
6734
6735 /* We don't expect the core to ask to resume an already resumed (from
6736 its point of view) thread. */
6737 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6738
6739 remote_thr->set_resumed_pending_vcont (step, siggnal);
6740
6741 /* There's actually nothing that says that the core can't
6742 request a wildcard resume in non-stop mode, though. It's
6743 just that we know it doesn't currently, so we don't bother
6744 with it. */
6745 gdb_assert (scope_ptid == inferior_ptid);
6746 return;
6747 }
6748
6749 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6750 (explained in remote-notif.c:handle_notification) so
6751 remote_notif_process is not called. We need find a place where
6752 it is safe to start a 'vNotif' sequence. It is good to do it
6753 before resuming inferior, because inferior was stopped and no RSP
6754 traffic at that moment. */
6755 if (!target_is_non_stop_p ())
6756 remote_notif_process (rs->notif_state, &notif_client_stop);
6757
6758 rs->last_resume_exec_dir = ::execution_direction;
6759
6760 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6761 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6762 remote_resume_with_hc (scope_ptid, step, siggnal);
6763
6764 /* Update resumed state tracked by the remote target. */
6765 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6766 get_remote_thread_info (tp)->set_resumed ();
6767
6768 /* We've just told the target to resume. The remote server will
6769 wait for the inferior to stop, and then send a stop reply. In
6770 the mean time, we can't start another command/query ourselves
6771 because the stub wouldn't be ready to process it. This applies
6772 only to the base all-stop protocol, however. In non-stop (which
6773 only supports vCont), the stub replies with an "OK", and is
6774 immediate able to process further serial input. */
6775 if (!target_is_non_stop_p ())
6776 rs->waiting_for_stop_reply = 1;
6777 }
6778
6779 /* Private per-inferior info for target remote processes. */
6780
6781 struct remote_inferior : public private_inferior
6782 {
6783 /* Whether we can send a wildcard vCont for this process. */
6784 bool may_wildcard_vcont = true;
6785 };
6786
6787 /* Get the remote private inferior data associated to INF. */
6788
6789 static remote_inferior *
6790 get_remote_inferior (inferior *inf)
6791 {
6792 if (inf->priv == NULL)
6793 inf->priv.reset (new remote_inferior);
6794
6795 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6796 }
6797
6798 /* Class used to track the construction of a vCont packet in the
6799 outgoing packet buffer. This is used to send multiple vCont
6800 packets if we have more actions than would fit a single packet. */
6801
6802 class vcont_builder
6803 {
6804 public:
6805 explicit vcont_builder (remote_target *remote)
6806 : m_remote (remote)
6807 {
6808 restart ();
6809 }
6810
6811 void flush ();
6812 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6813
6814 private:
6815 void restart ();
6816
6817 /* The remote target. */
6818 remote_target *m_remote;
6819
6820 /* Pointer to the first action. P points here if no action has been
6821 appended yet. */
6822 char *m_first_action;
6823
6824 /* Where the next action will be appended. */
6825 char *m_p;
6826
6827 /* The end of the buffer. Must never write past this. */
6828 char *m_endp;
6829 };
6830
6831 /* Prepare the outgoing buffer for a new vCont packet. */
6832
6833 void
6834 vcont_builder::restart ()
6835 {
6836 struct remote_state *rs = m_remote->get_remote_state ();
6837
6838 m_p = rs->buf.data ();
6839 m_endp = m_p + m_remote->get_remote_packet_size ();
6840 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6841 m_first_action = m_p;
6842 }
6843
6844 /* If the vCont packet being built has any action, send it to the
6845 remote end. */
6846
6847 void
6848 vcont_builder::flush ()
6849 {
6850 struct remote_state *rs;
6851
6852 if (m_p == m_first_action)
6853 return;
6854
6855 rs = m_remote->get_remote_state ();
6856 m_remote->putpkt (rs->buf);
6857 m_remote->getpkt (&rs->buf, 0);
6858 if (strcmp (rs->buf.data (), "OK") != 0)
6859 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6860 }
6861
6862 /* The largest action is range-stepping, with its two addresses. This
6863 is more than sufficient. If a new, bigger action is created, it'll
6864 quickly trigger a failed assertion in append_resumption (and we'll
6865 just bump this). */
6866 #define MAX_ACTION_SIZE 200
6867
6868 /* Append a new vCont action in the outgoing packet being built. If
6869 the action doesn't fit the packet along with previous actions, push
6870 what we've got so far to the remote end and start over a new vCont
6871 packet (with the new action). */
6872
6873 void
6874 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6875 {
6876 char buf[MAX_ACTION_SIZE + 1];
6877
6878 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6879 ptid, step, siggnal);
6880
6881 /* Check whether this new action would fit in the vCont packet along
6882 with previous actions. If not, send what we've got so far and
6883 start a new vCont packet. */
6884 size_t rsize = endp - buf;
6885 if (rsize > m_endp - m_p)
6886 {
6887 flush ();
6888 restart ();
6889
6890 /* Should now fit. */
6891 gdb_assert (rsize <= m_endp - m_p);
6892 }
6893
6894 memcpy (m_p, buf, rsize);
6895 m_p += rsize;
6896 *m_p = '\0';
6897 }
6898
6899 /* to_commit_resume implementation. */
6900
6901 void
6902 remote_target::commit_resumed ()
6903 {
6904 /* If connected in all-stop mode, we'd send the remote resume
6905 request directly from remote_resume. Likewise if
6906 reverse-debugging, as there are no defined vCont actions for
6907 reverse execution. */
6908 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6909 return;
6910
6911 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6912 instead of resuming all threads of each process individually.
6913 However, if any thread of a process must remain halted, we can't
6914 send wildcard resumes and must send one action per thread.
6915
6916 Care must be taken to not resume threads/processes the server
6917 side already told us are stopped, but the core doesn't know about
6918 yet, because the events are still in the vStopped notification
6919 queue. For example:
6920
6921 #1 => vCont s:p1.1;c
6922 #2 <= OK
6923 #3 <= %Stopped T05 p1.1
6924 #4 => vStopped
6925 #5 <= T05 p1.2
6926 #6 => vStopped
6927 #7 <= OK
6928 #8 (infrun handles the stop for p1.1 and continues stepping)
6929 #9 => vCont s:p1.1;c
6930
6931 The last vCont above would resume thread p1.2 by mistake, because
6932 the server has no idea that the event for p1.2 had not been
6933 handled yet.
6934
6935 The server side must similarly ignore resume actions for the
6936 thread that has a pending %Stopped notification (and any other
6937 threads with events pending), until GDB acks the notification
6938 with vStopped. Otherwise, e.g., the following case is
6939 mishandled:
6940
6941 #1 => g (or any other packet)
6942 #2 <= [registers]
6943 #3 <= %Stopped T05 p1.2
6944 #4 => vCont s:p1.1;c
6945 #5 <= OK
6946
6947 Above, the server must not resume thread p1.2. GDB can't know
6948 that p1.2 stopped until it acks the %Stopped notification, and
6949 since from GDB's perspective all threads should be running, it
6950 sends a "c" action.
6951
6952 Finally, special care must also be given to handling fork/vfork
6953 events. A (v)fork event actually tells us that two processes
6954 stopped -- the parent and the child. Until we follow the fork,
6955 we must not resume the child. Therefore, if we have a pending
6956 fork follow, we must not send a global wildcard resume action
6957 (vCont;c). We can still send process-wide wildcards though. */
6958
6959 /* Start by assuming a global wildcard (vCont;c) is possible. */
6960 bool may_global_wildcard_vcont = true;
6961
6962 /* And assume every process is individually wildcard-able too. */
6963 for (inferior *inf : all_non_exited_inferiors (this))
6964 {
6965 remote_inferior *priv = get_remote_inferior (inf);
6966
6967 priv->may_wildcard_vcont = true;
6968 }
6969
6970 /* Check for any pending events (not reported or processed yet) and
6971 disable process and global wildcard resumes appropriately. */
6972 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6973
6974 bool any_pending_vcont_resume = false;
6975
6976 for (thread_info *tp : all_non_exited_threads (this))
6977 {
6978 remote_thread_info *priv = get_remote_thread_info (tp);
6979
6980 /* If a thread of a process is not meant to be resumed, then we
6981 can't wildcard that process. */
6982 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6983 {
6984 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6985
6986 /* And if we can't wildcard a process, we can't wildcard
6987 everything either. */
6988 may_global_wildcard_vcont = false;
6989 continue;
6990 }
6991
6992 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6993 any_pending_vcont_resume = true;
6994
6995 /* If a thread is the parent of an unfollowed fork, then we
6996 can't do a global wildcard, as that would resume the fork
6997 child. */
6998 if (thread_pending_fork_status (tp) != nullptr)
6999 may_global_wildcard_vcont = false;
7000 }
7001
7002 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7003 do. */
7004 if (!any_pending_vcont_resume)
7005 return;
7006
7007 /* Now let's build the vCont packet(s). Actions must be appended
7008 from narrower to wider scopes (thread -> process -> global). If
7009 we end up with too many actions for a single packet vcont_builder
7010 flushes the current vCont packet to the remote side and starts a
7011 new one. */
7012 struct vcont_builder vcont_builder (this);
7013
7014 /* Threads first. */
7015 for (thread_info *tp : all_non_exited_threads (this))
7016 {
7017 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7018
7019 /* If the thread was previously vCont-resumed, no need to send a specific
7020 action for it. If we didn't receive a resume request for it, don't
7021 send an action for it either. */
7022 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7023 continue;
7024
7025 gdb_assert (!thread_is_in_step_over_chain (tp));
7026
7027 /* We should never be commit-resuming a thread that has a stop reply.
7028 Otherwise, we would end up reporting a stop event for a thread while
7029 it is running on the remote target. */
7030 remote_state *rs = get_remote_state ();
7031 for (const auto &stop_reply : rs->stop_reply_queue)
7032 gdb_assert (stop_reply->ptid != tp->ptid);
7033
7034 const resumed_pending_vcont_info &info
7035 = remote_thr->resumed_pending_vcont_info ();
7036
7037 /* Check if we need to send a specific action for this thread. If not,
7038 it will be included in a wildcard resume instead. */
7039 if (info.step || info.sig != GDB_SIGNAL_0
7040 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7041 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7042
7043 remote_thr->set_resumed ();
7044 }
7045
7046 /* Now check whether we can send any process-wide wildcard. This is
7047 to avoid sending a global wildcard in the case nothing is
7048 supposed to be resumed. */
7049 bool any_process_wildcard = false;
7050
7051 for (inferior *inf : all_non_exited_inferiors (this))
7052 {
7053 if (get_remote_inferior (inf)->may_wildcard_vcont)
7054 {
7055 any_process_wildcard = true;
7056 break;
7057 }
7058 }
7059
7060 if (any_process_wildcard)
7061 {
7062 /* If all processes are wildcard-able, then send a single "c"
7063 action, otherwise, send an "all (-1) threads of process"
7064 continue action for each running process, if any. */
7065 if (may_global_wildcard_vcont)
7066 {
7067 vcont_builder.push_action (minus_one_ptid,
7068 false, GDB_SIGNAL_0);
7069 }
7070 else
7071 {
7072 for (inferior *inf : all_non_exited_inferiors (this))
7073 {
7074 if (get_remote_inferior (inf)->may_wildcard_vcont)
7075 {
7076 vcont_builder.push_action (ptid_t (inf->pid),
7077 false, GDB_SIGNAL_0);
7078 }
7079 }
7080 }
7081 }
7082
7083 vcont_builder.flush ();
7084 }
7085
7086 /* Implementation of target_has_pending_events. */
7087
7088 bool
7089 remote_target::has_pending_events ()
7090 {
7091 if (target_can_async_p ())
7092 {
7093 remote_state *rs = get_remote_state ();
7094
7095 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
7096 return true;
7097
7098 /* Note that BUFCNT can be negative, indicating sticky
7099 error. */
7100 if (rs->remote_desc->bufcnt != 0)
7101 return true;
7102 }
7103 return false;
7104 }
7105
7106 \f
7107
7108 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7109 thread, all threads of a remote process, or all threads of all
7110 processes. */
7111
7112 void
7113 remote_target::remote_stop_ns (ptid_t ptid)
7114 {
7115 struct remote_state *rs = get_remote_state ();
7116 char *p = rs->buf.data ();
7117 char *endp = p + get_remote_packet_size ();
7118
7119 /* If any thread that needs to stop was resumed but pending a vCont
7120 resume, generate a phony stop_reply. However, first check
7121 whether the thread wasn't resumed with a signal. Generating a
7122 phony stop in that case would result in losing the signal. */
7123 bool needs_commit = false;
7124 for (thread_info *tp : all_non_exited_threads (this, ptid))
7125 {
7126 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7127
7128 if (remote_thr->get_resume_state ()
7129 == resume_state::RESUMED_PENDING_VCONT)
7130 {
7131 const resumed_pending_vcont_info &info
7132 = remote_thr->resumed_pending_vcont_info ();
7133 if (info.sig != GDB_SIGNAL_0)
7134 {
7135 /* This signal must be forwarded to the inferior. We
7136 could commit-resume just this thread, but its simpler
7137 to just commit-resume everything. */
7138 needs_commit = true;
7139 break;
7140 }
7141 }
7142 }
7143
7144 if (needs_commit)
7145 commit_resumed ();
7146 else
7147 for (thread_info *tp : all_non_exited_threads (this, ptid))
7148 {
7149 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7150
7151 if (remote_thr->get_resume_state ()
7152 == resume_state::RESUMED_PENDING_VCONT)
7153 {
7154 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7155 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7156 tp->ptid.lwp (),
7157 pulongest (tp->ptid.tid ()));
7158
7159 /* Check that the thread wasn't resumed with a signal.
7160 Generating a phony stop would result in losing the
7161 signal. */
7162 const resumed_pending_vcont_info &info
7163 = remote_thr->resumed_pending_vcont_info ();
7164 gdb_assert (info.sig == GDB_SIGNAL_0);
7165
7166 stop_reply *sr = new stop_reply ();
7167 sr->ptid = tp->ptid;
7168 sr->rs = rs;
7169 sr->ws.set_stopped (GDB_SIGNAL_0);
7170 sr->arch = tp->inf->gdbarch;
7171 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7172 sr->watch_data_address = 0;
7173 sr->core = 0;
7174 this->push_stop_reply (sr);
7175
7176 /* Pretend that this thread was actually resumed on the
7177 remote target, then stopped. If we leave it in the
7178 RESUMED_PENDING_VCONT state and the commit_resumed
7179 method is called while the stop reply is still in the
7180 queue, we'll end up reporting a stop event to the core
7181 for that thread while it is running on the remote
7182 target... that would be bad. */
7183 remote_thr->set_resumed ();
7184 }
7185 }
7186
7187 if (!rs->supports_vCont.t)
7188 error (_("Remote server does not support stopping threads"));
7189
7190 if (ptid == minus_one_ptid
7191 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7192 p += xsnprintf (p, endp - p, "vCont;t");
7193 else
7194 {
7195 ptid_t nptid;
7196
7197 p += xsnprintf (p, endp - p, "vCont;t:");
7198
7199 if (ptid.is_pid ())
7200 /* All (-1) threads of process. */
7201 nptid = ptid_t (ptid.pid (), -1);
7202 else
7203 {
7204 /* Small optimization: if we already have a stop reply for
7205 this thread, no use in telling the stub we want this
7206 stopped. */
7207 if (peek_stop_reply (ptid))
7208 return;
7209
7210 nptid = ptid;
7211 }
7212
7213 write_ptid (p, endp, nptid);
7214 }
7215
7216 /* In non-stop, we get an immediate OK reply. The stop reply will
7217 come in asynchronously by notification. */
7218 putpkt (rs->buf);
7219 getpkt (&rs->buf, 0);
7220 if (strcmp (rs->buf.data (), "OK") != 0)
7221 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7222 rs->buf.data ());
7223 }
7224
7225 /* All-stop version of target_interrupt. Sends a break or a ^C to
7226 interrupt the remote target. It is undefined which thread of which
7227 process reports the interrupt. */
7228
7229 void
7230 remote_target::remote_interrupt_as ()
7231 {
7232 struct remote_state *rs = get_remote_state ();
7233
7234 rs->ctrlc_pending_p = 1;
7235
7236 /* If the inferior is stopped already, but the core didn't know
7237 about it yet, just ignore the request. The pending stop events
7238 will be collected in remote_wait. */
7239 if (stop_reply_queue_length () > 0)
7240 return;
7241
7242 /* Send interrupt_sequence to remote target. */
7243 send_interrupt_sequence ();
7244 }
7245
7246 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7247 the remote target. It is undefined which thread of which process
7248 reports the interrupt. Throws an error if the packet is not
7249 supported by the server. */
7250
7251 void
7252 remote_target::remote_interrupt_ns ()
7253 {
7254 struct remote_state *rs = get_remote_state ();
7255 char *p = rs->buf.data ();
7256 char *endp = p + get_remote_packet_size ();
7257
7258 xsnprintf (p, endp - p, "vCtrlC");
7259
7260 /* In non-stop, we get an immediate OK reply. The stop reply will
7261 come in asynchronously by notification. */
7262 putpkt (rs->buf);
7263 getpkt (&rs->buf, 0);
7264
7265 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7266 {
7267 case PACKET_OK:
7268 break;
7269 case PACKET_UNKNOWN:
7270 error (_("No support for interrupting the remote target."));
7271 case PACKET_ERROR:
7272 error (_("Interrupting target failed: %s"), rs->buf.data ());
7273 }
7274 }
7275
7276 /* Implement the to_stop function for the remote targets. */
7277
7278 void
7279 remote_target::stop (ptid_t ptid)
7280 {
7281 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7282
7283 if (target_is_non_stop_p ())
7284 remote_stop_ns (ptid);
7285 else
7286 {
7287 /* We don't currently have a way to transparently pause the
7288 remote target in all-stop mode. Interrupt it instead. */
7289 remote_interrupt_as ();
7290 }
7291 }
7292
7293 /* Implement the to_interrupt function for the remote targets. */
7294
7295 void
7296 remote_target::interrupt ()
7297 {
7298 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7299
7300 if (target_is_non_stop_p ())
7301 remote_interrupt_ns ();
7302 else
7303 remote_interrupt_as ();
7304 }
7305
7306 /* Implement the to_pass_ctrlc function for the remote targets. */
7307
7308 void
7309 remote_target::pass_ctrlc ()
7310 {
7311 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7312
7313 struct remote_state *rs = get_remote_state ();
7314
7315 /* If we're starting up, we're not fully synced yet. Quit
7316 immediately. */
7317 if (rs->starting_up)
7318 quit ();
7319 /* If ^C has already been sent once, offer to disconnect. */
7320 else if (rs->ctrlc_pending_p)
7321 interrupt_query ();
7322 else
7323 target_interrupt ();
7324 }
7325
7326 /* Ask the user what to do when an interrupt is received. */
7327
7328 void
7329 remote_target::interrupt_query ()
7330 {
7331 struct remote_state *rs = get_remote_state ();
7332
7333 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7334 {
7335 if (query (_("The target is not responding to interrupt requests.\n"
7336 "Stop debugging it? ")))
7337 {
7338 remote_unpush_target (this);
7339 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7340 }
7341 }
7342 else
7343 {
7344 if (query (_("Interrupted while waiting for the program.\n"
7345 "Give up waiting? ")))
7346 quit ();
7347 }
7348 }
7349
7350 /* Enable/disable target terminal ownership. Most targets can use
7351 terminal groups to control terminal ownership. Remote targets are
7352 different in that explicit transfer of ownership to/from GDB/target
7353 is required. */
7354
7355 void
7356 remote_target::terminal_inferior ()
7357 {
7358 /* NOTE: At this point we could also register our selves as the
7359 recipient of all input. Any characters typed could then be
7360 passed on down to the target. */
7361 }
7362
7363 void
7364 remote_target::terminal_ours ()
7365 {
7366 }
7367
7368 static void
7369 remote_console_output (const char *msg)
7370 {
7371 const char *p;
7372
7373 for (p = msg; p[0] && p[1]; p += 2)
7374 {
7375 char tb[2];
7376 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7377
7378 tb[0] = c;
7379 tb[1] = 0;
7380 gdb_stdtarg->puts (tb);
7381 }
7382 gdb_stdtarg->flush ();
7383 }
7384
7385 /* Return the length of the stop reply queue. */
7386
7387 int
7388 remote_target::stop_reply_queue_length ()
7389 {
7390 remote_state *rs = get_remote_state ();
7391 return rs->stop_reply_queue.size ();
7392 }
7393
7394 static void
7395 remote_notif_stop_parse (remote_target *remote,
7396 const notif_client *self, const char *buf,
7397 struct notif_event *event)
7398 {
7399 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7400 }
7401
7402 static void
7403 remote_notif_stop_ack (remote_target *remote,
7404 const notif_client *self, const char *buf,
7405 struct notif_event *event)
7406 {
7407 struct stop_reply *stop_reply = (struct stop_reply *) event;
7408
7409 /* acknowledge */
7410 putpkt (remote, self->ack_command);
7411
7412 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7413 the notification. It was left in the queue because we need to
7414 acknowledge it and pull the rest of the notifications out. */
7415 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7416 remote->push_stop_reply (stop_reply);
7417 }
7418
7419 static int
7420 remote_notif_stop_can_get_pending_events (remote_target *remote,
7421 const notif_client *self)
7422 {
7423 /* We can't get pending events in remote_notif_process for
7424 notification stop, and we have to do this in remote_wait_ns
7425 instead. If we fetch all queued events from stub, remote stub
7426 may exit and we have no chance to process them back in
7427 remote_wait_ns. */
7428 remote_state *rs = remote->get_remote_state ();
7429 mark_async_event_handler (rs->remote_async_inferior_event_token);
7430 return 0;
7431 }
7432
7433 stop_reply::~stop_reply ()
7434 {
7435 for (cached_reg_t &reg : regcache)
7436 xfree (reg.data);
7437 }
7438
7439 static notif_event_up
7440 remote_notif_stop_alloc_reply ()
7441 {
7442 return notif_event_up (new struct stop_reply ());
7443 }
7444
7445 /* A client of notification Stop. */
7446
7447 const notif_client notif_client_stop =
7448 {
7449 "Stop",
7450 "vStopped",
7451 remote_notif_stop_parse,
7452 remote_notif_stop_ack,
7453 remote_notif_stop_can_get_pending_events,
7454 remote_notif_stop_alloc_reply,
7455 REMOTE_NOTIF_STOP,
7456 };
7457
7458 /* If CONTEXT contains any fork child threads that have not been
7459 reported yet, remove them from the CONTEXT list. If such a
7460 thread exists it is because we are stopped at a fork catchpoint
7461 and have not yet called follow_fork, which will set up the
7462 host-side data structures for the new process. */
7463
7464 void
7465 remote_target::remove_new_fork_children (threads_listing_context *context)
7466 {
7467 const notif_client *notif = &notif_client_stop;
7468
7469 /* For any threads stopped at a fork event, remove the corresponding
7470 fork child threads from the CONTEXT list. */
7471 for (thread_info *thread : all_non_exited_threads (this))
7472 {
7473 const target_waitstatus *ws = thread_pending_fork_status (thread);
7474
7475 if (ws == nullptr)
7476 continue;
7477
7478 context->remove_thread (ws->child_ptid ());
7479 }
7480
7481 /* Check for any pending fork events (not reported or processed yet)
7482 in process PID and remove those fork child threads from the
7483 CONTEXT list as well. */
7484 remote_notif_get_pending_events (notif);
7485 for (auto &event : get_remote_state ()->stop_reply_queue)
7486 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7487 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7488 context->remove_thread (event->ws.child_ptid ());
7489 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7490 context->remove_thread (event->ptid);
7491 }
7492
7493 /* Check whether any event pending in the vStopped queue would prevent a
7494 global or process wildcard vCont action. Set *may_global_wildcard to
7495 false if we can't do a global wildcard (vCont;c), and clear the event
7496 inferior's may_wildcard_vcont flag if we can't do a process-wide
7497 wildcard resume (vCont;c:pPID.-1). */
7498
7499 void
7500 remote_target::check_pending_events_prevent_wildcard_vcont
7501 (bool *may_global_wildcard)
7502 {
7503 const notif_client *notif = &notif_client_stop;
7504
7505 remote_notif_get_pending_events (notif);
7506 for (auto &event : get_remote_state ()->stop_reply_queue)
7507 {
7508 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7509 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7510 continue;
7511
7512 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7513 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7514 *may_global_wildcard = false;
7515
7516 /* This may be the first time we heard about this process.
7517 Regardless, we must not do a global wildcard resume, otherwise
7518 we'd resume this process too. */
7519 *may_global_wildcard = false;
7520 if (event->ptid != null_ptid)
7521 {
7522 inferior *inf = find_inferior_ptid (this, event->ptid);
7523 if (inf != NULL)
7524 get_remote_inferior (inf)->may_wildcard_vcont = false;
7525 }
7526 }
7527 }
7528
7529 /* Discard all pending stop replies of inferior INF. */
7530
7531 void
7532 remote_target::discard_pending_stop_replies (struct inferior *inf)
7533 {
7534 struct stop_reply *reply;
7535 struct remote_state *rs = get_remote_state ();
7536 struct remote_notif_state *rns = rs->notif_state;
7537
7538 /* This function can be notified when an inferior exists. When the
7539 target is not remote, the notification state is NULL. */
7540 if (rs->remote_desc == NULL)
7541 return;
7542
7543 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7544
7545 /* Discard the in-flight notification. */
7546 if (reply != NULL && reply->ptid.pid () == inf->pid)
7547 {
7548 /* Leave the notification pending, since the server expects that
7549 we acknowledge it with vStopped. But clear its contents, so
7550 that later on when we acknowledge it, we also discard it. */
7551 remote_debug_printf
7552 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7553 reply->ptid.to_string().c_str(),
7554 reply->ws.to_string ().c_str ());
7555 reply->ws.set_ignore ();
7556 }
7557
7558 /* Discard the stop replies we have already pulled with
7559 vStopped. */
7560 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7561 rs->stop_reply_queue.end (),
7562 [=] (const stop_reply_up &event)
7563 {
7564 return event->ptid.pid () == inf->pid;
7565 });
7566 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7567 remote_debug_printf
7568 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7569 reply->ptid.to_string().c_str(),
7570 reply->ws.to_string ().c_str ());
7571 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7572 }
7573
7574 /* Discard the stop replies for RS in stop_reply_queue. */
7575
7576 void
7577 remote_target::discard_pending_stop_replies_in_queue ()
7578 {
7579 remote_state *rs = get_remote_state ();
7580
7581 /* Discard the stop replies we have already pulled with
7582 vStopped. */
7583 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7584 rs->stop_reply_queue.end (),
7585 [=] (const stop_reply_up &event)
7586 {
7587 return event->rs == rs;
7588 });
7589 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7590 }
7591
7592 /* Remove the first reply in 'stop_reply_queue' which matches
7593 PTID. */
7594
7595 struct stop_reply *
7596 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7597 {
7598 remote_state *rs = get_remote_state ();
7599
7600 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7601 rs->stop_reply_queue.end (),
7602 [=] (const stop_reply_up &event)
7603 {
7604 return event->ptid.matches (ptid);
7605 });
7606 struct stop_reply *result;
7607 if (iter == rs->stop_reply_queue.end ())
7608 result = nullptr;
7609 else
7610 {
7611 result = iter->release ();
7612 rs->stop_reply_queue.erase (iter);
7613 }
7614
7615 if (notif_debug)
7616 gdb_printf (gdb_stdlog,
7617 "notif: discard queued event: 'Stop' in %s\n",
7618 ptid.to_string ().c_str ());
7619
7620 return result;
7621 }
7622
7623 /* Look for a queued stop reply belonging to PTID. If one is found,
7624 remove it from the queue, and return it. Returns NULL if none is
7625 found. If there are still queued events left to process, tell the
7626 event loop to get back to target_wait soon. */
7627
7628 struct stop_reply *
7629 remote_target::queued_stop_reply (ptid_t ptid)
7630 {
7631 remote_state *rs = get_remote_state ();
7632 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7633
7634 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7635 {
7636 /* There's still at least an event left. */
7637 mark_async_event_handler (rs->remote_async_inferior_event_token);
7638 }
7639
7640 return r;
7641 }
7642
7643 /* Push a fully parsed stop reply in the stop reply queue. Since we
7644 know that we now have at least one queued event left to pass to the
7645 core side, tell the event loop to get back to target_wait soon. */
7646
7647 void
7648 remote_target::push_stop_reply (struct stop_reply *new_event)
7649 {
7650 remote_state *rs = get_remote_state ();
7651 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7652
7653 if (notif_debug)
7654 gdb_printf (gdb_stdlog,
7655 "notif: push 'Stop' %s to queue %d\n",
7656 new_event->ptid.to_string ().c_str (),
7657 int (rs->stop_reply_queue.size ()));
7658
7659 /* Mark the pending event queue only if async mode is currently enabled.
7660 If async mode is not currently enabled, then, if it later becomes
7661 enabled, and there are events in this queue, we will mark the event
7662 token at that point, see remote_target::async. */
7663 if (target_is_async_p ())
7664 mark_async_event_handler (rs->remote_async_inferior_event_token);
7665 }
7666
7667 /* Returns true if we have a stop reply for PTID. */
7668
7669 int
7670 remote_target::peek_stop_reply (ptid_t ptid)
7671 {
7672 remote_state *rs = get_remote_state ();
7673 for (auto &event : rs->stop_reply_queue)
7674 if (ptid == event->ptid
7675 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7676 return 1;
7677 return 0;
7678 }
7679
7680 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7681 starting with P and ending with PEND matches PREFIX. */
7682
7683 static int
7684 strprefix (const char *p, const char *pend, const char *prefix)
7685 {
7686 for ( ; p < pend; p++, prefix++)
7687 if (*p != *prefix)
7688 return 0;
7689 return *prefix == '\0';
7690 }
7691
7692 /* Parse the stop reply in BUF. Either the function succeeds, and the
7693 result is stored in EVENT, or throws an error. */
7694
7695 void
7696 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7697 {
7698 remote_arch_state *rsa = NULL;
7699 ULONGEST addr;
7700 const char *p;
7701 int skipregs = 0;
7702
7703 event->ptid = null_ptid;
7704 event->rs = get_remote_state ();
7705 event->ws.set_ignore ();
7706 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7707 event->regcache.clear ();
7708 event->core = -1;
7709
7710 switch (buf[0])
7711 {
7712 case 'T': /* Status with PC, SP, FP, ... */
7713 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7714 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7715 ss = signal number
7716 n... = register number
7717 r... = register contents
7718 */
7719
7720 p = &buf[3]; /* after Txx */
7721 while (*p)
7722 {
7723 const char *p1;
7724 int fieldsize;
7725
7726 p1 = strchr (p, ':');
7727 if (p1 == NULL)
7728 error (_("Malformed packet(a) (missing colon): %s\n\
7729 Packet: '%s'\n"),
7730 p, buf);
7731 if (p == p1)
7732 error (_("Malformed packet(a) (missing register number): %s\n\
7733 Packet: '%s'\n"),
7734 p, buf);
7735
7736 /* Some "registers" are actually extended stop information.
7737 Note if you're adding a new entry here: GDB 7.9 and
7738 earlier assume that all register "numbers" that start
7739 with an hex digit are real register numbers. Make sure
7740 the server only sends such a packet if it knows the
7741 client understands it. */
7742
7743 if (strprefix (p, p1, "thread"))
7744 event->ptid = read_ptid (++p1, &p);
7745 else if (strprefix (p, p1, "syscall_entry"))
7746 {
7747 ULONGEST sysno;
7748
7749 p = unpack_varlen_hex (++p1, &sysno);
7750 event->ws.set_syscall_entry ((int) sysno);
7751 }
7752 else if (strprefix (p, p1, "syscall_return"))
7753 {
7754 ULONGEST sysno;
7755
7756 p = unpack_varlen_hex (++p1, &sysno);
7757 event->ws.set_syscall_return ((int) sysno);
7758 }
7759 else if (strprefix (p, p1, "watch")
7760 || strprefix (p, p1, "rwatch")
7761 || strprefix (p, p1, "awatch"))
7762 {
7763 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7764 p = unpack_varlen_hex (++p1, &addr);
7765 event->watch_data_address = (CORE_ADDR) addr;
7766 }
7767 else if (strprefix (p, p1, "swbreak"))
7768 {
7769 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7770
7771 /* Make sure the stub doesn't forget to indicate support
7772 with qSupported. */
7773 if (m_features.packet_support (PACKET_swbreak_feature)
7774 != PACKET_ENABLE)
7775 error (_("Unexpected swbreak stop reason"));
7776
7777 /* The value part is documented as "must be empty",
7778 though we ignore it, in case we ever decide to make
7779 use of it in a backward compatible way. */
7780 p = strchrnul (p1 + 1, ';');
7781 }
7782 else if (strprefix (p, p1, "hwbreak"))
7783 {
7784 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7785
7786 /* Make sure the stub doesn't forget to indicate support
7787 with qSupported. */
7788 if (m_features.packet_support (PACKET_hwbreak_feature)
7789 != PACKET_ENABLE)
7790 error (_("Unexpected hwbreak stop reason"));
7791
7792 /* See above. */
7793 p = strchrnul (p1 + 1, ';');
7794 }
7795 else if (strprefix (p, p1, "library"))
7796 {
7797 event->ws.set_loaded ();
7798 p = strchrnul (p1 + 1, ';');
7799 }
7800 else if (strprefix (p, p1, "replaylog"))
7801 {
7802 event->ws.set_no_history ();
7803 /* p1 will indicate "begin" or "end", but it makes
7804 no difference for now, so ignore it. */
7805 p = strchrnul (p1 + 1, ';');
7806 }
7807 else if (strprefix (p, p1, "core"))
7808 {
7809 ULONGEST c;
7810
7811 p = unpack_varlen_hex (++p1, &c);
7812 event->core = c;
7813 }
7814 else if (strprefix (p, p1, "fork"))
7815 event->ws.set_forked (read_ptid (++p1, &p));
7816 else if (strprefix (p, p1, "vfork"))
7817 event->ws.set_vforked (read_ptid (++p1, &p));
7818 else if (strprefix (p, p1, "vforkdone"))
7819 {
7820 event->ws.set_vfork_done ();
7821 p = strchrnul (p1 + 1, ';');
7822 }
7823 else if (strprefix (p, p1, "exec"))
7824 {
7825 ULONGEST ignored;
7826 int pathlen;
7827
7828 /* Determine the length of the execd pathname. */
7829 p = unpack_varlen_hex (++p1, &ignored);
7830 pathlen = (p - p1) / 2;
7831
7832 /* Save the pathname for event reporting and for
7833 the next run command. */
7834 gdb::unique_xmalloc_ptr<char> pathname
7835 ((char *) xmalloc (pathlen + 1));
7836 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7837 pathname.get ()[pathlen] = '\0';
7838
7839 /* This is freed during event handling. */
7840 event->ws.set_execd (std::move (pathname));
7841
7842 /* Skip the registers included in this packet, since
7843 they may be for an architecture different from the
7844 one used by the original program. */
7845 skipregs = 1;
7846 }
7847 else if (strprefix (p, p1, "create"))
7848 {
7849 event->ws.set_thread_created ();
7850 p = strchrnul (p1 + 1, ';');
7851 }
7852 else
7853 {
7854 ULONGEST pnum;
7855 const char *p_temp;
7856
7857 if (skipregs)
7858 {
7859 p = strchrnul (p1 + 1, ';');
7860 p++;
7861 continue;
7862 }
7863
7864 /* Maybe a real ``P'' register number. */
7865 p_temp = unpack_varlen_hex (p, &pnum);
7866 /* If the first invalid character is the colon, we got a
7867 register number. Otherwise, it's an unknown stop
7868 reason. */
7869 if (p_temp == p1)
7870 {
7871 /* If we haven't parsed the event's thread yet, find
7872 it now, in order to find the architecture of the
7873 reported expedited registers. */
7874 if (event->ptid == null_ptid)
7875 {
7876 /* If there is no thread-id information then leave
7877 the event->ptid as null_ptid. Later in
7878 process_stop_reply we will pick a suitable
7879 thread. */
7880 const char *thr = strstr (p1 + 1, ";thread:");
7881 if (thr != NULL)
7882 event->ptid = read_ptid (thr + strlen (";thread:"),
7883 NULL);
7884 }
7885
7886 if (rsa == NULL)
7887 {
7888 inferior *inf
7889 = (event->ptid == null_ptid
7890 ? NULL
7891 : find_inferior_ptid (this, event->ptid));
7892 /* If this is the first time we learn anything
7893 about this process, skip the registers
7894 included in this packet, since we don't yet
7895 know which architecture to use to parse them.
7896 We'll determine the architecture later when
7897 we process the stop reply and retrieve the
7898 target description, via
7899 remote_notice_new_inferior ->
7900 post_create_inferior. */
7901 if (inf == NULL)
7902 {
7903 p = strchrnul (p1 + 1, ';');
7904 p++;
7905 continue;
7906 }
7907
7908 event->arch = inf->gdbarch;
7909 rsa = event->rs->get_remote_arch_state (event->arch);
7910 }
7911
7912 packet_reg *reg
7913 = packet_reg_from_pnum (event->arch, rsa, pnum);
7914 cached_reg_t cached_reg;
7915
7916 if (reg == NULL)
7917 error (_("Remote sent bad register number %s: %s\n\
7918 Packet: '%s'\n"),
7919 hex_string (pnum), p, buf);
7920
7921 cached_reg.num = reg->regnum;
7922 cached_reg.data = (gdb_byte *)
7923 xmalloc (register_size (event->arch, reg->regnum));
7924
7925 p = p1 + 1;
7926 fieldsize = hex2bin (p, cached_reg.data,
7927 register_size (event->arch, reg->regnum));
7928 p += 2 * fieldsize;
7929 if (fieldsize < register_size (event->arch, reg->regnum))
7930 warning (_("Remote reply is too short: %s"), buf);
7931
7932 event->regcache.push_back (cached_reg);
7933 }
7934 else
7935 {
7936 /* Not a number. Silently skip unknown optional
7937 info. */
7938 p = strchrnul (p1 + 1, ';');
7939 }
7940 }
7941
7942 if (*p != ';')
7943 error (_("Remote register badly formatted: %s\nhere: %s"),
7944 buf, p);
7945 ++p;
7946 }
7947
7948 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7949 break;
7950
7951 /* fall through */
7952 case 'S': /* Old style status, just signal only. */
7953 {
7954 int sig;
7955
7956 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7957 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7958 event->ws.set_stopped ((enum gdb_signal) sig);
7959 else
7960 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7961 }
7962 break;
7963 case 'w': /* Thread exited. */
7964 {
7965 ULONGEST value;
7966
7967 p = unpack_varlen_hex (&buf[1], &value);
7968 event->ws.set_thread_exited (value);
7969 if (*p != ';')
7970 error (_("stop reply packet badly formatted: %s"), buf);
7971 event->ptid = read_ptid (++p, NULL);
7972 break;
7973 }
7974 case 'W': /* Target exited. */
7975 case 'X':
7976 {
7977 ULONGEST value;
7978
7979 /* GDB used to accept only 2 hex chars here. Stubs should
7980 only send more if they detect GDB supports multi-process
7981 support. */
7982 p = unpack_varlen_hex (&buf[1], &value);
7983
7984 if (buf[0] == 'W')
7985 {
7986 /* The remote process exited. */
7987 event->ws.set_exited (value);
7988 }
7989 else
7990 {
7991 /* The remote process exited with a signal. */
7992 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7993 event->ws.set_signalled ((enum gdb_signal) value);
7994 else
7995 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7996 }
7997
7998 /* If no process is specified, return null_ptid, and let the
7999 caller figure out the right process to use. */
8000 int pid = 0;
8001 if (*p == '\0')
8002 ;
8003 else if (*p == ';')
8004 {
8005 p++;
8006
8007 if (*p == '\0')
8008 ;
8009 else if (startswith (p, "process:"))
8010 {
8011 ULONGEST upid;
8012
8013 p += sizeof ("process:") - 1;
8014 unpack_varlen_hex (p, &upid);
8015 pid = upid;
8016 }
8017 else
8018 error (_("unknown stop reply packet: %s"), buf);
8019 }
8020 else
8021 error (_("unknown stop reply packet: %s"), buf);
8022 event->ptid = ptid_t (pid);
8023 }
8024 break;
8025 case 'N':
8026 event->ws.set_no_resumed ();
8027 event->ptid = minus_one_ptid;
8028 break;
8029 }
8030 }
8031
8032 /* When the stub wants to tell GDB about a new notification reply, it
8033 sends a notification (%Stop, for example). Those can come it at
8034 any time, hence, we have to make sure that any pending
8035 putpkt/getpkt sequence we're making is finished, before querying
8036 the stub for more events with the corresponding ack command
8037 (vStopped, for example). E.g., if we started a vStopped sequence
8038 immediately upon receiving the notification, something like this
8039 could happen:
8040
8041 1.1) --> Hg 1
8042 1.2) <-- OK
8043 1.3) --> g
8044 1.4) <-- %Stop
8045 1.5) --> vStopped
8046 1.6) <-- (registers reply to step #1.3)
8047
8048 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8049 query.
8050
8051 To solve this, whenever we parse a %Stop notification successfully,
8052 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8053 doing whatever we were doing:
8054
8055 2.1) --> Hg 1
8056 2.2) <-- OK
8057 2.3) --> g
8058 2.4) <-- %Stop
8059 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8060 2.5) <-- (registers reply to step #2.3)
8061
8062 Eventually after step #2.5, we return to the event loop, which
8063 notices there's an event on the
8064 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8065 associated callback --- the function below. At this point, we're
8066 always safe to start a vStopped sequence. :
8067
8068 2.6) --> vStopped
8069 2.7) <-- T05 thread:2
8070 2.8) --> vStopped
8071 2.9) --> OK
8072 */
8073
8074 void
8075 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8076 {
8077 struct remote_state *rs = get_remote_state ();
8078
8079 if (rs->notif_state->pending_event[nc->id] != NULL)
8080 {
8081 if (notif_debug)
8082 gdb_printf (gdb_stdlog,
8083 "notif: process: '%s' ack pending event\n",
8084 nc->name);
8085
8086 /* acknowledge */
8087 nc->ack (this, nc, rs->buf.data (),
8088 rs->notif_state->pending_event[nc->id]);
8089 rs->notif_state->pending_event[nc->id] = NULL;
8090
8091 while (1)
8092 {
8093 getpkt (&rs->buf, 0);
8094 if (strcmp (rs->buf.data (), "OK") == 0)
8095 break;
8096 else
8097 remote_notif_ack (this, nc, rs->buf.data ());
8098 }
8099 }
8100 else
8101 {
8102 if (notif_debug)
8103 gdb_printf (gdb_stdlog,
8104 "notif: process: '%s' no pending reply\n",
8105 nc->name);
8106 }
8107 }
8108
8109 /* Wrapper around remote_target::remote_notif_get_pending_events to
8110 avoid having to export the whole remote_target class. */
8111
8112 void
8113 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8114 {
8115 remote->remote_notif_get_pending_events (nc);
8116 }
8117
8118 /* Called from process_stop_reply when the stop packet we are responding
8119 to didn't include a process-id or thread-id. STATUS is the stop event
8120 we are responding to.
8121
8122 It is the task of this function to select a suitable thread (or process)
8123 and return its ptid, this is the thread (or process) we will assume the
8124 stop event came from.
8125
8126 In some cases there isn't really any choice about which thread (or
8127 process) is selected, a basic remote with a single process containing a
8128 single thread might choose not to send any process-id or thread-id in
8129 its stop packets, this function will select and return the one and only
8130 thread.
8131
8132 However, if a target supports multiple threads (or processes) and still
8133 doesn't include a thread-id (or process-id) in its stop packet then
8134 first, this is a badly behaving target, and second, we're going to have
8135 to select a thread (or process) at random and use that. This function
8136 will print a warning to the user if it detects that there is the
8137 possibility that GDB is guessing which thread (or process) to
8138 report.
8139
8140 Note that this is called before GDB fetches the updated thread list from the
8141 target. So it's possible for the stop reply to be ambiguous and for GDB to
8142 not realize it. For example, if there's initially one thread, the target
8143 spawns a second thread, and then sends a stop reply without an id that
8144 concerns the first thread. GDB will assume the stop reply is about the
8145 first thread - the only thread it knows about - without printing a warning.
8146 Anyway, if the remote meant for the stop reply to be about the second thread,
8147 then it would be really broken, because GDB doesn't know about that thread
8148 yet. */
8149
8150 ptid_t
8151 remote_target::select_thread_for_ambiguous_stop_reply
8152 (const target_waitstatus &status)
8153 {
8154 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8155
8156 /* Some stop events apply to all threads in an inferior, while others
8157 only apply to a single thread. */
8158 bool process_wide_stop
8159 = (status.kind () == TARGET_WAITKIND_EXITED
8160 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8161
8162 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8163
8164 thread_info *first_resumed_thread = nullptr;
8165 bool ambiguous = false;
8166
8167 /* Consider all non-exited threads of the target, find the first resumed
8168 one. */
8169 for (thread_info *thr : all_non_exited_threads (this))
8170 {
8171 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8172
8173 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8174 continue;
8175
8176 if (first_resumed_thread == nullptr)
8177 first_resumed_thread = thr;
8178 else if (!process_wide_stop
8179 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8180 ambiguous = true;
8181 }
8182
8183 gdb_assert (first_resumed_thread != nullptr);
8184
8185 remote_debug_printf ("first resumed thread is %s",
8186 pid_to_str (first_resumed_thread->ptid).c_str ());
8187 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8188
8189 /* Warn if the remote target is sending ambiguous stop replies. */
8190 if (ambiguous)
8191 {
8192 static bool warned = false;
8193
8194 if (!warned)
8195 {
8196 /* If you are seeing this warning then the remote target has
8197 stopped without specifying a thread-id, but the target
8198 does have multiple threads (or inferiors), and so GDB is
8199 having to guess which thread stopped.
8200
8201 Examples of what might cause this are the target sending
8202 and 'S' stop packet, or a 'T' stop packet and not
8203 including a thread-id.
8204
8205 Additionally, the target might send a 'W' or 'X packet
8206 without including a process-id, when the target has
8207 multiple running inferiors. */
8208 if (process_wide_stop)
8209 warning (_("multi-inferior target stopped without "
8210 "sending a process-id, using first "
8211 "non-exited inferior"));
8212 else
8213 warning (_("multi-threaded target stopped without "
8214 "sending a thread-id, using first "
8215 "non-exited thread"));
8216 warned = true;
8217 }
8218 }
8219
8220 /* If this is a stop for all threads then don't use a particular threads
8221 ptid, instead create a new ptid where only the pid field is set. */
8222 if (process_wide_stop)
8223 return ptid_t (first_resumed_thread->ptid.pid ());
8224 else
8225 return first_resumed_thread->ptid;
8226 }
8227
8228 /* Called when it is decided that STOP_REPLY holds the info of the
8229 event that is to be returned to the core. This function always
8230 destroys STOP_REPLY. */
8231
8232 ptid_t
8233 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8234 struct target_waitstatus *status)
8235 {
8236 *status = stop_reply->ws;
8237 ptid_t ptid = stop_reply->ptid;
8238
8239 /* If no thread/process was reported by the stub then select a suitable
8240 thread/process. */
8241 if (ptid == null_ptid)
8242 ptid = select_thread_for_ambiguous_stop_reply (*status);
8243 gdb_assert (ptid != null_ptid);
8244
8245 if (status->kind () != TARGET_WAITKIND_EXITED
8246 && status->kind () != TARGET_WAITKIND_SIGNALLED
8247 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8248 {
8249 /* Expedited registers. */
8250 if (!stop_reply->regcache.empty ())
8251 {
8252 struct regcache *regcache
8253 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8254
8255 for (cached_reg_t &reg : stop_reply->regcache)
8256 {
8257 regcache->raw_supply (reg.num, reg.data);
8258 xfree (reg.data);
8259 }
8260
8261 stop_reply->regcache.clear ();
8262 }
8263
8264 remote_notice_new_inferior (ptid, false);
8265 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8266 remote_thr->core = stop_reply->core;
8267 remote_thr->stop_reason = stop_reply->stop_reason;
8268 remote_thr->watch_data_address = stop_reply->watch_data_address;
8269
8270 if (target_is_non_stop_p ())
8271 {
8272 /* If the target works in non-stop mode, a stop-reply indicates that
8273 only this thread stopped. */
8274 remote_thr->set_not_resumed ();
8275 }
8276 else
8277 {
8278 /* If the target works in all-stop mode, a stop-reply indicates that
8279 all the target's threads stopped. */
8280 for (thread_info *tp : all_non_exited_threads (this))
8281 get_remote_thread_info (tp)->set_not_resumed ();
8282 }
8283 }
8284
8285 delete stop_reply;
8286 return ptid;
8287 }
8288
8289 /* The non-stop mode version of target_wait. */
8290
8291 ptid_t
8292 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8293 target_wait_flags options)
8294 {
8295 struct remote_state *rs = get_remote_state ();
8296 struct stop_reply *stop_reply;
8297 int ret;
8298 int is_notif = 0;
8299
8300 /* If in non-stop mode, get out of getpkt even if a
8301 notification is received. */
8302
8303 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8304 while (1)
8305 {
8306 if (ret != -1 && !is_notif)
8307 switch (rs->buf[0])
8308 {
8309 case 'E': /* Error of some sort. */
8310 /* We're out of sync with the target now. Did it continue
8311 or not? We can't tell which thread it was in non-stop,
8312 so just ignore this. */
8313 warning (_("Remote failure reply: %s"), rs->buf.data ());
8314 break;
8315 case 'O': /* Console output. */
8316 remote_console_output (&rs->buf[1]);
8317 break;
8318 default:
8319 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8320 break;
8321 }
8322
8323 /* Acknowledge a pending stop reply that may have arrived in the
8324 mean time. */
8325 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8326 remote_notif_get_pending_events (&notif_client_stop);
8327
8328 /* If indeed we noticed a stop reply, we're done. */
8329 stop_reply = queued_stop_reply (ptid);
8330 if (stop_reply != NULL)
8331 return process_stop_reply (stop_reply, status);
8332
8333 /* Still no event. If we're just polling for an event, then
8334 return to the event loop. */
8335 if (options & TARGET_WNOHANG)
8336 {
8337 status->set_ignore ();
8338 return minus_one_ptid;
8339 }
8340
8341 /* Otherwise do a blocking wait. */
8342 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8343 }
8344 }
8345
8346 /* Return the first resumed thread. */
8347
8348 static ptid_t
8349 first_remote_resumed_thread (remote_target *target)
8350 {
8351 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8352 if (tp->resumed ())
8353 return tp->ptid;
8354 return null_ptid;
8355 }
8356
8357 /* Wait until the remote machine stops, then return, storing status in
8358 STATUS just as `wait' would. */
8359
8360 ptid_t
8361 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8362 target_wait_flags options)
8363 {
8364 struct remote_state *rs = get_remote_state ();
8365 ptid_t event_ptid = null_ptid;
8366 char *buf;
8367 struct stop_reply *stop_reply;
8368
8369 again:
8370
8371 status->set_ignore ();
8372
8373 stop_reply = queued_stop_reply (ptid);
8374 if (stop_reply != NULL)
8375 {
8376 /* None of the paths that push a stop reply onto the queue should
8377 have set the waiting_for_stop_reply flag. */
8378 gdb_assert (!rs->waiting_for_stop_reply);
8379 event_ptid = process_stop_reply (stop_reply, status);
8380 }
8381 else
8382 {
8383 int forever = ((options & TARGET_WNOHANG) == 0
8384 && rs->wait_forever_enabled_p);
8385
8386 if (!rs->waiting_for_stop_reply)
8387 {
8388 status->set_no_resumed ();
8389 return minus_one_ptid;
8390 }
8391
8392 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8393 _never_ wait for ever -> test on target_is_async_p().
8394 However, before we do that we need to ensure that the caller
8395 knows how to take the target into/out of async mode. */
8396 int is_notif;
8397 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8398
8399 /* GDB gets a notification. Return to core as this event is
8400 not interesting. */
8401 if (ret != -1 && is_notif)
8402 return minus_one_ptid;
8403
8404 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8405 return minus_one_ptid;
8406
8407 buf = rs->buf.data ();
8408
8409 /* Assume that the target has acknowledged Ctrl-C unless we receive
8410 an 'F' or 'O' packet. */
8411 if (buf[0] != 'F' && buf[0] != 'O')
8412 rs->ctrlc_pending_p = 0;
8413
8414 switch (buf[0])
8415 {
8416 case 'E': /* Error of some sort. */
8417 /* We're out of sync with the target now. Did it continue or
8418 not? Not is more likely, so report a stop. */
8419 rs->waiting_for_stop_reply = 0;
8420
8421 warning (_("Remote failure reply: %s"), buf);
8422 status->set_stopped (GDB_SIGNAL_0);
8423 break;
8424 case 'F': /* File-I/O request. */
8425 /* GDB may access the inferior memory while handling the File-I/O
8426 request, but we don't want GDB accessing memory while waiting
8427 for a stop reply. See the comments in putpkt_binary. Set
8428 waiting_for_stop_reply to 0 temporarily. */
8429 rs->waiting_for_stop_reply = 0;
8430 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8431 rs->ctrlc_pending_p = 0;
8432 /* GDB handled the File-I/O request, and the target is running
8433 again. Keep waiting for events. */
8434 rs->waiting_for_stop_reply = 1;
8435 break;
8436 case 'N': case 'T': case 'S': case 'X': case 'W':
8437 {
8438 /* There is a stop reply to handle. */
8439 rs->waiting_for_stop_reply = 0;
8440
8441 stop_reply
8442 = (struct stop_reply *) remote_notif_parse (this,
8443 &notif_client_stop,
8444 rs->buf.data ());
8445
8446 event_ptid = process_stop_reply (stop_reply, status);
8447 break;
8448 }
8449 case 'O': /* Console output. */
8450 remote_console_output (buf + 1);
8451 break;
8452 case '\0':
8453 if (rs->last_sent_signal != GDB_SIGNAL_0)
8454 {
8455 /* Zero length reply means that we tried 'S' or 'C' and the
8456 remote system doesn't support it. */
8457 target_terminal::ours_for_output ();
8458 gdb_printf
8459 ("Can't send signals to this remote system. %s not sent.\n",
8460 gdb_signal_to_name (rs->last_sent_signal));
8461 rs->last_sent_signal = GDB_SIGNAL_0;
8462 target_terminal::inferior ();
8463
8464 strcpy (buf, rs->last_sent_step ? "s" : "c");
8465 putpkt (buf);
8466 break;
8467 }
8468 /* fallthrough */
8469 default:
8470 warning (_("Invalid remote reply: %s"), buf);
8471 break;
8472 }
8473 }
8474
8475 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8476 return minus_one_ptid;
8477 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8478 {
8479 /* Nothing interesting happened. If we're doing a non-blocking
8480 poll, we're done. Otherwise, go back to waiting. */
8481 if (options & TARGET_WNOHANG)
8482 return minus_one_ptid;
8483 else
8484 goto again;
8485 }
8486 else if (status->kind () != TARGET_WAITKIND_EXITED
8487 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8488 {
8489 if (event_ptid != null_ptid)
8490 record_currthread (rs, event_ptid);
8491 else
8492 event_ptid = first_remote_resumed_thread (this);
8493 }
8494 else
8495 {
8496 /* A process exit. Invalidate our notion of current thread. */
8497 record_currthread (rs, minus_one_ptid);
8498 /* It's possible that the packet did not include a pid. */
8499 if (event_ptid == null_ptid)
8500 event_ptid = first_remote_resumed_thread (this);
8501 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8502 if (event_ptid == null_ptid)
8503 event_ptid = magic_null_ptid;
8504 }
8505
8506 return event_ptid;
8507 }
8508
8509 /* Wait until the remote machine stops, then return, storing status in
8510 STATUS just as `wait' would. */
8511
8512 ptid_t
8513 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8514 target_wait_flags options)
8515 {
8516 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8517
8518 remote_state *rs = get_remote_state ();
8519
8520 /* Start by clearing the flag that asks for our wait method to be called,
8521 we'll mark it again at the end if needed. If the target is not in
8522 async mode then the async token should not be marked. */
8523 if (target_is_async_p ())
8524 clear_async_event_handler (rs->remote_async_inferior_event_token);
8525 else
8526 gdb_assert (!async_event_handler_marked
8527 (rs->remote_async_inferior_event_token));
8528
8529 ptid_t event_ptid;
8530
8531 if (target_is_non_stop_p ())
8532 event_ptid = wait_ns (ptid, status, options);
8533 else
8534 event_ptid = wait_as (ptid, status, options);
8535
8536 if (target_is_async_p ())
8537 {
8538 /* If there are events left in the queue, or unacknowledged
8539 notifications, then tell the event loop to call us again. */
8540 if (!rs->stop_reply_queue.empty ()
8541 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8542 mark_async_event_handler (rs->remote_async_inferior_event_token);
8543 }
8544
8545 return event_ptid;
8546 }
8547
8548 /* Fetch a single register using a 'p' packet. */
8549
8550 int
8551 remote_target::fetch_register_using_p (struct regcache *regcache,
8552 packet_reg *reg)
8553 {
8554 struct gdbarch *gdbarch = regcache->arch ();
8555 struct remote_state *rs = get_remote_state ();
8556 char *buf, *p;
8557 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8558 int i;
8559
8560 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8561 return 0;
8562
8563 if (reg->pnum == -1)
8564 return 0;
8565
8566 p = rs->buf.data ();
8567 *p++ = 'p';
8568 p += hexnumstr (p, reg->pnum);
8569 *p++ = '\0';
8570 putpkt (rs->buf);
8571 getpkt (&rs->buf, 0);
8572
8573 buf = rs->buf.data ();
8574
8575 switch (m_features.packet_ok (rs->buf, PACKET_p))
8576 {
8577 case PACKET_OK:
8578 break;
8579 case PACKET_UNKNOWN:
8580 return 0;
8581 case PACKET_ERROR:
8582 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8583 gdbarch_register_name (regcache->arch (),
8584 reg->regnum),
8585 buf);
8586 }
8587
8588 /* If this register is unfetchable, tell the regcache. */
8589 if (buf[0] == 'x')
8590 {
8591 regcache->raw_supply (reg->regnum, NULL);
8592 return 1;
8593 }
8594
8595 /* Otherwise, parse and supply the value. */
8596 p = buf;
8597 i = 0;
8598 while (p[0] != 0)
8599 {
8600 if (p[1] == 0)
8601 error (_("fetch_register_using_p: early buf termination"));
8602
8603 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8604 p += 2;
8605 }
8606 regcache->raw_supply (reg->regnum, regp);
8607 return 1;
8608 }
8609
8610 /* Fetch the registers included in the target's 'g' packet. */
8611
8612 int
8613 remote_target::send_g_packet ()
8614 {
8615 struct remote_state *rs = get_remote_state ();
8616 int buf_len;
8617
8618 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8619 putpkt (rs->buf);
8620 getpkt (&rs->buf, 0);
8621 if (packet_check_result (rs->buf) == PACKET_ERROR)
8622 error (_("Could not read registers; remote failure reply '%s'"),
8623 rs->buf.data ());
8624
8625 /* We can get out of synch in various cases. If the first character
8626 in the buffer is not a hex character, assume that has happened
8627 and try to fetch another packet to read. */
8628 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8629 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8630 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8631 && rs->buf[0] != 'x') /* New: unavailable register value. */
8632 {
8633 remote_debug_printf ("Bad register packet; fetching a new packet");
8634 getpkt (&rs->buf, 0);
8635 }
8636
8637 buf_len = strlen (rs->buf.data ());
8638
8639 /* Sanity check the received packet. */
8640 if (buf_len % 2 != 0)
8641 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8642
8643 return buf_len / 2;
8644 }
8645
8646 void
8647 remote_target::process_g_packet (struct regcache *regcache)
8648 {
8649 struct gdbarch *gdbarch = regcache->arch ();
8650 struct remote_state *rs = get_remote_state ();
8651 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8652 int i, buf_len;
8653 char *p;
8654 char *regs;
8655
8656 buf_len = strlen (rs->buf.data ());
8657
8658 /* Further sanity checks, with knowledge of the architecture. */
8659 if (buf_len > 2 * rsa->sizeof_g_packet)
8660 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8661 "bytes): %s"),
8662 rsa->sizeof_g_packet, buf_len / 2,
8663 rs->buf.data ());
8664
8665 /* Save the size of the packet sent to us by the target. It is used
8666 as a heuristic when determining the max size of packets that the
8667 target can safely receive. */
8668 if (rsa->actual_register_packet_size == 0)
8669 rsa->actual_register_packet_size = buf_len;
8670
8671 /* If this is smaller than we guessed the 'g' packet would be,
8672 update our records. A 'g' reply that doesn't include a register's
8673 value implies either that the register is not available, or that
8674 the 'p' packet must be used. */
8675 if (buf_len < 2 * rsa->sizeof_g_packet)
8676 {
8677 long sizeof_g_packet = buf_len / 2;
8678
8679 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8680 {
8681 long offset = rsa->regs[i].offset;
8682 long reg_size = register_size (gdbarch, i);
8683
8684 if (rsa->regs[i].pnum == -1)
8685 continue;
8686
8687 if (offset >= sizeof_g_packet)
8688 rsa->regs[i].in_g_packet = 0;
8689 else if (offset + reg_size > sizeof_g_packet)
8690 error (_("Truncated register %d in remote 'g' packet"), i);
8691 else
8692 rsa->regs[i].in_g_packet = 1;
8693 }
8694
8695 /* Looks valid enough, we can assume this is the correct length
8696 for a 'g' packet. It's important not to adjust
8697 rsa->sizeof_g_packet if we have truncated registers otherwise
8698 this "if" won't be run the next time the method is called
8699 with a packet of the same size and one of the internal errors
8700 below will trigger instead. */
8701 rsa->sizeof_g_packet = sizeof_g_packet;
8702 }
8703
8704 regs = (char *) alloca (rsa->sizeof_g_packet);
8705
8706 /* Unimplemented registers read as all bits zero. */
8707 memset (regs, 0, rsa->sizeof_g_packet);
8708
8709 /* Reply describes registers byte by byte, each byte encoded as two
8710 hex characters. Suck them all up, then supply them to the
8711 register cacheing/storage mechanism. */
8712
8713 p = rs->buf.data ();
8714 for (i = 0; i < rsa->sizeof_g_packet; i++)
8715 {
8716 if (p[0] == 0 || p[1] == 0)
8717 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8718 internal_error (_("unexpected end of 'g' packet reply"));
8719
8720 if (p[0] == 'x' && p[1] == 'x')
8721 regs[i] = 0; /* 'x' */
8722 else
8723 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8724 p += 2;
8725 }
8726
8727 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8728 {
8729 struct packet_reg *r = &rsa->regs[i];
8730 long reg_size = register_size (gdbarch, i);
8731
8732 if (r->in_g_packet)
8733 {
8734 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8735 /* This shouldn't happen - we adjusted in_g_packet above. */
8736 internal_error (_("unexpected end of 'g' packet reply"));
8737 else if (rs->buf[r->offset * 2] == 'x')
8738 {
8739 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8740 /* The register isn't available, mark it as such (at
8741 the same time setting the value to zero). */
8742 regcache->raw_supply (r->regnum, NULL);
8743 }
8744 else
8745 regcache->raw_supply (r->regnum, regs + r->offset);
8746 }
8747 }
8748 }
8749
8750 void
8751 remote_target::fetch_registers_using_g (struct regcache *regcache)
8752 {
8753 send_g_packet ();
8754 process_g_packet (regcache);
8755 }
8756
8757 /* Make the remote selected traceframe match GDB's selected
8758 traceframe. */
8759
8760 void
8761 remote_target::set_remote_traceframe ()
8762 {
8763 int newnum;
8764 struct remote_state *rs = get_remote_state ();
8765
8766 if (rs->remote_traceframe_number == get_traceframe_number ())
8767 return;
8768
8769 /* Avoid recursion, remote_trace_find calls us again. */
8770 rs->remote_traceframe_number = get_traceframe_number ();
8771
8772 newnum = target_trace_find (tfind_number,
8773 get_traceframe_number (), 0, 0, NULL);
8774
8775 /* Should not happen. If it does, all bets are off. */
8776 if (newnum != get_traceframe_number ())
8777 warning (_("could not set remote traceframe"));
8778 }
8779
8780 void
8781 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8782 {
8783 struct gdbarch *gdbarch = regcache->arch ();
8784 struct remote_state *rs = get_remote_state ();
8785 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8786 int i;
8787
8788 set_remote_traceframe ();
8789 set_general_thread (regcache->ptid ());
8790
8791 if (regnum >= 0)
8792 {
8793 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8794
8795 gdb_assert (reg != NULL);
8796
8797 /* If this register might be in the 'g' packet, try that first -
8798 we are likely to read more than one register. If this is the
8799 first 'g' packet, we might be overly optimistic about its
8800 contents, so fall back to 'p'. */
8801 if (reg->in_g_packet)
8802 {
8803 fetch_registers_using_g (regcache);
8804 if (reg->in_g_packet)
8805 return;
8806 }
8807
8808 if (fetch_register_using_p (regcache, reg))
8809 return;
8810
8811 /* This register is not available. */
8812 regcache->raw_supply (reg->regnum, NULL);
8813
8814 return;
8815 }
8816
8817 fetch_registers_using_g (regcache);
8818
8819 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8820 if (!rsa->regs[i].in_g_packet)
8821 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8822 {
8823 /* This register is not available. */
8824 regcache->raw_supply (i, NULL);
8825 }
8826 }
8827
8828 /* Prepare to store registers. Since we may send them all (using a
8829 'G' request), we have to read out the ones we don't want to change
8830 first. */
8831
8832 void
8833 remote_target::prepare_to_store (struct regcache *regcache)
8834 {
8835 struct remote_state *rs = get_remote_state ();
8836 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8837 int i;
8838
8839 /* Make sure the entire registers array is valid. */
8840 switch (m_features.packet_support (PACKET_P))
8841 {
8842 case PACKET_DISABLE:
8843 case PACKET_SUPPORT_UNKNOWN:
8844 /* Make sure all the necessary registers are cached. */
8845 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8846 if (rsa->regs[i].in_g_packet)
8847 regcache->raw_update (rsa->regs[i].regnum);
8848 break;
8849 case PACKET_ENABLE:
8850 break;
8851 }
8852 }
8853
8854 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8855 packet was not recognized. */
8856
8857 int
8858 remote_target::store_register_using_P (const struct regcache *regcache,
8859 packet_reg *reg)
8860 {
8861 struct gdbarch *gdbarch = regcache->arch ();
8862 struct remote_state *rs = get_remote_state ();
8863 /* Try storing a single register. */
8864 char *buf = rs->buf.data ();
8865 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8866 char *p;
8867
8868 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8869 return 0;
8870
8871 if (reg->pnum == -1)
8872 return 0;
8873
8874 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8875 p = buf + strlen (buf);
8876 regcache->raw_collect (reg->regnum, regp);
8877 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8878 putpkt (rs->buf);
8879 getpkt (&rs->buf, 0);
8880
8881 switch (m_features.packet_ok (rs->buf, PACKET_P))
8882 {
8883 case PACKET_OK:
8884 return 1;
8885 case PACKET_ERROR:
8886 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8887 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8888 case PACKET_UNKNOWN:
8889 return 0;
8890 default:
8891 internal_error (_("Bad result from packet_ok"));
8892 }
8893 }
8894
8895 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8896 contents of the register cache buffer. FIXME: ignores errors. */
8897
8898 void
8899 remote_target::store_registers_using_G (const struct regcache *regcache)
8900 {
8901 struct remote_state *rs = get_remote_state ();
8902 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8903 gdb_byte *regs;
8904 char *p;
8905
8906 /* Extract all the registers in the regcache copying them into a
8907 local buffer. */
8908 {
8909 int i;
8910
8911 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8912 memset (regs, 0, rsa->sizeof_g_packet);
8913 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8914 {
8915 struct packet_reg *r = &rsa->regs[i];
8916
8917 if (r->in_g_packet)
8918 regcache->raw_collect (r->regnum, regs + r->offset);
8919 }
8920 }
8921
8922 /* Command describes registers byte by byte,
8923 each byte encoded as two hex characters. */
8924 p = rs->buf.data ();
8925 *p++ = 'G';
8926 bin2hex (regs, p, rsa->sizeof_g_packet);
8927 putpkt (rs->buf);
8928 getpkt (&rs->buf, 0);
8929 if (packet_check_result (rs->buf) == PACKET_ERROR)
8930 error (_("Could not write registers; remote failure reply '%s'"),
8931 rs->buf.data ());
8932 }
8933
8934 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8935 of the register cache buffer. FIXME: ignores errors. */
8936
8937 void
8938 remote_target::store_registers (struct regcache *regcache, int regnum)
8939 {
8940 struct gdbarch *gdbarch = regcache->arch ();
8941 struct remote_state *rs = get_remote_state ();
8942 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8943 int i;
8944
8945 set_remote_traceframe ();
8946 set_general_thread (regcache->ptid ());
8947
8948 if (regnum >= 0)
8949 {
8950 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8951
8952 gdb_assert (reg != NULL);
8953
8954 /* Always prefer to store registers using the 'P' packet if
8955 possible; we often change only a small number of registers.
8956 Sometimes we change a larger number; we'd need help from a
8957 higher layer to know to use 'G'. */
8958 if (store_register_using_P (regcache, reg))
8959 return;
8960
8961 /* For now, don't complain if we have no way to write the
8962 register. GDB loses track of unavailable registers too
8963 easily. Some day, this may be an error. We don't have
8964 any way to read the register, either... */
8965 if (!reg->in_g_packet)
8966 return;
8967
8968 store_registers_using_G (regcache);
8969 return;
8970 }
8971
8972 store_registers_using_G (regcache);
8973
8974 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8975 if (!rsa->regs[i].in_g_packet)
8976 if (!store_register_using_P (regcache, &rsa->regs[i]))
8977 /* See above for why we do not issue an error here. */
8978 continue;
8979 }
8980 \f
8981
8982 /* Return the number of hex digits in num. */
8983
8984 static int
8985 hexnumlen (ULONGEST num)
8986 {
8987 int i;
8988
8989 for (i = 0; num != 0; i++)
8990 num >>= 4;
8991
8992 return std::max (i, 1);
8993 }
8994
8995 /* Set BUF to the minimum number of hex digits representing NUM. */
8996
8997 static int
8998 hexnumstr (char *buf, ULONGEST num)
8999 {
9000 int len = hexnumlen (num);
9001
9002 return hexnumnstr (buf, num, len);
9003 }
9004
9005
9006 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9007
9008 static int
9009 hexnumnstr (char *buf, ULONGEST num, int width)
9010 {
9011 int i;
9012
9013 buf[width] = '\0';
9014
9015 for (i = width - 1; i >= 0; i--)
9016 {
9017 buf[i] = "0123456789abcdef"[(num & 0xf)];
9018 num >>= 4;
9019 }
9020
9021 return width;
9022 }
9023
9024 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9025
9026 static CORE_ADDR
9027 remote_address_masked (CORE_ADDR addr)
9028 {
9029 unsigned int address_size = remote_address_size;
9030
9031 /* If "remoteaddresssize" was not set, default to target address size. */
9032 if (!address_size)
9033 address_size = gdbarch_addr_bit (target_gdbarch ());
9034
9035 if (address_size > 0
9036 && address_size < (sizeof (ULONGEST) * 8))
9037 {
9038 /* Only create a mask when that mask can safely be constructed
9039 in a ULONGEST variable. */
9040 ULONGEST mask = 1;
9041
9042 mask = (mask << address_size) - 1;
9043 addr &= mask;
9044 }
9045 return addr;
9046 }
9047
9048 /* Determine whether the remote target supports binary downloading.
9049 This is accomplished by sending a no-op memory write of zero length
9050 to the target at the specified address. It does not suffice to send
9051 the whole packet, since many stubs strip the eighth bit and
9052 subsequently compute a wrong checksum, which causes real havoc with
9053 remote_write_bytes.
9054
9055 NOTE: This can still lose if the serial line is not eight-bit
9056 clean. In cases like this, the user should clear "remote
9057 X-packet". */
9058
9059 void
9060 remote_target::check_binary_download (CORE_ADDR addr)
9061 {
9062 struct remote_state *rs = get_remote_state ();
9063
9064 switch (m_features.packet_support (PACKET_X))
9065 {
9066 case PACKET_DISABLE:
9067 break;
9068 case PACKET_ENABLE:
9069 break;
9070 case PACKET_SUPPORT_UNKNOWN:
9071 {
9072 char *p;
9073
9074 p = rs->buf.data ();
9075 *p++ = 'X';
9076 p += hexnumstr (p, (ULONGEST) addr);
9077 *p++ = ',';
9078 p += hexnumstr (p, (ULONGEST) 0);
9079 *p++ = ':';
9080 *p = '\0';
9081
9082 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9083 getpkt (&rs->buf, 0);
9084
9085 if (rs->buf[0] == '\0')
9086 {
9087 remote_debug_printf ("binary downloading NOT supported by target");
9088 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9089 }
9090 else
9091 {
9092 remote_debug_printf ("binary downloading supported by target");
9093 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9094 }
9095 break;
9096 }
9097 }
9098 }
9099
9100 /* Helper function to resize the payload in order to try to get a good
9101 alignment. We try to write an amount of data such that the next write will
9102 start on an address aligned on REMOTE_ALIGN_WRITES. */
9103
9104 static int
9105 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9106 {
9107 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9108 }
9109
9110 /* Write memory data directly to the remote machine.
9111 This does not inform the data cache; the data cache uses this.
9112 HEADER is the starting part of the packet.
9113 MEMADDR is the address in the remote memory space.
9114 MYADDR is the address of the buffer in our space.
9115 LEN_UNITS is the number of addressable units to write.
9116 UNIT_SIZE is the length in bytes of an addressable unit.
9117 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9118 should send data as binary ('X'), or hex-encoded ('M').
9119
9120 The function creates packet of the form
9121 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9122
9123 where encoding of <DATA> is terminated by PACKET_FORMAT.
9124
9125 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9126 are omitted.
9127
9128 Return the transferred status, error or OK (an
9129 'enum target_xfer_status' value). Save the number of addressable units
9130 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9131
9132 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9133 exchange between gdb and the stub could look like (?? in place of the
9134 checksum):
9135
9136 -> $m1000,4#??
9137 <- aaaabbbbccccdddd
9138
9139 -> $M1000,3:eeeeffffeeee#??
9140 <- OK
9141
9142 -> $m1000,4#??
9143 <- eeeeffffeeeedddd */
9144
9145 target_xfer_status
9146 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9147 const gdb_byte *myaddr,
9148 ULONGEST len_units,
9149 int unit_size,
9150 ULONGEST *xfered_len_units,
9151 char packet_format, int use_length)
9152 {
9153 struct remote_state *rs = get_remote_state ();
9154 char *p;
9155 char *plen = NULL;
9156 int plenlen = 0;
9157 int todo_units;
9158 int units_written;
9159 int payload_capacity_bytes;
9160 int payload_length_bytes;
9161
9162 if (packet_format != 'X' && packet_format != 'M')
9163 internal_error (_("remote_write_bytes_aux: bad packet format"));
9164
9165 if (len_units == 0)
9166 return TARGET_XFER_EOF;
9167
9168 payload_capacity_bytes = get_memory_write_packet_size ();
9169
9170 /* The packet buffer will be large enough for the payload;
9171 get_memory_packet_size ensures this. */
9172 rs->buf[0] = '\0';
9173
9174 /* Compute the size of the actual payload by subtracting out the
9175 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9176
9177 payload_capacity_bytes -= strlen ("$,:#NN");
9178 if (!use_length)
9179 /* The comma won't be used. */
9180 payload_capacity_bytes += 1;
9181 payload_capacity_bytes -= strlen (header);
9182 payload_capacity_bytes -= hexnumlen (memaddr);
9183
9184 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9185
9186 strcat (rs->buf.data (), header);
9187 p = rs->buf.data () + strlen (header);
9188
9189 /* Compute a best guess of the number of bytes actually transfered. */
9190 if (packet_format == 'X')
9191 {
9192 /* Best guess at number of bytes that will fit. */
9193 todo_units = std::min (len_units,
9194 (ULONGEST) payload_capacity_bytes / unit_size);
9195 if (use_length)
9196 payload_capacity_bytes -= hexnumlen (todo_units);
9197 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9198 }
9199 else
9200 {
9201 /* Number of bytes that will fit. */
9202 todo_units
9203 = std::min (len_units,
9204 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9205 if (use_length)
9206 payload_capacity_bytes -= hexnumlen (todo_units);
9207 todo_units = std::min (todo_units,
9208 (payload_capacity_bytes / unit_size) / 2);
9209 }
9210
9211 if (todo_units <= 0)
9212 internal_error (_("minimum packet size too small to write data"));
9213
9214 /* If we already need another packet, then try to align the end
9215 of this packet to a useful boundary. */
9216 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9217 todo_units = align_for_efficient_write (todo_units, memaddr);
9218
9219 /* Append "<memaddr>". */
9220 memaddr = remote_address_masked (memaddr);
9221 p += hexnumstr (p, (ULONGEST) memaddr);
9222
9223 if (use_length)
9224 {
9225 /* Append ",". */
9226 *p++ = ',';
9227
9228 /* Append the length and retain its location and size. It may need to be
9229 adjusted once the packet body has been created. */
9230 plen = p;
9231 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9232 p += plenlen;
9233 }
9234
9235 /* Append ":". */
9236 *p++ = ':';
9237 *p = '\0';
9238
9239 /* Append the packet body. */
9240 if (packet_format == 'X')
9241 {
9242 /* Binary mode. Send target system values byte by byte, in
9243 increasing byte addresses. Only escape certain critical
9244 characters. */
9245 payload_length_bytes =
9246 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9247 &units_written, payload_capacity_bytes);
9248
9249 /* If not all TODO units fit, then we'll need another packet. Make
9250 a second try to keep the end of the packet aligned. Don't do
9251 this if the packet is tiny. */
9252 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9253 {
9254 int new_todo_units;
9255
9256 new_todo_units = align_for_efficient_write (units_written, memaddr);
9257
9258 if (new_todo_units != units_written)
9259 payload_length_bytes =
9260 remote_escape_output (myaddr, new_todo_units, unit_size,
9261 (gdb_byte *) p, &units_written,
9262 payload_capacity_bytes);
9263 }
9264
9265 p += payload_length_bytes;
9266 if (use_length && units_written < todo_units)
9267 {
9268 /* Escape chars have filled up the buffer prematurely,
9269 and we have actually sent fewer units than planned.
9270 Fix-up the length field of the packet. Use the same
9271 number of characters as before. */
9272 plen += hexnumnstr (plen, (ULONGEST) units_written,
9273 plenlen);
9274 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9275 }
9276 }
9277 else
9278 {
9279 /* Normal mode: Send target system values byte by byte, in
9280 increasing byte addresses. Each byte is encoded as a two hex
9281 value. */
9282 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9283 units_written = todo_units;
9284 }
9285
9286 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9287 getpkt (&rs->buf, 0);
9288
9289 if (rs->buf[0] == 'E')
9290 return TARGET_XFER_E_IO;
9291
9292 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9293 send fewer units than we'd planned. */
9294 *xfered_len_units = (ULONGEST) units_written;
9295 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9296 }
9297
9298 /* Write memory data directly to the remote machine.
9299 This does not inform the data cache; the data cache uses this.
9300 MEMADDR is the address in the remote memory space.
9301 MYADDR is the address of the buffer in our space.
9302 LEN is the number of bytes.
9303
9304 Return the transferred status, error or OK (an
9305 'enum target_xfer_status' value). Save the number of bytes
9306 transferred in *XFERED_LEN. Only transfer a single packet. */
9307
9308 target_xfer_status
9309 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9310 ULONGEST len, int unit_size,
9311 ULONGEST *xfered_len)
9312 {
9313 const char *packet_format = NULL;
9314
9315 /* Check whether the target supports binary download. */
9316 check_binary_download (memaddr);
9317
9318 switch (m_features.packet_support (PACKET_X))
9319 {
9320 case PACKET_ENABLE:
9321 packet_format = "X";
9322 break;
9323 case PACKET_DISABLE:
9324 packet_format = "M";
9325 break;
9326 case PACKET_SUPPORT_UNKNOWN:
9327 internal_error (_("remote_write_bytes: bad internal state"));
9328 default:
9329 internal_error (_("bad switch"));
9330 }
9331
9332 return remote_write_bytes_aux (packet_format,
9333 memaddr, myaddr, len, unit_size, xfered_len,
9334 packet_format[0], 1);
9335 }
9336
9337 /* Read memory data directly from the remote machine.
9338 This does not use the data cache; the data cache uses this.
9339 MEMADDR is the address in the remote memory space.
9340 MYADDR is the address of the buffer in our space.
9341 LEN_UNITS is the number of addressable memory units to read..
9342 UNIT_SIZE is the length in bytes of an addressable unit.
9343
9344 Return the transferred status, error or OK (an
9345 'enum target_xfer_status' value). Save the number of bytes
9346 transferred in *XFERED_LEN_UNITS.
9347
9348 See the comment of remote_write_bytes_aux for an example of
9349 memory read/write exchange between gdb and the stub. */
9350
9351 target_xfer_status
9352 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9353 ULONGEST len_units,
9354 int unit_size, ULONGEST *xfered_len_units)
9355 {
9356 struct remote_state *rs = get_remote_state ();
9357 int buf_size_bytes; /* Max size of packet output buffer. */
9358 char *p;
9359 int todo_units;
9360 int decoded_bytes;
9361
9362 buf_size_bytes = get_memory_read_packet_size ();
9363 /* The packet buffer will be large enough for the payload;
9364 get_memory_packet_size ensures this. */
9365
9366 /* Number of units that will fit. */
9367 todo_units = std::min (len_units,
9368 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9369
9370 /* Construct "m"<memaddr>","<len>". */
9371 memaddr = remote_address_masked (memaddr);
9372 p = rs->buf.data ();
9373 *p++ = 'm';
9374 p += hexnumstr (p, (ULONGEST) memaddr);
9375 *p++ = ',';
9376 p += hexnumstr (p, (ULONGEST) todo_units);
9377 *p = '\0';
9378 putpkt (rs->buf);
9379 getpkt (&rs->buf, 0);
9380 if (rs->buf[0] == 'E'
9381 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9382 && rs->buf[3] == '\0')
9383 return TARGET_XFER_E_IO;
9384 /* Reply describes memory byte by byte, each byte encoded as two hex
9385 characters. */
9386 p = rs->buf.data ();
9387 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9388 /* Return what we have. Let higher layers handle partial reads. */
9389 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9390 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9391 }
9392
9393 /* Using the set of read-only target sections of remote, read live
9394 read-only memory.
9395
9396 For interface/parameters/return description see target.h,
9397 to_xfer_partial. */
9398
9399 target_xfer_status
9400 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9401 ULONGEST memaddr,
9402 ULONGEST len,
9403 int unit_size,
9404 ULONGEST *xfered_len)
9405 {
9406 const struct target_section *secp;
9407
9408 secp = target_section_by_addr (this, memaddr);
9409 if (secp != NULL
9410 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9411 {
9412 ULONGEST memend = memaddr + len;
9413
9414 const target_section_table *table = target_get_section_table (this);
9415 for (const target_section &p : *table)
9416 {
9417 if (memaddr >= p.addr)
9418 {
9419 if (memend <= p.endaddr)
9420 {
9421 /* Entire transfer is within this section. */
9422 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9423 xfered_len);
9424 }
9425 else if (memaddr >= p.endaddr)
9426 {
9427 /* This section ends before the transfer starts. */
9428 continue;
9429 }
9430 else
9431 {
9432 /* This section overlaps the transfer. Just do half. */
9433 len = p.endaddr - memaddr;
9434 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9435 xfered_len);
9436 }
9437 }
9438 }
9439 }
9440
9441 return TARGET_XFER_EOF;
9442 }
9443
9444 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9445 first if the requested memory is unavailable in traceframe.
9446 Otherwise, fall back to remote_read_bytes_1. */
9447
9448 target_xfer_status
9449 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9450 gdb_byte *myaddr, ULONGEST len, int unit_size,
9451 ULONGEST *xfered_len)
9452 {
9453 if (len == 0)
9454 return TARGET_XFER_EOF;
9455
9456 if (get_traceframe_number () != -1)
9457 {
9458 std::vector<mem_range> available;
9459
9460 /* If we fail to get the set of available memory, then the
9461 target does not support querying traceframe info, and so we
9462 attempt reading from the traceframe anyway (assuming the
9463 target implements the old QTro packet then). */
9464 if (traceframe_available_memory (&available, memaddr, len))
9465 {
9466 if (available.empty () || available[0].start != memaddr)
9467 {
9468 enum target_xfer_status res;
9469
9470 /* Don't read into the traceframe's available
9471 memory. */
9472 if (!available.empty ())
9473 {
9474 LONGEST oldlen = len;
9475
9476 len = available[0].start - memaddr;
9477 gdb_assert (len <= oldlen);
9478 }
9479
9480 /* This goes through the topmost target again. */
9481 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9482 len, unit_size, xfered_len);
9483 if (res == TARGET_XFER_OK)
9484 return TARGET_XFER_OK;
9485 else
9486 {
9487 /* No use trying further, we know some memory starting
9488 at MEMADDR isn't available. */
9489 *xfered_len = len;
9490 return (*xfered_len != 0) ?
9491 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9492 }
9493 }
9494
9495 /* Don't try to read more than how much is available, in
9496 case the target implements the deprecated QTro packet to
9497 cater for older GDBs (the target's knowledge of read-only
9498 sections may be outdated by now). */
9499 len = available[0].length;
9500 }
9501 }
9502
9503 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9504 }
9505
9506 \f
9507
9508 /* Sends a packet with content determined by the printf format string
9509 FORMAT and the remaining arguments, then gets the reply. Returns
9510 whether the packet was a success, a failure, or unknown. */
9511
9512 packet_result
9513 remote_target::remote_send_printf (const char *format, ...)
9514 {
9515 struct remote_state *rs = get_remote_state ();
9516 int max_size = get_remote_packet_size ();
9517 va_list ap;
9518
9519 va_start (ap, format);
9520
9521 rs->buf[0] = '\0';
9522 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9523
9524 va_end (ap);
9525
9526 if (size >= max_size)
9527 internal_error (_("Too long remote packet."));
9528
9529 if (putpkt (rs->buf) < 0)
9530 error (_("Communication problem with target."));
9531
9532 rs->buf[0] = '\0';
9533 getpkt (&rs->buf, 0);
9534
9535 return packet_check_result (rs->buf);
9536 }
9537
9538 /* Flash writing can take quite some time. We'll set
9539 effectively infinite timeout for flash operations.
9540 In future, we'll need to decide on a better approach. */
9541 static const int remote_flash_timeout = 1000;
9542
9543 void
9544 remote_target::flash_erase (ULONGEST address, LONGEST length)
9545 {
9546 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9547 enum packet_result ret;
9548 scoped_restore restore_timeout
9549 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9550
9551 ret = remote_send_printf ("vFlashErase:%s,%s",
9552 phex (address, addr_size),
9553 phex (length, 4));
9554 switch (ret)
9555 {
9556 case PACKET_UNKNOWN:
9557 error (_("Remote target does not support flash erase"));
9558 case PACKET_ERROR:
9559 error (_("Error erasing flash with vFlashErase packet"));
9560 default:
9561 break;
9562 }
9563 }
9564
9565 target_xfer_status
9566 remote_target::remote_flash_write (ULONGEST address,
9567 ULONGEST length, ULONGEST *xfered_len,
9568 const gdb_byte *data)
9569 {
9570 scoped_restore restore_timeout
9571 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9572 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9573 xfered_len,'X', 0);
9574 }
9575
9576 void
9577 remote_target::flash_done ()
9578 {
9579 int ret;
9580
9581 scoped_restore restore_timeout
9582 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9583
9584 ret = remote_send_printf ("vFlashDone");
9585
9586 switch (ret)
9587 {
9588 case PACKET_UNKNOWN:
9589 error (_("Remote target does not support vFlashDone"));
9590 case PACKET_ERROR:
9591 error (_("Error finishing flash operation"));
9592 default:
9593 break;
9594 }
9595 }
9596
9597 \f
9598 /* Stuff for dealing with the packets which are part of this protocol.
9599 See comment at top of file for details. */
9600
9601 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9602 error to higher layers. Called when a serial error is detected.
9603 The exception message is STRING, followed by a colon and a blank,
9604 the system error message for errno at function entry and final dot
9605 for output compatibility with throw_perror_with_name. */
9606
9607 static void
9608 unpush_and_perror (remote_target *target, const char *string)
9609 {
9610 int saved_errno = errno;
9611
9612 remote_unpush_target (target);
9613 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9614 safe_strerror (saved_errno));
9615 }
9616
9617 /* Read a single character from the remote end. The current quit
9618 handler is overridden to avoid quitting in the middle of packet
9619 sequence, as that would break communication with the remote server.
9620 See remote_serial_quit_handler for more detail. */
9621
9622 int
9623 remote_target::readchar (int timeout)
9624 {
9625 int ch;
9626 struct remote_state *rs = get_remote_state ();
9627
9628 {
9629 scoped_restore restore_quit_target
9630 = make_scoped_restore (&curr_quit_handler_target, this);
9631 scoped_restore restore_quit
9632 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9633
9634 rs->got_ctrlc_during_io = 0;
9635
9636 ch = serial_readchar (rs->remote_desc, timeout);
9637
9638 if (rs->got_ctrlc_during_io)
9639 set_quit_flag ();
9640 }
9641
9642 if (ch >= 0)
9643 return ch;
9644
9645 switch ((enum serial_rc) ch)
9646 {
9647 case SERIAL_EOF:
9648 remote_unpush_target (this);
9649 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9650 /* no return */
9651 case SERIAL_ERROR:
9652 unpush_and_perror (this, _("Remote communication error. "
9653 "Target disconnected."));
9654 /* no return */
9655 case SERIAL_TIMEOUT:
9656 break;
9657 }
9658 return ch;
9659 }
9660
9661 /* Wrapper for serial_write that closes the target and throws if
9662 writing fails. The current quit handler is overridden to avoid
9663 quitting in the middle of packet sequence, as that would break
9664 communication with the remote server. See
9665 remote_serial_quit_handler for more detail. */
9666
9667 void
9668 remote_target::remote_serial_write (const char *str, int len)
9669 {
9670 struct remote_state *rs = get_remote_state ();
9671
9672 scoped_restore restore_quit_target
9673 = make_scoped_restore (&curr_quit_handler_target, this);
9674 scoped_restore restore_quit
9675 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9676
9677 rs->got_ctrlc_during_io = 0;
9678
9679 if (serial_write (rs->remote_desc, str, len))
9680 {
9681 unpush_and_perror (this, _("Remote communication error. "
9682 "Target disconnected."));
9683 }
9684
9685 if (rs->got_ctrlc_during_io)
9686 set_quit_flag ();
9687 }
9688
9689 /* Return a string representing an escaped version of BUF, of len N.
9690 E.g. \n is converted to \\n, \t to \\t, etc. */
9691
9692 static std::string
9693 escape_buffer (const char *buf, int n)
9694 {
9695 string_file stb;
9696
9697 stb.putstrn (buf, n, '\\');
9698 return stb.release ();
9699 }
9700
9701 int
9702 remote_target::putpkt (const char *buf)
9703 {
9704 return putpkt_binary (buf, strlen (buf));
9705 }
9706
9707 /* Wrapper around remote_target::putpkt to avoid exporting
9708 remote_target. */
9709
9710 int
9711 putpkt (remote_target *remote, const char *buf)
9712 {
9713 return remote->putpkt (buf);
9714 }
9715
9716 /* Send a packet to the remote machine, with error checking. The data
9717 of the packet is in BUF. The string in BUF can be at most
9718 get_remote_packet_size () - 5 to account for the $, # and checksum,
9719 and for a possible /0 if we are debugging (remote_debug) and want
9720 to print the sent packet as a string. */
9721
9722 int
9723 remote_target::putpkt_binary (const char *buf, int cnt)
9724 {
9725 struct remote_state *rs = get_remote_state ();
9726 int i;
9727 unsigned char csum = 0;
9728 gdb::def_vector<char> data (cnt + 6);
9729 char *buf2 = data.data ();
9730
9731 int ch;
9732 int tcount = 0;
9733 char *p;
9734
9735 /* Catch cases like trying to read memory or listing threads while
9736 we're waiting for a stop reply. The remote server wouldn't be
9737 ready to handle this request, so we'd hang and timeout. We don't
9738 have to worry about this in synchronous mode, because in that
9739 case it's not possible to issue a command while the target is
9740 running. This is not a problem in non-stop mode, because in that
9741 case, the stub is always ready to process serial input. */
9742 if (!target_is_non_stop_p ()
9743 && target_is_async_p ()
9744 && rs->waiting_for_stop_reply)
9745 {
9746 error (_("Cannot execute this command while the target is running.\n"
9747 "Use the \"interrupt\" command to stop the target\n"
9748 "and then try again."));
9749 }
9750
9751 /* Copy the packet into buffer BUF2, encapsulating it
9752 and giving it a checksum. */
9753
9754 p = buf2;
9755 *p++ = '$';
9756
9757 for (i = 0; i < cnt; i++)
9758 {
9759 csum += buf[i];
9760 *p++ = buf[i];
9761 }
9762 *p++ = '#';
9763 *p++ = tohex ((csum >> 4) & 0xf);
9764 *p++ = tohex (csum & 0xf);
9765
9766 /* Send it over and over until we get a positive ack. */
9767
9768 while (1)
9769 {
9770 if (remote_debug)
9771 {
9772 *p = '\0';
9773
9774 int len = (int) (p - buf2);
9775 int max_chars;
9776
9777 if (remote_packet_max_chars < 0)
9778 max_chars = len;
9779 else
9780 max_chars = remote_packet_max_chars;
9781
9782 std::string str
9783 = escape_buffer (buf2, std::min (len, max_chars));
9784
9785 if (len > max_chars)
9786 remote_debug_printf_nofunc
9787 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9788 len - max_chars);
9789 else
9790 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9791 }
9792 remote_serial_write (buf2, p - buf2);
9793
9794 /* If this is a no acks version of the remote protocol, send the
9795 packet and move on. */
9796 if (rs->noack_mode)
9797 break;
9798
9799 /* Read until either a timeout occurs (-2) or '+' is read.
9800 Handle any notification that arrives in the mean time. */
9801 while (1)
9802 {
9803 ch = readchar (remote_timeout);
9804
9805 switch (ch)
9806 {
9807 case '+':
9808 remote_debug_printf_nofunc ("Received Ack");
9809 return 1;
9810 case '-':
9811 remote_debug_printf_nofunc ("Received Nak");
9812 /* FALLTHROUGH */
9813 case SERIAL_TIMEOUT:
9814 tcount++;
9815 if (tcount > 3)
9816 return 0;
9817 break; /* Retransmit buffer. */
9818 case '$':
9819 {
9820 remote_debug_printf ("Packet instead of Ack, ignoring it");
9821 /* It's probably an old response sent because an ACK
9822 was lost. Gobble up the packet and ack it so it
9823 doesn't get retransmitted when we resend this
9824 packet. */
9825 skip_frame ();
9826 remote_serial_write ("+", 1);
9827 continue; /* Now, go look for +. */
9828 }
9829
9830 case '%':
9831 {
9832 int val;
9833
9834 /* If we got a notification, handle it, and go back to looking
9835 for an ack. */
9836 /* We've found the start of a notification. Now
9837 collect the data. */
9838 val = read_frame (&rs->buf);
9839 if (val >= 0)
9840 {
9841 remote_debug_printf_nofunc
9842 (" Notification received: %s",
9843 escape_buffer (rs->buf.data (), val).c_str ());
9844
9845 handle_notification (rs->notif_state, rs->buf.data ());
9846 /* We're in sync now, rewait for the ack. */
9847 tcount = 0;
9848 }
9849 else
9850 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9851 rs->buf.data ());
9852 continue;
9853 }
9854 /* fall-through */
9855 default:
9856 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9857 rs->buf.data ());
9858 continue;
9859 }
9860 break; /* Here to retransmit. */
9861 }
9862
9863 #if 0
9864 /* This is wrong. If doing a long backtrace, the user should be
9865 able to get out next time we call QUIT, without anything as
9866 violent as interrupt_query. If we want to provide a way out of
9867 here without getting to the next QUIT, it should be based on
9868 hitting ^C twice as in remote_wait. */
9869 if (quit_flag)
9870 {
9871 quit_flag = 0;
9872 interrupt_query ();
9873 }
9874 #endif
9875 }
9876
9877 return 0;
9878 }
9879
9880 /* Come here after finding the start of a frame when we expected an
9881 ack. Do our best to discard the rest of this packet. */
9882
9883 void
9884 remote_target::skip_frame ()
9885 {
9886 int c;
9887
9888 while (1)
9889 {
9890 c = readchar (remote_timeout);
9891 switch (c)
9892 {
9893 case SERIAL_TIMEOUT:
9894 /* Nothing we can do. */
9895 return;
9896 case '#':
9897 /* Discard the two bytes of checksum and stop. */
9898 c = readchar (remote_timeout);
9899 if (c >= 0)
9900 c = readchar (remote_timeout);
9901
9902 return;
9903 case '*': /* Run length encoding. */
9904 /* Discard the repeat count. */
9905 c = readchar (remote_timeout);
9906 if (c < 0)
9907 return;
9908 break;
9909 default:
9910 /* A regular character. */
9911 break;
9912 }
9913 }
9914 }
9915
9916 /* Come here after finding the start of the frame. Collect the rest
9917 into *BUF, verifying the checksum, length, and handling run-length
9918 compression. NUL terminate the buffer. If there is not enough room,
9919 expand *BUF.
9920
9921 Returns -1 on error, number of characters in buffer (ignoring the
9922 trailing NULL) on success. (could be extended to return one of the
9923 SERIAL status indications). */
9924
9925 long
9926 remote_target::read_frame (gdb::char_vector *buf_p)
9927 {
9928 unsigned char csum;
9929 long bc;
9930 int c;
9931 char *buf = buf_p->data ();
9932 struct remote_state *rs = get_remote_state ();
9933
9934 csum = 0;
9935 bc = 0;
9936
9937 while (1)
9938 {
9939 c = readchar (remote_timeout);
9940 switch (c)
9941 {
9942 case SERIAL_TIMEOUT:
9943 remote_debug_printf ("Timeout in mid-packet, retrying");
9944 return -1;
9945
9946 case '$':
9947 remote_debug_printf ("Saw new packet start in middle of old one");
9948 return -1; /* Start a new packet, count retries. */
9949
9950 case '#':
9951 {
9952 unsigned char pktcsum;
9953 int check_0 = 0;
9954 int check_1 = 0;
9955
9956 buf[bc] = '\0';
9957
9958 check_0 = readchar (remote_timeout);
9959 if (check_0 >= 0)
9960 check_1 = readchar (remote_timeout);
9961
9962 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9963 {
9964 remote_debug_printf ("Timeout in checksum, retrying");
9965 return -1;
9966 }
9967 else if (check_0 < 0 || check_1 < 0)
9968 {
9969 remote_debug_printf ("Communication error in checksum");
9970 return -1;
9971 }
9972
9973 /* Don't recompute the checksum; with no ack packets we
9974 don't have any way to indicate a packet retransmission
9975 is necessary. */
9976 if (rs->noack_mode)
9977 return bc;
9978
9979 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9980 if (csum == pktcsum)
9981 return bc;
9982
9983 remote_debug_printf
9984 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9985 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9986
9987 /* Number of characters in buffer ignoring trailing
9988 NULL. */
9989 return -1;
9990 }
9991 case '*': /* Run length encoding. */
9992 {
9993 int repeat;
9994
9995 csum += c;
9996 c = readchar (remote_timeout);
9997 csum += c;
9998 repeat = c - ' ' + 3; /* Compute repeat count. */
9999
10000 /* The character before ``*'' is repeated. */
10001
10002 if (repeat > 0 && repeat <= 255 && bc > 0)
10003 {
10004 if (bc + repeat - 1 >= buf_p->size () - 1)
10005 {
10006 /* Make some more room in the buffer. */
10007 buf_p->resize (buf_p->size () + repeat);
10008 buf = buf_p->data ();
10009 }
10010
10011 memset (&buf[bc], buf[bc - 1], repeat);
10012 bc += repeat;
10013 continue;
10014 }
10015
10016 buf[bc] = '\0';
10017 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10018 return -1;
10019 }
10020 default:
10021 if (bc >= buf_p->size () - 1)
10022 {
10023 /* Make some more room in the buffer. */
10024 buf_p->resize (buf_p->size () * 2);
10025 buf = buf_p->data ();
10026 }
10027
10028 buf[bc++] = c;
10029 csum += c;
10030 continue;
10031 }
10032 }
10033 }
10034
10035 /* Set this to the maximum number of seconds to wait instead of waiting forever
10036 in target_wait(). If this timer times out, then it generates an error and
10037 the command is aborted. This replaces most of the need for timeouts in the
10038 GDB test suite, and makes it possible to distinguish between a hung target
10039 and one with slow communications. */
10040
10041 static int watchdog = 0;
10042 static void
10043 show_watchdog (struct ui_file *file, int from_tty,
10044 struct cmd_list_element *c, const char *value)
10045 {
10046 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10047 }
10048
10049 /* Read a packet from the remote machine, with error checking, and
10050 store it in *BUF. Resize *BUF if necessary to hold the result. If
10051 FOREVER, wait forever rather than timing out; this is used (in
10052 synchronous mode) to wait for a target that is is executing user
10053 code to stop. */
10054 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
10055 don't have to change all the calls to getpkt to deal with the
10056 return value, because at the moment I don't know what the right
10057 thing to do it for those. */
10058
10059 void
10060 remote_target::getpkt (gdb::char_vector *buf, int forever)
10061 {
10062 getpkt_sane (buf, forever);
10063 }
10064
10065
10066 /* Read a packet from the remote machine, with error checking, and
10067 store it in *BUF. Resize *BUF if necessary to hold the result. If
10068 FOREVER, wait forever rather than timing out; this is used (in
10069 synchronous mode) to wait for a target that is is executing user
10070 code to stop. If FOREVER == 0, this function is allowed to time
10071 out gracefully and return an indication of this to the caller.
10072 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
10073 consider receiving a notification enough reason to return to the
10074 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
10075 holds a notification or not (a regular packet). */
10076
10077 int
10078 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
10079 int forever, int expecting_notif,
10080 int *is_notif)
10081 {
10082 struct remote_state *rs = get_remote_state ();
10083 int c;
10084 int tries;
10085 int timeout;
10086 int val = -1;
10087
10088 strcpy (buf->data (), "timeout");
10089
10090 if (forever)
10091 timeout = watchdog > 0 ? watchdog : -1;
10092 else if (expecting_notif)
10093 timeout = 0; /* There should already be a char in the buffer. If
10094 not, bail out. */
10095 else
10096 timeout = remote_timeout;
10097
10098 #define MAX_TRIES 3
10099
10100 /* Process any number of notifications, and then return when
10101 we get a packet. */
10102 for (;;)
10103 {
10104 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10105 times. */
10106 for (tries = 1; tries <= MAX_TRIES; tries++)
10107 {
10108 /* This can loop forever if the remote side sends us
10109 characters continuously, but if it pauses, we'll get
10110 SERIAL_TIMEOUT from readchar because of timeout. Then
10111 we'll count that as a retry.
10112
10113 Note that even when forever is set, we will only wait
10114 forever prior to the start of a packet. After that, we
10115 expect characters to arrive at a brisk pace. They should
10116 show up within remote_timeout intervals. */
10117 do
10118 c = readchar (timeout);
10119 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10120
10121 if (c == SERIAL_TIMEOUT)
10122 {
10123 if (expecting_notif)
10124 return -1; /* Don't complain, it's normal to not get
10125 anything in this case. */
10126
10127 if (forever) /* Watchdog went off? Kill the target. */
10128 {
10129 remote_unpush_target (this);
10130 throw_error (TARGET_CLOSE_ERROR,
10131 _("Watchdog timeout has expired. "
10132 "Target detached."));
10133 }
10134
10135 remote_debug_printf ("Timed out.");
10136 }
10137 else
10138 {
10139 /* We've found the start of a packet or notification.
10140 Now collect the data. */
10141 val = read_frame (buf);
10142 if (val >= 0)
10143 break;
10144 }
10145
10146 remote_serial_write ("-", 1);
10147 }
10148
10149 if (tries > MAX_TRIES)
10150 {
10151 /* We have tried hard enough, and just can't receive the
10152 packet/notification. Give up. */
10153 gdb_printf (_("Ignoring packet error, continuing...\n"));
10154
10155 /* Skip the ack char if we're in no-ack mode. */
10156 if (!rs->noack_mode)
10157 remote_serial_write ("+", 1);
10158 return -1;
10159 }
10160
10161 /* If we got an ordinary packet, return that to our caller. */
10162 if (c == '$')
10163 {
10164 if (remote_debug)
10165 {
10166 int max_chars;
10167
10168 if (remote_packet_max_chars < 0)
10169 max_chars = val;
10170 else
10171 max_chars = remote_packet_max_chars;
10172
10173 std::string str
10174 = escape_buffer (buf->data (),
10175 std::min (val, max_chars));
10176
10177 if (val > max_chars)
10178 remote_debug_printf_nofunc
10179 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10180 val - max_chars);
10181 else
10182 remote_debug_printf_nofunc ("Packet received: %s",
10183 str.c_str ());
10184 }
10185
10186 /* Skip the ack char if we're in no-ack mode. */
10187 if (!rs->noack_mode)
10188 remote_serial_write ("+", 1);
10189 if (is_notif != NULL)
10190 *is_notif = 0;
10191 return val;
10192 }
10193
10194 /* If we got a notification, handle it, and go back to looking
10195 for a packet. */
10196 else
10197 {
10198 gdb_assert (c == '%');
10199
10200 remote_debug_printf_nofunc
10201 (" Notification received: %s",
10202 escape_buffer (buf->data (), val).c_str ());
10203
10204 if (is_notif != NULL)
10205 *is_notif = 1;
10206
10207 handle_notification (rs->notif_state, buf->data ());
10208
10209 /* Notifications require no acknowledgement. */
10210
10211 if (expecting_notif)
10212 return val;
10213 }
10214 }
10215 }
10216
10217 int
10218 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10219 {
10220 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10221 }
10222
10223 int
10224 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10225 int *is_notif)
10226 {
10227 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10228 }
10229
10230 /* Kill any new fork children of inferior INF that haven't been
10231 processed by follow_fork. */
10232
10233 void
10234 remote_target::kill_new_fork_children (inferior *inf)
10235 {
10236 remote_state *rs = get_remote_state ();
10237 const notif_client *notif = &notif_client_stop;
10238
10239 /* Kill the fork child threads of any threads in inferior INF that are stopped
10240 at a fork event. */
10241 for (thread_info *thread : inf->non_exited_threads ())
10242 {
10243 const target_waitstatus *ws = thread_pending_fork_status (thread);
10244
10245 if (ws == nullptr)
10246 continue;
10247
10248 int child_pid = ws->child_ptid ().pid ();
10249 int res = remote_vkill (child_pid);
10250
10251 if (res != 0)
10252 error (_("Can't kill fork child process %d"), child_pid);
10253 }
10254
10255 /* Check for any pending fork events (not reported or processed yet)
10256 in inferior INF and kill those fork child threads as well. */
10257 remote_notif_get_pending_events (notif);
10258 for (auto &event : rs->stop_reply_queue)
10259 {
10260 if (event->ptid.pid () != inf->pid)
10261 continue;
10262
10263 if (!is_fork_status (event->ws.kind ()))
10264 continue;
10265
10266 int child_pid = event->ws.child_ptid ().pid ();
10267 int res = remote_vkill (child_pid);
10268
10269 if (res != 0)
10270 error (_("Can't kill fork child process %d"), child_pid);
10271 }
10272 }
10273
10274 \f
10275 /* Target hook to kill the current inferior. */
10276
10277 void
10278 remote_target::kill ()
10279 {
10280 int res = -1;
10281 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10282
10283 gdb_assert (inf != nullptr);
10284
10285 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10286 {
10287 /* If we're stopped while forking and we haven't followed yet,
10288 kill the child task. We need to do this before killing the
10289 parent task because if this is a vfork then the parent will
10290 be sleeping. */
10291 kill_new_fork_children (inf);
10292
10293 res = remote_vkill (inf->pid);
10294 if (res == 0)
10295 {
10296 target_mourn_inferior (inferior_ptid);
10297 return;
10298 }
10299 }
10300
10301 /* If we are in 'target remote' mode and we are killing the only
10302 inferior, then we will tell gdbserver to exit and unpush the
10303 target. */
10304 if (res == -1 && !m_features.remote_multi_process_p ()
10305 && number_of_live_inferiors (this) == 1)
10306 {
10307 remote_kill_k ();
10308
10309 /* We've killed the remote end, we get to mourn it. If we are
10310 not in extended mode, mourning the inferior also unpushes
10311 remote_ops from the target stack, which closes the remote
10312 connection. */
10313 target_mourn_inferior (inferior_ptid);
10314
10315 return;
10316 }
10317
10318 error (_("Can't kill process"));
10319 }
10320
10321 /* Send a kill request to the target using the 'vKill' packet. */
10322
10323 int
10324 remote_target::remote_vkill (int pid)
10325 {
10326 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10327 return -1;
10328
10329 remote_state *rs = get_remote_state ();
10330
10331 /* Tell the remote target to detach. */
10332 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10333 putpkt (rs->buf);
10334 getpkt (&rs->buf, 0);
10335
10336 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10337 {
10338 case PACKET_OK:
10339 return 0;
10340 case PACKET_ERROR:
10341 return 1;
10342 case PACKET_UNKNOWN:
10343 return -1;
10344 default:
10345 internal_error (_("Bad result from packet_ok"));
10346 }
10347 }
10348
10349 /* Send a kill request to the target using the 'k' packet. */
10350
10351 void
10352 remote_target::remote_kill_k ()
10353 {
10354 /* Catch errors so the user can quit from gdb even when we
10355 aren't on speaking terms with the remote system. */
10356 try
10357 {
10358 putpkt ("k");
10359 }
10360 catch (const gdb_exception_error &ex)
10361 {
10362 if (ex.error == TARGET_CLOSE_ERROR)
10363 {
10364 /* If we got an (EOF) error that caused the target
10365 to go away, then we're done, that's what we wanted.
10366 "k" is susceptible to cause a premature EOF, given
10367 that the remote server isn't actually required to
10368 reply to "k", and it can happen that it doesn't
10369 even get to reply ACK to the "k". */
10370 return;
10371 }
10372
10373 /* Otherwise, something went wrong. We didn't actually kill
10374 the target. Just propagate the exception, and let the
10375 user or higher layers decide what to do. */
10376 throw;
10377 }
10378 }
10379
10380 void
10381 remote_target::mourn_inferior ()
10382 {
10383 struct remote_state *rs = get_remote_state ();
10384
10385 /* We're no longer interested in notification events of an inferior
10386 that exited or was killed/detached. */
10387 discard_pending_stop_replies (current_inferior ());
10388
10389 /* In 'target remote' mode with one inferior, we close the connection. */
10390 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10391 {
10392 remote_unpush_target (this);
10393 return;
10394 }
10395
10396 /* In case we got here due to an error, but we're going to stay
10397 connected. */
10398 rs->waiting_for_stop_reply = 0;
10399
10400 /* If the current general thread belonged to the process we just
10401 detached from or has exited, the remote side current general
10402 thread becomes undefined. Considering a case like this:
10403
10404 - We just got here due to a detach.
10405 - The process that we're detaching from happens to immediately
10406 report a global breakpoint being hit in non-stop mode, in the
10407 same thread we had selected before.
10408 - GDB attaches to this process again.
10409 - This event happens to be the next event we handle.
10410
10411 GDB would consider that the current general thread didn't need to
10412 be set on the stub side (with Hg), since for all it knew,
10413 GENERAL_THREAD hadn't changed.
10414
10415 Notice that although in all-stop mode, the remote server always
10416 sets the current thread to the thread reporting the stop event,
10417 that doesn't happen in non-stop mode; in non-stop, the stub *must
10418 not* change the current thread when reporting a breakpoint hit,
10419 due to the decoupling of event reporting and event handling.
10420
10421 To keep things simple, we always invalidate our notion of the
10422 current thread. */
10423 record_currthread (rs, minus_one_ptid);
10424
10425 /* Call common code to mark the inferior as not running. */
10426 generic_mourn_inferior ();
10427 }
10428
10429 bool
10430 extended_remote_target::supports_disable_randomization ()
10431 {
10432 return (m_features.packet_support (PACKET_QDisableRandomization)
10433 == PACKET_ENABLE);
10434 }
10435
10436 void
10437 remote_target::extended_remote_disable_randomization (int val)
10438 {
10439 struct remote_state *rs = get_remote_state ();
10440 char *reply;
10441
10442 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10443 "QDisableRandomization:%x", val);
10444 putpkt (rs->buf);
10445 reply = remote_get_noisy_reply ();
10446 if (*reply == '\0')
10447 error (_("Target does not support QDisableRandomization."));
10448 if (strcmp (reply, "OK") != 0)
10449 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10450 }
10451
10452 int
10453 remote_target::extended_remote_run (const std::string &args)
10454 {
10455 struct remote_state *rs = get_remote_state ();
10456 int len;
10457 const char *remote_exec_file = get_remote_exec_file ();
10458
10459 /* If the user has disabled vRun support, or we have detected that
10460 support is not available, do not try it. */
10461 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10462 return -1;
10463
10464 strcpy (rs->buf.data (), "vRun;");
10465 len = strlen (rs->buf.data ());
10466
10467 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10468 error (_("Remote file name too long for run packet"));
10469 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10470 strlen (remote_exec_file));
10471
10472 if (!args.empty ())
10473 {
10474 int i;
10475
10476 gdb_argv argv (args.c_str ());
10477 for (i = 0; argv[i] != NULL; i++)
10478 {
10479 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10480 error (_("Argument list too long for run packet"));
10481 rs->buf[len++] = ';';
10482 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10483 strlen (argv[i]));
10484 }
10485 }
10486
10487 rs->buf[len++] = '\0';
10488
10489 putpkt (rs->buf);
10490 getpkt (&rs->buf, 0);
10491
10492 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10493 {
10494 case PACKET_OK:
10495 /* We have a wait response. All is well. */
10496 return 0;
10497 case PACKET_UNKNOWN:
10498 return -1;
10499 case PACKET_ERROR:
10500 if (remote_exec_file[0] == '\0')
10501 error (_("Running the default executable on the remote target failed; "
10502 "try \"set remote exec-file\"?"));
10503 else
10504 error (_("Running \"%s\" on the remote target failed"),
10505 remote_exec_file);
10506 default:
10507 gdb_assert_not_reached ("bad switch");
10508 }
10509 }
10510
10511 /* Helper function to send set/unset environment packets. ACTION is
10512 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10513 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10514 sent. */
10515
10516 void
10517 remote_target::send_environment_packet (const char *action,
10518 const char *packet,
10519 const char *value)
10520 {
10521 remote_state *rs = get_remote_state ();
10522
10523 /* Convert the environment variable to an hex string, which
10524 is the best format to be transmitted over the wire. */
10525 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10526 strlen (value));
10527
10528 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10529 "%s:%s", packet, encoded_value.c_str ());
10530
10531 putpkt (rs->buf);
10532 getpkt (&rs->buf, 0);
10533 if (strcmp (rs->buf.data (), "OK") != 0)
10534 warning (_("Unable to %s environment variable '%s' on remote."),
10535 action, value);
10536 }
10537
10538 /* Helper function to handle the QEnvironment* packets. */
10539
10540 void
10541 remote_target::extended_remote_environment_support ()
10542 {
10543 remote_state *rs = get_remote_state ();
10544
10545 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10546 {
10547 putpkt ("QEnvironmentReset");
10548 getpkt (&rs->buf, 0);
10549 if (strcmp (rs->buf.data (), "OK") != 0)
10550 warning (_("Unable to reset environment on remote."));
10551 }
10552
10553 gdb_environ *e = &current_inferior ()->environment;
10554
10555 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10556 != PACKET_DISABLE)
10557 {
10558 for (const std::string &el : e->user_set_env ())
10559 send_environment_packet ("set", "QEnvironmentHexEncoded",
10560 el.c_str ());
10561 }
10562
10563
10564 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10565 for (const std::string &el : e->user_unset_env ())
10566 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10567 }
10568
10569 /* Helper function to set the current working directory for the
10570 inferior in the remote target. */
10571
10572 void
10573 remote_target::extended_remote_set_inferior_cwd ()
10574 {
10575 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10576 {
10577 const std::string &inferior_cwd = current_inferior ()->cwd ();
10578 remote_state *rs = get_remote_state ();
10579
10580 if (!inferior_cwd.empty ())
10581 {
10582 std::string hexpath
10583 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10584 inferior_cwd.size ());
10585
10586 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10587 "QSetWorkingDir:%s", hexpath.c_str ());
10588 }
10589 else
10590 {
10591 /* An empty inferior_cwd means that the user wants us to
10592 reset the remote server's inferior's cwd. */
10593 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10594 "QSetWorkingDir:");
10595 }
10596
10597 putpkt (rs->buf);
10598 getpkt (&rs->buf, 0);
10599 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10600 error (_("\
10601 Remote replied unexpectedly while setting the inferior's working\n\
10602 directory: %s"),
10603 rs->buf.data ());
10604
10605 }
10606 }
10607
10608 /* In the extended protocol we want to be able to do things like
10609 "run" and have them basically work as expected. So we need
10610 a special create_inferior function. We support changing the
10611 executable file and the command line arguments, but not the
10612 environment. */
10613
10614 void
10615 extended_remote_target::create_inferior (const char *exec_file,
10616 const std::string &args,
10617 char **env, int from_tty)
10618 {
10619 int run_worked;
10620 char *stop_reply;
10621 struct remote_state *rs = get_remote_state ();
10622 const char *remote_exec_file = get_remote_exec_file ();
10623
10624 /* If running asynchronously, register the target file descriptor
10625 with the event loop. */
10626 if (target_can_async_p ())
10627 target_async (true);
10628
10629 /* Disable address space randomization if requested (and supported). */
10630 if (supports_disable_randomization ())
10631 extended_remote_disable_randomization (disable_randomization);
10632
10633 /* If startup-with-shell is on, we inform gdbserver to start the
10634 remote inferior using a shell. */
10635 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10636 {
10637 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10638 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10639 putpkt (rs->buf);
10640 getpkt (&rs->buf, 0);
10641 if (strcmp (rs->buf.data (), "OK") != 0)
10642 error (_("\
10643 Remote replied unexpectedly while setting startup-with-shell: %s"),
10644 rs->buf.data ());
10645 }
10646
10647 extended_remote_environment_support ();
10648
10649 extended_remote_set_inferior_cwd ();
10650
10651 /* Now restart the remote server. */
10652 run_worked = extended_remote_run (args) != -1;
10653 if (!run_worked)
10654 {
10655 /* vRun was not supported. Fail if we need it to do what the
10656 user requested. */
10657 if (remote_exec_file[0])
10658 error (_("Remote target does not support \"set remote exec-file\""));
10659 if (!args.empty ())
10660 error (_("Remote target does not support \"set args\" or run ARGS"));
10661
10662 /* Fall back to "R". */
10663 extended_remote_restart ();
10664 }
10665
10666 /* vRun's success return is a stop reply. */
10667 stop_reply = run_worked ? rs->buf.data () : NULL;
10668 add_current_inferior_and_thread (stop_reply);
10669
10670 /* Get updated offsets, if the stub uses qOffsets. */
10671 get_offsets ();
10672 }
10673 \f
10674
10675 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10676 the list of conditions (in agent expression bytecode format), if any, the
10677 target needs to evaluate. The output is placed into the packet buffer
10678 started from BUF and ended at BUF_END. */
10679
10680 static int
10681 remote_add_target_side_condition (struct gdbarch *gdbarch,
10682 struct bp_target_info *bp_tgt, char *buf,
10683 char *buf_end)
10684 {
10685 if (bp_tgt->conditions.empty ())
10686 return 0;
10687
10688 buf += strlen (buf);
10689 xsnprintf (buf, buf_end - buf, "%s", ";");
10690 buf++;
10691
10692 /* Send conditions to the target. */
10693 for (agent_expr *aexpr : bp_tgt->conditions)
10694 {
10695 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10696 buf += strlen (buf);
10697 for (int i = 0; i < aexpr->len; ++i)
10698 buf = pack_hex_byte (buf, aexpr->buf[i]);
10699 *buf = '\0';
10700 }
10701 return 0;
10702 }
10703
10704 static void
10705 remote_add_target_side_commands (struct gdbarch *gdbarch,
10706 struct bp_target_info *bp_tgt, char *buf)
10707 {
10708 if (bp_tgt->tcommands.empty ())
10709 return;
10710
10711 buf += strlen (buf);
10712
10713 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10714 buf += strlen (buf);
10715
10716 /* Concatenate all the agent expressions that are commands into the
10717 cmds parameter. */
10718 for (agent_expr *aexpr : bp_tgt->tcommands)
10719 {
10720 sprintf (buf, "X%x,", aexpr->len);
10721 buf += strlen (buf);
10722 for (int i = 0; i < aexpr->len; ++i)
10723 buf = pack_hex_byte (buf, aexpr->buf[i]);
10724 *buf = '\0';
10725 }
10726 }
10727
10728 /* Insert a breakpoint. On targets that have software breakpoint
10729 support, we ask the remote target to do the work; on targets
10730 which don't, we insert a traditional memory breakpoint. */
10731
10732 int
10733 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10734 struct bp_target_info *bp_tgt)
10735 {
10736 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10737 If it succeeds, then set the support to PACKET_ENABLE. If it
10738 fails, and the user has explicitly requested the Z support then
10739 report an error, otherwise, mark it disabled and go on. */
10740
10741 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10742 {
10743 CORE_ADDR addr = bp_tgt->reqstd_address;
10744 struct remote_state *rs;
10745 char *p, *endbuf;
10746
10747 /* Make sure the remote is pointing at the right process, if
10748 necessary. */
10749 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10750 set_general_process ();
10751
10752 rs = get_remote_state ();
10753 p = rs->buf.data ();
10754 endbuf = p + get_remote_packet_size ();
10755
10756 *(p++) = 'Z';
10757 *(p++) = '0';
10758 *(p++) = ',';
10759 addr = (ULONGEST) remote_address_masked (addr);
10760 p += hexnumstr (p, addr);
10761 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10762
10763 if (supports_evaluation_of_breakpoint_conditions ())
10764 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10765
10766 if (can_run_breakpoint_commands ())
10767 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10768
10769 putpkt (rs->buf);
10770 getpkt (&rs->buf, 0);
10771
10772 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10773 {
10774 case PACKET_ERROR:
10775 return -1;
10776 case PACKET_OK:
10777 return 0;
10778 case PACKET_UNKNOWN:
10779 break;
10780 }
10781 }
10782
10783 /* If this breakpoint has target-side commands but this stub doesn't
10784 support Z0 packets, throw error. */
10785 if (!bp_tgt->tcommands.empty ())
10786 throw_error (NOT_SUPPORTED_ERROR, _("\
10787 Target doesn't support breakpoints that have target side commands."));
10788
10789 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10790 }
10791
10792 int
10793 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10794 struct bp_target_info *bp_tgt,
10795 enum remove_bp_reason reason)
10796 {
10797 CORE_ADDR addr = bp_tgt->placed_address;
10798 struct remote_state *rs = get_remote_state ();
10799
10800 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10801 {
10802 char *p = rs->buf.data ();
10803 char *endbuf = p + get_remote_packet_size ();
10804
10805 /* Make sure the remote is pointing at the right process, if
10806 necessary. */
10807 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10808 set_general_process ();
10809
10810 *(p++) = 'z';
10811 *(p++) = '0';
10812 *(p++) = ',';
10813
10814 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10815 p += hexnumstr (p, addr);
10816 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10817
10818 putpkt (rs->buf);
10819 getpkt (&rs->buf, 0);
10820
10821 return (rs->buf[0] == 'E');
10822 }
10823
10824 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10825 }
10826
10827 static enum Z_packet_type
10828 watchpoint_to_Z_packet (int type)
10829 {
10830 switch (type)
10831 {
10832 case hw_write:
10833 return Z_PACKET_WRITE_WP;
10834 break;
10835 case hw_read:
10836 return Z_PACKET_READ_WP;
10837 break;
10838 case hw_access:
10839 return Z_PACKET_ACCESS_WP;
10840 break;
10841 default:
10842 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10843 }
10844 }
10845
10846 int
10847 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10848 enum target_hw_bp_type type, struct expression *cond)
10849 {
10850 struct remote_state *rs = get_remote_state ();
10851 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10852 char *p;
10853 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10854
10855 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10856 return 1;
10857
10858 /* Make sure the remote is pointing at the right process, if
10859 necessary. */
10860 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10861 set_general_process ();
10862
10863 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10864 p = strchr (rs->buf.data (), '\0');
10865 addr = remote_address_masked (addr);
10866 p += hexnumstr (p, (ULONGEST) addr);
10867 xsnprintf (p, endbuf - p, ",%x", len);
10868
10869 putpkt (rs->buf);
10870 getpkt (&rs->buf, 0);
10871
10872 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
10873 {
10874 case PACKET_ERROR:
10875 return -1;
10876 case PACKET_UNKNOWN:
10877 return 1;
10878 case PACKET_OK:
10879 return 0;
10880 }
10881 internal_error (_("remote_insert_watchpoint: reached end of function"));
10882 }
10883
10884 bool
10885 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10886 CORE_ADDR start, int length)
10887 {
10888 CORE_ADDR diff = remote_address_masked (addr - start);
10889
10890 return diff < length;
10891 }
10892
10893
10894 int
10895 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10896 enum target_hw_bp_type type, struct expression *cond)
10897 {
10898 struct remote_state *rs = get_remote_state ();
10899 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10900 char *p;
10901 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10902
10903 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10904 return -1;
10905
10906 /* Make sure the remote is pointing at the right process, if
10907 necessary. */
10908 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10909 set_general_process ();
10910
10911 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10912 p = strchr (rs->buf.data (), '\0');
10913 addr = remote_address_masked (addr);
10914 p += hexnumstr (p, (ULONGEST) addr);
10915 xsnprintf (p, endbuf - p, ",%x", len);
10916 putpkt (rs->buf);
10917 getpkt (&rs->buf, 0);
10918
10919 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
10920 {
10921 case PACKET_ERROR:
10922 case PACKET_UNKNOWN:
10923 return -1;
10924 case PACKET_OK:
10925 return 0;
10926 }
10927 internal_error (_("remote_remove_watchpoint: reached end of function"));
10928 }
10929
10930
10931 static int remote_hw_watchpoint_limit = -1;
10932 static int remote_hw_watchpoint_length_limit = -1;
10933 static int remote_hw_breakpoint_limit = -1;
10934
10935 int
10936 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10937 {
10938 if (remote_hw_watchpoint_length_limit == 0)
10939 return 0;
10940 else if (remote_hw_watchpoint_length_limit < 0)
10941 return 1;
10942 else if (len <= remote_hw_watchpoint_length_limit)
10943 return 1;
10944 else
10945 return 0;
10946 }
10947
10948 int
10949 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10950 {
10951 if (type == bp_hardware_breakpoint)
10952 {
10953 if (remote_hw_breakpoint_limit == 0)
10954 return 0;
10955 else if (remote_hw_breakpoint_limit < 0)
10956 return 1;
10957 else if (cnt <= remote_hw_breakpoint_limit)
10958 return 1;
10959 }
10960 else
10961 {
10962 if (remote_hw_watchpoint_limit == 0)
10963 return 0;
10964 else if (remote_hw_watchpoint_limit < 0)
10965 return 1;
10966 else if (ot)
10967 return -1;
10968 else if (cnt <= remote_hw_watchpoint_limit)
10969 return 1;
10970 }
10971 return -1;
10972 }
10973
10974 /* The to_stopped_by_sw_breakpoint method of target remote. */
10975
10976 bool
10977 remote_target::stopped_by_sw_breakpoint ()
10978 {
10979 struct thread_info *thread = inferior_thread ();
10980
10981 return (thread->priv != NULL
10982 && (get_remote_thread_info (thread)->stop_reason
10983 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10984 }
10985
10986 /* The to_supports_stopped_by_sw_breakpoint method of target
10987 remote. */
10988
10989 bool
10990 remote_target::supports_stopped_by_sw_breakpoint ()
10991 {
10992 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10993 }
10994
10995 /* The to_stopped_by_hw_breakpoint method of target remote. */
10996
10997 bool
10998 remote_target::stopped_by_hw_breakpoint ()
10999 {
11000 struct thread_info *thread = inferior_thread ();
11001
11002 return (thread->priv != NULL
11003 && (get_remote_thread_info (thread)->stop_reason
11004 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11005 }
11006
11007 /* The to_supports_stopped_by_hw_breakpoint method of target
11008 remote. */
11009
11010 bool
11011 remote_target::supports_stopped_by_hw_breakpoint ()
11012 {
11013 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11014 }
11015
11016 bool
11017 remote_target::stopped_by_watchpoint ()
11018 {
11019 struct thread_info *thread = inferior_thread ();
11020
11021 return (thread->priv != NULL
11022 && (get_remote_thread_info (thread)->stop_reason
11023 == TARGET_STOPPED_BY_WATCHPOINT));
11024 }
11025
11026 bool
11027 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11028 {
11029 struct thread_info *thread = inferior_thread ();
11030
11031 if (thread->priv != NULL
11032 && (get_remote_thread_info (thread)->stop_reason
11033 == TARGET_STOPPED_BY_WATCHPOINT))
11034 {
11035 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11036 return true;
11037 }
11038
11039 return false;
11040 }
11041
11042
11043 int
11044 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11045 struct bp_target_info *bp_tgt)
11046 {
11047 CORE_ADDR addr = bp_tgt->reqstd_address;
11048 struct remote_state *rs;
11049 char *p, *endbuf;
11050 char *message;
11051
11052 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11053 return -1;
11054
11055 /* Make sure the remote is pointing at the right process, if
11056 necessary. */
11057 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11058 set_general_process ();
11059
11060 rs = get_remote_state ();
11061 p = rs->buf.data ();
11062 endbuf = p + get_remote_packet_size ();
11063
11064 *(p++) = 'Z';
11065 *(p++) = '1';
11066 *(p++) = ',';
11067
11068 addr = remote_address_masked (addr);
11069 p += hexnumstr (p, (ULONGEST) addr);
11070 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11071
11072 if (supports_evaluation_of_breakpoint_conditions ())
11073 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11074
11075 if (can_run_breakpoint_commands ())
11076 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11077
11078 putpkt (rs->buf);
11079 getpkt (&rs->buf, 0);
11080
11081 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11082 {
11083 case PACKET_ERROR:
11084 if (rs->buf[1] == '.')
11085 {
11086 message = strchr (&rs->buf[2], '.');
11087 if (message)
11088 error (_("Remote failure reply: %s"), message + 1);
11089 }
11090 return -1;
11091 case PACKET_UNKNOWN:
11092 return -1;
11093 case PACKET_OK:
11094 return 0;
11095 }
11096 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11097 }
11098
11099
11100 int
11101 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11102 struct bp_target_info *bp_tgt)
11103 {
11104 CORE_ADDR addr;
11105 struct remote_state *rs = get_remote_state ();
11106 char *p = rs->buf.data ();
11107 char *endbuf = p + get_remote_packet_size ();
11108
11109 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11110 return -1;
11111
11112 /* Make sure the remote is pointing at the right process, if
11113 necessary. */
11114 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11115 set_general_process ();
11116
11117 *(p++) = 'z';
11118 *(p++) = '1';
11119 *(p++) = ',';
11120
11121 addr = remote_address_masked (bp_tgt->placed_address);
11122 p += hexnumstr (p, (ULONGEST) addr);
11123 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11124
11125 putpkt (rs->buf);
11126 getpkt (&rs->buf, 0);
11127
11128 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11129 {
11130 case PACKET_ERROR:
11131 case PACKET_UNKNOWN:
11132 return -1;
11133 case PACKET_OK:
11134 return 0;
11135 }
11136 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11137 }
11138
11139 /* Verify memory using the "qCRC:" request. */
11140
11141 int
11142 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11143 {
11144 struct remote_state *rs = get_remote_state ();
11145 unsigned long host_crc, target_crc;
11146 char *tmp;
11147
11148 /* It doesn't make sense to use qCRC if the remote target is
11149 connected but not running. */
11150 if (target_has_execution ()
11151 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11152 {
11153 enum packet_result result;
11154
11155 /* Make sure the remote is pointing at the right process. */
11156 set_general_process ();
11157
11158 /* FIXME: assumes lma can fit into long. */
11159 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11160 (long) lma, (long) size);
11161 putpkt (rs->buf);
11162
11163 /* Be clever; compute the host_crc before waiting for target
11164 reply. */
11165 host_crc = xcrc32 (data, size, 0xffffffff);
11166
11167 getpkt (&rs->buf, 0);
11168
11169 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11170 if (result == PACKET_ERROR)
11171 return -1;
11172 else if (result == PACKET_OK)
11173 {
11174 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11175 target_crc = target_crc * 16 + fromhex (*tmp);
11176
11177 return (host_crc == target_crc);
11178 }
11179 }
11180
11181 return simple_verify_memory (this, data, lma, size);
11182 }
11183
11184 /* compare-sections command
11185
11186 With no arguments, compares each loadable section in the exec bfd
11187 with the same memory range on the target, and reports mismatches.
11188 Useful for verifying the image on the target against the exec file. */
11189
11190 static void
11191 compare_sections_command (const char *args, int from_tty)
11192 {
11193 asection *s;
11194 const char *sectname;
11195 bfd_size_type size;
11196 bfd_vma lma;
11197 int matched = 0;
11198 int mismatched = 0;
11199 int res;
11200 int read_only = 0;
11201
11202 if (!current_program_space->exec_bfd ())
11203 error (_("command cannot be used without an exec file"));
11204
11205 if (args != NULL && strcmp (args, "-r") == 0)
11206 {
11207 read_only = 1;
11208 args = NULL;
11209 }
11210
11211 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11212 {
11213 if (!(s->flags & SEC_LOAD))
11214 continue; /* Skip non-loadable section. */
11215
11216 if (read_only && (s->flags & SEC_READONLY) == 0)
11217 continue; /* Skip writeable sections */
11218
11219 size = bfd_section_size (s);
11220 if (size == 0)
11221 continue; /* Skip zero-length section. */
11222
11223 sectname = bfd_section_name (s);
11224 if (args && strcmp (args, sectname) != 0)
11225 continue; /* Not the section selected by user. */
11226
11227 matched = 1; /* Do this section. */
11228 lma = s->lma;
11229
11230 gdb::byte_vector sectdata (size);
11231 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11232 sectdata.data (), 0, size);
11233
11234 res = target_verify_memory (sectdata.data (), lma, size);
11235
11236 if (res == -1)
11237 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11238 paddress (target_gdbarch (), lma),
11239 paddress (target_gdbarch (), lma + size));
11240
11241 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11242 paddress (target_gdbarch (), lma),
11243 paddress (target_gdbarch (), lma + size));
11244 if (res)
11245 gdb_printf ("matched.\n");
11246 else
11247 {
11248 gdb_printf ("MIS-MATCHED!\n");
11249 mismatched++;
11250 }
11251 }
11252 if (mismatched > 0)
11253 warning (_("One or more sections of the target image does not match\n\
11254 the loaded file\n"));
11255 if (args && !matched)
11256 gdb_printf (_("No loaded section named '%s'.\n"), args);
11257 }
11258
11259 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11260 into remote target. The number of bytes written to the remote
11261 target is returned, or -1 for error. */
11262
11263 target_xfer_status
11264 remote_target::remote_write_qxfer (const char *object_name,
11265 const char *annex, const gdb_byte *writebuf,
11266 ULONGEST offset, LONGEST len,
11267 ULONGEST *xfered_len,
11268 const unsigned int which_packet)
11269 {
11270 int i, buf_len;
11271 ULONGEST n;
11272 struct remote_state *rs = get_remote_state ();
11273 int max_size = get_memory_write_packet_size ();
11274
11275 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11276 return TARGET_XFER_E_IO;
11277
11278 /* Insert header. */
11279 i = snprintf (rs->buf.data (), max_size,
11280 "qXfer:%s:write:%s:%s:",
11281 object_name, annex ? annex : "",
11282 phex_nz (offset, sizeof offset));
11283 max_size -= (i + 1);
11284
11285 /* Escape as much data as fits into rs->buf. */
11286 buf_len = remote_escape_output
11287 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11288
11289 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11290 || getpkt_sane (&rs->buf, 0) < 0
11291 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11292 return TARGET_XFER_E_IO;
11293
11294 unpack_varlen_hex (rs->buf.data (), &n);
11295
11296 *xfered_len = n;
11297 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11298 }
11299
11300 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11301 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11302 number of bytes read is returned, or 0 for EOF, or -1 for error.
11303 The number of bytes read may be less than LEN without indicating an
11304 EOF. PACKET is checked and updated to indicate whether the remote
11305 target supports this object. */
11306
11307 target_xfer_status
11308 remote_target::remote_read_qxfer (const char *object_name,
11309 const char *annex,
11310 gdb_byte *readbuf, ULONGEST offset,
11311 LONGEST len,
11312 ULONGEST *xfered_len,
11313 const unsigned int which_packet)
11314 {
11315 struct remote_state *rs = get_remote_state ();
11316 LONGEST i, n, packet_len;
11317
11318 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11319 return TARGET_XFER_E_IO;
11320
11321 /* Check whether we've cached an end-of-object packet that matches
11322 this request. */
11323 if (rs->finished_object)
11324 {
11325 if (strcmp (object_name, rs->finished_object) == 0
11326 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11327 && offset == rs->finished_offset)
11328 return TARGET_XFER_EOF;
11329
11330
11331 /* Otherwise, we're now reading something different. Discard
11332 the cache. */
11333 xfree (rs->finished_object);
11334 xfree (rs->finished_annex);
11335 rs->finished_object = NULL;
11336 rs->finished_annex = NULL;
11337 }
11338
11339 /* Request only enough to fit in a single packet. The actual data
11340 may not, since we don't know how much of it will need to be escaped;
11341 the target is free to respond with slightly less data. We subtract
11342 five to account for the response type and the protocol frame. */
11343 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11344 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11345 "qXfer:%s:read:%s:%s,%s",
11346 object_name, annex ? annex : "",
11347 phex_nz (offset, sizeof offset),
11348 phex_nz (n, sizeof n));
11349 i = putpkt (rs->buf);
11350 if (i < 0)
11351 return TARGET_XFER_E_IO;
11352
11353 rs->buf[0] = '\0';
11354 packet_len = getpkt_sane (&rs->buf, 0);
11355 if (packet_len < 0
11356 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11357 return TARGET_XFER_E_IO;
11358
11359 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11360 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11361
11362 /* 'm' means there is (or at least might be) more data after this
11363 batch. That does not make sense unless there's at least one byte
11364 of data in this reply. */
11365 if (rs->buf[0] == 'm' && packet_len == 1)
11366 error (_("Remote qXfer reply contained no data."));
11367
11368 /* Got some data. */
11369 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11370 packet_len - 1, readbuf, n);
11371
11372 /* 'l' is an EOF marker, possibly including a final block of data,
11373 or possibly empty. If we have the final block of a non-empty
11374 object, record this fact to bypass a subsequent partial read. */
11375 if (rs->buf[0] == 'l' && offset + i > 0)
11376 {
11377 rs->finished_object = xstrdup (object_name);
11378 rs->finished_annex = xstrdup (annex ? annex : "");
11379 rs->finished_offset = offset + i;
11380 }
11381
11382 if (i == 0)
11383 return TARGET_XFER_EOF;
11384 else
11385 {
11386 *xfered_len = i;
11387 return TARGET_XFER_OK;
11388 }
11389 }
11390
11391 enum target_xfer_status
11392 remote_target::xfer_partial (enum target_object object,
11393 const char *annex, gdb_byte *readbuf,
11394 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11395 ULONGEST *xfered_len)
11396 {
11397 struct remote_state *rs;
11398 int i;
11399 char *p2;
11400 char query_type;
11401 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11402
11403 set_remote_traceframe ();
11404 set_general_thread (inferior_ptid);
11405
11406 rs = get_remote_state ();
11407
11408 /* Handle memory using the standard memory routines. */
11409 if (object == TARGET_OBJECT_MEMORY)
11410 {
11411 /* If the remote target is connected but not running, we should
11412 pass this request down to a lower stratum (e.g. the executable
11413 file). */
11414 if (!target_has_execution ())
11415 return TARGET_XFER_EOF;
11416
11417 if (writebuf != NULL)
11418 return remote_write_bytes (offset, writebuf, len, unit_size,
11419 xfered_len);
11420 else
11421 return remote_read_bytes (offset, readbuf, len, unit_size,
11422 xfered_len);
11423 }
11424
11425 /* Handle extra signal info using qxfer packets. */
11426 if (object == TARGET_OBJECT_SIGNAL_INFO)
11427 {
11428 if (readbuf)
11429 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11430 xfered_len, PACKET_qXfer_siginfo_read);
11431 else
11432 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11433 xfered_len, PACKET_qXfer_siginfo_write);
11434 }
11435
11436 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11437 {
11438 if (readbuf)
11439 return remote_read_qxfer ("statictrace", annex,
11440 readbuf, offset, len, xfered_len,
11441 PACKET_qXfer_statictrace_read);
11442 else
11443 return TARGET_XFER_E_IO;
11444 }
11445
11446 /* Only handle flash writes. */
11447 if (writebuf != NULL)
11448 {
11449 switch (object)
11450 {
11451 case TARGET_OBJECT_FLASH:
11452 return remote_flash_write (offset, len, xfered_len,
11453 writebuf);
11454
11455 default:
11456 return TARGET_XFER_E_IO;
11457 }
11458 }
11459
11460 /* Map pre-existing objects onto letters. DO NOT do this for new
11461 objects!!! Instead specify new query packets. */
11462 switch (object)
11463 {
11464 case TARGET_OBJECT_AVR:
11465 query_type = 'R';
11466 break;
11467
11468 case TARGET_OBJECT_AUXV:
11469 gdb_assert (annex == NULL);
11470 return remote_read_qxfer
11471 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11472
11473 case TARGET_OBJECT_AVAILABLE_FEATURES:
11474 return remote_read_qxfer
11475 ("features", annex, readbuf, offset, len, xfered_len,
11476 PACKET_qXfer_features);
11477
11478 case TARGET_OBJECT_LIBRARIES:
11479 return remote_read_qxfer
11480 ("libraries", annex, readbuf, offset, len, xfered_len,
11481 PACKET_qXfer_libraries);
11482
11483 case TARGET_OBJECT_LIBRARIES_SVR4:
11484 return remote_read_qxfer
11485 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11486 PACKET_qXfer_libraries_svr4);
11487
11488 case TARGET_OBJECT_MEMORY_MAP:
11489 gdb_assert (annex == NULL);
11490 return remote_read_qxfer
11491 ("memory-map", annex, readbuf, offset, len, xfered_len,
11492 PACKET_qXfer_memory_map);
11493
11494 case TARGET_OBJECT_OSDATA:
11495 /* Should only get here if we're connected. */
11496 gdb_assert (rs->remote_desc);
11497 return remote_read_qxfer
11498 ("osdata", annex, readbuf, offset, len, xfered_len,
11499 PACKET_qXfer_osdata);
11500
11501 case TARGET_OBJECT_THREADS:
11502 gdb_assert (annex == NULL);
11503 return remote_read_qxfer
11504 ("threads", annex, readbuf, offset, len, xfered_len,
11505 PACKET_qXfer_threads);
11506
11507 case TARGET_OBJECT_TRACEFRAME_INFO:
11508 gdb_assert (annex == NULL);
11509 return remote_read_qxfer
11510 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11511 PACKET_qXfer_traceframe_info);
11512
11513 case TARGET_OBJECT_FDPIC:
11514 return remote_read_qxfer
11515 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11516
11517 case TARGET_OBJECT_OPENVMS_UIB:
11518 return remote_read_qxfer
11519 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11520
11521 case TARGET_OBJECT_BTRACE:
11522 return remote_read_qxfer
11523 ("btrace", annex, readbuf, offset, len, xfered_len,
11524 PACKET_qXfer_btrace);
11525
11526 case TARGET_OBJECT_BTRACE_CONF:
11527 return remote_read_qxfer
11528 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11529 PACKET_qXfer_btrace_conf);
11530
11531 case TARGET_OBJECT_EXEC_FILE:
11532 return remote_read_qxfer
11533 ("exec-file", annex, readbuf, offset, len, xfered_len,
11534 PACKET_qXfer_exec_file);
11535
11536 default:
11537 return TARGET_XFER_E_IO;
11538 }
11539
11540 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11541 large enough let the caller deal with it. */
11542 if (len < get_remote_packet_size ())
11543 return TARGET_XFER_E_IO;
11544 len = get_remote_packet_size ();
11545
11546 /* Except for querying the minimum buffer size, target must be open. */
11547 if (!rs->remote_desc)
11548 error (_("remote query is only available after target open"));
11549
11550 gdb_assert (annex != NULL);
11551 gdb_assert (readbuf != NULL);
11552
11553 p2 = rs->buf.data ();
11554 *p2++ = 'q';
11555 *p2++ = query_type;
11556
11557 /* We used one buffer char for the remote protocol q command and
11558 another for the query type. As the remote protocol encapsulation
11559 uses 4 chars plus one extra in case we are debugging
11560 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11561 string. */
11562 i = 0;
11563 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11564 {
11565 /* Bad caller may have sent forbidden characters. */
11566 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11567 *p2++ = annex[i];
11568 i++;
11569 }
11570 *p2 = '\0';
11571 gdb_assert (annex[i] == '\0');
11572
11573 i = putpkt (rs->buf);
11574 if (i < 0)
11575 return TARGET_XFER_E_IO;
11576
11577 getpkt (&rs->buf, 0);
11578 strcpy ((char *) readbuf, rs->buf.data ());
11579
11580 *xfered_len = strlen ((char *) readbuf);
11581 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11582 }
11583
11584 /* Implementation of to_get_memory_xfer_limit. */
11585
11586 ULONGEST
11587 remote_target::get_memory_xfer_limit ()
11588 {
11589 return get_memory_write_packet_size ();
11590 }
11591
11592 int
11593 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11594 const gdb_byte *pattern, ULONGEST pattern_len,
11595 CORE_ADDR *found_addrp)
11596 {
11597 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11598 struct remote_state *rs = get_remote_state ();
11599 int max_size = get_memory_write_packet_size ();
11600
11601 /* Number of packet bytes used to encode the pattern;
11602 this could be more than PATTERN_LEN due to escape characters. */
11603 int escaped_pattern_len;
11604 /* Amount of pattern that was encodable in the packet. */
11605 int used_pattern_len;
11606 int i;
11607 int found;
11608 ULONGEST found_addr;
11609
11610 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11611 {
11612 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11613 == len);
11614 };
11615
11616 /* Don't go to the target if we don't have to. This is done before
11617 checking packet_support to avoid the possibility that a success for this
11618 edge case means the facility works in general. */
11619 if (pattern_len > search_space_len)
11620 return 0;
11621 if (pattern_len == 0)
11622 {
11623 *found_addrp = start_addr;
11624 return 1;
11625 }
11626
11627 /* If we already know the packet isn't supported, fall back to the simple
11628 way of searching memory. */
11629
11630 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11631 {
11632 /* Target doesn't provided special support, fall back and use the
11633 standard support (copy memory and do the search here). */
11634 return simple_search_memory (read_memory, start_addr, search_space_len,
11635 pattern, pattern_len, found_addrp);
11636 }
11637
11638 /* Make sure the remote is pointing at the right process. */
11639 set_general_process ();
11640
11641 /* Insert header. */
11642 i = snprintf (rs->buf.data (), max_size,
11643 "qSearch:memory:%s;%s;",
11644 phex_nz (start_addr, addr_size),
11645 phex_nz (search_space_len, sizeof (search_space_len)));
11646 max_size -= (i + 1);
11647
11648 /* Escape as much data as fits into rs->buf. */
11649 escaped_pattern_len =
11650 remote_escape_output (pattern, pattern_len, 1,
11651 (gdb_byte *) rs->buf.data () + i,
11652 &used_pattern_len, max_size);
11653
11654 /* Bail if the pattern is too large. */
11655 if (used_pattern_len != pattern_len)
11656 error (_("Pattern is too large to transmit to remote target."));
11657
11658 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11659 || getpkt_sane (&rs->buf, 0) < 0
11660 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11661 {
11662 /* The request may not have worked because the command is not
11663 supported. If so, fall back to the simple way. */
11664 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11665 {
11666 return simple_search_memory (read_memory, start_addr, search_space_len,
11667 pattern, pattern_len, found_addrp);
11668 }
11669 return -1;
11670 }
11671
11672 if (rs->buf[0] == '0')
11673 found = 0;
11674 else if (rs->buf[0] == '1')
11675 {
11676 found = 1;
11677 if (rs->buf[1] != ',')
11678 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11679 unpack_varlen_hex (&rs->buf[2], &found_addr);
11680 *found_addrp = found_addr;
11681 }
11682 else
11683 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11684
11685 return found;
11686 }
11687
11688 void
11689 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11690 {
11691 struct remote_state *rs = get_remote_state ();
11692 char *p = rs->buf.data ();
11693
11694 if (!rs->remote_desc)
11695 error (_("remote rcmd is only available after target open"));
11696
11697 /* Send a NULL command across as an empty command. */
11698 if (command == NULL)
11699 command = "";
11700
11701 /* The query prefix. */
11702 strcpy (rs->buf.data (), "qRcmd,");
11703 p = strchr (rs->buf.data (), '\0');
11704
11705 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11706 > get_remote_packet_size ())
11707 error (_("\"monitor\" command ``%s'' is too long."), command);
11708
11709 /* Encode the actual command. */
11710 bin2hex ((const gdb_byte *) command, p, strlen (command));
11711
11712 if (putpkt (rs->buf) < 0)
11713 error (_("Communication problem with target."));
11714
11715 /* get/display the response */
11716 while (1)
11717 {
11718 char *buf;
11719
11720 /* XXX - see also remote_get_noisy_reply(). */
11721 QUIT; /* Allow user to bail out with ^C. */
11722 rs->buf[0] = '\0';
11723 if (getpkt_sane (&rs->buf, 0) == -1)
11724 {
11725 /* Timeout. Continue to (try to) read responses.
11726 This is better than stopping with an error, assuming the stub
11727 is still executing the (long) monitor command.
11728 If needed, the user can interrupt gdb using C-c, obtaining
11729 an effect similar to stop on timeout. */
11730 continue;
11731 }
11732 buf = rs->buf.data ();
11733 if (buf[0] == '\0')
11734 error (_("Target does not support this command."));
11735 if (buf[0] == 'O' && buf[1] != 'K')
11736 {
11737 remote_console_output (buf + 1); /* 'O' message from stub. */
11738 continue;
11739 }
11740 if (strcmp (buf, "OK") == 0)
11741 break;
11742 if (strlen (buf) == 3 && buf[0] == 'E'
11743 && isxdigit (buf[1]) && isxdigit (buf[2]))
11744 {
11745 error (_("Protocol error with Rcmd"));
11746 }
11747 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11748 {
11749 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11750
11751 gdb_putc (c, outbuf);
11752 }
11753 break;
11754 }
11755 }
11756
11757 std::vector<mem_region>
11758 remote_target::memory_map ()
11759 {
11760 std::vector<mem_region> result;
11761 gdb::optional<gdb::char_vector> text
11762 = target_read_stralloc (current_inferior ()->top_target (),
11763 TARGET_OBJECT_MEMORY_MAP, NULL);
11764
11765 if (text)
11766 result = parse_memory_map (text->data ());
11767
11768 return result;
11769 }
11770
11771 /* Set of callbacks used to implement the 'maint packet' command. */
11772
11773 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11774 {
11775 /* Called before the packet is sent. BUF is the packet content before
11776 the protocol specific prefix, suffix, and escaping is added. */
11777
11778 void sending (gdb::array_view<const char> &buf) override
11779 {
11780 gdb_puts ("sending: ");
11781 print_packet (buf);
11782 gdb_puts ("\n");
11783 }
11784
11785 /* Called with BUF, the reply from the remote target. */
11786
11787 void received (gdb::array_view<const char> &buf) override
11788 {
11789 gdb_puts ("received: \"");
11790 print_packet (buf);
11791 gdb_puts ("\"\n");
11792 }
11793
11794 private:
11795
11796 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11797 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11798
11799 static void
11800 print_packet (gdb::array_view<const char> &buf)
11801 {
11802 string_file stb;
11803
11804 for (int i = 0; i < buf.size (); ++i)
11805 {
11806 gdb_byte c = buf[i];
11807 if (isprint (c))
11808 gdb_putc (c, &stb);
11809 else
11810 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11811 }
11812
11813 gdb_puts (stb.string ().c_str ());
11814 }
11815 };
11816
11817 /* See remote.h. */
11818
11819 void
11820 send_remote_packet (gdb::array_view<const char> &buf,
11821 send_remote_packet_callbacks *callbacks)
11822 {
11823 if (buf.size () == 0 || buf.data ()[0] == '\0')
11824 error (_("a remote packet must not be empty"));
11825
11826 remote_target *remote = get_current_remote_target ();
11827 if (remote == nullptr)
11828 error (_("packets can only be sent to a remote target"));
11829
11830 callbacks->sending (buf);
11831
11832 remote->putpkt_binary (buf.data (), buf.size ());
11833 remote_state *rs = remote->get_remote_state ();
11834 int bytes = remote->getpkt_sane (&rs->buf, 0);
11835
11836 if (bytes < 0)
11837 error (_("error while fetching packet from remote target"));
11838
11839 gdb::array_view<const char> view (&rs->buf[0], bytes);
11840 callbacks->received (view);
11841 }
11842
11843 /* Entry point for the 'maint packet' command. */
11844
11845 static void
11846 cli_packet_command (const char *args, int from_tty)
11847 {
11848 cli_packet_command_callbacks cb;
11849 gdb::array_view<const char> view
11850 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11851 send_remote_packet (view, &cb);
11852 }
11853
11854 #if 0
11855 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11856
11857 static void display_thread_info (struct gdb_ext_thread_info *info);
11858
11859 static void threadset_test_cmd (char *cmd, int tty);
11860
11861 static void threadalive_test (char *cmd, int tty);
11862
11863 static void threadlist_test_cmd (char *cmd, int tty);
11864
11865 int get_and_display_threadinfo (threadref *ref);
11866
11867 static void threadinfo_test_cmd (char *cmd, int tty);
11868
11869 static int thread_display_step (threadref *ref, void *context);
11870
11871 static void threadlist_update_test_cmd (char *cmd, int tty);
11872
11873 static void init_remote_threadtests (void);
11874
11875 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11876
11877 static void
11878 threadset_test_cmd (const char *cmd, int tty)
11879 {
11880 int sample_thread = SAMPLE_THREAD;
11881
11882 gdb_printf (_("Remote threadset test\n"));
11883 set_general_thread (sample_thread);
11884 }
11885
11886
11887 static void
11888 threadalive_test (const char *cmd, int tty)
11889 {
11890 int sample_thread = SAMPLE_THREAD;
11891 int pid = inferior_ptid.pid ();
11892 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11893
11894 if (remote_thread_alive (ptid))
11895 gdb_printf ("PASS: Thread alive test\n");
11896 else
11897 gdb_printf ("FAIL: Thread alive test\n");
11898 }
11899
11900 void output_threadid (char *title, threadref *ref);
11901
11902 void
11903 output_threadid (char *title, threadref *ref)
11904 {
11905 char hexid[20];
11906
11907 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11908 hexid[16] = 0;
11909 gdb_printf ("%s %s\n", title, (&hexid[0]));
11910 }
11911
11912 static void
11913 threadlist_test_cmd (const char *cmd, int tty)
11914 {
11915 int startflag = 1;
11916 threadref nextthread;
11917 int done, result_count;
11918 threadref threadlist[3];
11919
11920 gdb_printf ("Remote Threadlist test\n");
11921 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11922 &result_count, &threadlist[0]))
11923 gdb_printf ("FAIL: threadlist test\n");
11924 else
11925 {
11926 threadref *scan = threadlist;
11927 threadref *limit = scan + result_count;
11928
11929 while (scan < limit)
11930 output_threadid (" thread ", scan++);
11931 }
11932 }
11933
11934 void
11935 display_thread_info (struct gdb_ext_thread_info *info)
11936 {
11937 output_threadid ("Threadid: ", &info->threadid);
11938 gdb_printf ("Name: %s\n ", info->shortname);
11939 gdb_printf ("State: %s\n", info->display);
11940 gdb_printf ("other: %s\n\n", info->more_display);
11941 }
11942
11943 int
11944 get_and_display_threadinfo (threadref *ref)
11945 {
11946 int result;
11947 int set;
11948 struct gdb_ext_thread_info threadinfo;
11949
11950 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11951 | TAG_MOREDISPLAY | TAG_DISPLAY;
11952 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11953 display_thread_info (&threadinfo);
11954 return result;
11955 }
11956
11957 static void
11958 threadinfo_test_cmd (const char *cmd, int tty)
11959 {
11960 int athread = SAMPLE_THREAD;
11961 threadref thread;
11962 int set;
11963
11964 int_to_threadref (&thread, athread);
11965 gdb_printf ("Remote Threadinfo test\n");
11966 if (!get_and_display_threadinfo (&thread))
11967 gdb_printf ("FAIL cannot get thread info\n");
11968 }
11969
11970 static int
11971 thread_display_step (threadref *ref, void *context)
11972 {
11973 /* output_threadid(" threadstep ",ref); *//* simple test */
11974 return get_and_display_threadinfo (ref);
11975 }
11976
11977 static void
11978 threadlist_update_test_cmd (const char *cmd, int tty)
11979 {
11980 gdb_printf ("Remote Threadlist update test\n");
11981 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11982 }
11983
11984 static void
11985 init_remote_threadtests (void)
11986 {
11987 add_com ("tlist", class_obscure, threadlist_test_cmd,
11988 _("Fetch and print the remote list of "
11989 "thread identifiers, one pkt only."));
11990 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11991 _("Fetch and display info about one thread."));
11992 add_com ("tset", class_obscure, threadset_test_cmd,
11993 _("Test setting to a different thread."));
11994 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11995 _("Iterate through updating all remote thread info."));
11996 add_com ("talive", class_obscure, threadalive_test,
11997 _("Remote thread alive test."));
11998 }
11999
12000 #endif /* 0 */
12001
12002 /* Convert a thread ID to a string. */
12003
12004 std::string
12005 remote_target::pid_to_str (ptid_t ptid)
12006 {
12007 if (ptid == null_ptid)
12008 return normal_pid_to_str (ptid);
12009 else if (ptid.is_pid ())
12010 {
12011 /* Printing an inferior target id. */
12012
12013 /* When multi-process extensions are off, there's no way in the
12014 remote protocol to know the remote process id, if there's any
12015 at all. There's one exception --- when we're connected with
12016 target extended-remote, and we manually attached to a process
12017 with "attach PID". We don't record anywhere a flag that
12018 allows us to distinguish that case from the case of
12019 connecting with extended-remote and the stub already being
12020 attached to a process, and reporting yes to qAttached, hence
12021 no smart special casing here. */
12022 if (!m_features.remote_multi_process_p ())
12023 return "Remote target";
12024
12025 return normal_pid_to_str (ptid);
12026 }
12027 else
12028 {
12029 if (magic_null_ptid == ptid)
12030 return "Thread <main>";
12031 else if (m_features.remote_multi_process_p ())
12032 if (ptid.lwp () == 0)
12033 return normal_pid_to_str (ptid);
12034 else
12035 return string_printf ("Thread %d.%ld",
12036 ptid.pid (), ptid.lwp ());
12037 else
12038 return string_printf ("Thread %ld", ptid.lwp ());
12039 }
12040 }
12041
12042 /* Get the address of the thread local variable in OBJFILE which is
12043 stored at OFFSET within the thread local storage for thread PTID. */
12044
12045 CORE_ADDR
12046 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12047 CORE_ADDR offset)
12048 {
12049 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12050 {
12051 struct remote_state *rs = get_remote_state ();
12052 char *p = rs->buf.data ();
12053 char *endp = p + get_remote_packet_size ();
12054 enum packet_result result;
12055
12056 strcpy (p, "qGetTLSAddr:");
12057 p += strlen (p);
12058 p = write_ptid (p, endp, ptid);
12059 *p++ = ',';
12060 p += hexnumstr (p, offset);
12061 *p++ = ',';
12062 p += hexnumstr (p, lm);
12063 *p++ = '\0';
12064
12065 putpkt (rs->buf);
12066 getpkt (&rs->buf, 0);
12067 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12068 if (result == PACKET_OK)
12069 {
12070 ULONGEST addr;
12071
12072 unpack_varlen_hex (rs->buf.data (), &addr);
12073 return addr;
12074 }
12075 else if (result == PACKET_UNKNOWN)
12076 throw_error (TLS_GENERIC_ERROR,
12077 _("Remote target doesn't support qGetTLSAddr packet"));
12078 else
12079 throw_error (TLS_GENERIC_ERROR,
12080 _("Remote target failed to process qGetTLSAddr request"));
12081 }
12082 else
12083 throw_error (TLS_GENERIC_ERROR,
12084 _("TLS not supported or disabled on this target"));
12085 /* Not reached. */
12086 return 0;
12087 }
12088
12089 /* Provide thread local base, i.e. Thread Information Block address.
12090 Returns 1 if ptid is found and thread_local_base is non zero. */
12091
12092 bool
12093 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12094 {
12095 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12096 {
12097 struct remote_state *rs = get_remote_state ();
12098 char *p = rs->buf.data ();
12099 char *endp = p + get_remote_packet_size ();
12100 enum packet_result result;
12101
12102 strcpy (p, "qGetTIBAddr:");
12103 p += strlen (p);
12104 p = write_ptid (p, endp, ptid);
12105 *p++ = '\0';
12106
12107 putpkt (rs->buf);
12108 getpkt (&rs->buf, 0);
12109 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12110 if (result == PACKET_OK)
12111 {
12112 ULONGEST val;
12113 unpack_varlen_hex (rs->buf.data (), &val);
12114 if (addr)
12115 *addr = (CORE_ADDR) val;
12116 return true;
12117 }
12118 else if (result == PACKET_UNKNOWN)
12119 error (_("Remote target doesn't support qGetTIBAddr packet"));
12120 else
12121 error (_("Remote target failed to process qGetTIBAddr request"));
12122 }
12123 else
12124 error (_("qGetTIBAddr not supported or disabled on this target"));
12125 /* Not reached. */
12126 return false;
12127 }
12128
12129 /* Support for inferring a target description based on the current
12130 architecture and the size of a 'g' packet. While the 'g' packet
12131 can have any size (since optional registers can be left off the
12132 end), some sizes are easily recognizable given knowledge of the
12133 approximate architecture. */
12134
12135 struct remote_g_packet_guess
12136 {
12137 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12138 : bytes (bytes_),
12139 tdesc (tdesc_)
12140 {
12141 }
12142
12143 int bytes;
12144 const struct target_desc *tdesc;
12145 };
12146
12147 struct remote_g_packet_data
12148 {
12149 std::vector<remote_g_packet_guess> guesses;
12150 };
12151
12152 static const registry<gdbarch>::key<struct remote_g_packet_data>
12153 remote_g_packet_data_handle;
12154
12155 static struct remote_g_packet_data *
12156 get_g_packet_data (struct gdbarch *gdbarch)
12157 {
12158 struct remote_g_packet_data *data
12159 = remote_g_packet_data_handle.get (gdbarch);
12160 if (data == nullptr)
12161 data = remote_g_packet_data_handle.emplace (gdbarch);
12162 return data;
12163 }
12164
12165 void
12166 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12167 const struct target_desc *tdesc)
12168 {
12169 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12170
12171 gdb_assert (tdesc != NULL);
12172
12173 for (const remote_g_packet_guess &guess : data->guesses)
12174 if (guess.bytes == bytes)
12175 internal_error (_("Duplicate g packet description added for size %d"),
12176 bytes);
12177
12178 data->guesses.emplace_back (bytes, tdesc);
12179 }
12180
12181 /* Return true if remote_read_description would do anything on this target
12182 and architecture, false otherwise. */
12183
12184 static bool
12185 remote_read_description_p (struct target_ops *target)
12186 {
12187 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12188
12189 return !data->guesses.empty ();
12190 }
12191
12192 const struct target_desc *
12193 remote_target::read_description ()
12194 {
12195 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12196
12197 /* Do not try this during initial connection, when we do not know
12198 whether there is a running but stopped thread. */
12199 if (!target_has_execution () || inferior_ptid == null_ptid)
12200 return beneath ()->read_description ();
12201
12202 if (!data->guesses.empty ())
12203 {
12204 int bytes = send_g_packet ();
12205
12206 for (const remote_g_packet_guess &guess : data->guesses)
12207 if (guess.bytes == bytes)
12208 return guess.tdesc;
12209
12210 /* We discard the g packet. A minor optimization would be to
12211 hold on to it, and fill the register cache once we have selected
12212 an architecture, but it's too tricky to do safely. */
12213 }
12214
12215 return beneath ()->read_description ();
12216 }
12217
12218 /* Remote file transfer support. This is host-initiated I/O, not
12219 target-initiated; for target-initiated, see remote-fileio.c. */
12220
12221 /* If *LEFT is at least the length of STRING, copy STRING to
12222 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12223 decrease *LEFT. Otherwise raise an error. */
12224
12225 static void
12226 remote_buffer_add_string (char **buffer, int *left, const char *string)
12227 {
12228 int len = strlen (string);
12229
12230 if (len > *left)
12231 error (_("Packet too long for target."));
12232
12233 memcpy (*buffer, string, len);
12234 *buffer += len;
12235 *left -= len;
12236
12237 /* NUL-terminate the buffer as a convenience, if there is
12238 room. */
12239 if (*left)
12240 **buffer = '\0';
12241 }
12242
12243 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12244 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12245 decrease *LEFT. Otherwise raise an error. */
12246
12247 static void
12248 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12249 int len)
12250 {
12251 if (2 * len > *left)
12252 error (_("Packet too long for target."));
12253
12254 bin2hex (bytes, *buffer, len);
12255 *buffer += 2 * len;
12256 *left -= 2 * len;
12257
12258 /* NUL-terminate the buffer as a convenience, if there is
12259 room. */
12260 if (*left)
12261 **buffer = '\0';
12262 }
12263
12264 /* If *LEFT is large enough, convert VALUE to hex and add it to
12265 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12266 decrease *LEFT. Otherwise raise an error. */
12267
12268 static void
12269 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12270 {
12271 int len = hexnumlen (value);
12272
12273 if (len > *left)
12274 error (_("Packet too long for target."));
12275
12276 hexnumstr (*buffer, value);
12277 *buffer += len;
12278 *left -= len;
12279
12280 /* NUL-terminate the buffer as a convenience, if there is
12281 room. */
12282 if (*left)
12283 **buffer = '\0';
12284 }
12285
12286 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12287 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12288 was included, and *ATTACHMENT to point to the start of the annex
12289 if any. The length of the packet isn't needed here; there may
12290 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12291
12292 Return 0 if the packet could be parsed, -1 if it could not. If
12293 -1 is returned, the other variables may not be initialized. */
12294
12295 static int
12296 remote_hostio_parse_result (const char *buffer, int *retcode,
12297 fileio_error *remote_errno, const char **attachment)
12298 {
12299 char *p, *p2;
12300
12301 *remote_errno = FILEIO_SUCCESS;
12302 *attachment = NULL;
12303
12304 if (buffer[0] != 'F')
12305 return -1;
12306
12307 errno = 0;
12308 *retcode = strtol (&buffer[1], &p, 16);
12309 if (errno != 0 || p == &buffer[1])
12310 return -1;
12311
12312 /* Check for ",errno". */
12313 if (*p == ',')
12314 {
12315 errno = 0;
12316 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12317 if (errno != 0 || p + 1 == p2)
12318 return -1;
12319 p = p2;
12320 }
12321
12322 /* Check for ";attachment". If there is no attachment, the
12323 packet should end here. */
12324 if (*p == ';')
12325 {
12326 *attachment = p + 1;
12327 return 0;
12328 }
12329 else if (*p == '\0')
12330 return 0;
12331 else
12332 return -1;
12333 }
12334
12335 /* Send a prepared I/O packet to the target and read its response.
12336 The prepared packet is in the global RS->BUF before this function
12337 is called, and the answer is there when we return.
12338
12339 COMMAND_BYTES is the length of the request to send, which may include
12340 binary data. WHICH_PACKET is the packet configuration to check
12341 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12342 is set to the error number and -1 is returned. Otherwise the value
12343 returned by the function is returned.
12344
12345 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12346 attachment is expected; an error will be reported if there's a
12347 mismatch. If one is found, *ATTACHMENT will be set to point into
12348 the packet buffer and *ATTACHMENT_LEN will be set to the
12349 attachment's length. */
12350
12351 int
12352 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12353 fileio_error *remote_errno, const char **attachment,
12354 int *attachment_len)
12355 {
12356 struct remote_state *rs = get_remote_state ();
12357 int ret, bytes_read;
12358 const char *attachment_tmp;
12359
12360 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12361 {
12362 *remote_errno = FILEIO_ENOSYS;
12363 return -1;
12364 }
12365
12366 putpkt_binary (rs->buf.data (), command_bytes);
12367 bytes_read = getpkt_sane (&rs->buf, 0);
12368
12369 /* If it timed out, something is wrong. Don't try to parse the
12370 buffer. */
12371 if (bytes_read < 0)
12372 {
12373 *remote_errno = FILEIO_EINVAL;
12374 return -1;
12375 }
12376
12377 switch (m_features.packet_ok (rs->buf, which_packet))
12378 {
12379 case PACKET_ERROR:
12380 *remote_errno = FILEIO_EINVAL;
12381 return -1;
12382 case PACKET_UNKNOWN:
12383 *remote_errno = FILEIO_ENOSYS;
12384 return -1;
12385 case PACKET_OK:
12386 break;
12387 }
12388
12389 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12390 &attachment_tmp))
12391 {
12392 *remote_errno = FILEIO_EINVAL;
12393 return -1;
12394 }
12395
12396 /* Make sure we saw an attachment if and only if we expected one. */
12397 if ((attachment_tmp == NULL && attachment != NULL)
12398 || (attachment_tmp != NULL && attachment == NULL))
12399 {
12400 *remote_errno = FILEIO_EINVAL;
12401 return -1;
12402 }
12403
12404 /* If an attachment was found, it must point into the packet buffer;
12405 work out how many bytes there were. */
12406 if (attachment_tmp != NULL)
12407 {
12408 *attachment = attachment_tmp;
12409 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12410 }
12411
12412 return ret;
12413 }
12414
12415 /* See declaration.h. */
12416
12417 void
12418 readahead_cache::invalidate ()
12419 {
12420 this->fd = -1;
12421 }
12422
12423 /* See declaration.h. */
12424
12425 void
12426 readahead_cache::invalidate_fd (int fd)
12427 {
12428 if (this->fd == fd)
12429 this->fd = -1;
12430 }
12431
12432 /* Set the filesystem remote_hostio functions that take FILENAME
12433 arguments will use. Return 0 on success, or -1 if an error
12434 occurs (and set *REMOTE_ERRNO). */
12435
12436 int
12437 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12438 fileio_error *remote_errno)
12439 {
12440 struct remote_state *rs = get_remote_state ();
12441 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12442 char *p = rs->buf.data ();
12443 int left = get_remote_packet_size () - 1;
12444 char arg[9];
12445 int ret;
12446
12447 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12448 return 0;
12449
12450 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12451 return 0;
12452
12453 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12454
12455 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12456 remote_buffer_add_string (&p, &left, arg);
12457
12458 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12459 remote_errno, NULL, NULL);
12460
12461 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12462 return 0;
12463
12464 if (ret == 0)
12465 rs->fs_pid = required_pid;
12466
12467 return ret;
12468 }
12469
12470 /* Implementation of to_fileio_open. */
12471
12472 int
12473 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12474 int flags, int mode, int warn_if_slow,
12475 fileio_error *remote_errno)
12476 {
12477 struct remote_state *rs = get_remote_state ();
12478 char *p = rs->buf.data ();
12479 int left = get_remote_packet_size () - 1;
12480
12481 if (warn_if_slow)
12482 {
12483 static int warning_issued = 0;
12484
12485 gdb_printf (_("Reading %s from remote target...\n"),
12486 filename);
12487
12488 if (!warning_issued)
12489 {
12490 warning (_("File transfers from remote targets can be slow."
12491 " Use \"set sysroot\" to access files locally"
12492 " instead."));
12493 warning_issued = 1;
12494 }
12495 }
12496
12497 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12498 return -1;
12499
12500 remote_buffer_add_string (&p, &left, "vFile:open:");
12501
12502 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12503 strlen (filename));
12504 remote_buffer_add_string (&p, &left, ",");
12505
12506 remote_buffer_add_int (&p, &left, flags);
12507 remote_buffer_add_string (&p, &left, ",");
12508
12509 remote_buffer_add_int (&p, &left, mode);
12510
12511 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12512 remote_errno, NULL, NULL);
12513 }
12514
12515 int
12516 remote_target::fileio_open (struct inferior *inf, const char *filename,
12517 int flags, int mode, int warn_if_slow,
12518 fileio_error *remote_errno)
12519 {
12520 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12521 remote_errno);
12522 }
12523
12524 /* Implementation of to_fileio_pwrite. */
12525
12526 int
12527 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12528 ULONGEST offset, fileio_error *remote_errno)
12529 {
12530 struct remote_state *rs = get_remote_state ();
12531 char *p = rs->buf.data ();
12532 int left = get_remote_packet_size ();
12533 int out_len;
12534
12535 rs->readahead_cache.invalidate_fd (fd);
12536
12537 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12538
12539 remote_buffer_add_int (&p, &left, fd);
12540 remote_buffer_add_string (&p, &left, ",");
12541
12542 remote_buffer_add_int (&p, &left, offset);
12543 remote_buffer_add_string (&p, &left, ",");
12544
12545 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12546 (get_remote_packet_size ()
12547 - (p - rs->buf.data ())));
12548
12549 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12550 remote_errno, NULL, NULL);
12551 }
12552
12553 int
12554 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12555 ULONGEST offset, fileio_error *remote_errno)
12556 {
12557 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12558 }
12559
12560 /* Helper for the implementation of to_fileio_pread. Read the file
12561 from the remote side with vFile:pread. */
12562
12563 int
12564 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12565 ULONGEST offset, fileio_error *remote_errno)
12566 {
12567 struct remote_state *rs = get_remote_state ();
12568 char *p = rs->buf.data ();
12569 const char *attachment;
12570 int left = get_remote_packet_size ();
12571 int ret, attachment_len;
12572 int read_len;
12573
12574 remote_buffer_add_string (&p, &left, "vFile:pread:");
12575
12576 remote_buffer_add_int (&p, &left, fd);
12577 remote_buffer_add_string (&p, &left, ",");
12578
12579 remote_buffer_add_int (&p, &left, len);
12580 remote_buffer_add_string (&p, &left, ",");
12581
12582 remote_buffer_add_int (&p, &left, offset);
12583
12584 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12585 remote_errno, &attachment,
12586 &attachment_len);
12587
12588 if (ret < 0)
12589 return ret;
12590
12591 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12592 read_buf, len);
12593 if (read_len != ret)
12594 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12595
12596 return ret;
12597 }
12598
12599 /* See declaration.h. */
12600
12601 int
12602 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12603 ULONGEST offset)
12604 {
12605 if (this->fd == fd
12606 && this->offset <= offset
12607 && offset < this->offset + this->bufsize)
12608 {
12609 ULONGEST max = this->offset + this->bufsize;
12610
12611 if (offset + len > max)
12612 len = max - offset;
12613
12614 memcpy (read_buf, this->buf + offset - this->offset, len);
12615 return len;
12616 }
12617
12618 return 0;
12619 }
12620
12621 /* Implementation of to_fileio_pread. */
12622
12623 int
12624 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12625 ULONGEST offset, fileio_error *remote_errno)
12626 {
12627 int ret;
12628 struct remote_state *rs = get_remote_state ();
12629 readahead_cache *cache = &rs->readahead_cache;
12630
12631 ret = cache->pread (fd, read_buf, len, offset);
12632 if (ret > 0)
12633 {
12634 cache->hit_count++;
12635
12636 remote_debug_printf ("readahead cache hit %s",
12637 pulongest (cache->hit_count));
12638 return ret;
12639 }
12640
12641 cache->miss_count++;
12642
12643 remote_debug_printf ("readahead cache miss %s",
12644 pulongest (cache->miss_count));
12645
12646 cache->fd = fd;
12647 cache->offset = offset;
12648 cache->bufsize = get_remote_packet_size ();
12649 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12650
12651 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12652 cache->offset, remote_errno);
12653 if (ret <= 0)
12654 {
12655 cache->invalidate_fd (fd);
12656 return ret;
12657 }
12658
12659 cache->bufsize = ret;
12660 return cache->pread (fd, read_buf, len, offset);
12661 }
12662
12663 int
12664 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12665 ULONGEST offset, fileio_error *remote_errno)
12666 {
12667 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12668 }
12669
12670 /* Implementation of to_fileio_close. */
12671
12672 int
12673 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12674 {
12675 struct remote_state *rs = get_remote_state ();
12676 char *p = rs->buf.data ();
12677 int left = get_remote_packet_size () - 1;
12678
12679 rs->readahead_cache.invalidate_fd (fd);
12680
12681 remote_buffer_add_string (&p, &left, "vFile:close:");
12682
12683 remote_buffer_add_int (&p, &left, fd);
12684
12685 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12686 remote_errno, NULL, NULL);
12687 }
12688
12689 int
12690 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12691 {
12692 return remote_hostio_close (fd, remote_errno);
12693 }
12694
12695 /* Implementation of to_fileio_unlink. */
12696
12697 int
12698 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12699 fileio_error *remote_errno)
12700 {
12701 struct remote_state *rs = get_remote_state ();
12702 char *p = rs->buf.data ();
12703 int left = get_remote_packet_size () - 1;
12704
12705 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12706 return -1;
12707
12708 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12709
12710 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12711 strlen (filename));
12712
12713 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12714 remote_errno, NULL, NULL);
12715 }
12716
12717 int
12718 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12719 fileio_error *remote_errno)
12720 {
12721 return remote_hostio_unlink (inf, filename, remote_errno);
12722 }
12723
12724 /* Implementation of to_fileio_readlink. */
12725
12726 gdb::optional<std::string>
12727 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12728 fileio_error *remote_errno)
12729 {
12730 struct remote_state *rs = get_remote_state ();
12731 char *p = rs->buf.data ();
12732 const char *attachment;
12733 int left = get_remote_packet_size ();
12734 int len, attachment_len;
12735 int read_len;
12736
12737 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12738 return {};
12739
12740 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12741
12742 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12743 strlen (filename));
12744
12745 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12746 remote_errno, &attachment,
12747 &attachment_len);
12748
12749 if (len < 0)
12750 return {};
12751
12752 std::string ret (len, '\0');
12753
12754 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12755 (gdb_byte *) &ret[0], len);
12756 if (read_len != len)
12757 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12758
12759 return ret;
12760 }
12761
12762 /* Implementation of to_fileio_fstat. */
12763
12764 int
12765 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12766 {
12767 struct remote_state *rs = get_remote_state ();
12768 char *p = rs->buf.data ();
12769 int left = get_remote_packet_size ();
12770 int attachment_len, ret;
12771 const char *attachment;
12772 struct fio_stat fst;
12773 int read_len;
12774
12775 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12776
12777 remote_buffer_add_int (&p, &left, fd);
12778
12779 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12780 remote_errno, &attachment,
12781 &attachment_len);
12782 if (ret < 0)
12783 {
12784 if (*remote_errno != FILEIO_ENOSYS)
12785 return ret;
12786
12787 /* Strictly we should return -1, ENOSYS here, but when
12788 "set sysroot remote:" was implemented in August 2008
12789 BFD's need for a stat function was sidestepped with
12790 this hack. This was not remedied until March 2015
12791 so we retain the previous behavior to avoid breaking
12792 compatibility.
12793
12794 Note that the memset is a March 2015 addition; older
12795 GDBs set st_size *and nothing else* so the structure
12796 would have garbage in all other fields. This might
12797 break something but retaining the previous behavior
12798 here would be just too wrong. */
12799
12800 memset (st, 0, sizeof (struct stat));
12801 st->st_size = INT_MAX;
12802 return 0;
12803 }
12804
12805 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12806 (gdb_byte *) &fst, sizeof (fst));
12807
12808 if (read_len != ret)
12809 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12810
12811 if (read_len != sizeof (fst))
12812 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12813 read_len, (int) sizeof (fst));
12814
12815 remote_fileio_to_host_stat (&fst, st);
12816
12817 return 0;
12818 }
12819
12820 /* Implementation of to_filesystem_is_local. */
12821
12822 bool
12823 remote_target::filesystem_is_local ()
12824 {
12825 /* Valgrind GDB presents itself as a remote target but works
12826 on the local filesystem: it does not implement remote get
12827 and users are not expected to set a sysroot. To handle
12828 this case we treat the remote filesystem as local if the
12829 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12830 does not support vFile:open. */
12831 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12832 {
12833 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12834
12835 if (ps == PACKET_SUPPORT_UNKNOWN)
12836 {
12837 int fd;
12838 fileio_error remote_errno;
12839
12840 /* Try opening a file to probe support. The supplied
12841 filename is irrelevant, we only care about whether
12842 the stub recognizes the packet or not. */
12843 fd = remote_hostio_open (NULL, "just probing",
12844 FILEIO_O_RDONLY, 0700, 0,
12845 &remote_errno);
12846
12847 if (fd >= 0)
12848 remote_hostio_close (fd, &remote_errno);
12849
12850 ps = m_features.packet_support (PACKET_vFile_open);
12851 }
12852
12853 if (ps == PACKET_DISABLE)
12854 {
12855 static int warning_issued = 0;
12856
12857 if (!warning_issued)
12858 {
12859 warning (_("remote target does not support file"
12860 " transfer, attempting to access files"
12861 " from local filesystem."));
12862 warning_issued = 1;
12863 }
12864
12865 return true;
12866 }
12867 }
12868
12869 return false;
12870 }
12871
12872 static char *
12873 remote_hostio_error (fileio_error errnum)
12874 {
12875 int host_error = fileio_error_to_host (errnum);
12876
12877 if (host_error == -1)
12878 error (_("Unknown remote I/O error %d"), errnum);
12879 else
12880 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12881 }
12882
12883 /* A RAII wrapper around a remote file descriptor. */
12884
12885 class scoped_remote_fd
12886 {
12887 public:
12888 scoped_remote_fd (remote_target *remote, int fd)
12889 : m_remote (remote), m_fd (fd)
12890 {
12891 }
12892
12893 ~scoped_remote_fd ()
12894 {
12895 if (m_fd != -1)
12896 {
12897 try
12898 {
12899 fileio_error remote_errno;
12900 m_remote->remote_hostio_close (m_fd, &remote_errno);
12901 }
12902 catch (...)
12903 {
12904 /* Swallow exception before it escapes the dtor. If
12905 something goes wrong, likely the connection is gone,
12906 and there's nothing else that can be done. */
12907 }
12908 }
12909 }
12910
12911 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12912
12913 /* Release ownership of the file descriptor, and return it. */
12914 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12915 {
12916 int fd = m_fd;
12917 m_fd = -1;
12918 return fd;
12919 }
12920
12921 /* Return the owned file descriptor. */
12922 int get () const noexcept
12923 {
12924 return m_fd;
12925 }
12926
12927 private:
12928 /* The remote target. */
12929 remote_target *m_remote;
12930
12931 /* The owned remote I/O file descriptor. */
12932 int m_fd;
12933 };
12934
12935 void
12936 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12937 {
12938 remote_target *remote = get_current_remote_target ();
12939
12940 if (remote == nullptr)
12941 error (_("command can only be used with remote target"));
12942
12943 remote->remote_file_put (local_file, remote_file, from_tty);
12944 }
12945
12946 void
12947 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12948 int from_tty)
12949 {
12950 int retcode, bytes, io_size;
12951 fileio_error remote_errno;
12952 int bytes_in_buffer;
12953 int saw_eof;
12954 ULONGEST offset;
12955
12956 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12957 if (file == NULL)
12958 perror_with_name (local_file);
12959
12960 scoped_remote_fd fd
12961 (this, remote_hostio_open (NULL,
12962 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12963 | FILEIO_O_TRUNC),
12964 0700, 0, &remote_errno));
12965 if (fd.get () == -1)
12966 remote_hostio_error (remote_errno);
12967
12968 /* Send up to this many bytes at once. They won't all fit in the
12969 remote packet limit, so we'll transfer slightly fewer. */
12970 io_size = get_remote_packet_size ();
12971 gdb::byte_vector buffer (io_size);
12972
12973 bytes_in_buffer = 0;
12974 saw_eof = 0;
12975 offset = 0;
12976 while (bytes_in_buffer || !saw_eof)
12977 {
12978 if (!saw_eof)
12979 {
12980 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12981 io_size - bytes_in_buffer,
12982 file.get ());
12983 if (bytes == 0)
12984 {
12985 if (ferror (file.get ()))
12986 error (_("Error reading %s."), local_file);
12987 else
12988 {
12989 /* EOF. Unless there is something still in the
12990 buffer from the last iteration, we are done. */
12991 saw_eof = 1;
12992 if (bytes_in_buffer == 0)
12993 break;
12994 }
12995 }
12996 }
12997 else
12998 bytes = 0;
12999
13000 bytes += bytes_in_buffer;
13001 bytes_in_buffer = 0;
13002
13003 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13004 offset, &remote_errno);
13005
13006 if (retcode < 0)
13007 remote_hostio_error (remote_errno);
13008 else if (retcode == 0)
13009 error (_("Remote write of %d bytes returned 0!"), bytes);
13010 else if (retcode < bytes)
13011 {
13012 /* Short write. Save the rest of the read data for the next
13013 write. */
13014 bytes_in_buffer = bytes - retcode;
13015 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13016 }
13017
13018 offset += retcode;
13019 }
13020
13021 if (remote_hostio_close (fd.release (), &remote_errno))
13022 remote_hostio_error (remote_errno);
13023
13024 if (from_tty)
13025 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13026 }
13027
13028 void
13029 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13030 {
13031 remote_target *remote = get_current_remote_target ();
13032
13033 if (remote == nullptr)
13034 error (_("command can only be used with remote target"));
13035
13036 remote->remote_file_get (remote_file, local_file, from_tty);
13037 }
13038
13039 void
13040 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13041 int from_tty)
13042 {
13043 fileio_error remote_errno;
13044 int bytes, io_size;
13045 ULONGEST offset;
13046
13047 scoped_remote_fd fd
13048 (this, remote_hostio_open (NULL,
13049 remote_file, FILEIO_O_RDONLY, 0, 0,
13050 &remote_errno));
13051 if (fd.get () == -1)
13052 remote_hostio_error (remote_errno);
13053
13054 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13055 if (file == NULL)
13056 perror_with_name (local_file);
13057
13058 /* Send up to this many bytes at once. They won't all fit in the
13059 remote packet limit, so we'll transfer slightly fewer. */
13060 io_size = get_remote_packet_size ();
13061 gdb::byte_vector buffer (io_size);
13062
13063 offset = 0;
13064 while (1)
13065 {
13066 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13067 &remote_errno);
13068 if (bytes == 0)
13069 /* Success, but no bytes, means end-of-file. */
13070 break;
13071 if (bytes == -1)
13072 remote_hostio_error (remote_errno);
13073
13074 offset += bytes;
13075
13076 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13077 if (bytes == 0)
13078 perror_with_name (local_file);
13079 }
13080
13081 if (remote_hostio_close (fd.release (), &remote_errno))
13082 remote_hostio_error (remote_errno);
13083
13084 if (from_tty)
13085 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13086 }
13087
13088 void
13089 remote_file_delete (const char *remote_file, int from_tty)
13090 {
13091 remote_target *remote = get_current_remote_target ();
13092
13093 if (remote == nullptr)
13094 error (_("command can only be used with remote target"));
13095
13096 remote->remote_file_delete (remote_file, from_tty);
13097 }
13098
13099 void
13100 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13101 {
13102 int retcode;
13103 fileio_error remote_errno;
13104
13105 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13106 if (retcode == -1)
13107 remote_hostio_error (remote_errno);
13108
13109 if (from_tty)
13110 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13111 }
13112
13113 static void
13114 remote_put_command (const char *args, int from_tty)
13115 {
13116 if (args == NULL)
13117 error_no_arg (_("file to put"));
13118
13119 gdb_argv argv (args);
13120 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13121 error (_("Invalid parameters to remote put"));
13122
13123 remote_file_put (argv[0], argv[1], from_tty);
13124 }
13125
13126 static void
13127 remote_get_command (const char *args, int from_tty)
13128 {
13129 if (args == NULL)
13130 error_no_arg (_("file to get"));
13131
13132 gdb_argv argv (args);
13133 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13134 error (_("Invalid parameters to remote get"));
13135
13136 remote_file_get (argv[0], argv[1], from_tty);
13137 }
13138
13139 static void
13140 remote_delete_command (const char *args, int from_tty)
13141 {
13142 if (args == NULL)
13143 error_no_arg (_("file to delete"));
13144
13145 gdb_argv argv (args);
13146 if (argv[0] == NULL || argv[1] != NULL)
13147 error (_("Invalid parameters to remote delete"));
13148
13149 remote_file_delete (argv[0], from_tty);
13150 }
13151
13152 bool
13153 remote_target::can_execute_reverse ()
13154 {
13155 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13156 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13157 return true;
13158 else
13159 return false;
13160 }
13161
13162 bool
13163 remote_target::supports_non_stop ()
13164 {
13165 return true;
13166 }
13167
13168 bool
13169 remote_target::supports_disable_randomization ()
13170 {
13171 /* Only supported in extended mode. */
13172 return false;
13173 }
13174
13175 bool
13176 remote_target::supports_multi_process ()
13177 {
13178 return m_features.remote_multi_process_p ();
13179 }
13180
13181 int
13182 remote_target::remote_supports_cond_tracepoints ()
13183 {
13184 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13185 == PACKET_ENABLE);
13186 }
13187
13188 bool
13189 remote_target::supports_evaluation_of_breakpoint_conditions ()
13190 {
13191 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13192 == PACKET_ENABLE);
13193 }
13194
13195 int
13196 remote_target::remote_supports_fast_tracepoints ()
13197 {
13198 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13199 }
13200
13201 int
13202 remote_target::remote_supports_static_tracepoints ()
13203 {
13204 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13205 }
13206
13207 int
13208 remote_target::remote_supports_install_in_trace ()
13209 {
13210 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13211 }
13212
13213 bool
13214 remote_target::supports_enable_disable_tracepoint ()
13215 {
13216 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13217 == PACKET_ENABLE);
13218 }
13219
13220 bool
13221 remote_target::supports_string_tracing ()
13222 {
13223 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13224 }
13225
13226 bool
13227 remote_target::can_run_breakpoint_commands ()
13228 {
13229 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13230 }
13231
13232 void
13233 remote_target::trace_init ()
13234 {
13235 struct remote_state *rs = get_remote_state ();
13236
13237 putpkt ("QTinit");
13238 remote_get_noisy_reply ();
13239 if (strcmp (rs->buf.data (), "OK") != 0)
13240 error (_("Target does not support this command."));
13241 }
13242
13243 /* Recursive routine to walk through command list including loops, and
13244 download packets for each command. */
13245
13246 void
13247 remote_target::remote_download_command_source (int num, ULONGEST addr,
13248 struct command_line *cmds)
13249 {
13250 struct remote_state *rs = get_remote_state ();
13251 struct command_line *cmd;
13252
13253 for (cmd = cmds; cmd; cmd = cmd->next)
13254 {
13255 QUIT; /* Allow user to bail out with ^C. */
13256 strcpy (rs->buf.data (), "QTDPsrc:");
13257 encode_source_string (num, addr, "cmd", cmd->line,
13258 rs->buf.data () + strlen (rs->buf.data ()),
13259 rs->buf.size () - strlen (rs->buf.data ()));
13260 putpkt (rs->buf);
13261 remote_get_noisy_reply ();
13262 if (strcmp (rs->buf.data (), "OK"))
13263 warning (_("Target does not support source download."));
13264
13265 if (cmd->control_type == while_control
13266 || cmd->control_type == while_stepping_control)
13267 {
13268 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13269
13270 QUIT; /* Allow user to bail out with ^C. */
13271 strcpy (rs->buf.data (), "QTDPsrc:");
13272 encode_source_string (num, addr, "cmd", "end",
13273 rs->buf.data () + strlen (rs->buf.data ()),
13274 rs->buf.size () - strlen (rs->buf.data ()));
13275 putpkt (rs->buf);
13276 remote_get_noisy_reply ();
13277 if (strcmp (rs->buf.data (), "OK"))
13278 warning (_("Target does not support source download."));
13279 }
13280 }
13281 }
13282
13283 void
13284 remote_target::download_tracepoint (struct bp_location *loc)
13285 {
13286 CORE_ADDR tpaddr;
13287 char addrbuf[40];
13288 std::vector<std::string> tdp_actions;
13289 std::vector<std::string> stepping_actions;
13290 char *pkt;
13291 struct breakpoint *b = loc->owner;
13292 struct tracepoint *t = (struct tracepoint *) b;
13293 struct remote_state *rs = get_remote_state ();
13294 int ret;
13295 const char *err_msg = _("Tracepoint packet too large for target.");
13296 size_t size_left;
13297
13298 /* We use a buffer other than rs->buf because we'll build strings
13299 across multiple statements, and other statements in between could
13300 modify rs->buf. */
13301 gdb::char_vector buf (get_remote_packet_size ());
13302
13303 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13304
13305 tpaddr = loc->address;
13306 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13307 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13308 b->number, addrbuf, /* address */
13309 (b->enable_state == bp_enabled ? 'E' : 'D'),
13310 t->step_count, t->pass_count);
13311
13312 if (ret < 0 || ret >= buf.size ())
13313 error ("%s", err_msg);
13314
13315 /* Fast tracepoints are mostly handled by the target, but we can
13316 tell the target how big of an instruction block should be moved
13317 around. */
13318 if (b->type == bp_fast_tracepoint)
13319 {
13320 /* Only test for support at download time; we may not know
13321 target capabilities at definition time. */
13322 if (remote_supports_fast_tracepoints ())
13323 {
13324 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13325 NULL))
13326 {
13327 size_left = buf.size () - strlen (buf.data ());
13328 ret = snprintf (buf.data () + strlen (buf.data ()),
13329 size_left, ":F%x",
13330 gdb_insn_length (loc->gdbarch, tpaddr));
13331
13332 if (ret < 0 || ret >= size_left)
13333 error ("%s", err_msg);
13334 }
13335 else
13336 /* If it passed validation at definition but fails now,
13337 something is very wrong. */
13338 internal_error (_("Fast tracepoint not valid during download"));
13339 }
13340 else
13341 /* Fast tracepoints are functionally identical to regular
13342 tracepoints, so don't take lack of support as a reason to
13343 give up on the trace run. */
13344 warning (_("Target does not support fast tracepoints, "
13345 "downloading %d as regular tracepoint"), b->number);
13346 }
13347 else if (b->type == bp_static_tracepoint
13348 || b->type == bp_static_marker_tracepoint)
13349 {
13350 /* Only test for support at download time; we may not know
13351 target capabilities at definition time. */
13352 if (remote_supports_static_tracepoints ())
13353 {
13354 struct static_tracepoint_marker marker;
13355
13356 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13357 {
13358 size_left = buf.size () - strlen (buf.data ());
13359 ret = snprintf (buf.data () + strlen (buf.data ()),
13360 size_left, ":S");
13361
13362 if (ret < 0 || ret >= size_left)
13363 error ("%s", err_msg);
13364 }
13365 else
13366 error (_("Static tracepoint not valid during download"));
13367 }
13368 else
13369 /* Fast tracepoints are functionally identical to regular
13370 tracepoints, so don't take lack of support as a reason
13371 to give up on the trace run. */
13372 error (_("Target does not support static tracepoints"));
13373 }
13374 /* If the tracepoint has a conditional, make it into an agent
13375 expression and append to the definition. */
13376 if (loc->cond)
13377 {
13378 /* Only test support at download time, we may not know target
13379 capabilities at definition time. */
13380 if (remote_supports_cond_tracepoints ())
13381 {
13382 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13383 loc->cond.get ());
13384
13385 size_left = buf.size () - strlen (buf.data ());
13386
13387 ret = snprintf (buf.data () + strlen (buf.data ()),
13388 size_left, ":X%x,", aexpr->len);
13389
13390 if (ret < 0 || ret >= size_left)
13391 error ("%s", err_msg);
13392
13393 size_left = buf.size () - strlen (buf.data ());
13394
13395 /* Two bytes to encode each aexpr byte, plus the terminating
13396 null byte. */
13397 if (aexpr->len * 2 + 1 > size_left)
13398 error ("%s", err_msg);
13399
13400 pkt = buf.data () + strlen (buf.data ());
13401
13402 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13403 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13404 *pkt = '\0';
13405 }
13406 else
13407 warning (_("Target does not support conditional tracepoints, "
13408 "ignoring tp %d cond"), b->number);
13409 }
13410
13411 if (b->commands || !default_collect.empty ())
13412 {
13413 size_left = buf.size () - strlen (buf.data ());
13414
13415 ret = snprintf (buf.data () + strlen (buf.data ()),
13416 size_left, "-");
13417
13418 if (ret < 0 || ret >= size_left)
13419 error ("%s", err_msg);
13420 }
13421
13422 putpkt (buf.data ());
13423 remote_get_noisy_reply ();
13424 if (strcmp (rs->buf.data (), "OK"))
13425 error (_("Target does not support tracepoints."));
13426
13427 /* do_single_steps (t); */
13428 for (auto action_it = tdp_actions.begin ();
13429 action_it != tdp_actions.end (); action_it++)
13430 {
13431 QUIT; /* Allow user to bail out with ^C. */
13432
13433 bool has_more = ((action_it + 1) != tdp_actions.end ()
13434 || !stepping_actions.empty ());
13435
13436 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13437 b->number, addrbuf, /* address */
13438 action_it->c_str (),
13439 has_more ? '-' : 0);
13440
13441 if (ret < 0 || ret >= buf.size ())
13442 error ("%s", err_msg);
13443
13444 putpkt (buf.data ());
13445 remote_get_noisy_reply ();
13446 if (strcmp (rs->buf.data (), "OK"))
13447 error (_("Error on target while setting tracepoints."));
13448 }
13449
13450 for (auto action_it = stepping_actions.begin ();
13451 action_it != stepping_actions.end (); action_it++)
13452 {
13453 QUIT; /* Allow user to bail out with ^C. */
13454
13455 bool is_first = action_it == stepping_actions.begin ();
13456 bool has_more = (action_it + 1) != stepping_actions.end ();
13457
13458 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13459 b->number, addrbuf, /* address */
13460 is_first ? "S" : "",
13461 action_it->c_str (),
13462 has_more ? "-" : "");
13463
13464 if (ret < 0 || ret >= buf.size ())
13465 error ("%s", err_msg);
13466
13467 putpkt (buf.data ());
13468 remote_get_noisy_reply ();
13469 if (strcmp (rs->buf.data (), "OK"))
13470 error (_("Error on target while setting tracepoints."));
13471 }
13472
13473 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13474 {
13475 if (b->locspec != nullptr)
13476 {
13477 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13478
13479 if (ret < 0 || ret >= buf.size ())
13480 error ("%s", err_msg);
13481
13482 const char *str = b->locspec->to_string ();
13483 encode_source_string (b->number, loc->address, "at", str,
13484 buf.data () + strlen (buf.data ()),
13485 buf.size () - strlen (buf.data ()));
13486 putpkt (buf.data ());
13487 remote_get_noisy_reply ();
13488 if (strcmp (rs->buf.data (), "OK"))
13489 warning (_("Target does not support source download."));
13490 }
13491 if (b->cond_string)
13492 {
13493 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13494
13495 if (ret < 0 || ret >= buf.size ())
13496 error ("%s", err_msg);
13497
13498 encode_source_string (b->number, loc->address,
13499 "cond", b->cond_string.get (),
13500 buf.data () + strlen (buf.data ()),
13501 buf.size () - strlen (buf.data ()));
13502 putpkt (buf.data ());
13503 remote_get_noisy_reply ();
13504 if (strcmp (rs->buf.data (), "OK"))
13505 warning (_("Target does not support source download."));
13506 }
13507 remote_download_command_source (b->number, loc->address,
13508 breakpoint_commands (b));
13509 }
13510 }
13511
13512 bool
13513 remote_target::can_download_tracepoint ()
13514 {
13515 struct remote_state *rs = get_remote_state ();
13516 struct trace_status *ts;
13517 int status;
13518
13519 /* Don't try to install tracepoints until we've relocated our
13520 symbols, and fetched and merged the target's tracepoint list with
13521 ours. */
13522 if (rs->starting_up)
13523 return false;
13524
13525 ts = current_trace_status ();
13526 status = get_trace_status (ts);
13527
13528 if (status == -1 || !ts->running_known || !ts->running)
13529 return false;
13530
13531 /* If we are in a tracing experiment, but remote stub doesn't support
13532 installing tracepoint in trace, we have to return. */
13533 if (!remote_supports_install_in_trace ())
13534 return false;
13535
13536 return true;
13537 }
13538
13539
13540 void
13541 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13542 {
13543 struct remote_state *rs = get_remote_state ();
13544 char *p;
13545
13546 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13547 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13548 tsv.builtin);
13549 p = rs->buf.data () + strlen (rs->buf.data ());
13550 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13551 >= get_remote_packet_size ())
13552 error (_("Trace state variable name too long for tsv definition packet"));
13553 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13554 *p++ = '\0';
13555 putpkt (rs->buf);
13556 remote_get_noisy_reply ();
13557 if (rs->buf[0] == '\0')
13558 error (_("Target does not support this command."));
13559 if (strcmp (rs->buf.data (), "OK") != 0)
13560 error (_("Error on target while downloading trace state variable."));
13561 }
13562
13563 void
13564 remote_target::enable_tracepoint (struct bp_location *location)
13565 {
13566 struct remote_state *rs = get_remote_state ();
13567
13568 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13569 location->owner->number,
13570 phex (location->address, sizeof (CORE_ADDR)));
13571 putpkt (rs->buf);
13572 remote_get_noisy_reply ();
13573 if (rs->buf[0] == '\0')
13574 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13575 if (strcmp (rs->buf.data (), "OK") != 0)
13576 error (_("Error on target while enabling tracepoint."));
13577 }
13578
13579 void
13580 remote_target::disable_tracepoint (struct bp_location *location)
13581 {
13582 struct remote_state *rs = get_remote_state ();
13583
13584 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13585 location->owner->number,
13586 phex (location->address, sizeof (CORE_ADDR)));
13587 putpkt (rs->buf);
13588 remote_get_noisy_reply ();
13589 if (rs->buf[0] == '\0')
13590 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13591 if (strcmp (rs->buf.data (), "OK") != 0)
13592 error (_("Error on target while disabling tracepoint."));
13593 }
13594
13595 void
13596 remote_target::trace_set_readonly_regions ()
13597 {
13598 asection *s;
13599 bfd_size_type size;
13600 bfd_vma vma;
13601 int anysecs = 0;
13602 int offset = 0;
13603 bfd *abfd = current_program_space->exec_bfd ();
13604
13605 if (!abfd)
13606 return; /* No information to give. */
13607
13608 struct remote_state *rs = get_remote_state ();
13609
13610 strcpy (rs->buf.data (), "QTro");
13611 offset = strlen (rs->buf.data ());
13612 for (s = abfd->sections; s; s = s->next)
13613 {
13614 char tmp1[40], tmp2[40];
13615 int sec_length;
13616
13617 if ((s->flags & SEC_LOAD) == 0
13618 /* || (s->flags & SEC_CODE) == 0 */
13619 || (s->flags & SEC_READONLY) == 0)
13620 continue;
13621
13622 anysecs = 1;
13623 vma = bfd_section_vma (s);
13624 size = bfd_section_size (s);
13625 bfd_sprintf_vma (abfd, tmp1, vma);
13626 bfd_sprintf_vma (abfd, tmp2, vma + size);
13627 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13628 if (offset + sec_length + 1 > rs->buf.size ())
13629 {
13630 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13631 != PACKET_ENABLE)
13632 warning (_("\
13633 Too many sections for read-only sections definition packet."));
13634 break;
13635 }
13636 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13637 tmp1, tmp2);
13638 offset += sec_length;
13639 }
13640 if (anysecs)
13641 {
13642 putpkt (rs->buf);
13643 getpkt (&rs->buf, 0);
13644 }
13645 }
13646
13647 void
13648 remote_target::trace_start ()
13649 {
13650 struct remote_state *rs = get_remote_state ();
13651
13652 putpkt ("QTStart");
13653 remote_get_noisy_reply ();
13654 if (rs->buf[0] == '\0')
13655 error (_("Target does not support this command."));
13656 if (strcmp (rs->buf.data (), "OK") != 0)
13657 error (_("Bogus reply from target: %s"), rs->buf.data ());
13658 }
13659
13660 int
13661 remote_target::get_trace_status (struct trace_status *ts)
13662 {
13663 /* Initialize it just to avoid a GCC false warning. */
13664 char *p = NULL;
13665 enum packet_result result;
13666 struct remote_state *rs = get_remote_state ();
13667
13668 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13669 return -1;
13670
13671 /* FIXME we need to get register block size some other way. */
13672 trace_regblock_size
13673 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13674
13675 putpkt ("qTStatus");
13676
13677 try
13678 {
13679 p = remote_get_noisy_reply ();
13680 }
13681 catch (const gdb_exception_error &ex)
13682 {
13683 if (ex.error != TARGET_CLOSE_ERROR)
13684 {
13685 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13686 return -1;
13687 }
13688 throw;
13689 }
13690
13691 result = m_features.packet_ok (p, PACKET_qTStatus);
13692
13693 /* If the remote target doesn't do tracing, flag it. */
13694 if (result == PACKET_UNKNOWN)
13695 return -1;
13696
13697 /* We're working with a live target. */
13698 ts->filename = NULL;
13699
13700 if (*p++ != 'T')
13701 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13702
13703 /* Function 'parse_trace_status' sets default value of each field of
13704 'ts' at first, so we don't have to do it here. */
13705 parse_trace_status (p, ts);
13706
13707 return ts->running;
13708 }
13709
13710 void
13711 remote_target::get_tracepoint_status (struct breakpoint *bp,
13712 struct uploaded_tp *utp)
13713 {
13714 struct remote_state *rs = get_remote_state ();
13715 char *reply;
13716 struct tracepoint *tp = (struct tracepoint *) bp;
13717 size_t size = get_remote_packet_size ();
13718
13719 if (tp)
13720 {
13721 tp->hit_count = 0;
13722 tp->traceframe_usage = 0;
13723 for (bp_location *loc : tp->locations ())
13724 {
13725 /* If the tracepoint was never downloaded, don't go asking for
13726 any status. */
13727 if (tp->number_on_target == 0)
13728 continue;
13729 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13730 phex_nz (loc->address, 0));
13731 putpkt (rs->buf);
13732 reply = remote_get_noisy_reply ();
13733 if (reply && *reply)
13734 {
13735 if (*reply == 'V')
13736 parse_tracepoint_status (reply + 1, bp, utp);
13737 }
13738 }
13739 }
13740 else if (utp)
13741 {
13742 utp->hit_count = 0;
13743 utp->traceframe_usage = 0;
13744 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13745 phex_nz (utp->addr, 0));
13746 putpkt (rs->buf);
13747 reply = remote_get_noisy_reply ();
13748 if (reply && *reply)
13749 {
13750 if (*reply == 'V')
13751 parse_tracepoint_status (reply + 1, bp, utp);
13752 }
13753 }
13754 }
13755
13756 void
13757 remote_target::trace_stop ()
13758 {
13759 struct remote_state *rs = get_remote_state ();
13760
13761 putpkt ("QTStop");
13762 remote_get_noisy_reply ();
13763 if (rs->buf[0] == '\0')
13764 error (_("Target does not support this command."));
13765 if (strcmp (rs->buf.data (), "OK") != 0)
13766 error (_("Bogus reply from target: %s"), rs->buf.data ());
13767 }
13768
13769 int
13770 remote_target::trace_find (enum trace_find_type type, int num,
13771 CORE_ADDR addr1, CORE_ADDR addr2,
13772 int *tpp)
13773 {
13774 struct remote_state *rs = get_remote_state ();
13775 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13776 char *p, *reply;
13777 int target_frameno = -1, target_tracept = -1;
13778
13779 /* Lookups other than by absolute frame number depend on the current
13780 trace selected, so make sure it is correct on the remote end
13781 first. */
13782 if (type != tfind_number)
13783 set_remote_traceframe ();
13784
13785 p = rs->buf.data ();
13786 strcpy (p, "QTFrame:");
13787 p = strchr (p, '\0');
13788 switch (type)
13789 {
13790 case tfind_number:
13791 xsnprintf (p, endbuf - p, "%x", num);
13792 break;
13793 case tfind_pc:
13794 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13795 break;
13796 case tfind_tp:
13797 xsnprintf (p, endbuf - p, "tdp:%x", num);
13798 break;
13799 case tfind_range:
13800 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13801 phex_nz (addr2, 0));
13802 break;
13803 case tfind_outside:
13804 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13805 phex_nz (addr2, 0));
13806 break;
13807 default:
13808 error (_("Unknown trace find type %d"), type);
13809 }
13810
13811 putpkt (rs->buf);
13812 reply = remote_get_noisy_reply ();
13813 if (*reply == '\0')
13814 error (_("Target does not support this command."));
13815
13816 while (reply && *reply)
13817 switch (*reply)
13818 {
13819 case 'F':
13820 p = ++reply;
13821 target_frameno = (int) strtol (p, &reply, 16);
13822 if (reply == p)
13823 error (_("Unable to parse trace frame number"));
13824 /* Don't update our remote traceframe number cache on failure
13825 to select a remote traceframe. */
13826 if (target_frameno == -1)
13827 return -1;
13828 break;
13829 case 'T':
13830 p = ++reply;
13831 target_tracept = (int) strtol (p, &reply, 16);
13832 if (reply == p)
13833 error (_("Unable to parse tracepoint number"));
13834 break;
13835 case 'O': /* "OK"? */
13836 if (reply[1] == 'K' && reply[2] == '\0')
13837 reply += 2;
13838 else
13839 error (_("Bogus reply from target: %s"), reply);
13840 break;
13841 default:
13842 error (_("Bogus reply from target: %s"), reply);
13843 }
13844 if (tpp)
13845 *tpp = target_tracept;
13846
13847 rs->remote_traceframe_number = target_frameno;
13848 return target_frameno;
13849 }
13850
13851 bool
13852 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13853 {
13854 struct remote_state *rs = get_remote_state ();
13855 char *reply;
13856 ULONGEST uval;
13857
13858 set_remote_traceframe ();
13859
13860 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13861 putpkt (rs->buf);
13862 reply = remote_get_noisy_reply ();
13863 if (reply && *reply)
13864 {
13865 if (*reply == 'V')
13866 {
13867 unpack_varlen_hex (reply + 1, &uval);
13868 *val = (LONGEST) uval;
13869 return true;
13870 }
13871 }
13872 return false;
13873 }
13874
13875 int
13876 remote_target::save_trace_data (const char *filename)
13877 {
13878 struct remote_state *rs = get_remote_state ();
13879 char *p, *reply;
13880
13881 p = rs->buf.data ();
13882 strcpy (p, "QTSave:");
13883 p += strlen (p);
13884 if ((p - rs->buf.data ()) + strlen (filename) * 2
13885 >= get_remote_packet_size ())
13886 error (_("Remote file name too long for trace save packet"));
13887 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13888 *p++ = '\0';
13889 putpkt (rs->buf);
13890 reply = remote_get_noisy_reply ();
13891 if (*reply == '\0')
13892 error (_("Target does not support this command."));
13893 if (strcmp (reply, "OK") != 0)
13894 error (_("Bogus reply from target: %s"), reply);
13895 return 0;
13896 }
13897
13898 /* This is basically a memory transfer, but needs to be its own packet
13899 because we don't know how the target actually organizes its trace
13900 memory, plus we want to be able to ask for as much as possible, but
13901 not be unhappy if we don't get as much as we ask for. */
13902
13903 LONGEST
13904 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13905 {
13906 struct remote_state *rs = get_remote_state ();
13907 char *reply;
13908 char *p;
13909 int rslt;
13910
13911 p = rs->buf.data ();
13912 strcpy (p, "qTBuffer:");
13913 p += strlen (p);
13914 p += hexnumstr (p, offset);
13915 *p++ = ',';
13916 p += hexnumstr (p, len);
13917 *p++ = '\0';
13918
13919 putpkt (rs->buf);
13920 reply = remote_get_noisy_reply ();
13921 if (reply && *reply)
13922 {
13923 /* 'l' by itself means we're at the end of the buffer and
13924 there is nothing more to get. */
13925 if (*reply == 'l')
13926 return 0;
13927
13928 /* Convert the reply into binary. Limit the number of bytes to
13929 convert according to our passed-in buffer size, rather than
13930 what was returned in the packet; if the target is
13931 unexpectedly generous and gives us a bigger reply than we
13932 asked for, we don't want to crash. */
13933 rslt = hex2bin (reply, buf, len);
13934 return rslt;
13935 }
13936
13937 /* Something went wrong, flag as an error. */
13938 return -1;
13939 }
13940
13941 void
13942 remote_target::set_disconnected_tracing (int val)
13943 {
13944 struct remote_state *rs = get_remote_state ();
13945
13946 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13947 == PACKET_ENABLE)
13948 {
13949 char *reply;
13950
13951 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13952 "QTDisconnected:%x", val);
13953 putpkt (rs->buf);
13954 reply = remote_get_noisy_reply ();
13955 if (*reply == '\0')
13956 error (_("Target does not support this command."));
13957 if (strcmp (reply, "OK") != 0)
13958 error (_("Bogus reply from target: %s"), reply);
13959 }
13960 else if (val)
13961 warning (_("Target does not support disconnected tracing."));
13962 }
13963
13964 int
13965 remote_target::core_of_thread (ptid_t ptid)
13966 {
13967 thread_info *info = find_thread_ptid (this, ptid);
13968
13969 if (info != NULL && info->priv != NULL)
13970 return get_remote_thread_info (info)->core;
13971
13972 return -1;
13973 }
13974
13975 void
13976 remote_target::set_circular_trace_buffer (int val)
13977 {
13978 struct remote_state *rs = get_remote_state ();
13979 char *reply;
13980
13981 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13982 "QTBuffer:circular:%x", val);
13983 putpkt (rs->buf);
13984 reply = remote_get_noisy_reply ();
13985 if (*reply == '\0')
13986 error (_("Target does not support this command."));
13987 if (strcmp (reply, "OK") != 0)
13988 error (_("Bogus reply from target: %s"), reply);
13989 }
13990
13991 traceframe_info_up
13992 remote_target::traceframe_info ()
13993 {
13994 gdb::optional<gdb::char_vector> text
13995 = target_read_stralloc (current_inferior ()->top_target (),
13996 TARGET_OBJECT_TRACEFRAME_INFO,
13997 NULL);
13998 if (text)
13999 return parse_traceframe_info (text->data ());
14000
14001 return NULL;
14002 }
14003
14004 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14005 instruction on which a fast tracepoint may be placed. Returns -1
14006 if the packet is not supported, and 0 if the minimum instruction
14007 length is unknown. */
14008
14009 int
14010 remote_target::get_min_fast_tracepoint_insn_len ()
14011 {
14012 struct remote_state *rs = get_remote_state ();
14013 char *reply;
14014
14015 /* If we're not debugging a process yet, the IPA can't be
14016 loaded. */
14017 if (!target_has_execution ())
14018 return 0;
14019
14020 /* Make sure the remote is pointing at the right process. */
14021 set_general_process ();
14022
14023 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14024 putpkt (rs->buf);
14025 reply = remote_get_noisy_reply ();
14026 if (*reply == '\0')
14027 return -1;
14028 else
14029 {
14030 ULONGEST min_insn_len;
14031
14032 unpack_varlen_hex (reply, &min_insn_len);
14033
14034 return (int) min_insn_len;
14035 }
14036 }
14037
14038 void
14039 remote_target::set_trace_buffer_size (LONGEST val)
14040 {
14041 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14042 {
14043 struct remote_state *rs = get_remote_state ();
14044 char *buf = rs->buf.data ();
14045 char *endbuf = buf + get_remote_packet_size ();
14046 enum packet_result result;
14047
14048 gdb_assert (val >= 0 || val == -1);
14049 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14050 /* Send -1 as literal "-1" to avoid host size dependency. */
14051 if (val < 0)
14052 {
14053 *buf++ = '-';
14054 buf += hexnumstr (buf, (ULONGEST) -val);
14055 }
14056 else
14057 buf += hexnumstr (buf, (ULONGEST) val);
14058
14059 putpkt (rs->buf);
14060 remote_get_noisy_reply ();
14061 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14062
14063 if (result != PACKET_OK)
14064 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14065 }
14066 }
14067
14068 bool
14069 remote_target::set_trace_notes (const char *user, const char *notes,
14070 const char *stop_notes)
14071 {
14072 struct remote_state *rs = get_remote_state ();
14073 char *reply;
14074 char *buf = rs->buf.data ();
14075 char *endbuf = buf + get_remote_packet_size ();
14076 int nbytes;
14077
14078 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14079 if (user)
14080 {
14081 buf += xsnprintf (buf, endbuf - buf, "user:");
14082 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14083 buf += 2 * nbytes;
14084 *buf++ = ';';
14085 }
14086 if (notes)
14087 {
14088 buf += xsnprintf (buf, endbuf - buf, "notes:");
14089 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14090 buf += 2 * nbytes;
14091 *buf++ = ';';
14092 }
14093 if (stop_notes)
14094 {
14095 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14096 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14097 buf += 2 * nbytes;
14098 *buf++ = ';';
14099 }
14100 /* Ensure the buffer is terminated. */
14101 *buf = '\0';
14102
14103 putpkt (rs->buf);
14104 reply = remote_get_noisy_reply ();
14105 if (*reply == '\0')
14106 return false;
14107
14108 if (strcmp (reply, "OK") != 0)
14109 error (_("Bogus reply from target: %s"), reply);
14110
14111 return true;
14112 }
14113
14114 bool
14115 remote_target::use_agent (bool use)
14116 {
14117 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14118 {
14119 struct remote_state *rs = get_remote_state ();
14120
14121 /* If the stub supports QAgent. */
14122 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14123 putpkt (rs->buf);
14124 getpkt (&rs->buf, 0);
14125
14126 if (strcmp (rs->buf.data (), "OK") == 0)
14127 {
14128 ::use_agent = use;
14129 return true;
14130 }
14131 }
14132
14133 return false;
14134 }
14135
14136 bool
14137 remote_target::can_use_agent ()
14138 {
14139 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14140 }
14141
14142 struct btrace_target_info
14143 {
14144 /* The ptid of the traced thread. */
14145 ptid_t ptid;
14146
14147 /* The obtained branch trace configuration. */
14148 struct btrace_config conf;
14149 };
14150
14151 /* Reset our idea of our target's btrace configuration. */
14152
14153 static void
14154 remote_btrace_reset (remote_state *rs)
14155 {
14156 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14157 }
14158
14159 /* Synchronize the configuration with the target. */
14160
14161 void
14162 remote_target::btrace_sync_conf (const btrace_config *conf)
14163 {
14164 struct remote_state *rs;
14165 char *buf, *pos, *endbuf;
14166
14167 rs = get_remote_state ();
14168 buf = rs->buf.data ();
14169 endbuf = buf + get_remote_packet_size ();
14170
14171 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14172 && conf->bts.size != rs->btrace_config.bts.size)
14173 {
14174 pos = buf;
14175 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14176 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14177 conf->bts.size);
14178
14179 putpkt (buf);
14180 getpkt (&rs->buf, 0);
14181
14182 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14183 == PACKET_ERROR)
14184 {
14185 if (buf[0] == 'E' && buf[1] == '.')
14186 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14187 else
14188 error (_("Failed to configure the BTS buffer size."));
14189 }
14190
14191 rs->btrace_config.bts.size = conf->bts.size;
14192 }
14193
14194 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14195 && conf->pt.size != rs->btrace_config.pt.size)
14196 {
14197 pos = buf;
14198 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14199 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14200 conf->pt.size);
14201
14202 putpkt (buf);
14203 getpkt (&rs->buf, 0);
14204
14205 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14206 == PACKET_ERROR)
14207 {
14208 if (buf[0] == 'E' && buf[1] == '.')
14209 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14210 else
14211 error (_("Failed to configure the trace buffer size."));
14212 }
14213
14214 rs->btrace_config.pt.size = conf->pt.size;
14215 }
14216 }
14217
14218 /* Read TP's btrace configuration from the target and store it into CONF. */
14219
14220 static void
14221 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14222 {
14223 /* target_read_stralloc relies on INFERIOR_PTID. */
14224 scoped_restore_current_thread restore_thread;
14225 switch_to_thread (tp);
14226
14227 gdb::optional<gdb::char_vector> xml
14228 = target_read_stralloc (current_inferior ()->top_target (),
14229 TARGET_OBJECT_BTRACE_CONF, "");
14230 if (xml)
14231 parse_xml_btrace_conf (conf, xml->data ());
14232 }
14233
14234 /* Maybe reopen target btrace. */
14235
14236 void
14237 remote_target::remote_btrace_maybe_reopen ()
14238 {
14239 struct remote_state *rs = get_remote_state ();
14240 int btrace_target_pushed = 0;
14241 #if !defined (HAVE_LIBIPT)
14242 int warned = 0;
14243 #endif
14244
14245 /* Don't bother walking the entirety of the remote thread list when
14246 we know the feature isn't supported by the remote. */
14247 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14248 return;
14249
14250 for (thread_info *tp : all_non_exited_threads (this))
14251 {
14252 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14253 btrace_read_config (tp, &rs->btrace_config);
14254
14255 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14256 continue;
14257
14258 #if !defined (HAVE_LIBIPT)
14259 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14260 {
14261 if (!warned)
14262 {
14263 warned = 1;
14264 warning (_("Target is recording using Intel Processor Trace "
14265 "but support was disabled at compile time."));
14266 }
14267
14268 continue;
14269 }
14270 #endif /* !defined (HAVE_LIBIPT) */
14271
14272 /* Push target, once, but before anything else happens. This way our
14273 changes to the threads will be cleaned up by unpushing the target
14274 in case btrace_read_config () throws. */
14275 if (!btrace_target_pushed)
14276 {
14277 btrace_target_pushed = 1;
14278 record_btrace_push_target ();
14279 gdb_printf (_("Target is recording using %s.\n"),
14280 btrace_format_string (rs->btrace_config.format));
14281 }
14282
14283 tp->btrace.target = XCNEW (struct btrace_target_info);
14284 tp->btrace.target->ptid = tp->ptid;
14285 tp->btrace.target->conf = rs->btrace_config;
14286 }
14287 }
14288
14289 /* Enable branch tracing. */
14290
14291 struct btrace_target_info *
14292 remote_target::enable_btrace (thread_info *tp,
14293 const struct btrace_config *conf)
14294 {
14295 struct btrace_target_info *tinfo = NULL;
14296 struct packet_config *packet = NULL;
14297 struct remote_state *rs = get_remote_state ();
14298 char *buf = rs->buf.data ();
14299 char *endbuf = buf + get_remote_packet_size ();
14300
14301 unsigned int which_packet;
14302 switch (conf->format)
14303 {
14304 case BTRACE_FORMAT_BTS:
14305 which_packet = PACKET_Qbtrace_bts;
14306 break;
14307 case BTRACE_FORMAT_PT:
14308 which_packet = PACKET_Qbtrace_pt;
14309 break;
14310 default:
14311 internal_error (_("Bad branch btrace format: %u."),
14312 (unsigned int) conf->format);
14313 }
14314
14315 packet = &m_features.m_protocol_packets[which_packet];
14316 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14317 error (_("Target does not support branch tracing."));
14318
14319 btrace_sync_conf (conf);
14320
14321 ptid_t ptid = tp->ptid;
14322 set_general_thread (ptid);
14323
14324 buf += xsnprintf (buf, endbuf - buf, "%s",
14325 packets_descriptions[which_packet].name);
14326 putpkt (rs->buf);
14327 getpkt (&rs->buf, 0);
14328
14329 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14330 {
14331 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14332 error (_("Could not enable branch tracing for %s: %s"),
14333 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14334 else
14335 error (_("Could not enable branch tracing for %s."),
14336 target_pid_to_str (ptid).c_str ());
14337 }
14338
14339 tinfo = XCNEW (struct btrace_target_info);
14340 tinfo->ptid = ptid;
14341
14342 /* If we fail to read the configuration, we lose some information, but the
14343 tracing itself is not impacted. */
14344 try
14345 {
14346 btrace_read_config (tp, &tinfo->conf);
14347 }
14348 catch (const gdb_exception_error &err)
14349 {
14350 if (err.message != NULL)
14351 warning ("%s", err.what ());
14352 }
14353
14354 return tinfo;
14355 }
14356
14357 /* Disable branch tracing. */
14358
14359 void
14360 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14361 {
14362 struct remote_state *rs = get_remote_state ();
14363 char *buf = rs->buf.data ();
14364 char *endbuf = buf + get_remote_packet_size ();
14365
14366 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14367 error (_("Target does not support branch tracing."));
14368
14369 set_general_thread (tinfo->ptid);
14370
14371 buf += xsnprintf (buf, endbuf - buf, "%s",
14372 packets_descriptions[PACKET_Qbtrace_off].name);
14373 putpkt (rs->buf);
14374 getpkt (&rs->buf, 0);
14375
14376 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14377 {
14378 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14379 error (_("Could not disable branch tracing for %s: %s"),
14380 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14381 else
14382 error (_("Could not disable branch tracing for %s."),
14383 target_pid_to_str (tinfo->ptid).c_str ());
14384 }
14385
14386 xfree (tinfo);
14387 }
14388
14389 /* Teardown branch tracing. */
14390
14391 void
14392 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14393 {
14394 /* We must not talk to the target during teardown. */
14395 xfree (tinfo);
14396 }
14397
14398 /* Read the branch trace. */
14399
14400 enum btrace_error
14401 remote_target::read_btrace (struct btrace_data *btrace,
14402 struct btrace_target_info *tinfo,
14403 enum btrace_read_type type)
14404 {
14405 const char *annex;
14406
14407 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14408 error (_("Target does not support branch tracing."));
14409
14410 #if !defined(HAVE_LIBEXPAT)
14411 error (_("Cannot process branch tracing result. XML parsing not supported."));
14412 #endif
14413
14414 switch (type)
14415 {
14416 case BTRACE_READ_ALL:
14417 annex = "all";
14418 break;
14419 case BTRACE_READ_NEW:
14420 annex = "new";
14421 break;
14422 case BTRACE_READ_DELTA:
14423 annex = "delta";
14424 break;
14425 default:
14426 internal_error (_("Bad branch tracing read type: %u."),
14427 (unsigned int) type);
14428 }
14429
14430 gdb::optional<gdb::char_vector> xml
14431 = target_read_stralloc (current_inferior ()->top_target (),
14432 TARGET_OBJECT_BTRACE, annex);
14433 if (!xml)
14434 return BTRACE_ERR_UNKNOWN;
14435
14436 parse_xml_btrace (btrace, xml->data ());
14437
14438 return BTRACE_ERR_NONE;
14439 }
14440
14441 const struct btrace_config *
14442 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14443 {
14444 return &tinfo->conf;
14445 }
14446
14447 bool
14448 remote_target::augmented_libraries_svr4_read ()
14449 {
14450 return
14451 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14452 == PACKET_ENABLE);
14453 }
14454
14455 /* Implementation of to_load. */
14456
14457 void
14458 remote_target::load (const char *name, int from_tty)
14459 {
14460 generic_load (name, from_tty);
14461 }
14462
14463 /* Accepts an integer PID; returns a string representing a file that
14464 can be opened on the remote side to get the symbols for the child
14465 process. Returns NULL if the operation is not supported. */
14466
14467 const char *
14468 remote_target::pid_to_exec_file (int pid)
14469 {
14470 static gdb::optional<gdb::char_vector> filename;
14471 char *annex = NULL;
14472
14473 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14474 return NULL;
14475
14476 inferior *inf = find_inferior_pid (this, pid);
14477 if (inf == NULL)
14478 internal_error (_("not currently attached to process %d"), pid);
14479
14480 if (!inf->fake_pid_p)
14481 {
14482 const int annex_size = 9;
14483
14484 annex = (char *) alloca (annex_size);
14485 xsnprintf (annex, annex_size, "%x", pid);
14486 }
14487
14488 filename = target_read_stralloc (current_inferior ()->top_target (),
14489 TARGET_OBJECT_EXEC_FILE, annex);
14490
14491 return filename ? filename->data () : nullptr;
14492 }
14493
14494 /* Implement the to_can_do_single_step target_ops method. */
14495
14496 int
14497 remote_target::can_do_single_step ()
14498 {
14499 /* We can only tell whether target supports single step or not by
14500 supported s and S vCont actions if the stub supports vContSupported
14501 feature. If the stub doesn't support vContSupported feature,
14502 we have conservatively to think target doesn't supports single
14503 step. */
14504 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14505 {
14506 struct remote_state *rs = get_remote_state ();
14507
14508 return rs->supports_vCont.s && rs->supports_vCont.S;
14509 }
14510 else
14511 return 0;
14512 }
14513
14514 /* Implementation of the to_execution_direction method for the remote
14515 target. */
14516
14517 enum exec_direction_kind
14518 remote_target::execution_direction ()
14519 {
14520 struct remote_state *rs = get_remote_state ();
14521
14522 return rs->last_resume_exec_dir;
14523 }
14524
14525 /* Return pointer to the thread_info struct which corresponds to
14526 THREAD_HANDLE (having length HANDLE_LEN). */
14527
14528 thread_info *
14529 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14530 int handle_len,
14531 inferior *inf)
14532 {
14533 for (thread_info *tp : all_non_exited_threads (this))
14534 {
14535 remote_thread_info *priv = get_remote_thread_info (tp);
14536
14537 if (tp->inf == inf && priv != NULL)
14538 {
14539 if (handle_len != priv->thread_handle.size ())
14540 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14541 handle_len, priv->thread_handle.size ());
14542 if (memcmp (thread_handle, priv->thread_handle.data (),
14543 handle_len) == 0)
14544 return tp;
14545 }
14546 }
14547
14548 return NULL;
14549 }
14550
14551 gdb::byte_vector
14552 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14553 {
14554 remote_thread_info *priv = get_remote_thread_info (tp);
14555 return priv->thread_handle;
14556 }
14557
14558 bool
14559 remote_target::can_async_p ()
14560 {
14561 /* This flag should be checked in the common target.c code. */
14562 gdb_assert (target_async_permitted);
14563
14564 /* We're async whenever the serial device can. */
14565 struct remote_state *rs = get_remote_state ();
14566 return serial_can_async_p (rs->remote_desc);
14567 }
14568
14569 bool
14570 remote_target::is_async_p ()
14571 {
14572 /* We're async whenever the serial device is. */
14573 struct remote_state *rs = get_remote_state ();
14574 return serial_is_async_p (rs->remote_desc);
14575 }
14576
14577 /* Pass the SERIAL event on and up to the client. One day this code
14578 will be able to delay notifying the client of an event until the
14579 point where an entire packet has been received. */
14580
14581 static serial_event_ftype remote_async_serial_handler;
14582
14583 static void
14584 remote_async_serial_handler (struct serial *scb, void *context)
14585 {
14586 /* Don't propogate error information up to the client. Instead let
14587 the client find out about the error by querying the target. */
14588 inferior_event_handler (INF_REG_EVENT);
14589 }
14590
14591 static void
14592 remote_async_inferior_event_handler (gdb_client_data data)
14593 {
14594 inferior_event_handler (INF_REG_EVENT);
14595 }
14596
14597 int
14598 remote_target::async_wait_fd ()
14599 {
14600 struct remote_state *rs = get_remote_state ();
14601 return rs->remote_desc->fd;
14602 }
14603
14604 void
14605 remote_target::async (bool enable)
14606 {
14607 struct remote_state *rs = get_remote_state ();
14608
14609 if (enable)
14610 {
14611 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14612
14613 /* If there are pending events in the stop reply queue tell the
14614 event loop to process them. */
14615 if (!rs->stop_reply_queue.empty ())
14616 mark_async_event_handler (rs->remote_async_inferior_event_token);
14617 /* For simplicity, below we clear the pending events token
14618 without remembering whether it is marked, so here we always
14619 mark it. If there's actually no pending notification to
14620 process, this ends up being a no-op (other than a spurious
14621 event-loop wakeup). */
14622 if (target_is_non_stop_p ())
14623 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14624 }
14625 else
14626 {
14627 serial_async (rs->remote_desc, NULL, NULL);
14628 /* If the core is disabling async, it doesn't want to be
14629 disturbed with target events. Clear all async event sources
14630 too. */
14631 clear_async_event_handler (rs->remote_async_inferior_event_token);
14632 if (target_is_non_stop_p ())
14633 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14634 }
14635 }
14636
14637 /* Implementation of the to_thread_events method. */
14638
14639 void
14640 remote_target::thread_events (int enable)
14641 {
14642 struct remote_state *rs = get_remote_state ();
14643 size_t size = get_remote_packet_size ();
14644
14645 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14646 return;
14647
14648 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14649 putpkt (rs->buf);
14650 getpkt (&rs->buf, 0);
14651
14652 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
14653 {
14654 case PACKET_OK:
14655 if (strcmp (rs->buf.data (), "OK") != 0)
14656 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14657 break;
14658 case PACKET_ERROR:
14659 warning (_("Remote failure reply: %s"), rs->buf.data ());
14660 break;
14661 case PACKET_UNKNOWN:
14662 break;
14663 }
14664 }
14665
14666 static void
14667 show_remote_cmd (const char *args, int from_tty)
14668 {
14669 /* We can't just use cmd_show_list here, because we want to skip
14670 the redundant "show remote Z-packet" and the legacy aliases. */
14671 struct cmd_list_element *list = remote_show_cmdlist;
14672 struct ui_out *uiout = current_uiout;
14673
14674 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14675 for (; list != NULL; list = list->next)
14676 if (strcmp (list->name, "Z-packet") == 0)
14677 continue;
14678 else if (list->type == not_set_cmd)
14679 /* Alias commands are exactly like the original, except they
14680 don't have the normal type. */
14681 continue;
14682 else
14683 {
14684 ui_out_emit_tuple option_emitter (uiout, "option");
14685
14686 uiout->field_string ("name", list->name);
14687 uiout->text (": ");
14688 if (list->type == show_cmd)
14689 do_show_command (NULL, from_tty, list);
14690 else
14691 cmd_func (list, NULL, from_tty);
14692 }
14693 }
14694
14695
14696 /* Function to be called whenever a new objfile (shlib) is detected. */
14697 static void
14698 remote_new_objfile (struct objfile *objfile)
14699 {
14700 /* The objfile change happened in that program space. */
14701 program_space *pspace = current_program_space;
14702
14703 /* The affected program space is possibly shared by multiple inferiors.
14704 Consider sending a qSymbol packet for each of the inferiors using that
14705 program space. */
14706 for (inferior *inf : all_inferiors ())
14707 {
14708 if (inf->pspace != pspace)
14709 continue;
14710
14711 /* Check whether the inferior's process target is a remote target. */
14712 remote_target *remote = as_remote_target (inf->process_target ());
14713 if (remote == nullptr)
14714 continue;
14715
14716 /* When we are attaching or handling a fork child and the shared library
14717 subsystem reads the list of loaded libraries, we receive new objfile
14718 events in between each found library. The libraries are read in an
14719 undefined order, so if we gave the remote side a chance to look up
14720 symbols between each objfile, we might give it an inconsistent picture
14721 of the inferior. It could appear that a library A appears loaded but
14722 a library B does not, even though library A requires library B. That
14723 would present a state that couldn't normally exist in the inferior.
14724
14725 So, skip these events, we'll give the remote a chance to look up
14726 symbols once all the loaded libraries and their symbols are known to
14727 GDB. */
14728 if (inf->in_initial_library_scan)
14729 continue;
14730
14731 if (!remote->has_execution (inf))
14732 continue;
14733
14734 /* Need to switch to a specific thread, because remote_check_symbols will
14735 set the general thread using INFERIOR_PTID.
14736
14737 It's possible to have inferiors with no thread here, because we are
14738 called very early in the connection process, while the inferior is
14739 being set up, before threads are added. Just skip it, start_remote_1
14740 also calls remote_check_symbols when it's done setting things up. */
14741 thread_info *thread = any_thread_of_inferior (inf);
14742 if (thread != nullptr)
14743 {
14744 scoped_restore_current_thread restore_thread;
14745 switch_to_thread (thread);
14746 remote->remote_check_symbols ();
14747 }
14748 }
14749 }
14750
14751 /* Pull all the tracepoints defined on the target and create local
14752 data structures representing them. We don't want to create real
14753 tracepoints yet, we don't want to mess up the user's existing
14754 collection. */
14755
14756 int
14757 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14758 {
14759 struct remote_state *rs = get_remote_state ();
14760 char *p;
14761
14762 /* Ask for a first packet of tracepoint definition. */
14763 putpkt ("qTfP");
14764 getpkt (&rs->buf, 0);
14765 p = rs->buf.data ();
14766 while (*p && *p != 'l')
14767 {
14768 parse_tracepoint_definition (p, utpp);
14769 /* Ask for another packet of tracepoint definition. */
14770 putpkt ("qTsP");
14771 getpkt (&rs->buf, 0);
14772 p = rs->buf.data ();
14773 }
14774 return 0;
14775 }
14776
14777 int
14778 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14779 {
14780 struct remote_state *rs = get_remote_state ();
14781 char *p;
14782
14783 /* Ask for a first packet of variable definition. */
14784 putpkt ("qTfV");
14785 getpkt (&rs->buf, 0);
14786 p = rs->buf.data ();
14787 while (*p && *p != 'l')
14788 {
14789 parse_tsv_definition (p, utsvp);
14790 /* Ask for another packet of variable definition. */
14791 putpkt ("qTsV");
14792 getpkt (&rs->buf, 0);
14793 p = rs->buf.data ();
14794 }
14795 return 0;
14796 }
14797
14798 /* The "set/show range-stepping" show hook. */
14799
14800 static void
14801 show_range_stepping (struct ui_file *file, int from_tty,
14802 struct cmd_list_element *c,
14803 const char *value)
14804 {
14805 gdb_printf (file,
14806 _("Debugger's willingness to use range stepping "
14807 "is %s.\n"), value);
14808 }
14809
14810 /* Return true if the vCont;r action is supported by the remote
14811 stub. */
14812
14813 bool
14814 remote_target::vcont_r_supported ()
14815 {
14816 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
14817 && get_remote_state ()->supports_vCont.r);
14818 }
14819
14820 /* The "set/show range-stepping" set hook. */
14821
14822 static void
14823 set_range_stepping (const char *ignore_args, int from_tty,
14824 struct cmd_list_element *c)
14825 {
14826 /* When enabling, check whether range stepping is actually supported
14827 by the target, and warn if not. */
14828 if (use_range_stepping)
14829 {
14830 remote_target *remote = get_current_remote_target ();
14831 if (remote == NULL
14832 || !remote->vcont_r_supported ())
14833 warning (_("Range stepping is not supported by the current target"));
14834 }
14835 }
14836
14837 static void
14838 show_remote_debug (struct ui_file *file, int from_tty,
14839 struct cmd_list_element *c, const char *value)
14840 {
14841 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14842 value);
14843 }
14844
14845 static void
14846 show_remote_timeout (struct ui_file *file, int from_tty,
14847 struct cmd_list_element *c, const char *value)
14848 {
14849 gdb_printf (file,
14850 _("Timeout limit to wait for target to respond is %s.\n"),
14851 value);
14852 }
14853
14854 /* Implement the "supports_memory_tagging" target_ops method. */
14855
14856 bool
14857 remote_target::supports_memory_tagging ()
14858 {
14859 return m_features.remote_memory_tagging_p ();
14860 }
14861
14862 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14863
14864 static void
14865 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14866 size_t len, int type)
14867 {
14868 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14869
14870 std::string request = string_printf ("qMemTags:%s,%s:%s",
14871 phex_nz (address, addr_size),
14872 phex_nz (len, sizeof (len)),
14873 phex_nz (type, sizeof (type)));
14874
14875 strcpy (packet.data (), request.c_str ());
14876 }
14877
14878 /* Parse the qMemTags packet reply into TAGS.
14879
14880 Return true if successful, false otherwise. */
14881
14882 static bool
14883 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14884 gdb::byte_vector &tags)
14885 {
14886 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14887 return false;
14888
14889 /* Copy the tag data. */
14890 tags = hex2bin (reply.data () + 1);
14891
14892 return true;
14893 }
14894
14895 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14896
14897 static void
14898 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14899 size_t len, int type,
14900 const gdb::byte_vector &tags)
14901 {
14902 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14903
14904 /* Put together the main packet, address and length. */
14905 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14906 phex_nz (address, addr_size),
14907 phex_nz (len, sizeof (len)),
14908 phex_nz (type, sizeof (type)));
14909 request += bin2hex (tags.data (), tags.size ());
14910
14911 /* Check if we have exceeded the maximum packet size. */
14912 if (packet.size () < request.length ())
14913 error (_("Contents too big for packet QMemTags."));
14914
14915 strcpy (packet.data (), request.c_str ());
14916 }
14917
14918 /* Implement the "fetch_memtags" target_ops method. */
14919
14920 bool
14921 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14922 gdb::byte_vector &tags, int type)
14923 {
14924 /* Make sure the qMemTags packet is supported. */
14925 if (!m_features.remote_memory_tagging_p ())
14926 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14927
14928 struct remote_state *rs = get_remote_state ();
14929
14930 create_fetch_memtags_request (rs->buf, address, len, type);
14931
14932 putpkt (rs->buf);
14933 getpkt (&rs->buf, 0);
14934
14935 return parse_fetch_memtags_reply (rs->buf, tags);
14936 }
14937
14938 /* Implement the "store_memtags" target_ops method. */
14939
14940 bool
14941 remote_target::store_memtags (CORE_ADDR address, size_t len,
14942 const gdb::byte_vector &tags, int type)
14943 {
14944 /* Make sure the QMemTags packet is supported. */
14945 if (!m_features.remote_memory_tagging_p ())
14946 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14947
14948 struct remote_state *rs = get_remote_state ();
14949
14950 create_store_memtags_request (rs->buf, address, len, type, tags);
14951
14952 putpkt (rs->buf);
14953 getpkt (&rs->buf, 0);
14954
14955 /* Verify if the request was successful. */
14956 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14957 }
14958
14959 /* Return true if remote target T is non-stop. */
14960
14961 bool
14962 remote_target_is_non_stop_p (remote_target *t)
14963 {
14964 scoped_restore_current_thread restore_thread;
14965 switch_to_target_no_thread (t);
14966
14967 return target_is_non_stop_p ();
14968 }
14969
14970 #if GDB_SELF_TEST
14971
14972 namespace selftests {
14973
14974 static void
14975 test_memory_tagging_functions ()
14976 {
14977 remote_target remote;
14978
14979 struct packet_config *config
14980 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
14981
14982 scoped_restore restore_memtag_support_
14983 = make_scoped_restore (&config->support);
14984
14985 /* Test memory tagging packet support. */
14986 config->support = PACKET_SUPPORT_UNKNOWN;
14987 SELF_CHECK (remote.supports_memory_tagging () == false);
14988 config->support = PACKET_DISABLE;
14989 SELF_CHECK (remote.supports_memory_tagging () == false);
14990 config->support = PACKET_ENABLE;
14991 SELF_CHECK (remote.supports_memory_tagging () == true);
14992
14993 /* Setup testing. */
14994 gdb::char_vector packet;
14995 gdb::byte_vector tags, bv;
14996 std::string expected, reply;
14997 packet.resize (32000);
14998
14999 /* Test creating a qMemTags request. */
15000
15001 expected = "qMemTags:0,0:0";
15002 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15003 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15004
15005 expected = "qMemTags:deadbeef,10:1";
15006 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15007 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15008
15009 /* Test parsing a qMemTags reply. */
15010
15011 /* Error reply, tags vector unmodified. */
15012 reply = "E00";
15013 strcpy (packet.data (), reply.c_str ());
15014 tags.resize (0);
15015 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15016 SELF_CHECK (tags.size () == 0);
15017
15018 /* Valid reply, tags vector updated. */
15019 tags.resize (0);
15020 bv.resize (0);
15021
15022 for (int i = 0; i < 5; i++)
15023 bv.push_back (i);
15024
15025 reply = "m" + bin2hex (bv.data (), bv.size ());
15026 strcpy (packet.data (), reply.c_str ());
15027
15028 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15029 SELF_CHECK (tags.size () == 5);
15030
15031 for (int i = 0; i < 5; i++)
15032 SELF_CHECK (tags[i] == i);
15033
15034 /* Test creating a QMemTags request. */
15035
15036 /* Empty tag data. */
15037 tags.resize (0);
15038 expected = "QMemTags:0,0:0:";
15039 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15040 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15041 expected.length ()) == 0);
15042
15043 /* Non-empty tag data. */
15044 tags.resize (0);
15045 for (int i = 0; i < 5; i++)
15046 tags.push_back (i);
15047 expected = "QMemTags:deadbeef,ff:1:0001020304";
15048 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15049 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15050 expected.length ()) == 0);
15051 }
15052
15053 } // namespace selftests
15054 #endif /* GDB_SELF_TEST */
15055
15056 void _initialize_remote ();
15057 void
15058 _initialize_remote ()
15059 {
15060 add_target (remote_target_info, remote_target::open);
15061 add_target (extended_remote_target_info, extended_remote_target::open);
15062
15063 /* Hook into new objfile notification. */
15064 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15065
15066 #if 0
15067 init_remote_threadtests ();
15068 #endif
15069
15070 /* set/show remote ... */
15071
15072 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15073 Remote protocol specific variables.\n\
15074 Configure various remote-protocol specific variables such as\n\
15075 the packets being used."),
15076 &remote_set_cmdlist,
15077 0 /* allow-unknown */, &setlist);
15078 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15079 Remote protocol specific variables.\n\
15080 Configure various remote-protocol specific variables such as\n\
15081 the packets being used."),
15082 &remote_show_cmdlist,
15083 0 /* allow-unknown */, &showlist);
15084
15085 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15086 Compare section data on target to the exec file.\n\
15087 Argument is a single section name (default: all loaded sections).\n\
15088 To compare only read-only loaded sections, specify the -r option."),
15089 &cmdlist);
15090
15091 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15092 Send an arbitrary packet to a remote target.\n\
15093 maintenance packet TEXT\n\
15094 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15095 this command sends the string TEXT to the inferior, and displays the\n\
15096 response packet. GDB supplies the initial `$' character, and the\n\
15097 terminating `#' character and checksum."),
15098 &maintenancelist);
15099
15100 set_show_commands remotebreak_cmds
15101 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15102 Set whether to send break if interrupted."), _("\
15103 Show whether to send break if interrupted."), _("\
15104 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15105 set_remotebreak, show_remotebreak,
15106 &setlist, &showlist);
15107 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15108 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15109
15110 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15111 interrupt_sequence_modes, &interrupt_sequence_mode,
15112 _("\
15113 Set interrupt sequence to remote target."), _("\
15114 Show interrupt sequence to remote target."), _("\
15115 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15116 NULL, show_interrupt_sequence,
15117 &remote_set_cmdlist,
15118 &remote_show_cmdlist);
15119
15120 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15121 &interrupt_on_connect, _("\
15122 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15123 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15124 If set, interrupt sequence is sent to remote target."),
15125 NULL, NULL,
15126 &remote_set_cmdlist, &remote_show_cmdlist);
15127
15128 /* Install commands for configuring memory read/write packets. */
15129
15130 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15131 Set the maximum number of bytes per memory write packet (deprecated)."),
15132 &setlist);
15133 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15134 Show the maximum number of bytes per memory write packet (deprecated)."),
15135 &showlist);
15136 add_cmd ("memory-write-packet-size", no_class,
15137 set_memory_write_packet_size, _("\
15138 Set the maximum number of bytes per memory-write packet.\n\
15139 Specify the number of bytes in a packet or 0 (zero) for the\n\
15140 default packet size. The actual limit is further reduced\n\
15141 dependent on the target. Specify \"fixed\" to disable the\n\
15142 further restriction and \"limit\" to enable that restriction."),
15143 &remote_set_cmdlist);
15144 add_cmd ("memory-read-packet-size", no_class,
15145 set_memory_read_packet_size, _("\
15146 Set the maximum number of bytes per memory-read packet.\n\
15147 Specify the number of bytes in a packet or 0 (zero) for the\n\
15148 default packet size. The actual limit is further reduced\n\
15149 dependent on the target. Specify \"fixed\" to disable the\n\
15150 further restriction and \"limit\" to enable that restriction."),
15151 &remote_set_cmdlist);
15152 add_cmd ("memory-write-packet-size", no_class,
15153 show_memory_write_packet_size,
15154 _("Show the maximum number of bytes per memory-write packet."),
15155 &remote_show_cmdlist);
15156 add_cmd ("memory-read-packet-size", no_class,
15157 show_memory_read_packet_size,
15158 _("Show the maximum number of bytes per memory-read packet."),
15159 &remote_show_cmdlist);
15160
15161 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15162 &remote_hw_watchpoint_limit, _("\
15163 Set the maximum number of target hardware watchpoints."), _("\
15164 Show the maximum number of target hardware watchpoints."), _("\
15165 Specify \"unlimited\" for unlimited hardware watchpoints."),
15166 NULL, show_hardware_watchpoint_limit,
15167 &remote_set_cmdlist,
15168 &remote_show_cmdlist);
15169 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15170 no_class,
15171 &remote_hw_watchpoint_length_limit, _("\
15172 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15173 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15174 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15175 NULL, show_hardware_watchpoint_length_limit,
15176 &remote_set_cmdlist, &remote_show_cmdlist);
15177 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15178 &remote_hw_breakpoint_limit, _("\
15179 Set the maximum number of target hardware breakpoints."), _("\
15180 Show the maximum number of target hardware breakpoints."), _("\
15181 Specify \"unlimited\" for unlimited hardware breakpoints."),
15182 NULL, show_hardware_breakpoint_limit,
15183 &remote_set_cmdlist, &remote_show_cmdlist);
15184
15185 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15186 &remote_address_size, _("\
15187 Set the maximum size of the address (in bits) in a memory packet."), _("\
15188 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15189 NULL,
15190 NULL, /* FIXME: i18n: */
15191 &setlist, &showlist);
15192
15193 init_all_packet_configs ();
15194
15195 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15196
15197 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15198
15199 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15200 0);
15201
15202 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15203 "catch-syscalls", 0);
15204
15205 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15206 "program-signals", 0);
15207
15208 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15209 "set-working-dir", 0);
15210
15211 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15212 "startup-with-shell", 0);
15213
15214 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15215 "environment-hex-encoded", 0);
15216
15217 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15218 "environment-reset", 0);
15219
15220 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15221 "environment-unset", 0);
15222
15223 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15224
15225 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15226
15227 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15228
15229 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15230
15231 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15232
15233 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15234
15235 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15236
15237 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15238
15239 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15240 "read-aux-vector", 0);
15241
15242 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15243 "pid-to-exec-file", 0);
15244
15245 add_packet_config_cmd (PACKET_qXfer_features,
15246 "qXfer:features:read", "target-features", 0);
15247
15248 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15249 "library-info", 0);
15250
15251 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15252 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15253
15254 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15255 "memory-map", 0);
15256
15257 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15258
15259 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15260 0);
15261
15262 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15263 "read-siginfo-object", 0);
15264
15265 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15266 "write-siginfo-object", 0);
15267
15268 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15269 "qXfer:traceframe-info:read", "traceframe-info", 0);
15270
15271 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15272 "unwind-info-block", 0);
15273
15274 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15275 "get-thread-local-storage-address", 0);
15276
15277 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15278 "get-thread-information-block-address", 0);
15279
15280 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15281
15282 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15283
15284 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15285 0);
15286
15287 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15288 "search-memory", 0);
15289
15290 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15291
15292 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15293
15294 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15295
15296 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15297
15298 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15299 0);
15300
15301 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15302
15303 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15304 0);
15305
15306 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15307 "hostio-readlink", 0);
15308
15309 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15310
15311 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15312
15313 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15314
15315 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15316
15317 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15318
15319 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15320
15321 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15322 "ConditionalTracepoints", "conditional-tracepoints",
15323 0);
15324
15325 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15326 "ConditionalBreakpoints", "conditional-breakpoints",
15327 0);
15328
15329 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15330 "breakpoint-commands", 0);
15331
15332 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15333 "fast-tracepoints", 0);
15334
15335 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15336 "TracepointSource", 0);
15337
15338 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15339
15340 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15341 "static-tracepoints", 0);
15342
15343 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15344 "install-in-trace", 0);
15345
15346 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15347 "qXfer:statictrace:read", "read-sdata-object", 0);
15348
15349 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15350 "read-fdpic-loadmap", 0);
15351
15352 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15353 "disable-randomization", 0);
15354
15355 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15356
15357 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15358 "trace-buffer-size", 0);
15359
15360 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15361 0);
15362
15363 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15364 0);
15365
15366 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15367 0);
15368
15369 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15370
15371 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15372 "read-btrace-conf", 0);
15373
15374 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15375 "btrace-conf-bts-size", 0);
15376
15377 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15378 "multiprocess-feature", 0);
15379
15380 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15381 "swbreak-feature", 0);
15382
15383 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15384 "hwbreak-feature", 0);
15385
15386 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15387 "fork-event-feature", 0);
15388
15389 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15390 "vfork-event-feature", 0);
15391
15392 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15393 "btrace-conf-pt-size", 0);
15394
15395 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15396 "verbose-resume-supported", 0);
15397
15398 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15399 "exec-event-feature", 0);
15400
15401 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15402
15403 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15404 0);
15405
15406 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15407 "no-resumed-stop-reply", 0);
15408
15409 add_packet_config_cmd (PACKET_memory_tagging_feature,
15410 "memory-tagging-feature", "memory-tagging-feature", 0);
15411
15412 /* Assert that we've registered "set remote foo-packet" commands
15413 for all packet configs. */
15414 {
15415 int i;
15416
15417 for (i = 0; i < PACKET_MAX; i++)
15418 {
15419 /* Ideally all configs would have a command associated. Some
15420 still don't though. */
15421 int excepted;
15422
15423 switch (i)
15424 {
15425 case PACKET_QNonStop:
15426 case PACKET_EnableDisableTracepoints_feature:
15427 case PACKET_tracenz_feature:
15428 case PACKET_DisconnectedTracing_feature:
15429 case PACKET_augmented_libraries_svr4_read_feature:
15430 case PACKET_qCRC:
15431 /* Additions to this list need to be well justified:
15432 pre-existing packets are OK; new packets are not. */
15433 excepted = 1;
15434 break;
15435 default:
15436 excepted = 0;
15437 break;
15438 }
15439
15440 /* This catches both forgetting to add a config command, and
15441 forgetting to remove a packet from the exception list. */
15442 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15443 }
15444 }
15445
15446 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15447 Z sub-packet has its own set and show commands, but users may
15448 have sets to this variable in their .gdbinit files (or in their
15449 documentation). */
15450 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15451 &remote_Z_packet_detect, _("\
15452 Set use of remote protocol `Z' packets."), _("\
15453 Show use of remote protocol `Z' packets."), _("\
15454 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15455 packets."),
15456 set_remote_protocol_Z_packet_cmd,
15457 show_remote_protocol_Z_packet_cmd,
15458 /* FIXME: i18n: Use of remote protocol
15459 `Z' packets is %s. */
15460 &remote_set_cmdlist, &remote_show_cmdlist);
15461
15462 add_basic_prefix_cmd ("remote", class_files, _("\
15463 Manipulate files on the remote system.\n\
15464 Transfer files to and from the remote target system."),
15465 &remote_cmdlist,
15466 0 /* allow-unknown */, &cmdlist);
15467
15468 add_cmd ("put", class_files, remote_put_command,
15469 _("Copy a local file to the remote system."),
15470 &remote_cmdlist);
15471
15472 add_cmd ("get", class_files, remote_get_command,
15473 _("Copy a remote file to the local system."),
15474 &remote_cmdlist);
15475
15476 add_cmd ("delete", class_files, remote_delete_command,
15477 _("Delete a remote file."),
15478 &remote_cmdlist);
15479
15480 add_setshow_string_noescape_cmd ("exec-file", class_files,
15481 &remote_exec_file_var, _("\
15482 Set the remote pathname for \"run\"."), _("\
15483 Show the remote pathname for \"run\"."), NULL,
15484 set_remote_exec_file,
15485 show_remote_exec_file,
15486 &remote_set_cmdlist,
15487 &remote_show_cmdlist);
15488
15489 add_setshow_boolean_cmd ("range-stepping", class_run,
15490 &use_range_stepping, _("\
15491 Enable or disable range stepping."), _("\
15492 Show whether target-assisted range stepping is enabled."), _("\
15493 If on, and the target supports it, when stepping a source line, GDB\n\
15494 tells the target to step the corresponding range of addresses itself instead\n\
15495 of issuing multiple single-steps. This speeds up source level\n\
15496 stepping. If off, GDB always issues single-steps, even if range\n\
15497 stepping is supported by the target. The default is on."),
15498 set_range_stepping,
15499 show_range_stepping,
15500 &setlist,
15501 &showlist);
15502
15503 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15504 Set watchdog timer."), _("\
15505 Show watchdog timer."), _("\
15506 When non-zero, this timeout is used instead of waiting forever for a target\n\
15507 to finish a low-level step or continue operation. If the specified amount\n\
15508 of time passes without a response from the target, an error occurs."),
15509 NULL,
15510 show_watchdog,
15511 &setlist, &showlist);
15512
15513 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15514 &remote_packet_max_chars, _("\
15515 Set the maximum number of characters to display for each remote packet."), _("\
15516 Show the maximum number of characters to display for each remote packet."), _("\
15517 Specify \"unlimited\" to display all the characters."),
15518 NULL, show_remote_packet_max_chars,
15519 &setdebuglist, &showdebuglist);
15520
15521 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15522 _("Set debugging of remote protocol."),
15523 _("Show debugging of remote protocol."),
15524 _("\
15525 When enabled, each packet sent or received with the remote target\n\
15526 is displayed."),
15527 NULL,
15528 show_remote_debug,
15529 &setdebuglist, &showdebuglist);
15530
15531 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15532 &remote_timeout, _("\
15533 Set timeout limit to wait for target to respond."), _("\
15534 Show timeout limit to wait for target to respond."), _("\
15535 This value is used to set the time limit for gdb to wait for a response\n\
15536 from the target."),
15537 NULL,
15538 show_remote_timeout,
15539 &setlist, &showlist);
15540
15541 /* Eventually initialize fileio. See fileio.c */
15542 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15543
15544 #if GDB_SELF_TEST
15545 selftests::register_test ("remote_memory_tagging",
15546 selftests::test_memory_tagging_functions);
15547 #endif
15548 }