]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/remote.c
gdb: add interp::on_normal_stop method
[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 = this->find_thread (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 = target->find_thread (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 = this->find_thread (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 notify_signal_received (sig);
4724 }
4725
4726 notify_normal_stop (nullptr, 1);
4727 }
4728
4729 /* Process all initial stop replies the remote side sent in response
4730 to the ? packet. These indicate threads that were already stopped
4731 on initial connection. We mark these threads as stopped and print
4732 their current frame before giving the user the prompt. */
4733
4734 void
4735 remote_target::process_initial_stop_replies (int from_tty)
4736 {
4737 int pending_stop_replies = stop_reply_queue_length ();
4738 struct thread_info *selected = NULL;
4739 struct thread_info *lowest_stopped = NULL;
4740 struct thread_info *first = NULL;
4741
4742 /* This is only used when the target is non-stop. */
4743 gdb_assert (target_is_non_stop_p ());
4744
4745 /* Consume the initial pending events. */
4746 while (pending_stop_replies-- > 0)
4747 {
4748 ptid_t waiton_ptid = minus_one_ptid;
4749 ptid_t event_ptid;
4750 struct target_waitstatus ws;
4751 int ignore_event = 0;
4752
4753 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4754 if (remote_debug)
4755 print_target_wait_results (waiton_ptid, event_ptid, ws);
4756
4757 switch (ws.kind ())
4758 {
4759 case TARGET_WAITKIND_IGNORE:
4760 case TARGET_WAITKIND_NO_RESUMED:
4761 case TARGET_WAITKIND_SIGNALLED:
4762 case TARGET_WAITKIND_EXITED:
4763 /* We shouldn't see these, but if we do, just ignore. */
4764 remote_debug_printf ("event ignored");
4765 ignore_event = 1;
4766 break;
4767
4768 default:
4769 break;
4770 }
4771
4772 if (ignore_event)
4773 continue;
4774
4775 thread_info *evthread = this->find_thread (event_ptid);
4776
4777 if (ws.kind () == TARGET_WAITKIND_STOPPED)
4778 {
4779 enum gdb_signal sig = ws.sig ();
4780
4781 /* Stubs traditionally report SIGTRAP as initial signal,
4782 instead of signal 0. Suppress it. */
4783 if (sig == GDB_SIGNAL_TRAP)
4784 sig = GDB_SIGNAL_0;
4785 evthread->set_stop_signal (sig);
4786 ws.set_stopped (sig);
4787 }
4788
4789 if (ws.kind () != TARGET_WAITKIND_STOPPED
4790 || ws.sig () != GDB_SIGNAL_0)
4791 evthread->set_pending_waitstatus (ws);
4792
4793 set_executing (this, event_ptid, false);
4794 set_running (this, event_ptid, false);
4795 get_remote_thread_info (evthread)->set_not_resumed ();
4796 }
4797
4798 /* "Notice" the new inferiors before anything related to
4799 registers/memory. */
4800 for (inferior *inf : all_non_exited_inferiors (this))
4801 {
4802 inf->needs_setup = true;
4803
4804 if (non_stop)
4805 {
4806 thread_info *thread = any_live_thread_of_inferior (inf);
4807 notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4808 from_tty);
4809 }
4810 }
4811
4812 /* If all-stop on top of non-stop, pause all threads. Note this
4813 records the threads' stop pc, so must be done after "noticing"
4814 the inferiors. */
4815 if (!non_stop)
4816 {
4817 {
4818 /* At this point, the remote target is not async. It needs to be for
4819 the poll in stop_all_threads to consider events from it, so enable
4820 it temporarily. */
4821 gdb_assert (!this->is_async_p ());
4822 SCOPE_EXIT { target_async (false); };
4823 target_async (true);
4824 stop_all_threads ("remote connect in all-stop");
4825 }
4826
4827 /* If all threads of an inferior were already stopped, we
4828 haven't setup the inferior yet. */
4829 for (inferior *inf : all_non_exited_inferiors (this))
4830 {
4831 if (inf->needs_setup)
4832 {
4833 thread_info *thread = any_live_thread_of_inferior (inf);
4834 switch_to_thread_no_regs (thread);
4835 setup_inferior (0);
4836 }
4837 }
4838 }
4839
4840 /* Now go over all threads that are stopped, and print their current
4841 frame. If all-stop, then if there's a signalled thread, pick
4842 that as current. */
4843 for (thread_info *thread : all_non_exited_threads (this))
4844 {
4845 if (first == NULL)
4846 first = thread;
4847
4848 if (!non_stop)
4849 thread->set_running (false);
4850 else if (thread->state != THREAD_STOPPED)
4851 continue;
4852
4853 if (selected == nullptr && thread->has_pending_waitstatus ())
4854 selected = thread;
4855
4856 if (lowest_stopped == NULL
4857 || thread->inf->num < lowest_stopped->inf->num
4858 || thread->per_inf_num < lowest_stopped->per_inf_num)
4859 lowest_stopped = thread;
4860
4861 if (non_stop)
4862 print_one_stopped_thread (thread);
4863 }
4864
4865 /* In all-stop, we only print the status of one thread, and leave
4866 others with their status pending. */
4867 if (!non_stop)
4868 {
4869 thread_info *thread = selected;
4870 if (thread == NULL)
4871 thread = lowest_stopped;
4872 if (thread == NULL)
4873 thread = first;
4874
4875 print_one_stopped_thread (thread);
4876 }
4877 }
4878
4879 /* Mark a remote_target as starting (by setting the starting_up flag within
4880 its remote_state) for the lifetime of this object. The reference count
4881 on the remote target is temporarily incremented, to prevent the target
4882 being deleted under our feet. */
4883
4884 struct scoped_mark_target_starting
4885 {
4886 /* Constructor, TARGET is the target to be marked as starting, its
4887 reference count will be incremented. */
4888 scoped_mark_target_starting (remote_target *target)
4889 : m_remote_target (remote_target_ref::new_reference (target)),
4890 m_restore_starting_up (set_starting_up_flag (target))
4891 { /* Nothing. */ }
4892
4893 private:
4894
4895 /* Helper function, set the starting_up flag on TARGET and return an
4896 object which, when it goes out of scope, will restore the previous
4897 value of the starting_up flag. */
4898 static scoped_restore_tmpl<bool>
4899 set_starting_up_flag (remote_target *target)
4900 {
4901 remote_state *rs = target->get_remote_state ();
4902 gdb_assert (!rs->starting_up);
4903 return make_scoped_restore (&rs->starting_up, true);
4904 }
4905
4906 /* A gdb::ref_ptr pointer to a remote_target. */
4907 using remote_target_ref = gdb::ref_ptr<remote_target, target_ops_ref_policy>;
4908
4909 /* A reference to the target on which we are operating. */
4910 remote_target_ref m_remote_target;
4911
4912 /* An object which restores the previous value of the starting_up flag
4913 when it goes out of scope. */
4914 scoped_restore_tmpl<bool> m_restore_starting_up;
4915 };
4916
4917 /* Helper for remote_target::start_remote, start the remote connection and
4918 sync state. Return true if everything goes OK, otherwise, return false.
4919 This function exists so that the scoped_restore created within it will
4920 expire before we return to remote_target::start_remote. */
4921
4922 bool
4923 remote_target::start_remote_1 (int from_tty, int extended_p)
4924 {
4925 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
4926
4927 struct remote_state *rs = get_remote_state ();
4928
4929 /* Signal other parts that we're going through the initial setup,
4930 and so things may not be stable yet. E.g., we don't try to
4931 install tracepoints until we've relocated symbols. Also, a
4932 Ctrl-C before we're connected and synced up can't interrupt the
4933 target. Instead, it offers to drop the (potentially wedged)
4934 connection. */
4935 scoped_mark_target_starting target_is_starting (this);
4936
4937 QUIT;
4938
4939 if (interrupt_on_connect)
4940 send_interrupt_sequence ();
4941
4942 /* Ack any packet which the remote side has already sent. */
4943 remote_serial_write ("+", 1);
4944
4945 /* The first packet we send to the target is the optional "supported
4946 packets" request. If the target can answer this, it will tell us
4947 which later probes to skip. */
4948 remote_query_supported ();
4949
4950 /* Check vCont support and set the remote state's vCont_action_support
4951 attribute. */
4952 remote_vcont_probe ();
4953
4954 /* If the stub wants to get a QAllow, compose one and send it. */
4955 if (m_features.packet_support (PACKET_QAllow) != PACKET_DISABLE)
4956 set_permissions ();
4957
4958 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4959 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4960 as a reply to known packet. For packet "vFile:setfs:" it is an
4961 invalid reply and GDB would return error in
4962 remote_hostio_set_filesystem, making remote files access impossible.
4963 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4964 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4965 {
4966 const char v_mustreplyempty[] = "vMustReplyEmpty";
4967
4968 putpkt (v_mustreplyempty);
4969 getpkt (&rs->buf, 0);
4970 if (strcmp (rs->buf.data (), "OK") == 0)
4971 {
4972 m_features.m_protocol_packets[PACKET_vFile_setfs].support
4973 = PACKET_DISABLE;
4974 }
4975 else if (strcmp (rs->buf.data (), "") != 0)
4976 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4977 rs->buf.data ());
4978 }
4979
4980 /* Next, we possibly activate noack mode.
4981
4982 If the QStartNoAckMode packet configuration is set to AUTO,
4983 enable noack mode if the stub reported a wish for it with
4984 qSupported.
4985
4986 If set to TRUE, then enable noack mode even if the stub didn't
4987 report it in qSupported. If the stub doesn't reply OK, the
4988 session ends with an error.
4989
4990 If FALSE, then don't activate noack mode, regardless of what the
4991 stub claimed should be the default with qSupported. */
4992
4993 if (m_features.packet_support (PACKET_QStartNoAckMode) != PACKET_DISABLE)
4994 {
4995 putpkt ("QStartNoAckMode");
4996 getpkt (&rs->buf, 0);
4997 if (m_features.packet_ok (rs->buf, PACKET_QStartNoAckMode) == PACKET_OK)
4998 rs->noack_mode = 1;
4999 }
5000
5001 if (extended_p)
5002 {
5003 /* Tell the remote that we are using the extended protocol. */
5004 putpkt ("!");
5005 getpkt (&rs->buf, 0);
5006 }
5007
5008 /* Let the target know which signals it is allowed to pass down to
5009 the program. */
5010 update_signals_program_target ();
5011
5012 /* Next, if the target can specify a description, read it. We do
5013 this before anything involving memory or registers. */
5014 target_find_description ();
5015
5016 /* Next, now that we know something about the target, update the
5017 address spaces in the program spaces. */
5018 update_address_spaces ();
5019
5020 /* On OSs where the list of libraries is global to all
5021 processes, we fetch them early. */
5022 if (gdbarch_has_global_solist (target_gdbarch ()))
5023 solib_add (NULL, from_tty, auto_solib_add);
5024
5025 if (target_is_non_stop_p ())
5026 {
5027 if (m_features.packet_support (PACKET_QNonStop) != PACKET_ENABLE)
5028 error (_("Non-stop mode requested, but remote "
5029 "does not support non-stop"));
5030
5031 putpkt ("QNonStop:1");
5032 getpkt (&rs->buf, 0);
5033
5034 if (strcmp (rs->buf.data (), "OK") != 0)
5035 error (_("Remote refused setting non-stop mode with: %s"),
5036 rs->buf.data ());
5037
5038 /* Find about threads and processes the stub is already
5039 controlling. We default to adding them in the running state.
5040 The '?' query below will then tell us about which threads are
5041 stopped. */
5042 this->update_thread_list ();
5043 }
5044 else if (m_features.packet_support (PACKET_QNonStop) == PACKET_ENABLE)
5045 {
5046 /* Don't assume that the stub can operate in all-stop mode.
5047 Request it explicitly. */
5048 putpkt ("QNonStop:0");
5049 getpkt (&rs->buf, 0);
5050
5051 if (strcmp (rs->buf.data (), "OK") != 0)
5052 error (_("Remote refused setting all-stop mode with: %s"),
5053 rs->buf.data ());
5054 }
5055
5056 /* Upload TSVs regardless of whether the target is running or not. The
5057 remote stub, such as GDBserver, may have some predefined or builtin
5058 TSVs, even if the target is not running. */
5059 if (get_trace_status (current_trace_status ()) != -1)
5060 {
5061 struct uploaded_tsv *uploaded_tsvs = NULL;
5062
5063 upload_trace_state_variables (&uploaded_tsvs);
5064 merge_uploaded_trace_state_variables (&uploaded_tsvs);
5065 }
5066
5067 /* Check whether the target is running now. */
5068 putpkt ("?");
5069 getpkt (&rs->buf, 0);
5070
5071 if (!target_is_non_stop_p ())
5072 {
5073 char *wait_status = NULL;
5074
5075 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
5076 {
5077 if (!extended_p)
5078 error (_("The target is not running (try extended-remote?)"));
5079 return false;
5080 }
5081 else
5082 {
5083 /* Save the reply for later. */
5084 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5085 strcpy (wait_status, rs->buf.data ());
5086 }
5087
5088 /* Fetch thread list. */
5089 target_update_thread_list ();
5090
5091 /* Let the stub know that we want it to return the thread. */
5092 set_continue_thread (minus_one_ptid);
5093
5094 if (thread_count (this) == 0)
5095 {
5096 /* Target has no concept of threads at all. GDB treats
5097 non-threaded target as single-threaded; add a main
5098 thread. */
5099 thread_info *tp = add_current_inferior_and_thread (wait_status);
5100 get_remote_thread_info (tp)->set_resumed ();
5101 }
5102 else
5103 {
5104 /* We have thread information; select the thread the target
5105 says should be current. If we're reconnecting to a
5106 multi-threaded program, this will ideally be the thread
5107 that last reported an event before GDB disconnected. */
5108 ptid_t curr_thread = get_current_thread (wait_status);
5109 if (curr_thread == null_ptid)
5110 {
5111 /* Odd... The target was able to list threads, but not
5112 tell us which thread was current (no "thread"
5113 register in T stop reply?). Just pick the first
5114 thread in the thread list then. */
5115
5116 remote_debug_printf ("warning: couldn't determine remote "
5117 "current thread; picking first in list.");
5118
5119 for (thread_info *tp : all_non_exited_threads (this,
5120 minus_one_ptid))
5121 {
5122 switch_to_thread (tp);
5123 break;
5124 }
5125 }
5126 else
5127 switch_to_thread (this->find_thread (curr_thread));
5128 }
5129
5130 /* init_wait_for_inferior should be called before get_offsets in order
5131 to manage `inserted' flag in bp loc in a correct state.
5132 breakpoint_init_inferior, called from init_wait_for_inferior, set
5133 `inserted' flag to 0, while before breakpoint_re_set, called from
5134 start_remote, set `inserted' flag to 1. In the initialization of
5135 inferior, breakpoint_init_inferior should be called first, and then
5136 breakpoint_re_set can be called. If this order is broken, state of
5137 `inserted' flag is wrong, and cause some problems on breakpoint
5138 manipulation. */
5139 init_wait_for_inferior ();
5140
5141 get_offsets (); /* Get text, data & bss offsets. */
5142
5143 /* If we could not find a description using qXfer, and we know
5144 how to do it some other way, try again. This is not
5145 supported for non-stop; it could be, but it is tricky if
5146 there are no stopped threads when we connect. */
5147 if (remote_read_description_p (this)
5148 && gdbarch_target_desc (target_gdbarch ()) == NULL)
5149 {
5150 target_clear_description ();
5151 target_find_description ();
5152 }
5153
5154 /* Use the previously fetched status. */
5155 gdb_assert (wait_status != NULL);
5156 struct notif_event *reply
5157 = remote_notif_parse (this, &notif_client_stop, wait_status);
5158 push_stop_reply ((struct stop_reply *) reply);
5159
5160 ::start_remote (from_tty); /* Initialize gdb process mechanisms. */
5161 }
5162 else
5163 {
5164 /* Clear WFI global state. Do this before finding about new
5165 threads and inferiors, and setting the current inferior.
5166 Otherwise we would clear the proceed status of the current
5167 inferior when we want its stop_soon state to be preserved
5168 (see notice_new_inferior). */
5169 init_wait_for_inferior ();
5170
5171 /* In non-stop, we will either get an "OK", meaning that there
5172 are no stopped threads at this time; or, a regular stop
5173 reply. In the latter case, there may be more than one thread
5174 stopped --- we pull them all out using the vStopped
5175 mechanism. */
5176 if (strcmp (rs->buf.data (), "OK") != 0)
5177 {
5178 const notif_client *notif = &notif_client_stop;
5179
5180 /* remote_notif_get_pending_replies acks this one, and gets
5181 the rest out. */
5182 rs->notif_state->pending_event[notif_client_stop.id]
5183 = remote_notif_parse (this, notif, rs->buf.data ());
5184 remote_notif_get_pending_events (notif);
5185 }
5186
5187 if (thread_count (this) == 0)
5188 {
5189 if (!extended_p)
5190 error (_("The target is not running (try extended-remote?)"));
5191 return false;
5192 }
5193
5194 /* Report all signals during attach/startup. */
5195 pass_signals ({});
5196
5197 /* If there are already stopped threads, mark them stopped and
5198 report their stops before giving the prompt to the user. */
5199 process_initial_stop_replies (from_tty);
5200
5201 if (target_can_async_p ())
5202 target_async (true);
5203 }
5204
5205 /* Give the target a chance to look up symbols. */
5206 for (inferior *inf : all_inferiors (this))
5207 {
5208 /* The inferiors that exist at this point were created from what
5209 was found already running on the remote side, so we know they
5210 have execution. */
5211 gdb_assert (this->has_execution (inf));
5212
5213 /* No use without a symbol-file. */
5214 if (inf->pspace->symfile_object_file == nullptr)
5215 continue;
5216
5217 /* Need to switch to a specific thread, because remote_check_symbols
5218 uses INFERIOR_PTID to set the general thread. */
5219 scoped_restore_current_thread restore_thread;
5220 thread_info *thread = any_thread_of_inferior (inf);
5221 switch_to_thread (thread);
5222 this->remote_check_symbols ();
5223 }
5224
5225 /* Possibly the target has been engaged in a trace run started
5226 previously; find out where things are at. */
5227 if (get_trace_status (current_trace_status ()) != -1)
5228 {
5229 struct uploaded_tp *uploaded_tps = NULL;
5230
5231 if (current_trace_status ()->running)
5232 gdb_printf (_("Trace is already running on the target.\n"));
5233
5234 upload_tracepoints (&uploaded_tps);
5235
5236 merge_uploaded_tracepoints (&uploaded_tps);
5237 }
5238
5239 /* Possibly the target has been engaged in a btrace record started
5240 previously; find out where things are at. */
5241 remote_btrace_maybe_reopen ();
5242
5243 return true;
5244 }
5245
5246 /* Start the remote connection and sync state. */
5247
5248 void
5249 remote_target::start_remote (int from_tty, int extended_p)
5250 {
5251 if (start_remote_1 (from_tty, extended_p)
5252 && breakpoints_should_be_inserted_now ())
5253 insert_breakpoints ();
5254 }
5255
5256 const char *
5257 remote_target::connection_string ()
5258 {
5259 remote_state *rs = get_remote_state ();
5260
5261 if (rs->remote_desc->name != NULL)
5262 return rs->remote_desc->name;
5263 else
5264 return NULL;
5265 }
5266
5267 /* Open a connection to a remote debugger.
5268 NAME is the filename used for communication. */
5269
5270 void
5271 remote_target::open (const char *name, int from_tty)
5272 {
5273 open_1 (name, from_tty, 0);
5274 }
5275
5276 /* Open a connection to a remote debugger using the extended
5277 remote gdb protocol. NAME is the filename used for communication. */
5278
5279 void
5280 extended_remote_target::open (const char *name, int from_tty)
5281 {
5282 open_1 (name, from_tty, 1 /*extended_p */);
5283 }
5284
5285 void
5286 remote_features::reset_all_packet_configs_support ()
5287 {
5288 int i;
5289
5290 for (i = 0; i < PACKET_MAX; i++)
5291 m_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5292 }
5293
5294 /* Initialize all packet configs. */
5295
5296 static void
5297 init_all_packet_configs (void)
5298 {
5299 int i;
5300
5301 for (i = 0; i < PACKET_MAX; i++)
5302 {
5303 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
5304 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
5305 }
5306 }
5307
5308 /* Symbol look-up. */
5309
5310 void
5311 remote_target::remote_check_symbols ()
5312 {
5313 char *tmp;
5314 int end;
5315
5316 /* It doesn't make sense to send a qSymbol packet for an inferior that
5317 doesn't have execution, because the remote side doesn't know about
5318 inferiors without execution. */
5319 gdb_assert (target_has_execution ());
5320
5321 if (m_features.packet_support (PACKET_qSymbol) == PACKET_DISABLE)
5322 return;
5323
5324 /* Make sure the remote is pointing at the right process. Note
5325 there's no way to select "no process". */
5326 set_general_process ();
5327
5328 /* Allocate a message buffer. We can't reuse the input buffer in RS,
5329 because we need both at the same time. */
5330 gdb::char_vector msg (get_remote_packet_size ());
5331 gdb::char_vector reply (get_remote_packet_size ());
5332
5333 /* Invite target to request symbol lookups. */
5334
5335 putpkt ("qSymbol::");
5336 getpkt (&reply, 0);
5337 m_features.packet_ok (reply, PACKET_qSymbol);
5338
5339 while (startswith (reply.data (), "qSymbol:"))
5340 {
5341 struct bound_minimal_symbol sym;
5342
5343 tmp = &reply[8];
5344 end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
5345 strlen (tmp) / 2);
5346 msg[end] = '\0';
5347 sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
5348 if (sym.minsym == NULL)
5349 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
5350 &reply[8]);
5351 else
5352 {
5353 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5354 CORE_ADDR sym_addr = sym.value_address ();
5355
5356 /* If this is a function address, return the start of code
5357 instead of any data function descriptor. */
5358 sym_addr = gdbarch_convert_from_func_ptr_addr
5359 (target_gdbarch (), sym_addr, current_inferior ()->top_target ());
5360
5361 xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
5362 phex_nz (sym_addr, addr_size), &reply[8]);
5363 }
5364
5365 putpkt (msg.data ());
5366 getpkt (&reply, 0);
5367 }
5368 }
5369
5370 static struct serial *
5371 remote_serial_open (const char *name)
5372 {
5373 static int udp_warning = 0;
5374
5375 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
5376 of in ser-tcp.c, because it is the remote protocol assuming that the
5377 serial connection is reliable and not the serial connection promising
5378 to be. */
5379 if (!udp_warning && startswith (name, "udp:"))
5380 {
5381 warning (_("The remote protocol may be unreliable over UDP.\n"
5382 "Some events may be lost, rendering further debugging "
5383 "impossible."));
5384 udp_warning = 1;
5385 }
5386
5387 return serial_open (name);
5388 }
5389
5390 /* Inform the target of our permission settings. The permission flags
5391 work without this, but if the target knows the settings, it can do
5392 a couple things. First, it can add its own check, to catch cases
5393 that somehow manage to get by the permissions checks in target
5394 methods. Second, if the target is wired to disallow particular
5395 settings (for instance, a system in the field that is not set up to
5396 be able to stop at a breakpoint), it can object to any unavailable
5397 permissions. */
5398
5399 void
5400 remote_target::set_permissions ()
5401 {
5402 struct remote_state *rs = get_remote_state ();
5403
5404 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
5405 "WriteReg:%x;WriteMem:%x;"
5406 "InsertBreak:%x;InsertTrace:%x;"
5407 "InsertFastTrace:%x;Stop:%x",
5408 may_write_registers, may_write_memory,
5409 may_insert_breakpoints, may_insert_tracepoints,
5410 may_insert_fast_tracepoints, may_stop);
5411 putpkt (rs->buf);
5412 getpkt (&rs->buf, 0);
5413
5414 /* If the target didn't like the packet, warn the user. Do not try
5415 to undo the user's settings, that would just be maddening. */
5416 if (strcmp (rs->buf.data (), "OK") != 0)
5417 warning (_("Remote refused setting permissions with: %s"),
5418 rs->buf.data ());
5419 }
5420
5421 /* This type describes each known response to the qSupported
5422 packet. */
5423 struct protocol_feature
5424 {
5425 /* The name of this protocol feature. */
5426 const char *name;
5427
5428 /* The default for this protocol feature. */
5429 enum packet_support default_support;
5430
5431 /* The function to call when this feature is reported, or after
5432 qSupported processing if the feature is not supported.
5433 The first argument points to this structure. The second
5434 argument indicates whether the packet requested support be
5435 enabled, disabled, or probed (or the default, if this function
5436 is being called at the end of processing and this feature was
5437 not reported). The third argument may be NULL; if not NULL, it
5438 is a NUL-terminated string taken from the packet following
5439 this feature's name and an equals sign. */
5440 void (*func) (remote_target *remote, const struct protocol_feature *,
5441 enum packet_support, const char *);
5442
5443 /* The corresponding packet for this feature. Only used if
5444 FUNC is remote_supported_packet. */
5445 int packet;
5446 };
5447
5448 static void
5449 remote_supported_packet (remote_target *remote,
5450 const struct protocol_feature *feature,
5451 enum packet_support support,
5452 const char *argument)
5453 {
5454 if (argument)
5455 {
5456 warning (_("Remote qSupported response supplied an unexpected value for"
5457 " \"%s\"."), feature->name);
5458 return;
5459 }
5460
5461 remote->m_features.m_protocol_packets[feature->packet].support = support;
5462 }
5463
5464 void
5465 remote_target::remote_packet_size (const protocol_feature *feature,
5466 enum packet_support support, const char *value)
5467 {
5468 struct remote_state *rs = get_remote_state ();
5469
5470 int packet_size;
5471 char *value_end;
5472
5473 if (support != PACKET_ENABLE)
5474 return;
5475
5476 if (value == NULL || *value == '\0')
5477 {
5478 warning (_("Remote target reported \"%s\" without a size."),
5479 feature->name);
5480 return;
5481 }
5482
5483 errno = 0;
5484 packet_size = strtol (value, &value_end, 16);
5485 if (errno != 0 || *value_end != '\0' || packet_size < 0)
5486 {
5487 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5488 feature->name, value);
5489 return;
5490 }
5491
5492 /* Record the new maximum packet size. */
5493 rs->explicit_packet_size = packet_size;
5494 }
5495
5496 static void
5497 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5498 enum packet_support support, const char *value)
5499 {
5500 remote->remote_packet_size (feature, support, value);
5501 }
5502
5503 static const struct protocol_feature remote_protocol_features[] = {
5504 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5505 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5506 PACKET_qXfer_auxv },
5507 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5508 PACKET_qXfer_exec_file },
5509 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5510 PACKET_qXfer_features },
5511 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5512 PACKET_qXfer_libraries },
5513 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5514 PACKET_qXfer_libraries_svr4 },
5515 { "augmented-libraries-svr4-read", PACKET_DISABLE,
5516 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5517 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5518 PACKET_qXfer_memory_map },
5519 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5520 PACKET_qXfer_osdata },
5521 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5522 PACKET_qXfer_threads },
5523 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5524 PACKET_qXfer_traceframe_info },
5525 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5526 PACKET_QPassSignals },
5527 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5528 PACKET_QCatchSyscalls },
5529 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5530 PACKET_QProgramSignals },
5531 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5532 PACKET_QSetWorkingDir },
5533 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5534 PACKET_QStartupWithShell },
5535 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5536 PACKET_QEnvironmentHexEncoded },
5537 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5538 PACKET_QEnvironmentReset },
5539 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5540 PACKET_QEnvironmentUnset },
5541 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5542 PACKET_QStartNoAckMode },
5543 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5544 PACKET_multiprocess_feature },
5545 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5546 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5547 PACKET_qXfer_siginfo_read },
5548 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5549 PACKET_qXfer_siginfo_write },
5550 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5551 PACKET_ConditionalTracepoints },
5552 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5553 PACKET_ConditionalBreakpoints },
5554 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5555 PACKET_BreakpointCommands },
5556 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5557 PACKET_FastTracepoints },
5558 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5559 PACKET_StaticTracepoints },
5560 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5561 PACKET_InstallInTrace},
5562 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5563 PACKET_DisconnectedTracing_feature },
5564 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5565 PACKET_bc },
5566 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5567 PACKET_bs },
5568 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5569 PACKET_TracepointSource },
5570 { "QAllow", PACKET_DISABLE, remote_supported_packet,
5571 PACKET_QAllow },
5572 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5573 PACKET_EnableDisableTracepoints_feature },
5574 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5575 PACKET_qXfer_fdpic },
5576 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5577 PACKET_qXfer_uib },
5578 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5579 PACKET_QDisableRandomization },
5580 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5581 { "QTBuffer:size", PACKET_DISABLE,
5582 remote_supported_packet, PACKET_QTBuffer_size},
5583 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5584 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5585 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5586 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5587 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5588 PACKET_qXfer_btrace },
5589 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5590 PACKET_qXfer_btrace_conf },
5591 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5592 PACKET_Qbtrace_conf_bts_size },
5593 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5594 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5595 { "fork-events", PACKET_DISABLE, remote_supported_packet,
5596 PACKET_fork_event_feature },
5597 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5598 PACKET_vfork_event_feature },
5599 { "exec-events", PACKET_DISABLE, remote_supported_packet,
5600 PACKET_exec_event_feature },
5601 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5602 PACKET_Qbtrace_conf_pt_size },
5603 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5604 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5605 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5606 { "memory-tagging", PACKET_DISABLE, remote_supported_packet,
5607 PACKET_memory_tagging_feature },
5608 };
5609
5610 static char *remote_support_xml;
5611
5612 /* Register string appended to "xmlRegisters=" in qSupported query. */
5613
5614 void
5615 register_remote_support_xml (const char *xml)
5616 {
5617 #if defined(HAVE_LIBEXPAT)
5618 if (remote_support_xml == NULL)
5619 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5620 else
5621 {
5622 char *copy = xstrdup (remote_support_xml + 13);
5623 char *saveptr;
5624 char *p = strtok_r (copy, ",", &saveptr);
5625
5626 do
5627 {
5628 if (strcmp (p, xml) == 0)
5629 {
5630 /* already there */
5631 xfree (copy);
5632 return;
5633 }
5634 }
5635 while ((p = strtok_r (NULL, ",", &saveptr)) != NULL);
5636 xfree (copy);
5637
5638 remote_support_xml = reconcat (remote_support_xml,
5639 remote_support_xml, ",", xml,
5640 (char *) NULL);
5641 }
5642 #endif
5643 }
5644
5645 static void
5646 remote_query_supported_append (std::string *msg, const char *append)
5647 {
5648 if (!msg->empty ())
5649 msg->append (";");
5650 msg->append (append);
5651 }
5652
5653 void
5654 remote_target::remote_query_supported ()
5655 {
5656 struct remote_state *rs = get_remote_state ();
5657 char *next;
5658 int i;
5659 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5660
5661 /* The packet support flags are handled differently for this packet
5662 than for most others. We treat an error, a disabled packet, and
5663 an empty response identically: any features which must be reported
5664 to be used will be automatically disabled. An empty buffer
5665 accomplishes this, since that is also the representation for a list
5666 containing no features. */
5667
5668 rs->buf[0] = 0;
5669 if (m_features.packet_support (PACKET_qSupported) != PACKET_DISABLE)
5670 {
5671 std::string q;
5672
5673 if (m_features.packet_set_cmd_state (PACKET_multiprocess_feature)
5674 != AUTO_BOOLEAN_FALSE)
5675 remote_query_supported_append (&q, "multiprocess+");
5676
5677 if (m_features.packet_set_cmd_state (PACKET_swbreak_feature)
5678 != AUTO_BOOLEAN_FALSE)
5679 remote_query_supported_append (&q, "swbreak+");
5680
5681 if (m_features.packet_set_cmd_state (PACKET_hwbreak_feature)
5682 != AUTO_BOOLEAN_FALSE)
5683 remote_query_supported_append (&q, "hwbreak+");
5684
5685 remote_query_supported_append (&q, "qRelocInsn+");
5686
5687 if (m_features.packet_set_cmd_state (PACKET_fork_event_feature)
5688 != AUTO_BOOLEAN_FALSE)
5689 remote_query_supported_append (&q, "fork-events+");
5690
5691 if (m_features.packet_set_cmd_state (PACKET_vfork_event_feature)
5692 != AUTO_BOOLEAN_FALSE)
5693 remote_query_supported_append (&q, "vfork-events+");
5694
5695 if (m_features.packet_set_cmd_state (PACKET_exec_event_feature)
5696 != AUTO_BOOLEAN_FALSE)
5697 remote_query_supported_append (&q, "exec-events+");
5698
5699 if (m_features.packet_set_cmd_state (PACKET_vContSupported)
5700 != AUTO_BOOLEAN_FALSE)
5701 remote_query_supported_append (&q, "vContSupported+");
5702
5703 if (m_features.packet_set_cmd_state (PACKET_QThreadEvents)
5704 != AUTO_BOOLEAN_FALSE)
5705 remote_query_supported_append (&q, "QThreadEvents+");
5706
5707 if (m_features.packet_set_cmd_state (PACKET_no_resumed)
5708 != AUTO_BOOLEAN_FALSE)
5709 remote_query_supported_append (&q, "no-resumed+");
5710
5711 if (m_features.packet_set_cmd_state (PACKET_memory_tagging_feature)
5712 != AUTO_BOOLEAN_FALSE)
5713 remote_query_supported_append (&q, "memory-tagging+");
5714
5715 /* Keep this one last to work around a gdbserver <= 7.10 bug in
5716 the qSupported:xmlRegisters=i386 handling. */
5717 if (remote_support_xml != NULL
5718 && (m_features.packet_support (PACKET_qXfer_features)
5719 != PACKET_DISABLE))
5720 remote_query_supported_append (&q, remote_support_xml);
5721
5722 q = "qSupported:" + q;
5723 putpkt (q.c_str ());
5724
5725 getpkt (&rs->buf, 0);
5726
5727 /* If an error occured, warn, but do not return - just reset the
5728 buffer to empty and go on to disable features. */
5729 if (m_features.packet_ok (rs->buf, PACKET_qSupported) == PACKET_ERROR)
5730 {
5731 warning (_("Remote failure reply: %s"), rs->buf.data ());
5732 rs->buf[0] = 0;
5733 }
5734 }
5735
5736 memset (seen, 0, sizeof (seen));
5737
5738 next = rs->buf.data ();
5739 while (*next)
5740 {
5741 enum packet_support is_supported;
5742 char *p, *end, *name_end, *value;
5743
5744 /* First separate out this item from the rest of the packet. If
5745 there's another item after this, we overwrite the separator
5746 (terminated strings are much easier to work with). */
5747 p = next;
5748 end = strchr (p, ';');
5749 if (end == NULL)
5750 {
5751 end = p + strlen (p);
5752 next = end;
5753 }
5754 else
5755 {
5756 *end = '\0';
5757 next = end + 1;
5758
5759 if (end == p)
5760 {
5761 warning (_("empty item in \"qSupported\" response"));
5762 continue;
5763 }
5764 }
5765
5766 name_end = strchr (p, '=');
5767 if (name_end)
5768 {
5769 /* This is a name=value entry. */
5770 is_supported = PACKET_ENABLE;
5771 value = name_end + 1;
5772 *name_end = '\0';
5773 }
5774 else
5775 {
5776 value = NULL;
5777 switch (end[-1])
5778 {
5779 case '+':
5780 is_supported = PACKET_ENABLE;
5781 break;
5782
5783 case '-':
5784 is_supported = PACKET_DISABLE;
5785 break;
5786
5787 case '?':
5788 is_supported = PACKET_SUPPORT_UNKNOWN;
5789 break;
5790
5791 default:
5792 warning (_("unrecognized item \"%s\" "
5793 "in \"qSupported\" response"), p);
5794 continue;
5795 }
5796 end[-1] = '\0';
5797 }
5798
5799 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5800 if (strcmp (remote_protocol_features[i].name, p) == 0)
5801 {
5802 const struct protocol_feature *feature;
5803
5804 seen[i] = 1;
5805 feature = &remote_protocol_features[i];
5806 feature->func (this, feature, is_supported, value);
5807 break;
5808 }
5809 }
5810
5811 /* If we increased the packet size, make sure to increase the global
5812 buffer size also. We delay this until after parsing the entire
5813 qSupported packet, because this is the same buffer we were
5814 parsing. */
5815 if (rs->buf.size () < rs->explicit_packet_size)
5816 rs->buf.resize (rs->explicit_packet_size);
5817
5818 /* Handle the defaults for unmentioned features. */
5819 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5820 if (!seen[i])
5821 {
5822 const struct protocol_feature *feature;
5823
5824 feature = &remote_protocol_features[i];
5825 feature->func (this, feature, feature->default_support, NULL);
5826 }
5827 }
5828
5829 /* Serial QUIT handler for the remote serial descriptor.
5830
5831 Defers handling a Ctrl-C until we're done with the current
5832 command/response packet sequence, unless:
5833
5834 - We're setting up the connection. Don't send a remote interrupt
5835 request, as we're not fully synced yet. Quit immediately
5836 instead.
5837
5838 - The target has been resumed in the foreground
5839 (target_terminal::is_ours is false) with a synchronous resume
5840 packet, and we're blocked waiting for the stop reply, thus a
5841 Ctrl-C should be immediately sent to the target.
5842
5843 - We get a second Ctrl-C while still within the same serial read or
5844 write. In that case the serial is seemingly wedged --- offer to
5845 quit/disconnect.
5846
5847 - We see a second Ctrl-C without target response, after having
5848 previously interrupted the target. In that case the target/stub
5849 is probably wedged --- offer to quit/disconnect.
5850 */
5851
5852 void
5853 remote_target::remote_serial_quit_handler ()
5854 {
5855 struct remote_state *rs = get_remote_state ();
5856
5857 if (check_quit_flag ())
5858 {
5859 /* If we're starting up, we're not fully synced yet. Quit
5860 immediately. */
5861 if (rs->starting_up)
5862 quit ();
5863 else if (rs->got_ctrlc_during_io)
5864 {
5865 if (query (_("The target is not responding to GDB commands.\n"
5866 "Stop debugging it? ")))
5867 remote_unpush_and_throw (this);
5868 }
5869 /* If ^C has already been sent once, offer to disconnect. */
5870 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5871 interrupt_query ();
5872 /* All-stop protocol, and blocked waiting for stop reply. Send
5873 an interrupt request. */
5874 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5875 target_interrupt ();
5876 else
5877 rs->got_ctrlc_during_io = 1;
5878 }
5879 }
5880
5881 /* The remote_target that is current while the quit handler is
5882 overridden with remote_serial_quit_handler. */
5883 static remote_target *curr_quit_handler_target;
5884
5885 static void
5886 remote_serial_quit_handler ()
5887 {
5888 curr_quit_handler_target->remote_serial_quit_handler ();
5889 }
5890
5891 /* Remove the remote target from the target stack of each inferior
5892 that is using it. Upper targets depend on it so remove them
5893 first. */
5894
5895 static void
5896 remote_unpush_target (remote_target *target)
5897 {
5898 /* We have to unpush the target from all inferiors, even those that
5899 aren't running. */
5900 scoped_restore_current_inferior restore_current_inferior;
5901
5902 for (inferior *inf : all_inferiors (target))
5903 {
5904 switch_to_inferior_no_thread (inf);
5905 inf->pop_all_targets_at_and_above (process_stratum);
5906 generic_mourn_inferior ();
5907 }
5908
5909 /* Don't rely on target_close doing this when the target is popped
5910 from the last remote inferior above, because something may be
5911 holding a reference to the target higher up on the stack, meaning
5912 target_close won't be called yet. We lost the connection to the
5913 target, so clear these now, otherwise we may later throw
5914 TARGET_CLOSE_ERROR while trying to tell the remote target to
5915 close the file. */
5916 fileio_handles_invalidate_target (target);
5917 }
5918
5919 static void
5920 remote_unpush_and_throw (remote_target *target)
5921 {
5922 remote_unpush_target (target);
5923 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5924 }
5925
5926 void
5927 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5928 {
5929 remote_target *curr_remote = get_current_remote_target ();
5930
5931 if (name == 0)
5932 error (_("To open a remote debug connection, you need to specify what\n"
5933 "serial device is attached to the remote system\n"
5934 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5935
5936 /* If we're connected to a running target, target_preopen will kill it.
5937 Ask this question first, before target_preopen has a chance to kill
5938 anything. */
5939 if (curr_remote != NULL && !target_has_execution ())
5940 {
5941 if (from_tty
5942 && !query (_("Already connected to a remote target. Disconnect? ")))
5943 error (_("Still connected."));
5944 }
5945
5946 /* Here the possibly existing remote target gets unpushed. */
5947 target_preopen (from_tty);
5948
5949 remote_fileio_reset ();
5950 reopen_exec_file ();
5951 reread_symbols (from_tty);
5952
5953 remote_target *remote
5954 = (extended_p ? new extended_remote_target () : new remote_target ());
5955 target_ops_up target_holder (remote);
5956
5957 remote_state *rs = remote->get_remote_state ();
5958
5959 /* See FIXME above. */
5960 if (!target_async_permitted)
5961 rs->wait_forever_enabled_p = 1;
5962
5963 rs->remote_desc = remote_serial_open (name);
5964 if (!rs->remote_desc)
5965 perror_with_name (name);
5966
5967 if (baud_rate != -1)
5968 {
5969 if (serial_setbaudrate (rs->remote_desc, baud_rate))
5970 {
5971 /* The requested speed could not be set. Error out to
5972 top level after closing remote_desc. Take care to
5973 set remote_desc to NULL to avoid closing remote_desc
5974 more than once. */
5975 serial_close (rs->remote_desc);
5976 rs->remote_desc = NULL;
5977 perror_with_name (name);
5978 }
5979 }
5980
5981 serial_setparity (rs->remote_desc, serial_parity);
5982 serial_raw (rs->remote_desc);
5983
5984 /* If there is something sitting in the buffer we might take it as a
5985 response to a command, which would be bad. */
5986 serial_flush_input (rs->remote_desc);
5987
5988 if (from_tty)
5989 {
5990 gdb_puts ("Remote debugging using ");
5991 gdb_puts (name);
5992 gdb_puts ("\n");
5993 }
5994
5995 /* Switch to using the remote target now. */
5996 current_inferior ()->push_target (std::move (target_holder));
5997
5998 /* Register extra event sources in the event loop. */
5999 rs->remote_async_inferior_event_token
6000 = create_async_event_handler (remote_async_inferior_event_handler, nullptr,
6001 "remote");
6002 rs->notif_state = remote_notif_state_allocate (remote);
6003
6004 /* Reset the target state; these things will be queried either by
6005 remote_query_supported or as they are needed. */
6006 remote->m_features.reset_all_packet_configs_support ();
6007 rs->explicit_packet_size = 0;
6008 rs->noack_mode = 0;
6009 rs->extended = extended_p;
6010 rs->waiting_for_stop_reply = 0;
6011 rs->ctrlc_pending_p = 0;
6012 rs->got_ctrlc_during_io = 0;
6013
6014 rs->general_thread = not_sent_ptid;
6015 rs->continue_thread = not_sent_ptid;
6016 rs->remote_traceframe_number = -1;
6017
6018 rs->last_resume_exec_dir = EXEC_FORWARD;
6019
6020 /* Probe for ability to use "ThreadInfo" query, as required. */
6021 rs->use_threadinfo_query = 1;
6022 rs->use_threadextra_query = 1;
6023
6024 rs->readahead_cache.invalidate ();
6025
6026 if (target_async_permitted)
6027 {
6028 /* FIXME: cagney/1999-09-23: During the initial connection it is
6029 assumed that the target is already ready and able to respond to
6030 requests. Unfortunately remote_start_remote() eventually calls
6031 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
6032 around this. Eventually a mechanism that allows
6033 wait_for_inferior() to expect/get timeouts will be
6034 implemented. */
6035 rs->wait_forever_enabled_p = 0;
6036 }
6037
6038 /* First delete any symbols previously loaded from shared libraries. */
6039 no_shared_libraries (NULL, 0);
6040
6041 /* Start the remote connection. If error() or QUIT, discard this
6042 target (we'd otherwise be in an inconsistent state) and then
6043 propogate the error on up the exception chain. This ensures that
6044 the caller doesn't stumble along blindly assuming that the
6045 function succeeded. The CLI doesn't have this problem but other
6046 UI's, such as MI do.
6047
6048 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
6049 this function should return an error indication letting the
6050 caller restore the previous state. Unfortunately the command
6051 ``target remote'' is directly wired to this function making that
6052 impossible. On a positive note, the CLI side of this problem has
6053 been fixed - the function set_cmd_context() makes it possible for
6054 all the ``target ....'' commands to share a common callback
6055 function. See cli-dump.c. */
6056 {
6057
6058 try
6059 {
6060 remote->start_remote (from_tty, extended_p);
6061 }
6062 catch (const gdb_exception &ex)
6063 {
6064 /* Pop the partially set up target - unless something else did
6065 already before throwing the exception. */
6066 if (ex.error != TARGET_CLOSE_ERROR)
6067 remote_unpush_target (remote);
6068 throw;
6069 }
6070 }
6071
6072 remote_btrace_reset (rs);
6073
6074 if (target_async_permitted)
6075 rs->wait_forever_enabled_p = 1;
6076 }
6077
6078 /* Determine if WS represents a fork status. */
6079
6080 static bool
6081 is_fork_status (target_waitkind kind)
6082 {
6083 return (kind == TARGET_WAITKIND_FORKED
6084 || kind == TARGET_WAITKIND_VFORKED);
6085 }
6086
6087 /* Return THREAD's pending status if it is a pending fork parent, else
6088 return nullptr. */
6089
6090 static const target_waitstatus *
6091 thread_pending_fork_status (struct thread_info *thread)
6092 {
6093 const target_waitstatus &ws
6094 = (thread->has_pending_waitstatus ()
6095 ? thread->pending_waitstatus ()
6096 : thread->pending_follow);
6097
6098 if (!is_fork_status (ws.kind ()))
6099 return nullptr;
6100
6101 return &ws;
6102 }
6103
6104 /* Detach the specified process. */
6105
6106 void
6107 remote_target::remote_detach_pid (int pid)
6108 {
6109 struct remote_state *rs = get_remote_state ();
6110
6111 /* This should not be necessary, but the handling for D;PID in
6112 GDBserver versions prior to 8.2 incorrectly assumes that the
6113 selected process points to the same process we're detaching,
6114 leading to misbehavior (and possibly GDBserver crashing) when it
6115 does not. Since it's easy and cheap, work around it by forcing
6116 GDBserver to select GDB's current process. */
6117 set_general_process ();
6118
6119 if (m_features.remote_multi_process_p ())
6120 xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
6121 else
6122 strcpy (rs->buf.data (), "D");
6123
6124 putpkt (rs->buf);
6125 getpkt (&rs->buf, 0);
6126
6127 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
6128 ;
6129 else if (rs->buf[0] == '\0')
6130 error (_("Remote doesn't know how to detach"));
6131 else
6132 error (_("Can't detach process."));
6133 }
6134
6135 /* This detaches a program to which we previously attached, using
6136 inferior_ptid to identify the process. After this is done, GDB
6137 can be used to debug some other program. We better not have left
6138 any breakpoints in the target program or it'll die when it hits
6139 one. */
6140
6141 void
6142 remote_target::remote_detach_1 (inferior *inf, int from_tty)
6143 {
6144 int pid = inferior_ptid.pid ();
6145 struct remote_state *rs = get_remote_state ();
6146 int is_fork_parent;
6147
6148 if (!target_has_execution ())
6149 error (_("No process to detach from."));
6150
6151 target_announce_detach (from_tty);
6152
6153 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
6154 {
6155 /* If we're in breakpoints-always-inserted mode, or the inferior
6156 is running, we have to remove breakpoints before detaching.
6157 We don't do this in common code instead because not all
6158 targets support removing breakpoints while the target is
6159 running. The remote target / gdbserver does, though. */
6160 remove_breakpoints_inf (current_inferior ());
6161 }
6162
6163 /* Tell the remote target to detach. */
6164 remote_detach_pid (pid);
6165
6166 /* Exit only if this is the only active inferior. */
6167 if (from_tty && !rs->extended && number_of_live_inferiors (this) == 1)
6168 gdb_puts (_("Ending remote debugging.\n"));
6169
6170 /* See if any thread of the inferior we are detaching has a pending fork
6171 status. In that case, we must detach from the child resulting from
6172 that fork. */
6173 for (thread_info *thread : inf->non_exited_threads ())
6174 {
6175 const target_waitstatus *ws = thread_pending_fork_status (thread);
6176
6177 if (ws == nullptr)
6178 continue;
6179
6180 remote_detach_pid (ws->child_ptid ().pid ());
6181 }
6182
6183 /* Check also for any pending fork events in the stop reply queue. */
6184 remote_notif_get_pending_events (&notif_client_stop);
6185 for (stop_reply_up &reply : rs->stop_reply_queue)
6186 {
6187 if (reply->ptid.pid () != pid)
6188 continue;
6189
6190 if (!is_fork_status (reply->ws.kind ()))
6191 continue;
6192
6193 remote_detach_pid (reply->ws.child_ptid ().pid ());
6194 }
6195
6196 thread_info *tp = this->find_thread (inferior_ptid);
6197
6198 /* Check to see if we are detaching a fork parent. Note that if we
6199 are detaching a fork child, tp == NULL. */
6200 is_fork_parent = (tp != NULL
6201 && tp->pending_follow.kind () == TARGET_WAITKIND_FORKED);
6202
6203 /* If doing detach-on-fork, we don't mourn, because that will delete
6204 breakpoints that should be available for the followed inferior. */
6205 if (!is_fork_parent)
6206 {
6207 /* Save the pid as a string before mourning, since that will
6208 unpush the remote target, and we need the string after. */
6209 std::string infpid = target_pid_to_str (ptid_t (pid));
6210
6211 target_mourn_inferior (inferior_ptid);
6212 if (print_inferior_events)
6213 gdb_printf (_("[Inferior %d (%s) detached]\n"),
6214 inf->num, infpid.c_str ());
6215 }
6216 else
6217 {
6218 switch_to_no_thread ();
6219 detach_inferior (current_inferior ());
6220 }
6221 }
6222
6223 void
6224 remote_target::detach (inferior *inf, int from_tty)
6225 {
6226 remote_detach_1 (inf, from_tty);
6227 }
6228
6229 void
6230 extended_remote_target::detach (inferior *inf, int from_tty)
6231 {
6232 remote_detach_1 (inf, from_tty);
6233 }
6234
6235 /* Target follow-fork function for remote targets. On entry, and
6236 at return, the current inferior is the fork parent.
6237
6238 Note that although this is currently only used for extended-remote,
6239 it is named remote_follow_fork in anticipation of using it for the
6240 remote target as well. */
6241
6242 void
6243 remote_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
6244 target_waitkind fork_kind, bool follow_child,
6245 bool detach_fork)
6246 {
6247 process_stratum_target::follow_fork (child_inf, child_ptid,
6248 fork_kind, follow_child, detach_fork);
6249
6250 if ((fork_kind == TARGET_WAITKIND_FORKED
6251 && m_features.remote_fork_event_p ())
6252 || (fork_kind == TARGET_WAITKIND_VFORKED
6253 && m_features.remote_vfork_event_p ()))
6254 {
6255 /* When following the parent and detaching the child, we detach
6256 the child here. For the case of following the child and
6257 detaching the parent, the detach is done in the target-
6258 independent follow fork code in infrun.c. We can't use
6259 target_detach when detaching an unfollowed child because
6260 the client side doesn't know anything about the child. */
6261 if (detach_fork && !follow_child)
6262 {
6263 /* Detach the fork child. */
6264 remote_detach_pid (child_ptid.pid ());
6265 }
6266 }
6267 }
6268
6269 /* Target follow-exec function for remote targets. Save EXECD_PATHNAME
6270 in the program space of the new inferior. */
6271
6272 void
6273 remote_target::follow_exec (inferior *follow_inf, ptid_t ptid,
6274 const char *execd_pathname)
6275 {
6276 process_stratum_target::follow_exec (follow_inf, ptid, execd_pathname);
6277
6278 /* We know that this is a target file name, so if it has the "target:"
6279 prefix we strip it off before saving it in the program space. */
6280 if (is_target_filename (execd_pathname))
6281 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
6282
6283 set_pspace_remote_exec_file (follow_inf->pspace, execd_pathname);
6284 }
6285
6286 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
6287
6288 void
6289 remote_target::disconnect (const char *args, int from_tty)
6290 {
6291 if (args)
6292 error (_("Argument given to \"disconnect\" when remotely debugging."));
6293
6294 /* Make sure we unpush even the extended remote targets. Calling
6295 target_mourn_inferior won't unpush, and
6296 remote_target::mourn_inferior won't unpush if there is more than
6297 one inferior left. */
6298 remote_unpush_target (this);
6299
6300 if (from_tty)
6301 gdb_puts ("Ending remote debugging.\n");
6302 }
6303
6304 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
6305 be chatty about it. */
6306
6307 void
6308 extended_remote_target::attach (const char *args, int from_tty)
6309 {
6310 struct remote_state *rs = get_remote_state ();
6311 int pid;
6312 char *wait_status = NULL;
6313
6314 pid = parse_pid_to_attach (args);
6315
6316 /* Remote PID can be freely equal to getpid, do not check it here the same
6317 way as in other targets. */
6318
6319 if (m_features.packet_support (PACKET_vAttach) == PACKET_DISABLE)
6320 error (_("This target does not support attaching to a process"));
6321
6322 target_announce_attach (from_tty, pid);
6323
6324 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
6325 putpkt (rs->buf);
6326 getpkt (&rs->buf, 0);
6327
6328 switch (m_features.packet_ok (rs->buf, PACKET_vAttach))
6329 {
6330 case PACKET_OK:
6331 if (!target_is_non_stop_p ())
6332 {
6333 /* Save the reply for later. */
6334 wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
6335 strcpy (wait_status, rs->buf.data ());
6336 }
6337 else if (strcmp (rs->buf.data (), "OK") != 0)
6338 error (_("Attaching to %s failed with: %s"),
6339 target_pid_to_str (ptid_t (pid)).c_str (),
6340 rs->buf.data ());
6341 break;
6342 case PACKET_UNKNOWN:
6343 error (_("This target does not support attaching to a process"));
6344 default:
6345 error (_("Attaching to %s failed"),
6346 target_pid_to_str (ptid_t (pid)).c_str ());
6347 }
6348
6349 switch_to_inferior_no_thread (remote_add_inferior (false, pid, 1, 0));
6350
6351 inferior_ptid = ptid_t (pid);
6352
6353 if (target_is_non_stop_p ())
6354 {
6355 /* Get list of threads. */
6356 update_thread_list ();
6357
6358 thread_info *thread = first_thread_of_inferior (current_inferior ());
6359 if (thread != nullptr)
6360 switch_to_thread (thread);
6361
6362 /* Invalidate our notion of the remote current thread. */
6363 record_currthread (rs, minus_one_ptid);
6364 }
6365 else
6366 {
6367 /* Now, if we have thread information, update the main thread's
6368 ptid. */
6369 ptid_t curr_ptid = remote_current_thread (ptid_t (pid));
6370
6371 /* Add the main thread to the thread list. We add the thread
6372 silently in this case (the final true parameter). */
6373 thread_info *thr = remote_add_thread (curr_ptid, true, true, true);
6374
6375 switch_to_thread (thr);
6376 }
6377
6378 /* Next, if the target can specify a description, read it. We do
6379 this before anything involving memory or registers. */
6380 target_find_description ();
6381
6382 if (!target_is_non_stop_p ())
6383 {
6384 /* Use the previously fetched status. */
6385 gdb_assert (wait_status != NULL);
6386
6387 struct notif_event *reply
6388 = remote_notif_parse (this, &notif_client_stop, wait_status);
6389
6390 push_stop_reply ((struct stop_reply *) reply);
6391 }
6392 else
6393 {
6394 gdb_assert (wait_status == NULL);
6395
6396 gdb_assert (target_can_async_p ());
6397 }
6398 }
6399
6400 /* Implementation of the to_post_attach method. */
6401
6402 void
6403 extended_remote_target::post_attach (int pid)
6404 {
6405 /* Get text, data & bss offsets. */
6406 get_offsets ();
6407
6408 /* In certain cases GDB might not have had the chance to start
6409 symbol lookup up until now. This could happen if the debugged
6410 binary is not using shared libraries, the vsyscall page is not
6411 present (on Linux) and the binary itself hadn't changed since the
6412 debugging process was started. */
6413 if (current_program_space->symfile_object_file != NULL)
6414 remote_check_symbols();
6415 }
6416
6417 \f
6418 /* Check for the availability of vCont. This function should also check
6419 the response. */
6420
6421 void
6422 remote_target::remote_vcont_probe ()
6423 {
6424 remote_state *rs = get_remote_state ();
6425 char *buf;
6426
6427 strcpy (rs->buf.data (), "vCont?");
6428 putpkt (rs->buf);
6429 getpkt (&rs->buf, 0);
6430 buf = rs->buf.data ();
6431
6432 /* Make sure that the features we assume are supported. */
6433 if (startswith (buf, "vCont"))
6434 {
6435 char *p = &buf[5];
6436 int support_c, support_C;
6437
6438 rs->supports_vCont.s = 0;
6439 rs->supports_vCont.S = 0;
6440 support_c = 0;
6441 support_C = 0;
6442 rs->supports_vCont.t = 0;
6443 rs->supports_vCont.r = 0;
6444 while (p && *p == ';')
6445 {
6446 p++;
6447 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
6448 rs->supports_vCont.s = 1;
6449 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
6450 rs->supports_vCont.S = 1;
6451 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
6452 support_c = 1;
6453 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
6454 support_C = 1;
6455 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
6456 rs->supports_vCont.t = 1;
6457 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6458 rs->supports_vCont.r = 1;
6459
6460 p = strchr (p, ';');
6461 }
6462
6463 /* If c, and C are not all supported, we can't use vCont. Clearing
6464 BUF will make packet_ok disable the packet. */
6465 if (!support_c || !support_C)
6466 buf[0] = 0;
6467 }
6468
6469 m_features.packet_ok (rs->buf, PACKET_vCont);
6470 }
6471
6472 /* Helper function for building "vCont" resumptions. Write a
6473 resumption to P. ENDP points to one-passed-the-end of the buffer
6474 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
6475 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6476 resumed thread should be single-stepped and/or signalled. If PTID
6477 equals minus_one_ptid, then all threads are resumed; if PTID
6478 represents a process, then all threads of the process are
6479 resumed. */
6480
6481 char *
6482 remote_target::append_resumption (char *p, char *endp,
6483 ptid_t ptid, int step, gdb_signal siggnal)
6484 {
6485 struct remote_state *rs = get_remote_state ();
6486
6487 if (step && siggnal != GDB_SIGNAL_0)
6488 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6489 else if (step
6490 /* GDB is willing to range step. */
6491 && use_range_stepping
6492 /* Target supports range stepping. */
6493 && rs->supports_vCont.r
6494 /* We don't currently support range stepping multiple
6495 threads with a wildcard (though the protocol allows it,
6496 so stubs shouldn't make an active effort to forbid
6497 it). */
6498 && !(m_features.remote_multi_process_p () && ptid.is_pid ()))
6499 {
6500 struct thread_info *tp;
6501
6502 if (ptid == minus_one_ptid)
6503 {
6504 /* If we don't know about the target thread's tid, then
6505 we're resuming magic_null_ptid (see caller). */
6506 tp = this->find_thread (magic_null_ptid);
6507 }
6508 else
6509 tp = this->find_thread (ptid);
6510 gdb_assert (tp != NULL);
6511
6512 if (tp->control.may_range_step)
6513 {
6514 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6515
6516 p += xsnprintf (p, endp - p, ";r%s,%s",
6517 phex_nz (tp->control.step_range_start,
6518 addr_size),
6519 phex_nz (tp->control.step_range_end,
6520 addr_size));
6521 }
6522 else
6523 p += xsnprintf (p, endp - p, ";s");
6524 }
6525 else if (step)
6526 p += xsnprintf (p, endp - p, ";s");
6527 else if (siggnal != GDB_SIGNAL_0)
6528 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6529 else
6530 p += xsnprintf (p, endp - p, ";c");
6531
6532 if (m_features.remote_multi_process_p () && ptid.is_pid ())
6533 {
6534 ptid_t nptid;
6535
6536 /* All (-1) threads of process. */
6537 nptid = ptid_t (ptid.pid (), -1);
6538
6539 p += xsnprintf (p, endp - p, ":");
6540 p = write_ptid (p, endp, nptid);
6541 }
6542 else if (ptid != minus_one_ptid)
6543 {
6544 p += xsnprintf (p, endp - p, ":");
6545 p = write_ptid (p, endp, ptid);
6546 }
6547
6548 return p;
6549 }
6550
6551 /* Clear the thread's private info on resume. */
6552
6553 static void
6554 resume_clear_thread_private_info (struct thread_info *thread)
6555 {
6556 if (thread->priv != NULL)
6557 {
6558 remote_thread_info *priv = get_remote_thread_info (thread);
6559
6560 priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6561 priv->watch_data_address = 0;
6562 }
6563 }
6564
6565 /* Append a vCont continue-with-signal action for threads that have a
6566 non-zero stop signal. */
6567
6568 char *
6569 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6570 ptid_t ptid)
6571 {
6572 for (thread_info *thread : all_non_exited_threads (this, ptid))
6573 if (inferior_ptid != thread->ptid
6574 && thread->stop_signal () != GDB_SIGNAL_0)
6575 {
6576 p = append_resumption (p, endp, thread->ptid,
6577 0, thread->stop_signal ());
6578 thread->set_stop_signal (GDB_SIGNAL_0);
6579 resume_clear_thread_private_info (thread);
6580 }
6581
6582 return p;
6583 }
6584
6585 /* Set the target running, using the packets that use Hc
6586 (c/s/C/S). */
6587
6588 void
6589 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6590 gdb_signal siggnal)
6591 {
6592 struct remote_state *rs = get_remote_state ();
6593 char *buf;
6594
6595 rs->last_sent_signal = siggnal;
6596 rs->last_sent_step = step;
6597
6598 /* The c/s/C/S resume packets use Hc, so set the continue
6599 thread. */
6600 if (ptid == minus_one_ptid)
6601 set_continue_thread (any_thread_ptid);
6602 else
6603 set_continue_thread (ptid);
6604
6605 for (thread_info *thread : all_non_exited_threads (this))
6606 resume_clear_thread_private_info (thread);
6607
6608 buf = rs->buf.data ();
6609 if (::execution_direction == EXEC_REVERSE)
6610 {
6611 /* We don't pass signals to the target in reverse exec mode. */
6612 if (info_verbose && siggnal != GDB_SIGNAL_0)
6613 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6614 siggnal);
6615
6616 if (step && m_features.packet_support (PACKET_bs) == PACKET_DISABLE)
6617 error (_("Remote reverse-step not supported."));
6618 if (!step && m_features.packet_support (PACKET_bc) == PACKET_DISABLE)
6619 error (_("Remote reverse-continue not supported."));
6620
6621 strcpy (buf, step ? "bs" : "bc");
6622 }
6623 else if (siggnal != GDB_SIGNAL_0)
6624 {
6625 buf[0] = step ? 'S' : 'C';
6626 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6627 buf[2] = tohex (((int) siggnal) & 0xf);
6628 buf[3] = '\0';
6629 }
6630 else
6631 strcpy (buf, step ? "s" : "c");
6632
6633 putpkt (buf);
6634 }
6635
6636 /* Resume the remote inferior by using a "vCont" packet. SCOPE_PTID,
6637 STEP, and SIGGNAL have the same meaning as in target_resume. This
6638 function returns non-zero iff it resumes the inferior.
6639
6640 This function issues a strict subset of all possible vCont commands
6641 at the moment. */
6642
6643 int
6644 remote_target::remote_resume_with_vcont (ptid_t scope_ptid, int step,
6645 enum gdb_signal siggnal)
6646 {
6647 struct remote_state *rs = get_remote_state ();
6648 char *p;
6649 char *endp;
6650
6651 /* No reverse execution actions defined for vCont. */
6652 if (::execution_direction == EXEC_REVERSE)
6653 return 0;
6654
6655 if (m_features.packet_support (PACKET_vCont) == PACKET_DISABLE)
6656 return 0;
6657
6658 p = rs->buf.data ();
6659 endp = p + get_remote_packet_size ();
6660
6661 /* If we could generate a wider range of packets, we'd have to worry
6662 about overflowing BUF. Should there be a generic
6663 "multi-part-packet" packet? */
6664
6665 p += xsnprintf (p, endp - p, "vCont");
6666
6667 if (scope_ptid == magic_null_ptid)
6668 {
6669 /* MAGIC_NULL_PTID means that we don't have any active threads,
6670 so we don't have any TID numbers the inferior will
6671 understand. Make sure to only send forms that do not specify
6672 a TID. */
6673 append_resumption (p, endp, minus_one_ptid, step, siggnal);
6674 }
6675 else if (scope_ptid == minus_one_ptid || scope_ptid.is_pid ())
6676 {
6677 /* Resume all threads (of all processes, or of a single
6678 process), with preference for INFERIOR_PTID. This assumes
6679 inferior_ptid belongs to the set of all threads we are about
6680 to resume. */
6681 if (step || siggnal != GDB_SIGNAL_0)
6682 {
6683 /* Step inferior_ptid, with or without signal. */
6684 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6685 }
6686
6687 /* Also pass down any pending signaled resumption for other
6688 threads not the current. */
6689 p = append_pending_thread_resumptions (p, endp, scope_ptid);
6690
6691 /* And continue others without a signal. */
6692 append_resumption (p, endp, scope_ptid, /*step=*/ 0, GDB_SIGNAL_0);
6693 }
6694 else
6695 {
6696 /* Scheduler locking; resume only SCOPE_PTID. */
6697 append_resumption (p, endp, scope_ptid, step, siggnal);
6698 }
6699
6700 gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6701 putpkt (rs->buf);
6702
6703 if (target_is_non_stop_p ())
6704 {
6705 /* In non-stop, the stub replies to vCont with "OK". The stop
6706 reply will be reported asynchronously by means of a `%Stop'
6707 notification. */
6708 getpkt (&rs->buf, 0);
6709 if (strcmp (rs->buf.data (), "OK") != 0)
6710 error (_("Unexpected vCont reply in non-stop mode: %s"),
6711 rs->buf.data ());
6712 }
6713
6714 return 1;
6715 }
6716
6717 /* Tell the remote machine to resume. */
6718
6719 void
6720 remote_target::resume (ptid_t scope_ptid, int step, enum gdb_signal siggnal)
6721 {
6722 struct remote_state *rs = get_remote_state ();
6723
6724 /* When connected in non-stop mode, the core resumes threads
6725 individually. Resuming remote threads directly in target_resume
6726 would thus result in sending one packet per thread. Instead, to
6727 minimize roundtrip latency, here we just store the resume
6728 request (put the thread in RESUMED_PENDING_VCONT state); the actual remote
6729 resumption will be done in remote_target::commit_resume, where we'll be
6730 able to do vCont action coalescing. */
6731 if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6732 {
6733 remote_thread_info *remote_thr
6734 = get_remote_thread_info (inferior_thread ());
6735
6736 /* We don't expect the core to ask to resume an already resumed (from
6737 its point of view) thread. */
6738 gdb_assert (remote_thr->get_resume_state () == resume_state::NOT_RESUMED);
6739
6740 remote_thr->set_resumed_pending_vcont (step, siggnal);
6741
6742 /* There's actually nothing that says that the core can't
6743 request a wildcard resume in non-stop mode, though. It's
6744 just that we know it doesn't currently, so we don't bother
6745 with it. */
6746 gdb_assert (scope_ptid == inferior_ptid);
6747 return;
6748 }
6749
6750 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6751 (explained in remote-notif.c:handle_notification) so
6752 remote_notif_process is not called. We need find a place where
6753 it is safe to start a 'vNotif' sequence. It is good to do it
6754 before resuming inferior, because inferior was stopped and no RSP
6755 traffic at that moment. */
6756 if (!target_is_non_stop_p ())
6757 remote_notif_process (rs->notif_state, &notif_client_stop);
6758
6759 rs->last_resume_exec_dir = ::execution_direction;
6760
6761 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
6762 if (!remote_resume_with_vcont (scope_ptid, step, siggnal))
6763 remote_resume_with_hc (scope_ptid, step, siggnal);
6764
6765 /* Update resumed state tracked by the remote target. */
6766 for (thread_info *tp : all_non_exited_threads (this, scope_ptid))
6767 get_remote_thread_info (tp)->set_resumed ();
6768
6769 /* We've just told the target to resume. The remote server will
6770 wait for the inferior to stop, and then send a stop reply. In
6771 the mean time, we can't start another command/query ourselves
6772 because the stub wouldn't be ready to process it. This applies
6773 only to the base all-stop protocol, however. In non-stop (which
6774 only supports vCont), the stub replies with an "OK", and is
6775 immediate able to process further serial input. */
6776 if (!target_is_non_stop_p ())
6777 rs->waiting_for_stop_reply = 1;
6778 }
6779
6780 /* Private per-inferior info for target remote processes. */
6781
6782 struct remote_inferior : public private_inferior
6783 {
6784 /* Whether we can send a wildcard vCont for this process. */
6785 bool may_wildcard_vcont = true;
6786 };
6787
6788 /* Get the remote private inferior data associated to INF. */
6789
6790 static remote_inferior *
6791 get_remote_inferior (inferior *inf)
6792 {
6793 if (inf->priv == NULL)
6794 inf->priv.reset (new remote_inferior);
6795
6796 return gdb::checked_static_cast<remote_inferior *> (inf->priv.get ());
6797 }
6798
6799 /* Class used to track the construction of a vCont packet in the
6800 outgoing packet buffer. This is used to send multiple vCont
6801 packets if we have more actions than would fit a single packet. */
6802
6803 class vcont_builder
6804 {
6805 public:
6806 explicit vcont_builder (remote_target *remote)
6807 : m_remote (remote)
6808 {
6809 restart ();
6810 }
6811
6812 void flush ();
6813 void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6814
6815 private:
6816 void restart ();
6817
6818 /* The remote target. */
6819 remote_target *m_remote;
6820
6821 /* Pointer to the first action. P points here if no action has been
6822 appended yet. */
6823 char *m_first_action;
6824
6825 /* Where the next action will be appended. */
6826 char *m_p;
6827
6828 /* The end of the buffer. Must never write past this. */
6829 char *m_endp;
6830 };
6831
6832 /* Prepare the outgoing buffer for a new vCont packet. */
6833
6834 void
6835 vcont_builder::restart ()
6836 {
6837 struct remote_state *rs = m_remote->get_remote_state ();
6838
6839 m_p = rs->buf.data ();
6840 m_endp = m_p + m_remote->get_remote_packet_size ();
6841 m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6842 m_first_action = m_p;
6843 }
6844
6845 /* If the vCont packet being built has any action, send it to the
6846 remote end. */
6847
6848 void
6849 vcont_builder::flush ()
6850 {
6851 struct remote_state *rs;
6852
6853 if (m_p == m_first_action)
6854 return;
6855
6856 rs = m_remote->get_remote_state ();
6857 m_remote->putpkt (rs->buf);
6858 m_remote->getpkt (&rs->buf, 0);
6859 if (strcmp (rs->buf.data (), "OK") != 0)
6860 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6861 }
6862
6863 /* The largest action is range-stepping, with its two addresses. This
6864 is more than sufficient. If a new, bigger action is created, it'll
6865 quickly trigger a failed assertion in append_resumption (and we'll
6866 just bump this). */
6867 #define MAX_ACTION_SIZE 200
6868
6869 /* Append a new vCont action in the outgoing packet being built. If
6870 the action doesn't fit the packet along with previous actions, push
6871 what we've got so far to the remote end and start over a new vCont
6872 packet (with the new action). */
6873
6874 void
6875 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6876 {
6877 char buf[MAX_ACTION_SIZE + 1];
6878
6879 char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6880 ptid, step, siggnal);
6881
6882 /* Check whether this new action would fit in the vCont packet along
6883 with previous actions. If not, send what we've got so far and
6884 start a new vCont packet. */
6885 size_t rsize = endp - buf;
6886 if (rsize > m_endp - m_p)
6887 {
6888 flush ();
6889 restart ();
6890
6891 /* Should now fit. */
6892 gdb_assert (rsize <= m_endp - m_p);
6893 }
6894
6895 memcpy (m_p, buf, rsize);
6896 m_p += rsize;
6897 *m_p = '\0';
6898 }
6899
6900 /* to_commit_resume implementation. */
6901
6902 void
6903 remote_target::commit_resumed ()
6904 {
6905 /* If connected in all-stop mode, we'd send the remote resume
6906 request directly from remote_resume. Likewise if
6907 reverse-debugging, as there are no defined vCont actions for
6908 reverse execution. */
6909 if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6910 return;
6911
6912 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6913 instead of resuming all threads of each process individually.
6914 However, if any thread of a process must remain halted, we can't
6915 send wildcard resumes and must send one action per thread.
6916
6917 Care must be taken to not resume threads/processes the server
6918 side already told us are stopped, but the core doesn't know about
6919 yet, because the events are still in the vStopped notification
6920 queue. For example:
6921
6922 #1 => vCont s:p1.1;c
6923 #2 <= OK
6924 #3 <= %Stopped T05 p1.1
6925 #4 => vStopped
6926 #5 <= T05 p1.2
6927 #6 => vStopped
6928 #7 <= OK
6929 #8 (infrun handles the stop for p1.1 and continues stepping)
6930 #9 => vCont s:p1.1;c
6931
6932 The last vCont above would resume thread p1.2 by mistake, because
6933 the server has no idea that the event for p1.2 had not been
6934 handled yet.
6935
6936 The server side must similarly ignore resume actions for the
6937 thread that has a pending %Stopped notification (and any other
6938 threads with events pending), until GDB acks the notification
6939 with vStopped. Otherwise, e.g., the following case is
6940 mishandled:
6941
6942 #1 => g (or any other packet)
6943 #2 <= [registers]
6944 #3 <= %Stopped T05 p1.2
6945 #4 => vCont s:p1.1;c
6946 #5 <= OK
6947
6948 Above, the server must not resume thread p1.2. GDB can't know
6949 that p1.2 stopped until it acks the %Stopped notification, and
6950 since from GDB's perspective all threads should be running, it
6951 sends a "c" action.
6952
6953 Finally, special care must also be given to handling fork/vfork
6954 events. A (v)fork event actually tells us that two processes
6955 stopped -- the parent and the child. Until we follow the fork,
6956 we must not resume the child. Therefore, if we have a pending
6957 fork follow, we must not send a global wildcard resume action
6958 (vCont;c). We can still send process-wide wildcards though. */
6959
6960 /* Start by assuming a global wildcard (vCont;c) is possible. */
6961 bool may_global_wildcard_vcont = true;
6962
6963 /* And assume every process is individually wildcard-able too. */
6964 for (inferior *inf : all_non_exited_inferiors (this))
6965 {
6966 remote_inferior *priv = get_remote_inferior (inf);
6967
6968 priv->may_wildcard_vcont = true;
6969 }
6970
6971 /* Check for any pending events (not reported or processed yet) and
6972 disable process and global wildcard resumes appropriately. */
6973 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6974
6975 bool any_pending_vcont_resume = false;
6976
6977 for (thread_info *tp : all_non_exited_threads (this))
6978 {
6979 remote_thread_info *priv = get_remote_thread_info (tp);
6980
6981 /* If a thread of a process is not meant to be resumed, then we
6982 can't wildcard that process. */
6983 if (priv->get_resume_state () == resume_state::NOT_RESUMED)
6984 {
6985 get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6986
6987 /* And if we can't wildcard a process, we can't wildcard
6988 everything either. */
6989 may_global_wildcard_vcont = false;
6990 continue;
6991 }
6992
6993 if (priv->get_resume_state () == resume_state::RESUMED_PENDING_VCONT)
6994 any_pending_vcont_resume = true;
6995
6996 /* If a thread is the parent of an unfollowed fork, then we
6997 can't do a global wildcard, as that would resume the fork
6998 child. */
6999 if (thread_pending_fork_status (tp) != nullptr)
7000 may_global_wildcard_vcont = false;
7001 }
7002
7003 /* We didn't have any resumed thread pending a vCont resume, so nothing to
7004 do. */
7005 if (!any_pending_vcont_resume)
7006 return;
7007
7008 /* Now let's build the vCont packet(s). Actions must be appended
7009 from narrower to wider scopes (thread -> process -> global). If
7010 we end up with too many actions for a single packet vcont_builder
7011 flushes the current vCont packet to the remote side and starts a
7012 new one. */
7013 struct vcont_builder vcont_builder (this);
7014
7015 /* Threads first. */
7016 for (thread_info *tp : all_non_exited_threads (this))
7017 {
7018 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7019
7020 /* If the thread was previously vCont-resumed, no need to send a specific
7021 action for it. If we didn't receive a resume request for it, don't
7022 send an action for it either. */
7023 if (remote_thr->get_resume_state () != resume_state::RESUMED_PENDING_VCONT)
7024 continue;
7025
7026 gdb_assert (!thread_is_in_step_over_chain (tp));
7027
7028 /* We should never be commit-resuming a thread that has a stop reply.
7029 Otherwise, we would end up reporting a stop event for a thread while
7030 it is running on the remote target. */
7031 remote_state *rs = get_remote_state ();
7032 for (const auto &stop_reply : rs->stop_reply_queue)
7033 gdb_assert (stop_reply->ptid != tp->ptid);
7034
7035 const resumed_pending_vcont_info &info
7036 = remote_thr->resumed_pending_vcont_info ();
7037
7038 /* Check if we need to send a specific action for this thread. If not,
7039 it will be included in a wildcard resume instead. */
7040 if (info.step || info.sig != GDB_SIGNAL_0
7041 || !get_remote_inferior (tp->inf)->may_wildcard_vcont)
7042 vcont_builder.push_action (tp->ptid, info.step, info.sig);
7043
7044 remote_thr->set_resumed ();
7045 }
7046
7047 /* Now check whether we can send any process-wide wildcard. This is
7048 to avoid sending a global wildcard in the case nothing is
7049 supposed to be resumed. */
7050 bool any_process_wildcard = false;
7051
7052 for (inferior *inf : all_non_exited_inferiors (this))
7053 {
7054 if (get_remote_inferior (inf)->may_wildcard_vcont)
7055 {
7056 any_process_wildcard = true;
7057 break;
7058 }
7059 }
7060
7061 if (any_process_wildcard)
7062 {
7063 /* If all processes are wildcard-able, then send a single "c"
7064 action, otherwise, send an "all (-1) threads of process"
7065 continue action for each running process, if any. */
7066 if (may_global_wildcard_vcont)
7067 {
7068 vcont_builder.push_action (minus_one_ptid,
7069 false, GDB_SIGNAL_0);
7070 }
7071 else
7072 {
7073 for (inferior *inf : all_non_exited_inferiors (this))
7074 {
7075 if (get_remote_inferior (inf)->may_wildcard_vcont)
7076 {
7077 vcont_builder.push_action (ptid_t (inf->pid),
7078 false, GDB_SIGNAL_0);
7079 }
7080 }
7081 }
7082 }
7083
7084 vcont_builder.flush ();
7085 }
7086
7087 /* Implementation of target_has_pending_events. */
7088
7089 bool
7090 remote_target::has_pending_events ()
7091 {
7092 if (target_can_async_p ())
7093 {
7094 remote_state *rs = get_remote_state ();
7095
7096 if (async_event_handler_marked (rs->remote_async_inferior_event_token))
7097 return true;
7098
7099 /* Note that BUFCNT can be negative, indicating sticky
7100 error. */
7101 if (rs->remote_desc->bufcnt != 0)
7102 return true;
7103 }
7104 return false;
7105 }
7106
7107 \f
7108
7109 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
7110 thread, all threads of a remote process, or all threads of all
7111 processes. */
7112
7113 void
7114 remote_target::remote_stop_ns (ptid_t ptid)
7115 {
7116 struct remote_state *rs = get_remote_state ();
7117 char *p = rs->buf.data ();
7118 char *endp = p + get_remote_packet_size ();
7119
7120 /* If any thread that needs to stop was resumed but pending a vCont
7121 resume, generate a phony stop_reply. However, first check
7122 whether the thread wasn't resumed with a signal. Generating a
7123 phony stop in that case would result in losing the signal. */
7124 bool needs_commit = false;
7125 for (thread_info *tp : all_non_exited_threads (this, ptid))
7126 {
7127 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7128
7129 if (remote_thr->get_resume_state ()
7130 == resume_state::RESUMED_PENDING_VCONT)
7131 {
7132 const resumed_pending_vcont_info &info
7133 = remote_thr->resumed_pending_vcont_info ();
7134 if (info.sig != GDB_SIGNAL_0)
7135 {
7136 /* This signal must be forwarded to the inferior. We
7137 could commit-resume just this thread, but its simpler
7138 to just commit-resume everything. */
7139 needs_commit = true;
7140 break;
7141 }
7142 }
7143 }
7144
7145 if (needs_commit)
7146 commit_resumed ();
7147 else
7148 for (thread_info *tp : all_non_exited_threads (this, ptid))
7149 {
7150 remote_thread_info *remote_thr = get_remote_thread_info (tp);
7151
7152 if (remote_thr->get_resume_state ()
7153 == resume_state::RESUMED_PENDING_VCONT)
7154 {
7155 remote_debug_printf ("Enqueueing phony stop reply for thread pending "
7156 "vCont-resume (%d, %ld, %s)", tp->ptid.pid(),
7157 tp->ptid.lwp (),
7158 pulongest (tp->ptid.tid ()));
7159
7160 /* Check that the thread wasn't resumed with a signal.
7161 Generating a phony stop would result in losing the
7162 signal. */
7163 const resumed_pending_vcont_info &info
7164 = remote_thr->resumed_pending_vcont_info ();
7165 gdb_assert (info.sig == GDB_SIGNAL_0);
7166
7167 stop_reply *sr = new stop_reply ();
7168 sr->ptid = tp->ptid;
7169 sr->rs = rs;
7170 sr->ws.set_stopped (GDB_SIGNAL_0);
7171 sr->arch = tp->inf->gdbarch;
7172 sr->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7173 sr->watch_data_address = 0;
7174 sr->core = 0;
7175 this->push_stop_reply (sr);
7176
7177 /* Pretend that this thread was actually resumed on the
7178 remote target, then stopped. If we leave it in the
7179 RESUMED_PENDING_VCONT state and the commit_resumed
7180 method is called while the stop reply is still in the
7181 queue, we'll end up reporting a stop event to the core
7182 for that thread while it is running on the remote
7183 target... that would be bad. */
7184 remote_thr->set_resumed ();
7185 }
7186 }
7187
7188 if (!rs->supports_vCont.t)
7189 error (_("Remote server does not support stopping threads"));
7190
7191 if (ptid == minus_one_ptid
7192 || (!m_features.remote_multi_process_p () && ptid.is_pid ()))
7193 p += xsnprintf (p, endp - p, "vCont;t");
7194 else
7195 {
7196 ptid_t nptid;
7197
7198 p += xsnprintf (p, endp - p, "vCont;t:");
7199
7200 if (ptid.is_pid ())
7201 /* All (-1) threads of process. */
7202 nptid = ptid_t (ptid.pid (), -1);
7203 else
7204 {
7205 /* Small optimization: if we already have a stop reply for
7206 this thread, no use in telling the stub we want this
7207 stopped. */
7208 if (peek_stop_reply (ptid))
7209 return;
7210
7211 nptid = ptid;
7212 }
7213
7214 write_ptid (p, endp, nptid);
7215 }
7216
7217 /* In non-stop, we get an immediate OK reply. The stop reply will
7218 come in asynchronously by notification. */
7219 putpkt (rs->buf);
7220 getpkt (&rs->buf, 0);
7221 if (strcmp (rs->buf.data (), "OK") != 0)
7222 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
7223 rs->buf.data ());
7224 }
7225
7226 /* All-stop version of target_interrupt. Sends a break or a ^C to
7227 interrupt the remote target. It is undefined which thread of which
7228 process reports the interrupt. */
7229
7230 void
7231 remote_target::remote_interrupt_as ()
7232 {
7233 struct remote_state *rs = get_remote_state ();
7234
7235 rs->ctrlc_pending_p = 1;
7236
7237 /* If the inferior is stopped already, but the core didn't know
7238 about it yet, just ignore the request. The pending stop events
7239 will be collected in remote_wait. */
7240 if (stop_reply_queue_length () > 0)
7241 return;
7242
7243 /* Send interrupt_sequence to remote target. */
7244 send_interrupt_sequence ();
7245 }
7246
7247 /* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
7248 the remote target. It is undefined which thread of which process
7249 reports the interrupt. Throws an error if the packet is not
7250 supported by the server. */
7251
7252 void
7253 remote_target::remote_interrupt_ns ()
7254 {
7255 struct remote_state *rs = get_remote_state ();
7256 char *p = rs->buf.data ();
7257 char *endp = p + get_remote_packet_size ();
7258
7259 xsnprintf (p, endp - p, "vCtrlC");
7260
7261 /* In non-stop, we get an immediate OK reply. The stop reply will
7262 come in asynchronously by notification. */
7263 putpkt (rs->buf);
7264 getpkt (&rs->buf, 0);
7265
7266 switch (m_features.packet_ok (rs->buf, PACKET_vCtrlC))
7267 {
7268 case PACKET_OK:
7269 break;
7270 case PACKET_UNKNOWN:
7271 error (_("No support for interrupting the remote target."));
7272 case PACKET_ERROR:
7273 error (_("Interrupting target failed: %s"), rs->buf.data ());
7274 }
7275 }
7276
7277 /* Implement the to_stop function for the remote targets. */
7278
7279 void
7280 remote_target::stop (ptid_t ptid)
7281 {
7282 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7283
7284 if (target_is_non_stop_p ())
7285 remote_stop_ns (ptid);
7286 else
7287 {
7288 /* We don't currently have a way to transparently pause the
7289 remote target in all-stop mode. Interrupt it instead. */
7290 remote_interrupt_as ();
7291 }
7292 }
7293
7294 /* Implement the to_interrupt function for the remote targets. */
7295
7296 void
7297 remote_target::interrupt ()
7298 {
7299 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7300
7301 if (target_is_non_stop_p ())
7302 remote_interrupt_ns ();
7303 else
7304 remote_interrupt_as ();
7305 }
7306
7307 /* Implement the to_pass_ctrlc function for the remote targets. */
7308
7309 void
7310 remote_target::pass_ctrlc ()
7311 {
7312 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
7313
7314 struct remote_state *rs = get_remote_state ();
7315
7316 /* If we're starting up, we're not fully synced yet. Quit
7317 immediately. */
7318 if (rs->starting_up)
7319 quit ();
7320 /* If ^C has already been sent once, offer to disconnect. */
7321 else if (rs->ctrlc_pending_p)
7322 interrupt_query ();
7323 else
7324 target_interrupt ();
7325 }
7326
7327 /* Ask the user what to do when an interrupt is received. */
7328
7329 void
7330 remote_target::interrupt_query ()
7331 {
7332 struct remote_state *rs = get_remote_state ();
7333
7334 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
7335 {
7336 if (query (_("The target is not responding to interrupt requests.\n"
7337 "Stop debugging it? ")))
7338 {
7339 remote_unpush_target (this);
7340 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
7341 }
7342 }
7343 else
7344 {
7345 if (query (_("Interrupted while waiting for the program.\n"
7346 "Give up waiting? ")))
7347 quit ();
7348 }
7349 }
7350
7351 /* Enable/disable target terminal ownership. Most targets can use
7352 terminal groups to control terminal ownership. Remote targets are
7353 different in that explicit transfer of ownership to/from GDB/target
7354 is required. */
7355
7356 void
7357 remote_target::terminal_inferior ()
7358 {
7359 /* NOTE: At this point we could also register our selves as the
7360 recipient of all input. Any characters typed could then be
7361 passed on down to the target. */
7362 }
7363
7364 void
7365 remote_target::terminal_ours ()
7366 {
7367 }
7368
7369 static void
7370 remote_console_output (const char *msg)
7371 {
7372 const char *p;
7373
7374 for (p = msg; p[0] && p[1]; p += 2)
7375 {
7376 char tb[2];
7377 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
7378
7379 tb[0] = c;
7380 tb[1] = 0;
7381 gdb_stdtarg->puts (tb);
7382 }
7383 gdb_stdtarg->flush ();
7384 }
7385
7386 /* Return the length of the stop reply queue. */
7387
7388 int
7389 remote_target::stop_reply_queue_length ()
7390 {
7391 remote_state *rs = get_remote_state ();
7392 return rs->stop_reply_queue.size ();
7393 }
7394
7395 static void
7396 remote_notif_stop_parse (remote_target *remote,
7397 const notif_client *self, const char *buf,
7398 struct notif_event *event)
7399 {
7400 remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
7401 }
7402
7403 static void
7404 remote_notif_stop_ack (remote_target *remote,
7405 const notif_client *self, const char *buf,
7406 struct notif_event *event)
7407 {
7408 struct stop_reply *stop_reply = (struct stop_reply *) event;
7409
7410 /* acknowledge */
7411 putpkt (remote, self->ack_command);
7412
7413 /* Kind can be TARGET_WAITKIND_IGNORE if we have meanwhile discarded
7414 the notification. It was left in the queue because we need to
7415 acknowledge it and pull the rest of the notifications out. */
7416 if (stop_reply->ws.kind () != TARGET_WAITKIND_IGNORE)
7417 remote->push_stop_reply (stop_reply);
7418 }
7419
7420 static int
7421 remote_notif_stop_can_get_pending_events (remote_target *remote,
7422 const notif_client *self)
7423 {
7424 /* We can't get pending events in remote_notif_process for
7425 notification stop, and we have to do this in remote_wait_ns
7426 instead. If we fetch all queued events from stub, remote stub
7427 may exit and we have no chance to process them back in
7428 remote_wait_ns. */
7429 remote_state *rs = remote->get_remote_state ();
7430 mark_async_event_handler (rs->remote_async_inferior_event_token);
7431 return 0;
7432 }
7433
7434 stop_reply::~stop_reply ()
7435 {
7436 for (cached_reg_t &reg : regcache)
7437 xfree (reg.data);
7438 }
7439
7440 static notif_event_up
7441 remote_notif_stop_alloc_reply ()
7442 {
7443 return notif_event_up (new struct stop_reply ());
7444 }
7445
7446 /* A client of notification Stop. */
7447
7448 const notif_client notif_client_stop =
7449 {
7450 "Stop",
7451 "vStopped",
7452 remote_notif_stop_parse,
7453 remote_notif_stop_ack,
7454 remote_notif_stop_can_get_pending_events,
7455 remote_notif_stop_alloc_reply,
7456 REMOTE_NOTIF_STOP,
7457 };
7458
7459 /* If CONTEXT contains any fork child threads that have not been
7460 reported yet, remove them from the CONTEXT list. If such a
7461 thread exists it is because we are stopped at a fork catchpoint
7462 and have not yet called follow_fork, which will set up the
7463 host-side data structures for the new process. */
7464
7465 void
7466 remote_target::remove_new_fork_children (threads_listing_context *context)
7467 {
7468 const notif_client *notif = &notif_client_stop;
7469
7470 /* For any threads stopped at a fork event, remove the corresponding
7471 fork child threads from the CONTEXT list. */
7472 for (thread_info *thread : all_non_exited_threads (this))
7473 {
7474 const target_waitstatus *ws = thread_pending_fork_status (thread);
7475
7476 if (ws == nullptr)
7477 continue;
7478
7479 context->remove_thread (ws->child_ptid ());
7480 }
7481
7482 /* Check for any pending fork events (not reported or processed yet)
7483 in process PID and remove those fork child threads from the
7484 CONTEXT list as well. */
7485 remote_notif_get_pending_events (notif);
7486 for (auto &event : get_remote_state ()->stop_reply_queue)
7487 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7488 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7489 context->remove_thread (event->ws.child_ptid ());
7490 else if (event->ws.kind () == TARGET_WAITKIND_THREAD_EXITED)
7491 context->remove_thread (event->ptid);
7492 }
7493
7494 /* Check whether any event pending in the vStopped queue would prevent a
7495 global or process wildcard vCont action. Set *may_global_wildcard to
7496 false if we can't do a global wildcard (vCont;c), and clear the event
7497 inferior's may_wildcard_vcont flag if we can't do a process-wide
7498 wildcard resume (vCont;c:pPID.-1). */
7499
7500 void
7501 remote_target::check_pending_events_prevent_wildcard_vcont
7502 (bool *may_global_wildcard)
7503 {
7504 const notif_client *notif = &notif_client_stop;
7505
7506 remote_notif_get_pending_events (notif);
7507 for (auto &event : get_remote_state ()->stop_reply_queue)
7508 {
7509 if (event->ws.kind () == TARGET_WAITKIND_NO_RESUMED
7510 || event->ws.kind () == TARGET_WAITKIND_NO_HISTORY)
7511 continue;
7512
7513 if (event->ws.kind () == TARGET_WAITKIND_FORKED
7514 || event->ws.kind () == TARGET_WAITKIND_VFORKED)
7515 *may_global_wildcard = false;
7516
7517 /* This may be the first time we heard about this process.
7518 Regardless, we must not do a global wildcard resume, otherwise
7519 we'd resume this process too. */
7520 *may_global_wildcard = false;
7521 if (event->ptid != null_ptid)
7522 {
7523 inferior *inf = find_inferior_ptid (this, event->ptid);
7524 if (inf != NULL)
7525 get_remote_inferior (inf)->may_wildcard_vcont = false;
7526 }
7527 }
7528 }
7529
7530 /* Discard all pending stop replies of inferior INF. */
7531
7532 void
7533 remote_target::discard_pending_stop_replies (struct inferior *inf)
7534 {
7535 struct stop_reply *reply;
7536 struct remote_state *rs = get_remote_state ();
7537 struct remote_notif_state *rns = rs->notif_state;
7538
7539 /* This function can be notified when an inferior exists. When the
7540 target is not remote, the notification state is NULL. */
7541 if (rs->remote_desc == NULL)
7542 return;
7543
7544 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7545
7546 /* Discard the in-flight notification. */
7547 if (reply != NULL && reply->ptid.pid () == inf->pid)
7548 {
7549 /* Leave the notification pending, since the server expects that
7550 we acknowledge it with vStopped. But clear its contents, so
7551 that later on when we acknowledge it, we also discard it. */
7552 remote_debug_printf
7553 ("discarding in-flight notification: ptid: %s, ws: %s\n",
7554 reply->ptid.to_string().c_str(),
7555 reply->ws.to_string ().c_str ());
7556 reply->ws.set_ignore ();
7557 }
7558
7559 /* Discard the stop replies we have already pulled with
7560 vStopped. */
7561 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7562 rs->stop_reply_queue.end (),
7563 [=] (const stop_reply_up &event)
7564 {
7565 return event->ptid.pid () == inf->pid;
7566 });
7567 for (auto it = iter; it != rs->stop_reply_queue.end (); ++it)
7568 remote_debug_printf
7569 ("discarding queued stop reply: ptid: %s, ws: %s\n",
7570 reply->ptid.to_string().c_str(),
7571 reply->ws.to_string ().c_str ());
7572 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7573 }
7574
7575 /* Discard the stop replies for RS in stop_reply_queue. */
7576
7577 void
7578 remote_target::discard_pending_stop_replies_in_queue ()
7579 {
7580 remote_state *rs = get_remote_state ();
7581
7582 /* Discard the stop replies we have already pulled with
7583 vStopped. */
7584 auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7585 rs->stop_reply_queue.end (),
7586 [=] (const stop_reply_up &event)
7587 {
7588 return event->rs == rs;
7589 });
7590 rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7591 }
7592
7593 /* Remove the first reply in 'stop_reply_queue' which matches
7594 PTID. */
7595
7596 struct stop_reply *
7597 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7598 {
7599 remote_state *rs = get_remote_state ();
7600
7601 auto iter = std::find_if (rs->stop_reply_queue.begin (),
7602 rs->stop_reply_queue.end (),
7603 [=] (const stop_reply_up &event)
7604 {
7605 return event->ptid.matches (ptid);
7606 });
7607 struct stop_reply *result;
7608 if (iter == rs->stop_reply_queue.end ())
7609 result = nullptr;
7610 else
7611 {
7612 result = iter->release ();
7613 rs->stop_reply_queue.erase (iter);
7614 }
7615
7616 if (notif_debug)
7617 gdb_printf (gdb_stdlog,
7618 "notif: discard queued event: 'Stop' in %s\n",
7619 ptid.to_string ().c_str ());
7620
7621 return result;
7622 }
7623
7624 /* Look for a queued stop reply belonging to PTID. If one is found,
7625 remove it from the queue, and return it. Returns NULL if none is
7626 found. If there are still queued events left to process, tell the
7627 event loop to get back to target_wait soon. */
7628
7629 struct stop_reply *
7630 remote_target::queued_stop_reply (ptid_t ptid)
7631 {
7632 remote_state *rs = get_remote_state ();
7633 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7634
7635 if (!rs->stop_reply_queue.empty () && target_can_async_p ())
7636 {
7637 /* There's still at least an event left. */
7638 mark_async_event_handler (rs->remote_async_inferior_event_token);
7639 }
7640
7641 return r;
7642 }
7643
7644 /* Push a fully parsed stop reply in the stop reply queue. Since we
7645 know that we now have at least one queued event left to pass to the
7646 core side, tell the event loop to get back to target_wait soon. */
7647
7648 void
7649 remote_target::push_stop_reply (struct stop_reply *new_event)
7650 {
7651 remote_state *rs = get_remote_state ();
7652 rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7653
7654 if (notif_debug)
7655 gdb_printf (gdb_stdlog,
7656 "notif: push 'Stop' %s to queue %d\n",
7657 new_event->ptid.to_string ().c_str (),
7658 int (rs->stop_reply_queue.size ()));
7659
7660 /* Mark the pending event queue only if async mode is currently enabled.
7661 If async mode is not currently enabled, then, if it later becomes
7662 enabled, and there are events in this queue, we will mark the event
7663 token at that point, see remote_target::async. */
7664 if (target_is_async_p ())
7665 mark_async_event_handler (rs->remote_async_inferior_event_token);
7666 }
7667
7668 /* Returns true if we have a stop reply for PTID. */
7669
7670 int
7671 remote_target::peek_stop_reply (ptid_t ptid)
7672 {
7673 remote_state *rs = get_remote_state ();
7674 for (auto &event : rs->stop_reply_queue)
7675 if (ptid == event->ptid
7676 && event->ws.kind () == TARGET_WAITKIND_STOPPED)
7677 return 1;
7678 return 0;
7679 }
7680
7681 /* Helper for remote_parse_stop_reply. Return nonzero if the substring
7682 starting with P and ending with PEND matches PREFIX. */
7683
7684 static int
7685 strprefix (const char *p, const char *pend, const char *prefix)
7686 {
7687 for ( ; p < pend; p++, prefix++)
7688 if (*p != *prefix)
7689 return 0;
7690 return *prefix == '\0';
7691 }
7692
7693 /* Parse the stop reply in BUF. Either the function succeeds, and the
7694 result is stored in EVENT, or throws an error. */
7695
7696 void
7697 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7698 {
7699 remote_arch_state *rsa = NULL;
7700 ULONGEST addr;
7701 const char *p;
7702 int skipregs = 0;
7703
7704 event->ptid = null_ptid;
7705 event->rs = get_remote_state ();
7706 event->ws.set_ignore ();
7707 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7708 event->regcache.clear ();
7709 event->core = -1;
7710
7711 switch (buf[0])
7712 {
7713 case 'T': /* Status with PC, SP, FP, ... */
7714 /* Expedited reply, containing Signal, {regno, reg} repeat. */
7715 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
7716 ss = signal number
7717 n... = register number
7718 r... = register contents
7719 */
7720
7721 p = &buf[3]; /* after Txx */
7722 while (*p)
7723 {
7724 const char *p1;
7725 int fieldsize;
7726
7727 p1 = strchr (p, ':');
7728 if (p1 == NULL)
7729 error (_("Malformed packet(a) (missing colon): %s\n\
7730 Packet: '%s'\n"),
7731 p, buf);
7732 if (p == p1)
7733 error (_("Malformed packet(a) (missing register number): %s\n\
7734 Packet: '%s'\n"),
7735 p, buf);
7736
7737 /* Some "registers" are actually extended stop information.
7738 Note if you're adding a new entry here: GDB 7.9 and
7739 earlier assume that all register "numbers" that start
7740 with an hex digit are real register numbers. Make sure
7741 the server only sends such a packet if it knows the
7742 client understands it. */
7743
7744 if (strprefix (p, p1, "thread"))
7745 event->ptid = read_ptid (++p1, &p);
7746 else if (strprefix (p, p1, "syscall_entry"))
7747 {
7748 ULONGEST sysno;
7749
7750 p = unpack_varlen_hex (++p1, &sysno);
7751 event->ws.set_syscall_entry ((int) sysno);
7752 }
7753 else if (strprefix (p, p1, "syscall_return"))
7754 {
7755 ULONGEST sysno;
7756
7757 p = unpack_varlen_hex (++p1, &sysno);
7758 event->ws.set_syscall_return ((int) sysno);
7759 }
7760 else if (strprefix (p, p1, "watch")
7761 || strprefix (p, p1, "rwatch")
7762 || strprefix (p, p1, "awatch"))
7763 {
7764 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7765 p = unpack_varlen_hex (++p1, &addr);
7766 event->watch_data_address = (CORE_ADDR) addr;
7767 }
7768 else if (strprefix (p, p1, "swbreak"))
7769 {
7770 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7771
7772 /* Make sure the stub doesn't forget to indicate support
7773 with qSupported. */
7774 if (m_features.packet_support (PACKET_swbreak_feature)
7775 != PACKET_ENABLE)
7776 error (_("Unexpected swbreak stop reason"));
7777
7778 /* The value part is documented as "must be empty",
7779 though we ignore it, in case we ever decide to make
7780 use of it in a backward compatible way. */
7781 p = strchrnul (p1 + 1, ';');
7782 }
7783 else if (strprefix (p, p1, "hwbreak"))
7784 {
7785 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7786
7787 /* Make sure the stub doesn't forget to indicate support
7788 with qSupported. */
7789 if (m_features.packet_support (PACKET_hwbreak_feature)
7790 != PACKET_ENABLE)
7791 error (_("Unexpected hwbreak stop reason"));
7792
7793 /* See above. */
7794 p = strchrnul (p1 + 1, ';');
7795 }
7796 else if (strprefix (p, p1, "library"))
7797 {
7798 event->ws.set_loaded ();
7799 p = strchrnul (p1 + 1, ';');
7800 }
7801 else if (strprefix (p, p1, "replaylog"))
7802 {
7803 event->ws.set_no_history ();
7804 /* p1 will indicate "begin" or "end", but it makes
7805 no difference for now, so ignore it. */
7806 p = strchrnul (p1 + 1, ';');
7807 }
7808 else if (strprefix (p, p1, "core"))
7809 {
7810 ULONGEST c;
7811
7812 p = unpack_varlen_hex (++p1, &c);
7813 event->core = c;
7814 }
7815 else if (strprefix (p, p1, "fork"))
7816 event->ws.set_forked (read_ptid (++p1, &p));
7817 else if (strprefix (p, p1, "vfork"))
7818 event->ws.set_vforked (read_ptid (++p1, &p));
7819 else if (strprefix (p, p1, "vforkdone"))
7820 {
7821 event->ws.set_vfork_done ();
7822 p = strchrnul (p1 + 1, ';');
7823 }
7824 else if (strprefix (p, p1, "exec"))
7825 {
7826 ULONGEST ignored;
7827 int pathlen;
7828
7829 /* Determine the length of the execd pathname. */
7830 p = unpack_varlen_hex (++p1, &ignored);
7831 pathlen = (p - p1) / 2;
7832
7833 /* Save the pathname for event reporting and for
7834 the next run command. */
7835 gdb::unique_xmalloc_ptr<char> pathname
7836 ((char *) xmalloc (pathlen + 1));
7837 hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7838 pathname.get ()[pathlen] = '\0';
7839
7840 /* This is freed during event handling. */
7841 event->ws.set_execd (std::move (pathname));
7842
7843 /* Skip the registers included in this packet, since
7844 they may be for an architecture different from the
7845 one used by the original program. */
7846 skipregs = 1;
7847 }
7848 else if (strprefix (p, p1, "create"))
7849 {
7850 event->ws.set_thread_created ();
7851 p = strchrnul (p1 + 1, ';');
7852 }
7853 else
7854 {
7855 ULONGEST pnum;
7856 const char *p_temp;
7857
7858 if (skipregs)
7859 {
7860 p = strchrnul (p1 + 1, ';');
7861 p++;
7862 continue;
7863 }
7864
7865 /* Maybe a real ``P'' register number. */
7866 p_temp = unpack_varlen_hex (p, &pnum);
7867 /* If the first invalid character is the colon, we got a
7868 register number. Otherwise, it's an unknown stop
7869 reason. */
7870 if (p_temp == p1)
7871 {
7872 /* If we haven't parsed the event's thread yet, find
7873 it now, in order to find the architecture of the
7874 reported expedited registers. */
7875 if (event->ptid == null_ptid)
7876 {
7877 /* If there is no thread-id information then leave
7878 the event->ptid as null_ptid. Later in
7879 process_stop_reply we will pick a suitable
7880 thread. */
7881 const char *thr = strstr (p1 + 1, ";thread:");
7882 if (thr != NULL)
7883 event->ptid = read_ptid (thr + strlen (";thread:"),
7884 NULL);
7885 }
7886
7887 if (rsa == NULL)
7888 {
7889 inferior *inf
7890 = (event->ptid == null_ptid
7891 ? NULL
7892 : find_inferior_ptid (this, event->ptid));
7893 /* If this is the first time we learn anything
7894 about this process, skip the registers
7895 included in this packet, since we don't yet
7896 know which architecture to use to parse them.
7897 We'll determine the architecture later when
7898 we process the stop reply and retrieve the
7899 target description, via
7900 remote_notice_new_inferior ->
7901 post_create_inferior. */
7902 if (inf == NULL)
7903 {
7904 p = strchrnul (p1 + 1, ';');
7905 p++;
7906 continue;
7907 }
7908
7909 event->arch = inf->gdbarch;
7910 rsa = event->rs->get_remote_arch_state (event->arch);
7911 }
7912
7913 packet_reg *reg
7914 = packet_reg_from_pnum (event->arch, rsa, pnum);
7915 cached_reg_t cached_reg;
7916
7917 if (reg == NULL)
7918 error (_("Remote sent bad register number %s: %s\n\
7919 Packet: '%s'\n"),
7920 hex_string (pnum), p, buf);
7921
7922 cached_reg.num = reg->regnum;
7923 cached_reg.data = (gdb_byte *)
7924 xmalloc (register_size (event->arch, reg->regnum));
7925
7926 p = p1 + 1;
7927 fieldsize = hex2bin (p, cached_reg.data,
7928 register_size (event->arch, reg->regnum));
7929 p += 2 * fieldsize;
7930 if (fieldsize < register_size (event->arch, reg->regnum))
7931 warning (_("Remote reply is too short: %s"), buf);
7932
7933 event->regcache.push_back (cached_reg);
7934 }
7935 else
7936 {
7937 /* Not a number. Silently skip unknown optional
7938 info. */
7939 p = strchrnul (p1 + 1, ';');
7940 }
7941 }
7942
7943 if (*p != ';')
7944 error (_("Remote register badly formatted: %s\nhere: %s"),
7945 buf, p);
7946 ++p;
7947 }
7948
7949 if (event->ws.kind () != TARGET_WAITKIND_IGNORE)
7950 break;
7951
7952 /* fall through */
7953 case 'S': /* Old style status, just signal only. */
7954 {
7955 int sig;
7956
7957 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7958 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7959 event->ws.set_stopped ((enum gdb_signal) sig);
7960 else
7961 event->ws.set_stopped (GDB_SIGNAL_UNKNOWN);
7962 }
7963 break;
7964 case 'w': /* Thread exited. */
7965 {
7966 ULONGEST value;
7967
7968 p = unpack_varlen_hex (&buf[1], &value);
7969 event->ws.set_thread_exited (value);
7970 if (*p != ';')
7971 error (_("stop reply packet badly formatted: %s"), buf);
7972 event->ptid = read_ptid (++p, NULL);
7973 break;
7974 }
7975 case 'W': /* Target exited. */
7976 case 'X':
7977 {
7978 ULONGEST value;
7979
7980 /* GDB used to accept only 2 hex chars here. Stubs should
7981 only send more if they detect GDB supports multi-process
7982 support. */
7983 p = unpack_varlen_hex (&buf[1], &value);
7984
7985 if (buf[0] == 'W')
7986 {
7987 /* The remote process exited. */
7988 event->ws.set_exited (value);
7989 }
7990 else
7991 {
7992 /* The remote process exited with a signal. */
7993 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7994 event->ws.set_signalled ((enum gdb_signal) value);
7995 else
7996 event->ws.set_signalled (GDB_SIGNAL_UNKNOWN);
7997 }
7998
7999 /* If no process is specified, return null_ptid, and let the
8000 caller figure out the right process to use. */
8001 int pid = 0;
8002 if (*p == '\0')
8003 ;
8004 else if (*p == ';')
8005 {
8006 p++;
8007
8008 if (*p == '\0')
8009 ;
8010 else if (startswith (p, "process:"))
8011 {
8012 ULONGEST upid;
8013
8014 p += sizeof ("process:") - 1;
8015 unpack_varlen_hex (p, &upid);
8016 pid = upid;
8017 }
8018 else
8019 error (_("unknown stop reply packet: %s"), buf);
8020 }
8021 else
8022 error (_("unknown stop reply packet: %s"), buf);
8023 event->ptid = ptid_t (pid);
8024 }
8025 break;
8026 case 'N':
8027 event->ws.set_no_resumed ();
8028 event->ptid = minus_one_ptid;
8029 break;
8030 }
8031 }
8032
8033 /* When the stub wants to tell GDB about a new notification reply, it
8034 sends a notification (%Stop, for example). Those can come it at
8035 any time, hence, we have to make sure that any pending
8036 putpkt/getpkt sequence we're making is finished, before querying
8037 the stub for more events with the corresponding ack command
8038 (vStopped, for example). E.g., if we started a vStopped sequence
8039 immediately upon receiving the notification, something like this
8040 could happen:
8041
8042 1.1) --> Hg 1
8043 1.2) <-- OK
8044 1.3) --> g
8045 1.4) <-- %Stop
8046 1.5) --> vStopped
8047 1.6) <-- (registers reply to step #1.3)
8048
8049 Obviously, the reply in step #1.6 would be unexpected to a vStopped
8050 query.
8051
8052 To solve this, whenever we parse a %Stop notification successfully,
8053 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
8054 doing whatever we were doing:
8055
8056 2.1) --> Hg 1
8057 2.2) <-- OK
8058 2.3) --> g
8059 2.4) <-- %Stop
8060 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
8061 2.5) <-- (registers reply to step #2.3)
8062
8063 Eventually after step #2.5, we return to the event loop, which
8064 notices there's an event on the
8065 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
8066 associated callback --- the function below. At this point, we're
8067 always safe to start a vStopped sequence. :
8068
8069 2.6) --> vStopped
8070 2.7) <-- T05 thread:2
8071 2.8) --> vStopped
8072 2.9) --> OK
8073 */
8074
8075 void
8076 remote_target::remote_notif_get_pending_events (const notif_client *nc)
8077 {
8078 struct remote_state *rs = get_remote_state ();
8079
8080 if (rs->notif_state->pending_event[nc->id] != NULL)
8081 {
8082 if (notif_debug)
8083 gdb_printf (gdb_stdlog,
8084 "notif: process: '%s' ack pending event\n",
8085 nc->name);
8086
8087 /* acknowledge */
8088 nc->ack (this, nc, rs->buf.data (),
8089 rs->notif_state->pending_event[nc->id]);
8090 rs->notif_state->pending_event[nc->id] = NULL;
8091
8092 while (1)
8093 {
8094 getpkt (&rs->buf, 0);
8095 if (strcmp (rs->buf.data (), "OK") == 0)
8096 break;
8097 else
8098 remote_notif_ack (this, nc, rs->buf.data ());
8099 }
8100 }
8101 else
8102 {
8103 if (notif_debug)
8104 gdb_printf (gdb_stdlog,
8105 "notif: process: '%s' no pending reply\n",
8106 nc->name);
8107 }
8108 }
8109
8110 /* Wrapper around remote_target::remote_notif_get_pending_events to
8111 avoid having to export the whole remote_target class. */
8112
8113 void
8114 remote_notif_get_pending_events (remote_target *remote, const notif_client *nc)
8115 {
8116 remote->remote_notif_get_pending_events (nc);
8117 }
8118
8119 /* Called from process_stop_reply when the stop packet we are responding
8120 to didn't include a process-id or thread-id. STATUS is the stop event
8121 we are responding to.
8122
8123 It is the task of this function to select a suitable thread (or process)
8124 and return its ptid, this is the thread (or process) we will assume the
8125 stop event came from.
8126
8127 In some cases there isn't really any choice about which thread (or
8128 process) is selected, a basic remote with a single process containing a
8129 single thread might choose not to send any process-id or thread-id in
8130 its stop packets, this function will select and return the one and only
8131 thread.
8132
8133 However, if a target supports multiple threads (or processes) and still
8134 doesn't include a thread-id (or process-id) in its stop packet then
8135 first, this is a badly behaving target, and second, we're going to have
8136 to select a thread (or process) at random and use that. This function
8137 will print a warning to the user if it detects that there is the
8138 possibility that GDB is guessing which thread (or process) to
8139 report.
8140
8141 Note that this is called before GDB fetches the updated thread list from the
8142 target. So it's possible for the stop reply to be ambiguous and for GDB to
8143 not realize it. For example, if there's initially one thread, the target
8144 spawns a second thread, and then sends a stop reply without an id that
8145 concerns the first thread. GDB will assume the stop reply is about the
8146 first thread - the only thread it knows about - without printing a warning.
8147 Anyway, if the remote meant for the stop reply to be about the second thread,
8148 then it would be really broken, because GDB doesn't know about that thread
8149 yet. */
8150
8151 ptid_t
8152 remote_target::select_thread_for_ambiguous_stop_reply
8153 (const target_waitstatus &status)
8154 {
8155 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8156
8157 /* Some stop events apply to all threads in an inferior, while others
8158 only apply to a single thread. */
8159 bool process_wide_stop
8160 = (status.kind () == TARGET_WAITKIND_EXITED
8161 || status.kind () == TARGET_WAITKIND_SIGNALLED);
8162
8163 remote_debug_printf ("process_wide_stop = %d", process_wide_stop);
8164
8165 thread_info *first_resumed_thread = nullptr;
8166 bool ambiguous = false;
8167
8168 /* Consider all non-exited threads of the target, find the first resumed
8169 one. */
8170 for (thread_info *thr : all_non_exited_threads (this))
8171 {
8172 remote_thread_info *remote_thr = get_remote_thread_info (thr);
8173
8174 if (remote_thr->get_resume_state () != resume_state::RESUMED)
8175 continue;
8176
8177 if (first_resumed_thread == nullptr)
8178 first_resumed_thread = thr;
8179 else if (!process_wide_stop
8180 || first_resumed_thread->ptid.pid () != thr->ptid.pid ())
8181 ambiguous = true;
8182 }
8183
8184 gdb_assert (first_resumed_thread != nullptr);
8185
8186 remote_debug_printf ("first resumed thread is %s",
8187 pid_to_str (first_resumed_thread->ptid).c_str ());
8188 remote_debug_printf ("is this guess ambiguous? = %d", ambiguous);
8189
8190 /* Warn if the remote target is sending ambiguous stop replies. */
8191 if (ambiguous)
8192 {
8193 static bool warned = false;
8194
8195 if (!warned)
8196 {
8197 /* If you are seeing this warning then the remote target has
8198 stopped without specifying a thread-id, but the target
8199 does have multiple threads (or inferiors), and so GDB is
8200 having to guess which thread stopped.
8201
8202 Examples of what might cause this are the target sending
8203 and 'S' stop packet, or a 'T' stop packet and not
8204 including a thread-id.
8205
8206 Additionally, the target might send a 'W' or 'X packet
8207 without including a process-id, when the target has
8208 multiple running inferiors. */
8209 if (process_wide_stop)
8210 warning (_("multi-inferior target stopped without "
8211 "sending a process-id, using first "
8212 "non-exited inferior"));
8213 else
8214 warning (_("multi-threaded target stopped without "
8215 "sending a thread-id, using first "
8216 "non-exited thread"));
8217 warned = true;
8218 }
8219 }
8220
8221 /* If this is a stop for all threads then don't use a particular threads
8222 ptid, instead create a new ptid where only the pid field is set. */
8223 if (process_wide_stop)
8224 return ptid_t (first_resumed_thread->ptid.pid ());
8225 else
8226 return first_resumed_thread->ptid;
8227 }
8228
8229 /* Called when it is decided that STOP_REPLY holds the info of the
8230 event that is to be returned to the core. This function always
8231 destroys STOP_REPLY. */
8232
8233 ptid_t
8234 remote_target::process_stop_reply (struct stop_reply *stop_reply,
8235 struct target_waitstatus *status)
8236 {
8237 *status = stop_reply->ws;
8238 ptid_t ptid = stop_reply->ptid;
8239
8240 /* If no thread/process was reported by the stub then select a suitable
8241 thread/process. */
8242 if (ptid == null_ptid)
8243 ptid = select_thread_for_ambiguous_stop_reply (*status);
8244 gdb_assert (ptid != null_ptid);
8245
8246 if (status->kind () != TARGET_WAITKIND_EXITED
8247 && status->kind () != TARGET_WAITKIND_SIGNALLED
8248 && status->kind () != TARGET_WAITKIND_NO_RESUMED)
8249 {
8250 /* Expedited registers. */
8251 if (!stop_reply->regcache.empty ())
8252 {
8253 struct regcache *regcache
8254 = get_thread_arch_regcache (this, ptid, stop_reply->arch);
8255
8256 for (cached_reg_t &reg : stop_reply->regcache)
8257 {
8258 regcache->raw_supply (reg.num, reg.data);
8259 xfree (reg.data);
8260 }
8261
8262 stop_reply->regcache.clear ();
8263 }
8264
8265 remote_notice_new_inferior (ptid, false);
8266 remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
8267 remote_thr->core = stop_reply->core;
8268 remote_thr->stop_reason = stop_reply->stop_reason;
8269 remote_thr->watch_data_address = stop_reply->watch_data_address;
8270
8271 if (target_is_non_stop_p ())
8272 {
8273 /* If the target works in non-stop mode, a stop-reply indicates that
8274 only this thread stopped. */
8275 remote_thr->set_not_resumed ();
8276 }
8277 else
8278 {
8279 /* If the target works in all-stop mode, a stop-reply indicates that
8280 all the target's threads stopped. */
8281 for (thread_info *tp : all_non_exited_threads (this))
8282 get_remote_thread_info (tp)->set_not_resumed ();
8283 }
8284 }
8285
8286 delete stop_reply;
8287 return ptid;
8288 }
8289
8290 /* The non-stop mode version of target_wait. */
8291
8292 ptid_t
8293 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status,
8294 target_wait_flags options)
8295 {
8296 struct remote_state *rs = get_remote_state ();
8297 struct stop_reply *stop_reply;
8298 int ret;
8299 int is_notif = 0;
8300
8301 /* If in non-stop mode, get out of getpkt even if a
8302 notification is received. */
8303
8304 ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
8305 while (1)
8306 {
8307 if (ret != -1 && !is_notif)
8308 switch (rs->buf[0])
8309 {
8310 case 'E': /* Error of some sort. */
8311 /* We're out of sync with the target now. Did it continue
8312 or not? We can't tell which thread it was in non-stop,
8313 so just ignore this. */
8314 warning (_("Remote failure reply: %s"), rs->buf.data ());
8315 break;
8316 case 'O': /* Console output. */
8317 remote_console_output (&rs->buf[1]);
8318 break;
8319 default:
8320 warning (_("Invalid remote reply: %s"), rs->buf.data ());
8321 break;
8322 }
8323
8324 /* Acknowledge a pending stop reply that may have arrived in the
8325 mean time. */
8326 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
8327 remote_notif_get_pending_events (&notif_client_stop);
8328
8329 /* If indeed we noticed a stop reply, we're done. */
8330 stop_reply = queued_stop_reply (ptid);
8331 if (stop_reply != NULL)
8332 return process_stop_reply (stop_reply, status);
8333
8334 /* Still no event. If we're just polling for an event, then
8335 return to the event loop. */
8336 if (options & TARGET_WNOHANG)
8337 {
8338 status->set_ignore ();
8339 return minus_one_ptid;
8340 }
8341
8342 /* Otherwise do a blocking wait. */
8343 ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
8344 }
8345 }
8346
8347 /* Return the first resumed thread. */
8348
8349 static ptid_t
8350 first_remote_resumed_thread (remote_target *target)
8351 {
8352 for (thread_info *tp : all_non_exited_threads (target, minus_one_ptid))
8353 if (tp->resumed ())
8354 return tp->ptid;
8355 return null_ptid;
8356 }
8357
8358 /* Wait until the remote machine stops, then return, storing status in
8359 STATUS just as `wait' would. */
8360
8361 ptid_t
8362 remote_target::wait_as (ptid_t ptid, target_waitstatus *status,
8363 target_wait_flags options)
8364 {
8365 struct remote_state *rs = get_remote_state ();
8366 ptid_t event_ptid = null_ptid;
8367 char *buf;
8368 struct stop_reply *stop_reply;
8369
8370 again:
8371
8372 status->set_ignore ();
8373
8374 stop_reply = queued_stop_reply (ptid);
8375 if (stop_reply != NULL)
8376 {
8377 /* None of the paths that push a stop reply onto the queue should
8378 have set the waiting_for_stop_reply flag. */
8379 gdb_assert (!rs->waiting_for_stop_reply);
8380 event_ptid = process_stop_reply (stop_reply, status);
8381 }
8382 else
8383 {
8384 int forever = ((options & TARGET_WNOHANG) == 0
8385 && rs->wait_forever_enabled_p);
8386
8387 if (!rs->waiting_for_stop_reply)
8388 {
8389 status->set_no_resumed ();
8390 return minus_one_ptid;
8391 }
8392
8393 /* FIXME: cagney/1999-09-27: If we're in async mode we should
8394 _never_ wait for ever -> test on target_is_async_p().
8395 However, before we do that we need to ensure that the caller
8396 knows how to take the target into/out of async mode. */
8397 int is_notif;
8398 int ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
8399
8400 /* GDB gets a notification. Return to core as this event is
8401 not interesting. */
8402 if (ret != -1 && is_notif)
8403 return minus_one_ptid;
8404
8405 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
8406 return minus_one_ptid;
8407
8408 buf = rs->buf.data ();
8409
8410 /* Assume that the target has acknowledged Ctrl-C unless we receive
8411 an 'F' or 'O' packet. */
8412 if (buf[0] != 'F' && buf[0] != 'O')
8413 rs->ctrlc_pending_p = 0;
8414
8415 switch (buf[0])
8416 {
8417 case 'E': /* Error of some sort. */
8418 /* We're out of sync with the target now. Did it continue or
8419 not? Not is more likely, so report a stop. */
8420 rs->waiting_for_stop_reply = 0;
8421
8422 warning (_("Remote failure reply: %s"), buf);
8423 status->set_stopped (GDB_SIGNAL_0);
8424 break;
8425 case 'F': /* File-I/O request. */
8426 /* GDB may access the inferior memory while handling the File-I/O
8427 request, but we don't want GDB accessing memory while waiting
8428 for a stop reply. See the comments in putpkt_binary. Set
8429 waiting_for_stop_reply to 0 temporarily. */
8430 rs->waiting_for_stop_reply = 0;
8431 remote_fileio_request (this, buf, rs->ctrlc_pending_p);
8432 rs->ctrlc_pending_p = 0;
8433 /* GDB handled the File-I/O request, and the target is running
8434 again. Keep waiting for events. */
8435 rs->waiting_for_stop_reply = 1;
8436 break;
8437 case 'N': case 'T': case 'S': case 'X': case 'W':
8438 {
8439 /* There is a stop reply to handle. */
8440 rs->waiting_for_stop_reply = 0;
8441
8442 stop_reply
8443 = (struct stop_reply *) remote_notif_parse (this,
8444 &notif_client_stop,
8445 rs->buf.data ());
8446
8447 event_ptid = process_stop_reply (stop_reply, status);
8448 break;
8449 }
8450 case 'O': /* Console output. */
8451 remote_console_output (buf + 1);
8452 break;
8453 case '\0':
8454 if (rs->last_sent_signal != GDB_SIGNAL_0)
8455 {
8456 /* Zero length reply means that we tried 'S' or 'C' and the
8457 remote system doesn't support it. */
8458 target_terminal::ours_for_output ();
8459 gdb_printf
8460 ("Can't send signals to this remote system. %s not sent.\n",
8461 gdb_signal_to_name (rs->last_sent_signal));
8462 rs->last_sent_signal = GDB_SIGNAL_0;
8463 target_terminal::inferior ();
8464
8465 strcpy (buf, rs->last_sent_step ? "s" : "c");
8466 putpkt (buf);
8467 break;
8468 }
8469 /* fallthrough */
8470 default:
8471 warning (_("Invalid remote reply: %s"), buf);
8472 break;
8473 }
8474 }
8475
8476 if (status->kind () == TARGET_WAITKIND_NO_RESUMED)
8477 return minus_one_ptid;
8478 else if (status->kind () == TARGET_WAITKIND_IGNORE)
8479 {
8480 /* Nothing interesting happened. If we're doing a non-blocking
8481 poll, we're done. Otherwise, go back to waiting. */
8482 if (options & TARGET_WNOHANG)
8483 return minus_one_ptid;
8484 else
8485 goto again;
8486 }
8487 else if (status->kind () != TARGET_WAITKIND_EXITED
8488 && status->kind () != TARGET_WAITKIND_SIGNALLED)
8489 {
8490 if (event_ptid != null_ptid)
8491 record_currthread (rs, event_ptid);
8492 else
8493 event_ptid = first_remote_resumed_thread (this);
8494 }
8495 else
8496 {
8497 /* A process exit. Invalidate our notion of current thread. */
8498 record_currthread (rs, minus_one_ptid);
8499 /* It's possible that the packet did not include a pid. */
8500 if (event_ptid == null_ptid)
8501 event_ptid = first_remote_resumed_thread (this);
8502 /* EVENT_PTID could still be NULL_PTID. Double-check. */
8503 if (event_ptid == null_ptid)
8504 event_ptid = magic_null_ptid;
8505 }
8506
8507 return event_ptid;
8508 }
8509
8510 /* Wait until the remote machine stops, then return, storing status in
8511 STATUS just as `wait' would. */
8512
8513 ptid_t
8514 remote_target::wait (ptid_t ptid, struct target_waitstatus *status,
8515 target_wait_flags options)
8516 {
8517 REMOTE_SCOPED_DEBUG_ENTER_EXIT;
8518
8519 remote_state *rs = get_remote_state ();
8520
8521 /* Start by clearing the flag that asks for our wait method to be called,
8522 we'll mark it again at the end if needed. If the target is not in
8523 async mode then the async token should not be marked. */
8524 if (target_is_async_p ())
8525 clear_async_event_handler (rs->remote_async_inferior_event_token);
8526 else
8527 gdb_assert (!async_event_handler_marked
8528 (rs->remote_async_inferior_event_token));
8529
8530 ptid_t event_ptid;
8531
8532 if (target_is_non_stop_p ())
8533 event_ptid = wait_ns (ptid, status, options);
8534 else
8535 event_ptid = wait_as (ptid, status, options);
8536
8537 if (target_is_async_p ())
8538 {
8539 /* If there are events left in the queue, or unacknowledged
8540 notifications, then tell the event loop to call us again. */
8541 if (!rs->stop_reply_queue.empty ()
8542 || rs->notif_state->pending_event[notif_client_stop.id] != nullptr)
8543 mark_async_event_handler (rs->remote_async_inferior_event_token);
8544 }
8545
8546 return event_ptid;
8547 }
8548
8549 /* Fetch a single register using a 'p' packet. */
8550
8551 int
8552 remote_target::fetch_register_using_p (struct regcache *regcache,
8553 packet_reg *reg)
8554 {
8555 struct gdbarch *gdbarch = regcache->arch ();
8556 struct remote_state *rs = get_remote_state ();
8557 char *buf, *p;
8558 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8559 int i;
8560
8561 if (m_features.packet_support (PACKET_p) == PACKET_DISABLE)
8562 return 0;
8563
8564 if (reg->pnum == -1)
8565 return 0;
8566
8567 p = rs->buf.data ();
8568 *p++ = 'p';
8569 p += hexnumstr (p, reg->pnum);
8570 *p++ = '\0';
8571 putpkt (rs->buf);
8572 getpkt (&rs->buf, 0);
8573
8574 buf = rs->buf.data ();
8575
8576 switch (m_features.packet_ok (rs->buf, PACKET_p))
8577 {
8578 case PACKET_OK:
8579 break;
8580 case PACKET_UNKNOWN:
8581 return 0;
8582 case PACKET_ERROR:
8583 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8584 gdbarch_register_name (regcache->arch (),
8585 reg->regnum),
8586 buf);
8587 }
8588
8589 /* If this register is unfetchable, tell the regcache. */
8590 if (buf[0] == 'x')
8591 {
8592 regcache->raw_supply (reg->regnum, NULL);
8593 return 1;
8594 }
8595
8596 /* Otherwise, parse and supply the value. */
8597 p = buf;
8598 i = 0;
8599 while (p[0] != 0)
8600 {
8601 if (p[1] == 0)
8602 error (_("fetch_register_using_p: early buf termination"));
8603
8604 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8605 p += 2;
8606 }
8607 regcache->raw_supply (reg->regnum, regp);
8608 return 1;
8609 }
8610
8611 /* Fetch the registers included in the target's 'g' packet. */
8612
8613 int
8614 remote_target::send_g_packet ()
8615 {
8616 struct remote_state *rs = get_remote_state ();
8617 int buf_len;
8618
8619 xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
8620 putpkt (rs->buf);
8621 getpkt (&rs->buf, 0);
8622 if (packet_check_result (rs->buf) == PACKET_ERROR)
8623 error (_("Could not read registers; remote failure reply '%s'"),
8624 rs->buf.data ());
8625
8626 /* We can get out of synch in various cases. If the first character
8627 in the buffer is not a hex character, assume that has happened
8628 and try to fetch another packet to read. */
8629 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8630 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8631 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8632 && rs->buf[0] != 'x') /* New: unavailable register value. */
8633 {
8634 remote_debug_printf ("Bad register packet; fetching a new packet");
8635 getpkt (&rs->buf, 0);
8636 }
8637
8638 buf_len = strlen (rs->buf.data ());
8639
8640 /* Sanity check the received packet. */
8641 if (buf_len % 2 != 0)
8642 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
8643
8644 return buf_len / 2;
8645 }
8646
8647 void
8648 remote_target::process_g_packet (struct regcache *regcache)
8649 {
8650 struct gdbarch *gdbarch = regcache->arch ();
8651 struct remote_state *rs = get_remote_state ();
8652 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8653 int i, buf_len;
8654 char *p;
8655 char *regs;
8656
8657 buf_len = strlen (rs->buf.data ());
8658
8659 /* Further sanity checks, with knowledge of the architecture. */
8660 if (buf_len > 2 * rsa->sizeof_g_packet)
8661 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8662 "bytes): %s"),
8663 rsa->sizeof_g_packet, buf_len / 2,
8664 rs->buf.data ());
8665
8666 /* Save the size of the packet sent to us by the target. It is used
8667 as a heuristic when determining the max size of packets that the
8668 target can safely receive. */
8669 if (rsa->actual_register_packet_size == 0)
8670 rsa->actual_register_packet_size = buf_len;
8671
8672 /* If this is smaller than we guessed the 'g' packet would be,
8673 update our records. A 'g' reply that doesn't include a register's
8674 value implies either that the register is not available, or that
8675 the 'p' packet must be used. */
8676 if (buf_len < 2 * rsa->sizeof_g_packet)
8677 {
8678 long sizeof_g_packet = buf_len / 2;
8679
8680 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8681 {
8682 long offset = rsa->regs[i].offset;
8683 long reg_size = register_size (gdbarch, i);
8684
8685 if (rsa->regs[i].pnum == -1)
8686 continue;
8687
8688 if (offset >= sizeof_g_packet)
8689 rsa->regs[i].in_g_packet = 0;
8690 else if (offset + reg_size > sizeof_g_packet)
8691 error (_("Truncated register %d in remote 'g' packet"), i);
8692 else
8693 rsa->regs[i].in_g_packet = 1;
8694 }
8695
8696 /* Looks valid enough, we can assume this is the correct length
8697 for a 'g' packet. It's important not to adjust
8698 rsa->sizeof_g_packet if we have truncated registers otherwise
8699 this "if" won't be run the next time the method is called
8700 with a packet of the same size and one of the internal errors
8701 below will trigger instead. */
8702 rsa->sizeof_g_packet = sizeof_g_packet;
8703 }
8704
8705 regs = (char *) alloca (rsa->sizeof_g_packet);
8706
8707 /* Unimplemented registers read as all bits zero. */
8708 memset (regs, 0, rsa->sizeof_g_packet);
8709
8710 /* Reply describes registers byte by byte, each byte encoded as two
8711 hex characters. Suck them all up, then supply them to the
8712 register cacheing/storage mechanism. */
8713
8714 p = rs->buf.data ();
8715 for (i = 0; i < rsa->sizeof_g_packet; i++)
8716 {
8717 if (p[0] == 0 || p[1] == 0)
8718 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
8719 internal_error (_("unexpected end of 'g' packet reply"));
8720
8721 if (p[0] == 'x' && p[1] == 'x')
8722 regs[i] = 0; /* 'x' */
8723 else
8724 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8725 p += 2;
8726 }
8727
8728 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8729 {
8730 struct packet_reg *r = &rsa->regs[i];
8731 long reg_size = register_size (gdbarch, i);
8732
8733 if (r->in_g_packet)
8734 {
8735 if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8736 /* This shouldn't happen - we adjusted in_g_packet above. */
8737 internal_error (_("unexpected end of 'g' packet reply"));
8738 else if (rs->buf[r->offset * 2] == 'x')
8739 {
8740 gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8741 /* The register isn't available, mark it as such (at
8742 the same time setting the value to zero). */
8743 regcache->raw_supply (r->regnum, NULL);
8744 }
8745 else
8746 regcache->raw_supply (r->regnum, regs + r->offset);
8747 }
8748 }
8749 }
8750
8751 void
8752 remote_target::fetch_registers_using_g (struct regcache *regcache)
8753 {
8754 send_g_packet ();
8755 process_g_packet (regcache);
8756 }
8757
8758 /* Make the remote selected traceframe match GDB's selected
8759 traceframe. */
8760
8761 void
8762 remote_target::set_remote_traceframe ()
8763 {
8764 int newnum;
8765 struct remote_state *rs = get_remote_state ();
8766
8767 if (rs->remote_traceframe_number == get_traceframe_number ())
8768 return;
8769
8770 /* Avoid recursion, remote_trace_find calls us again. */
8771 rs->remote_traceframe_number = get_traceframe_number ();
8772
8773 newnum = target_trace_find (tfind_number,
8774 get_traceframe_number (), 0, 0, NULL);
8775
8776 /* Should not happen. If it does, all bets are off. */
8777 if (newnum != get_traceframe_number ())
8778 warning (_("could not set remote traceframe"));
8779 }
8780
8781 void
8782 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8783 {
8784 struct gdbarch *gdbarch = regcache->arch ();
8785 struct remote_state *rs = get_remote_state ();
8786 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8787 int i;
8788
8789 set_remote_traceframe ();
8790 set_general_thread (regcache->ptid ());
8791
8792 if (regnum >= 0)
8793 {
8794 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8795
8796 gdb_assert (reg != NULL);
8797
8798 /* If this register might be in the 'g' packet, try that first -
8799 we are likely to read more than one register. If this is the
8800 first 'g' packet, we might be overly optimistic about its
8801 contents, so fall back to 'p'. */
8802 if (reg->in_g_packet)
8803 {
8804 fetch_registers_using_g (regcache);
8805 if (reg->in_g_packet)
8806 return;
8807 }
8808
8809 if (fetch_register_using_p (regcache, reg))
8810 return;
8811
8812 /* This register is not available. */
8813 regcache->raw_supply (reg->regnum, NULL);
8814
8815 return;
8816 }
8817
8818 fetch_registers_using_g (regcache);
8819
8820 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8821 if (!rsa->regs[i].in_g_packet)
8822 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8823 {
8824 /* This register is not available. */
8825 regcache->raw_supply (i, NULL);
8826 }
8827 }
8828
8829 /* Prepare to store registers. Since we may send them all (using a
8830 'G' request), we have to read out the ones we don't want to change
8831 first. */
8832
8833 void
8834 remote_target::prepare_to_store (struct regcache *regcache)
8835 {
8836 struct remote_state *rs = get_remote_state ();
8837 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8838 int i;
8839
8840 /* Make sure the entire registers array is valid. */
8841 switch (m_features.packet_support (PACKET_P))
8842 {
8843 case PACKET_DISABLE:
8844 case PACKET_SUPPORT_UNKNOWN:
8845 /* Make sure all the necessary registers are cached. */
8846 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8847 if (rsa->regs[i].in_g_packet)
8848 regcache->raw_update (rsa->regs[i].regnum);
8849 break;
8850 case PACKET_ENABLE:
8851 break;
8852 }
8853 }
8854
8855 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
8856 packet was not recognized. */
8857
8858 int
8859 remote_target::store_register_using_P (const struct regcache *regcache,
8860 packet_reg *reg)
8861 {
8862 struct gdbarch *gdbarch = regcache->arch ();
8863 struct remote_state *rs = get_remote_state ();
8864 /* Try storing a single register. */
8865 char *buf = rs->buf.data ();
8866 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8867 char *p;
8868
8869 if (m_features.packet_support (PACKET_P) == PACKET_DISABLE)
8870 return 0;
8871
8872 if (reg->pnum == -1)
8873 return 0;
8874
8875 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8876 p = buf + strlen (buf);
8877 regcache->raw_collect (reg->regnum, regp);
8878 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8879 putpkt (rs->buf);
8880 getpkt (&rs->buf, 0);
8881
8882 switch (m_features.packet_ok (rs->buf, PACKET_P))
8883 {
8884 case PACKET_OK:
8885 return 1;
8886 case PACKET_ERROR:
8887 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8888 gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8889 case PACKET_UNKNOWN:
8890 return 0;
8891 default:
8892 internal_error (_("Bad result from packet_ok"));
8893 }
8894 }
8895
8896 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8897 contents of the register cache buffer. FIXME: ignores errors. */
8898
8899 void
8900 remote_target::store_registers_using_G (const struct regcache *regcache)
8901 {
8902 struct remote_state *rs = get_remote_state ();
8903 remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8904 gdb_byte *regs;
8905 char *p;
8906
8907 /* Extract all the registers in the regcache copying them into a
8908 local buffer. */
8909 {
8910 int i;
8911
8912 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8913 memset (regs, 0, rsa->sizeof_g_packet);
8914 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8915 {
8916 struct packet_reg *r = &rsa->regs[i];
8917
8918 if (r->in_g_packet)
8919 regcache->raw_collect (r->regnum, regs + r->offset);
8920 }
8921 }
8922
8923 /* Command describes registers byte by byte,
8924 each byte encoded as two hex characters. */
8925 p = rs->buf.data ();
8926 *p++ = 'G';
8927 bin2hex (regs, p, rsa->sizeof_g_packet);
8928 putpkt (rs->buf);
8929 getpkt (&rs->buf, 0);
8930 if (packet_check_result (rs->buf) == PACKET_ERROR)
8931 error (_("Could not write registers; remote failure reply '%s'"),
8932 rs->buf.data ());
8933 }
8934
8935 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8936 of the register cache buffer. FIXME: ignores errors. */
8937
8938 void
8939 remote_target::store_registers (struct regcache *regcache, int regnum)
8940 {
8941 struct gdbarch *gdbarch = regcache->arch ();
8942 struct remote_state *rs = get_remote_state ();
8943 remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8944 int i;
8945
8946 set_remote_traceframe ();
8947 set_general_thread (regcache->ptid ());
8948
8949 if (regnum >= 0)
8950 {
8951 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8952
8953 gdb_assert (reg != NULL);
8954
8955 /* Always prefer to store registers using the 'P' packet if
8956 possible; we often change only a small number of registers.
8957 Sometimes we change a larger number; we'd need help from a
8958 higher layer to know to use 'G'. */
8959 if (store_register_using_P (regcache, reg))
8960 return;
8961
8962 /* For now, don't complain if we have no way to write the
8963 register. GDB loses track of unavailable registers too
8964 easily. Some day, this may be an error. We don't have
8965 any way to read the register, either... */
8966 if (!reg->in_g_packet)
8967 return;
8968
8969 store_registers_using_G (regcache);
8970 return;
8971 }
8972
8973 store_registers_using_G (regcache);
8974
8975 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8976 if (!rsa->regs[i].in_g_packet)
8977 if (!store_register_using_P (regcache, &rsa->regs[i]))
8978 /* See above for why we do not issue an error here. */
8979 continue;
8980 }
8981 \f
8982
8983 /* Return the number of hex digits in num. */
8984
8985 static int
8986 hexnumlen (ULONGEST num)
8987 {
8988 int i;
8989
8990 for (i = 0; num != 0; i++)
8991 num >>= 4;
8992
8993 return std::max (i, 1);
8994 }
8995
8996 /* Set BUF to the minimum number of hex digits representing NUM. */
8997
8998 static int
8999 hexnumstr (char *buf, ULONGEST num)
9000 {
9001 int len = hexnumlen (num);
9002
9003 return hexnumnstr (buf, num, len);
9004 }
9005
9006
9007 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
9008
9009 static int
9010 hexnumnstr (char *buf, ULONGEST num, int width)
9011 {
9012 int i;
9013
9014 buf[width] = '\0';
9015
9016 for (i = width - 1; i >= 0; i--)
9017 {
9018 buf[i] = "0123456789abcdef"[(num & 0xf)];
9019 num >>= 4;
9020 }
9021
9022 return width;
9023 }
9024
9025 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
9026
9027 static CORE_ADDR
9028 remote_address_masked (CORE_ADDR addr)
9029 {
9030 unsigned int address_size = remote_address_size;
9031
9032 /* If "remoteaddresssize" was not set, default to target address size. */
9033 if (!address_size)
9034 address_size = gdbarch_addr_bit (target_gdbarch ());
9035
9036 if (address_size > 0
9037 && address_size < (sizeof (ULONGEST) * 8))
9038 {
9039 /* Only create a mask when that mask can safely be constructed
9040 in a ULONGEST variable. */
9041 ULONGEST mask = 1;
9042
9043 mask = (mask << address_size) - 1;
9044 addr &= mask;
9045 }
9046 return addr;
9047 }
9048
9049 /* Determine whether the remote target supports binary downloading.
9050 This is accomplished by sending a no-op memory write of zero length
9051 to the target at the specified address. It does not suffice to send
9052 the whole packet, since many stubs strip the eighth bit and
9053 subsequently compute a wrong checksum, which causes real havoc with
9054 remote_write_bytes.
9055
9056 NOTE: This can still lose if the serial line is not eight-bit
9057 clean. In cases like this, the user should clear "remote
9058 X-packet". */
9059
9060 void
9061 remote_target::check_binary_download (CORE_ADDR addr)
9062 {
9063 struct remote_state *rs = get_remote_state ();
9064
9065 switch (m_features.packet_support (PACKET_X))
9066 {
9067 case PACKET_DISABLE:
9068 break;
9069 case PACKET_ENABLE:
9070 break;
9071 case PACKET_SUPPORT_UNKNOWN:
9072 {
9073 char *p;
9074
9075 p = rs->buf.data ();
9076 *p++ = 'X';
9077 p += hexnumstr (p, (ULONGEST) addr);
9078 *p++ = ',';
9079 p += hexnumstr (p, (ULONGEST) 0);
9080 *p++ = ':';
9081 *p = '\0';
9082
9083 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9084 getpkt (&rs->buf, 0);
9085
9086 if (rs->buf[0] == '\0')
9087 {
9088 remote_debug_printf ("binary downloading NOT supported by target");
9089 m_features.m_protocol_packets[PACKET_X].support = PACKET_DISABLE;
9090 }
9091 else
9092 {
9093 remote_debug_printf ("binary downloading supported by target");
9094 m_features.m_protocol_packets[PACKET_X].support = PACKET_ENABLE;
9095 }
9096 break;
9097 }
9098 }
9099 }
9100
9101 /* Helper function to resize the payload in order to try to get a good
9102 alignment. We try to write an amount of data such that the next write will
9103 start on an address aligned on REMOTE_ALIGN_WRITES. */
9104
9105 static int
9106 align_for_efficient_write (int todo, CORE_ADDR memaddr)
9107 {
9108 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
9109 }
9110
9111 /* Write memory data directly to the remote machine.
9112 This does not inform the data cache; the data cache uses this.
9113 HEADER is the starting part of the packet.
9114 MEMADDR is the address in the remote memory space.
9115 MYADDR is the address of the buffer in our space.
9116 LEN_UNITS is the number of addressable units to write.
9117 UNIT_SIZE is the length in bytes of an addressable unit.
9118 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
9119 should send data as binary ('X'), or hex-encoded ('M').
9120
9121 The function creates packet of the form
9122 <HEADER><ADDRESS>,<LENGTH>:<DATA>
9123
9124 where encoding of <DATA> is terminated by PACKET_FORMAT.
9125
9126 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
9127 are omitted.
9128
9129 Return the transferred status, error or OK (an
9130 'enum target_xfer_status' value). Save the number of addressable units
9131 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
9132
9133 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
9134 exchange between gdb and the stub could look like (?? in place of the
9135 checksum):
9136
9137 -> $m1000,4#??
9138 <- aaaabbbbccccdddd
9139
9140 -> $M1000,3:eeeeffffeeee#??
9141 <- OK
9142
9143 -> $m1000,4#??
9144 <- eeeeffffeeeedddd */
9145
9146 target_xfer_status
9147 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
9148 const gdb_byte *myaddr,
9149 ULONGEST len_units,
9150 int unit_size,
9151 ULONGEST *xfered_len_units,
9152 char packet_format, int use_length)
9153 {
9154 struct remote_state *rs = get_remote_state ();
9155 char *p;
9156 char *plen = NULL;
9157 int plenlen = 0;
9158 int todo_units;
9159 int units_written;
9160 int payload_capacity_bytes;
9161 int payload_length_bytes;
9162
9163 if (packet_format != 'X' && packet_format != 'M')
9164 internal_error (_("remote_write_bytes_aux: bad packet format"));
9165
9166 if (len_units == 0)
9167 return TARGET_XFER_EOF;
9168
9169 payload_capacity_bytes = get_memory_write_packet_size ();
9170
9171 /* The packet buffer will be large enough for the payload;
9172 get_memory_packet_size ensures this. */
9173 rs->buf[0] = '\0';
9174
9175 /* Compute the size of the actual payload by subtracting out the
9176 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
9177
9178 payload_capacity_bytes -= strlen ("$,:#NN");
9179 if (!use_length)
9180 /* The comma won't be used. */
9181 payload_capacity_bytes += 1;
9182 payload_capacity_bytes -= strlen (header);
9183 payload_capacity_bytes -= hexnumlen (memaddr);
9184
9185 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
9186
9187 strcat (rs->buf.data (), header);
9188 p = rs->buf.data () + strlen (header);
9189
9190 /* Compute a best guess of the number of bytes actually transfered. */
9191 if (packet_format == 'X')
9192 {
9193 /* Best guess at number of bytes that will fit. */
9194 todo_units = std::min (len_units,
9195 (ULONGEST) payload_capacity_bytes / unit_size);
9196 if (use_length)
9197 payload_capacity_bytes -= hexnumlen (todo_units);
9198 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
9199 }
9200 else
9201 {
9202 /* Number of bytes that will fit. */
9203 todo_units
9204 = std::min (len_units,
9205 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
9206 if (use_length)
9207 payload_capacity_bytes -= hexnumlen (todo_units);
9208 todo_units = std::min (todo_units,
9209 (payload_capacity_bytes / unit_size) / 2);
9210 }
9211
9212 if (todo_units <= 0)
9213 internal_error (_("minimum packet size too small to write data"));
9214
9215 /* If we already need another packet, then try to align the end
9216 of this packet to a useful boundary. */
9217 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
9218 todo_units = align_for_efficient_write (todo_units, memaddr);
9219
9220 /* Append "<memaddr>". */
9221 memaddr = remote_address_masked (memaddr);
9222 p += hexnumstr (p, (ULONGEST) memaddr);
9223
9224 if (use_length)
9225 {
9226 /* Append ",". */
9227 *p++ = ',';
9228
9229 /* Append the length and retain its location and size. It may need to be
9230 adjusted once the packet body has been created. */
9231 plen = p;
9232 plenlen = hexnumstr (p, (ULONGEST) todo_units);
9233 p += plenlen;
9234 }
9235
9236 /* Append ":". */
9237 *p++ = ':';
9238 *p = '\0';
9239
9240 /* Append the packet body. */
9241 if (packet_format == 'X')
9242 {
9243 /* Binary mode. Send target system values byte by byte, in
9244 increasing byte addresses. Only escape certain critical
9245 characters. */
9246 payload_length_bytes =
9247 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
9248 &units_written, payload_capacity_bytes);
9249
9250 /* If not all TODO units fit, then we'll need another packet. Make
9251 a second try to keep the end of the packet aligned. Don't do
9252 this if the packet is tiny. */
9253 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
9254 {
9255 int new_todo_units;
9256
9257 new_todo_units = align_for_efficient_write (units_written, memaddr);
9258
9259 if (new_todo_units != units_written)
9260 payload_length_bytes =
9261 remote_escape_output (myaddr, new_todo_units, unit_size,
9262 (gdb_byte *) p, &units_written,
9263 payload_capacity_bytes);
9264 }
9265
9266 p += payload_length_bytes;
9267 if (use_length && units_written < todo_units)
9268 {
9269 /* Escape chars have filled up the buffer prematurely,
9270 and we have actually sent fewer units than planned.
9271 Fix-up the length field of the packet. Use the same
9272 number of characters as before. */
9273 plen += hexnumnstr (plen, (ULONGEST) units_written,
9274 plenlen);
9275 *plen = ':'; /* overwrite \0 from hexnumnstr() */
9276 }
9277 }
9278 else
9279 {
9280 /* Normal mode: Send target system values byte by byte, in
9281 increasing byte addresses. Each byte is encoded as a two hex
9282 value. */
9283 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
9284 units_written = todo_units;
9285 }
9286
9287 putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
9288 getpkt (&rs->buf, 0);
9289
9290 if (rs->buf[0] == 'E')
9291 return TARGET_XFER_E_IO;
9292
9293 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
9294 send fewer units than we'd planned. */
9295 *xfered_len_units = (ULONGEST) units_written;
9296 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9297 }
9298
9299 /* Write memory data directly to the remote machine.
9300 This does not inform the data cache; the data cache uses this.
9301 MEMADDR is the address in the remote memory space.
9302 MYADDR is the address of the buffer in our space.
9303 LEN is the number of bytes.
9304
9305 Return the transferred status, error or OK (an
9306 'enum target_xfer_status' value). Save the number of bytes
9307 transferred in *XFERED_LEN. Only transfer a single packet. */
9308
9309 target_xfer_status
9310 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
9311 ULONGEST len, int unit_size,
9312 ULONGEST *xfered_len)
9313 {
9314 const char *packet_format = NULL;
9315
9316 /* Check whether the target supports binary download. */
9317 check_binary_download (memaddr);
9318
9319 switch (m_features.packet_support (PACKET_X))
9320 {
9321 case PACKET_ENABLE:
9322 packet_format = "X";
9323 break;
9324 case PACKET_DISABLE:
9325 packet_format = "M";
9326 break;
9327 case PACKET_SUPPORT_UNKNOWN:
9328 internal_error (_("remote_write_bytes: bad internal state"));
9329 default:
9330 internal_error (_("bad switch"));
9331 }
9332
9333 return remote_write_bytes_aux (packet_format,
9334 memaddr, myaddr, len, unit_size, xfered_len,
9335 packet_format[0], 1);
9336 }
9337
9338 /* Read memory data directly from the remote machine.
9339 This does not use the data cache; the data cache uses this.
9340 MEMADDR is the address in the remote memory space.
9341 MYADDR is the address of the buffer in our space.
9342 LEN_UNITS is the number of addressable memory units to read..
9343 UNIT_SIZE is the length in bytes of an addressable unit.
9344
9345 Return the transferred status, error or OK (an
9346 'enum target_xfer_status' value). Save the number of bytes
9347 transferred in *XFERED_LEN_UNITS.
9348
9349 See the comment of remote_write_bytes_aux for an example of
9350 memory read/write exchange between gdb and the stub. */
9351
9352 target_xfer_status
9353 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
9354 ULONGEST len_units,
9355 int unit_size, ULONGEST *xfered_len_units)
9356 {
9357 struct remote_state *rs = get_remote_state ();
9358 int buf_size_bytes; /* Max size of packet output buffer. */
9359 char *p;
9360 int todo_units;
9361 int decoded_bytes;
9362
9363 buf_size_bytes = get_memory_read_packet_size ();
9364 /* The packet buffer will be large enough for the payload;
9365 get_memory_packet_size ensures this. */
9366
9367 /* Number of units that will fit. */
9368 todo_units = std::min (len_units,
9369 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9370
9371 /* Construct "m"<memaddr>","<len>". */
9372 memaddr = remote_address_masked (memaddr);
9373 p = rs->buf.data ();
9374 *p++ = 'm';
9375 p += hexnumstr (p, (ULONGEST) memaddr);
9376 *p++ = ',';
9377 p += hexnumstr (p, (ULONGEST) todo_units);
9378 *p = '\0';
9379 putpkt (rs->buf);
9380 getpkt (&rs->buf, 0);
9381 if (rs->buf[0] == 'E'
9382 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
9383 && rs->buf[3] == '\0')
9384 return TARGET_XFER_E_IO;
9385 /* Reply describes memory byte by byte, each byte encoded as two hex
9386 characters. */
9387 p = rs->buf.data ();
9388 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9389 /* Return what we have. Let higher layers handle partial reads. */
9390 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9391 return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
9392 }
9393
9394 /* Using the set of read-only target sections of remote, read live
9395 read-only memory.
9396
9397 For interface/parameters/return description see target.h,
9398 to_xfer_partial. */
9399
9400 target_xfer_status
9401 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
9402 ULONGEST memaddr,
9403 ULONGEST len,
9404 int unit_size,
9405 ULONGEST *xfered_len)
9406 {
9407 const struct target_section *secp;
9408
9409 secp = target_section_by_addr (this, memaddr);
9410 if (secp != NULL
9411 && (bfd_section_flags (secp->the_bfd_section) & SEC_READONLY))
9412 {
9413 ULONGEST memend = memaddr + len;
9414
9415 const target_section_table *table = target_get_section_table (this);
9416 for (const target_section &p : *table)
9417 {
9418 if (memaddr >= p.addr)
9419 {
9420 if (memend <= p.endaddr)
9421 {
9422 /* Entire transfer is within this section. */
9423 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9424 xfered_len);
9425 }
9426 else if (memaddr >= p.endaddr)
9427 {
9428 /* This section ends before the transfer starts. */
9429 continue;
9430 }
9431 else
9432 {
9433 /* This section overlaps the transfer. Just do half. */
9434 len = p.endaddr - memaddr;
9435 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
9436 xfered_len);
9437 }
9438 }
9439 }
9440 }
9441
9442 return TARGET_XFER_EOF;
9443 }
9444
9445 /* Similar to remote_read_bytes_1, but it reads from the remote stub
9446 first if the requested memory is unavailable in traceframe.
9447 Otherwise, fall back to remote_read_bytes_1. */
9448
9449 target_xfer_status
9450 remote_target::remote_read_bytes (CORE_ADDR memaddr,
9451 gdb_byte *myaddr, ULONGEST len, int unit_size,
9452 ULONGEST *xfered_len)
9453 {
9454 if (len == 0)
9455 return TARGET_XFER_EOF;
9456
9457 if (get_traceframe_number () != -1)
9458 {
9459 std::vector<mem_range> available;
9460
9461 /* If we fail to get the set of available memory, then the
9462 target does not support querying traceframe info, and so we
9463 attempt reading from the traceframe anyway (assuming the
9464 target implements the old QTro packet then). */
9465 if (traceframe_available_memory (&available, memaddr, len))
9466 {
9467 if (available.empty () || available[0].start != memaddr)
9468 {
9469 enum target_xfer_status res;
9470
9471 /* Don't read into the traceframe's available
9472 memory. */
9473 if (!available.empty ())
9474 {
9475 LONGEST oldlen = len;
9476
9477 len = available[0].start - memaddr;
9478 gdb_assert (len <= oldlen);
9479 }
9480
9481 /* This goes through the topmost target again. */
9482 res = remote_xfer_live_readonly_partial (myaddr, memaddr,
9483 len, unit_size, xfered_len);
9484 if (res == TARGET_XFER_OK)
9485 return TARGET_XFER_OK;
9486 else
9487 {
9488 /* No use trying further, we know some memory starting
9489 at MEMADDR isn't available. */
9490 *xfered_len = len;
9491 return (*xfered_len != 0) ?
9492 TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
9493 }
9494 }
9495
9496 /* Don't try to read more than how much is available, in
9497 case the target implements the deprecated QTro packet to
9498 cater for older GDBs (the target's knowledge of read-only
9499 sections may be outdated by now). */
9500 len = available[0].length;
9501 }
9502 }
9503
9504 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9505 }
9506
9507 \f
9508
9509 /* Sends a packet with content determined by the printf format string
9510 FORMAT and the remaining arguments, then gets the reply. Returns
9511 whether the packet was a success, a failure, or unknown. */
9512
9513 packet_result
9514 remote_target::remote_send_printf (const char *format, ...)
9515 {
9516 struct remote_state *rs = get_remote_state ();
9517 int max_size = get_remote_packet_size ();
9518 va_list ap;
9519
9520 va_start (ap, format);
9521
9522 rs->buf[0] = '\0';
9523 int size = vsnprintf (rs->buf.data (), max_size, format, ap);
9524
9525 va_end (ap);
9526
9527 if (size >= max_size)
9528 internal_error (_("Too long remote packet."));
9529
9530 if (putpkt (rs->buf) < 0)
9531 error (_("Communication problem with target."));
9532
9533 rs->buf[0] = '\0';
9534 getpkt (&rs->buf, 0);
9535
9536 return packet_check_result (rs->buf);
9537 }
9538
9539 /* Flash writing can take quite some time. We'll set
9540 effectively infinite timeout for flash operations.
9541 In future, we'll need to decide on a better approach. */
9542 static const int remote_flash_timeout = 1000;
9543
9544 void
9545 remote_target::flash_erase (ULONGEST address, LONGEST length)
9546 {
9547 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9548 enum packet_result ret;
9549 scoped_restore restore_timeout
9550 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9551
9552 ret = remote_send_printf ("vFlashErase:%s,%s",
9553 phex (address, addr_size),
9554 phex (length, 4));
9555 switch (ret)
9556 {
9557 case PACKET_UNKNOWN:
9558 error (_("Remote target does not support flash erase"));
9559 case PACKET_ERROR:
9560 error (_("Error erasing flash with vFlashErase packet"));
9561 default:
9562 break;
9563 }
9564 }
9565
9566 target_xfer_status
9567 remote_target::remote_flash_write (ULONGEST address,
9568 ULONGEST length, ULONGEST *xfered_len,
9569 const gdb_byte *data)
9570 {
9571 scoped_restore restore_timeout
9572 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9573 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9574 xfered_len,'X', 0);
9575 }
9576
9577 void
9578 remote_target::flash_done ()
9579 {
9580 int ret;
9581
9582 scoped_restore restore_timeout
9583 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9584
9585 ret = remote_send_printf ("vFlashDone");
9586
9587 switch (ret)
9588 {
9589 case PACKET_UNKNOWN:
9590 error (_("Remote target does not support vFlashDone"));
9591 case PACKET_ERROR:
9592 error (_("Error finishing flash operation"));
9593 default:
9594 break;
9595 }
9596 }
9597
9598 \f
9599 /* Stuff for dealing with the packets which are part of this protocol.
9600 See comment at top of file for details. */
9601
9602 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9603 error to higher layers. Called when a serial error is detected.
9604 The exception message is STRING, followed by a colon and a blank,
9605 the system error message for errno at function entry and final dot
9606 for output compatibility with throw_perror_with_name. */
9607
9608 static void
9609 unpush_and_perror (remote_target *target, const char *string)
9610 {
9611 int saved_errno = errno;
9612
9613 remote_unpush_target (target);
9614 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9615 safe_strerror (saved_errno));
9616 }
9617
9618 /* Read a single character from the remote end. The current quit
9619 handler is overridden to avoid quitting in the middle of packet
9620 sequence, as that would break communication with the remote server.
9621 See remote_serial_quit_handler for more detail. */
9622
9623 int
9624 remote_target::readchar (int timeout)
9625 {
9626 int ch;
9627 struct remote_state *rs = get_remote_state ();
9628
9629 {
9630 scoped_restore restore_quit_target
9631 = make_scoped_restore (&curr_quit_handler_target, this);
9632 scoped_restore restore_quit
9633 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9634
9635 rs->got_ctrlc_during_io = 0;
9636
9637 ch = serial_readchar (rs->remote_desc, timeout);
9638
9639 if (rs->got_ctrlc_during_io)
9640 set_quit_flag ();
9641 }
9642
9643 if (ch >= 0)
9644 return ch;
9645
9646 switch ((enum serial_rc) ch)
9647 {
9648 case SERIAL_EOF:
9649 remote_unpush_target (this);
9650 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9651 /* no return */
9652 case SERIAL_ERROR:
9653 unpush_and_perror (this, _("Remote communication error. "
9654 "Target disconnected."));
9655 /* no return */
9656 case SERIAL_TIMEOUT:
9657 break;
9658 }
9659 return ch;
9660 }
9661
9662 /* Wrapper for serial_write that closes the target and throws if
9663 writing fails. The current quit handler is overridden to avoid
9664 quitting in the middle of packet sequence, as that would break
9665 communication with the remote server. See
9666 remote_serial_quit_handler for more detail. */
9667
9668 void
9669 remote_target::remote_serial_write (const char *str, int len)
9670 {
9671 struct remote_state *rs = get_remote_state ();
9672
9673 scoped_restore restore_quit_target
9674 = make_scoped_restore (&curr_quit_handler_target, this);
9675 scoped_restore restore_quit
9676 = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9677
9678 rs->got_ctrlc_during_io = 0;
9679
9680 if (serial_write (rs->remote_desc, str, len))
9681 {
9682 unpush_and_perror (this, _("Remote communication error. "
9683 "Target disconnected."));
9684 }
9685
9686 if (rs->got_ctrlc_during_io)
9687 set_quit_flag ();
9688 }
9689
9690 /* Return a string representing an escaped version of BUF, of len N.
9691 E.g. \n is converted to \\n, \t to \\t, etc. */
9692
9693 static std::string
9694 escape_buffer (const char *buf, int n)
9695 {
9696 string_file stb;
9697
9698 stb.putstrn (buf, n, '\\');
9699 return stb.release ();
9700 }
9701
9702 int
9703 remote_target::putpkt (const char *buf)
9704 {
9705 return putpkt_binary (buf, strlen (buf));
9706 }
9707
9708 /* Wrapper around remote_target::putpkt to avoid exporting
9709 remote_target. */
9710
9711 int
9712 putpkt (remote_target *remote, const char *buf)
9713 {
9714 return remote->putpkt (buf);
9715 }
9716
9717 /* Send a packet to the remote machine, with error checking. The data
9718 of the packet is in BUF. The string in BUF can be at most
9719 get_remote_packet_size () - 5 to account for the $, # and checksum,
9720 and for a possible /0 if we are debugging (remote_debug) and want
9721 to print the sent packet as a string. */
9722
9723 int
9724 remote_target::putpkt_binary (const char *buf, int cnt)
9725 {
9726 struct remote_state *rs = get_remote_state ();
9727 int i;
9728 unsigned char csum = 0;
9729 gdb::def_vector<char> data (cnt + 6);
9730 char *buf2 = data.data ();
9731
9732 int ch;
9733 int tcount = 0;
9734 char *p;
9735
9736 /* Catch cases like trying to read memory or listing threads while
9737 we're waiting for a stop reply. The remote server wouldn't be
9738 ready to handle this request, so we'd hang and timeout. We don't
9739 have to worry about this in synchronous mode, because in that
9740 case it's not possible to issue a command while the target is
9741 running. This is not a problem in non-stop mode, because in that
9742 case, the stub is always ready to process serial input. */
9743 if (!target_is_non_stop_p ()
9744 && target_is_async_p ()
9745 && rs->waiting_for_stop_reply)
9746 {
9747 error (_("Cannot execute this command while the target is running.\n"
9748 "Use the \"interrupt\" command to stop the target\n"
9749 "and then try again."));
9750 }
9751
9752 /* Copy the packet into buffer BUF2, encapsulating it
9753 and giving it a checksum. */
9754
9755 p = buf2;
9756 *p++ = '$';
9757
9758 for (i = 0; i < cnt; i++)
9759 {
9760 csum += buf[i];
9761 *p++ = buf[i];
9762 }
9763 *p++ = '#';
9764 *p++ = tohex ((csum >> 4) & 0xf);
9765 *p++ = tohex (csum & 0xf);
9766
9767 /* Send it over and over until we get a positive ack. */
9768
9769 while (1)
9770 {
9771 if (remote_debug)
9772 {
9773 *p = '\0';
9774
9775 int len = (int) (p - buf2);
9776 int max_chars;
9777
9778 if (remote_packet_max_chars < 0)
9779 max_chars = len;
9780 else
9781 max_chars = remote_packet_max_chars;
9782
9783 std::string str
9784 = escape_buffer (buf2, std::min (len, max_chars));
9785
9786 if (len > max_chars)
9787 remote_debug_printf_nofunc
9788 ("Sending packet: %s [%d bytes omitted]", str.c_str (),
9789 len - max_chars);
9790 else
9791 remote_debug_printf_nofunc ("Sending packet: %s", str.c_str ());
9792 }
9793 remote_serial_write (buf2, p - buf2);
9794
9795 /* If this is a no acks version of the remote protocol, send the
9796 packet and move on. */
9797 if (rs->noack_mode)
9798 break;
9799
9800 /* Read until either a timeout occurs (-2) or '+' is read.
9801 Handle any notification that arrives in the mean time. */
9802 while (1)
9803 {
9804 ch = readchar (remote_timeout);
9805
9806 switch (ch)
9807 {
9808 case '+':
9809 remote_debug_printf_nofunc ("Received Ack");
9810 return 1;
9811 case '-':
9812 remote_debug_printf_nofunc ("Received Nak");
9813 /* FALLTHROUGH */
9814 case SERIAL_TIMEOUT:
9815 tcount++;
9816 if (tcount > 3)
9817 return 0;
9818 break; /* Retransmit buffer. */
9819 case '$':
9820 {
9821 remote_debug_printf ("Packet instead of Ack, ignoring it");
9822 /* It's probably an old response sent because an ACK
9823 was lost. Gobble up the packet and ack it so it
9824 doesn't get retransmitted when we resend this
9825 packet. */
9826 skip_frame ();
9827 remote_serial_write ("+", 1);
9828 continue; /* Now, go look for +. */
9829 }
9830
9831 case '%':
9832 {
9833 int val;
9834
9835 /* If we got a notification, handle it, and go back to looking
9836 for an ack. */
9837 /* We've found the start of a notification. Now
9838 collect the data. */
9839 val = read_frame (&rs->buf);
9840 if (val >= 0)
9841 {
9842 remote_debug_printf_nofunc
9843 (" Notification received: %s",
9844 escape_buffer (rs->buf.data (), val).c_str ());
9845
9846 handle_notification (rs->notif_state, rs->buf.data ());
9847 /* We're in sync now, rewait for the ack. */
9848 tcount = 0;
9849 }
9850 else
9851 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9852 rs->buf.data ());
9853 continue;
9854 }
9855 /* fall-through */
9856 default:
9857 remote_debug_printf_nofunc ("Junk: %c%s", ch & 0177,
9858 rs->buf.data ());
9859 continue;
9860 }
9861 break; /* Here to retransmit. */
9862 }
9863
9864 #if 0
9865 /* This is wrong. If doing a long backtrace, the user should be
9866 able to get out next time we call QUIT, without anything as
9867 violent as interrupt_query. If we want to provide a way out of
9868 here without getting to the next QUIT, it should be based on
9869 hitting ^C twice as in remote_wait. */
9870 if (quit_flag)
9871 {
9872 quit_flag = 0;
9873 interrupt_query ();
9874 }
9875 #endif
9876 }
9877
9878 return 0;
9879 }
9880
9881 /* Come here after finding the start of a frame when we expected an
9882 ack. Do our best to discard the rest of this packet. */
9883
9884 void
9885 remote_target::skip_frame ()
9886 {
9887 int c;
9888
9889 while (1)
9890 {
9891 c = readchar (remote_timeout);
9892 switch (c)
9893 {
9894 case SERIAL_TIMEOUT:
9895 /* Nothing we can do. */
9896 return;
9897 case '#':
9898 /* Discard the two bytes of checksum and stop. */
9899 c = readchar (remote_timeout);
9900 if (c >= 0)
9901 c = readchar (remote_timeout);
9902
9903 return;
9904 case '*': /* Run length encoding. */
9905 /* Discard the repeat count. */
9906 c = readchar (remote_timeout);
9907 if (c < 0)
9908 return;
9909 break;
9910 default:
9911 /* A regular character. */
9912 break;
9913 }
9914 }
9915 }
9916
9917 /* Come here after finding the start of the frame. Collect the rest
9918 into *BUF, verifying the checksum, length, and handling run-length
9919 compression. NUL terminate the buffer. If there is not enough room,
9920 expand *BUF.
9921
9922 Returns -1 on error, number of characters in buffer (ignoring the
9923 trailing NULL) on success. (could be extended to return one of the
9924 SERIAL status indications). */
9925
9926 long
9927 remote_target::read_frame (gdb::char_vector *buf_p)
9928 {
9929 unsigned char csum;
9930 long bc;
9931 int c;
9932 char *buf = buf_p->data ();
9933 struct remote_state *rs = get_remote_state ();
9934
9935 csum = 0;
9936 bc = 0;
9937
9938 while (1)
9939 {
9940 c = readchar (remote_timeout);
9941 switch (c)
9942 {
9943 case SERIAL_TIMEOUT:
9944 remote_debug_printf ("Timeout in mid-packet, retrying");
9945 return -1;
9946
9947 case '$':
9948 remote_debug_printf ("Saw new packet start in middle of old one");
9949 return -1; /* Start a new packet, count retries. */
9950
9951 case '#':
9952 {
9953 unsigned char pktcsum;
9954 int check_0 = 0;
9955 int check_1 = 0;
9956
9957 buf[bc] = '\0';
9958
9959 check_0 = readchar (remote_timeout);
9960 if (check_0 >= 0)
9961 check_1 = readchar (remote_timeout);
9962
9963 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9964 {
9965 remote_debug_printf ("Timeout in checksum, retrying");
9966 return -1;
9967 }
9968 else if (check_0 < 0 || check_1 < 0)
9969 {
9970 remote_debug_printf ("Communication error in checksum");
9971 return -1;
9972 }
9973
9974 /* Don't recompute the checksum; with no ack packets we
9975 don't have any way to indicate a packet retransmission
9976 is necessary. */
9977 if (rs->noack_mode)
9978 return bc;
9979
9980 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9981 if (csum == pktcsum)
9982 return bc;
9983
9984 remote_debug_printf
9985 ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s",
9986 pktcsum, csum, escape_buffer (buf, bc).c_str ());
9987
9988 /* Number of characters in buffer ignoring trailing
9989 NULL. */
9990 return -1;
9991 }
9992 case '*': /* Run length encoding. */
9993 {
9994 int repeat;
9995
9996 csum += c;
9997 c = readchar (remote_timeout);
9998 csum += c;
9999 repeat = c - ' ' + 3; /* Compute repeat count. */
10000
10001 /* The character before ``*'' is repeated. */
10002
10003 if (repeat > 0 && repeat <= 255 && bc > 0)
10004 {
10005 if (bc + repeat - 1 >= buf_p->size () - 1)
10006 {
10007 /* Make some more room in the buffer. */
10008 buf_p->resize (buf_p->size () + repeat);
10009 buf = buf_p->data ();
10010 }
10011
10012 memset (&buf[bc], buf[bc - 1], repeat);
10013 bc += repeat;
10014 continue;
10015 }
10016
10017 buf[bc] = '\0';
10018 gdb_printf (_("Invalid run length encoding: %s\n"), buf);
10019 return -1;
10020 }
10021 default:
10022 if (bc >= buf_p->size () - 1)
10023 {
10024 /* Make some more room in the buffer. */
10025 buf_p->resize (buf_p->size () * 2);
10026 buf = buf_p->data ();
10027 }
10028
10029 buf[bc++] = c;
10030 csum += c;
10031 continue;
10032 }
10033 }
10034 }
10035
10036 /* Set this to the maximum number of seconds to wait instead of waiting forever
10037 in target_wait(). If this timer times out, then it generates an error and
10038 the command is aborted. This replaces most of the need for timeouts in the
10039 GDB test suite, and makes it possible to distinguish between a hung target
10040 and one with slow communications. */
10041
10042 static int watchdog = 0;
10043 static void
10044 show_watchdog (struct ui_file *file, int from_tty,
10045 struct cmd_list_element *c, const char *value)
10046 {
10047 gdb_printf (file, _("Watchdog timer is %s.\n"), value);
10048 }
10049
10050 /* Read a packet from the remote machine, with error checking, and
10051 store it in *BUF. Resize *BUF if necessary to hold the result. If
10052 FOREVER, wait forever rather than timing out; this is used (in
10053 synchronous mode) to wait for a target that is is executing user
10054 code to stop. */
10055 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
10056 don't have to change all the calls to getpkt to deal with the
10057 return value, because at the moment I don't know what the right
10058 thing to do it for those. */
10059
10060 void
10061 remote_target::getpkt (gdb::char_vector *buf, int forever)
10062 {
10063 getpkt_sane (buf, forever);
10064 }
10065
10066
10067 /* Read a packet from the remote machine, with error checking, and
10068 store it in *BUF. Resize *BUF if necessary to hold the result. If
10069 FOREVER, wait forever rather than timing out; this is used (in
10070 synchronous mode) to wait for a target that is is executing user
10071 code to stop. If FOREVER == 0, this function is allowed to time
10072 out gracefully and return an indication of this to the caller.
10073 Otherwise return the number of bytes read. If EXPECTING_NOTIF,
10074 consider receiving a notification enough reason to return to the
10075 caller. *IS_NOTIF is an output boolean that indicates whether *BUF
10076 holds a notification or not (a regular packet). */
10077
10078 int
10079 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
10080 int forever, int expecting_notif,
10081 int *is_notif)
10082 {
10083 struct remote_state *rs = get_remote_state ();
10084 int c;
10085 int tries;
10086 int timeout;
10087 int val = -1;
10088
10089 strcpy (buf->data (), "timeout");
10090
10091 if (forever)
10092 timeout = watchdog > 0 ? watchdog : -1;
10093 else if (expecting_notif)
10094 timeout = 0; /* There should already be a char in the buffer. If
10095 not, bail out. */
10096 else
10097 timeout = remote_timeout;
10098
10099 #define MAX_TRIES 3
10100
10101 /* Process any number of notifications, and then return when
10102 we get a packet. */
10103 for (;;)
10104 {
10105 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
10106 times. */
10107 for (tries = 1; tries <= MAX_TRIES; tries++)
10108 {
10109 /* This can loop forever if the remote side sends us
10110 characters continuously, but if it pauses, we'll get
10111 SERIAL_TIMEOUT from readchar because of timeout. Then
10112 we'll count that as a retry.
10113
10114 Note that even when forever is set, we will only wait
10115 forever prior to the start of a packet. After that, we
10116 expect characters to arrive at a brisk pace. They should
10117 show up within remote_timeout intervals. */
10118 do
10119 c = readchar (timeout);
10120 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
10121
10122 if (c == SERIAL_TIMEOUT)
10123 {
10124 if (expecting_notif)
10125 return -1; /* Don't complain, it's normal to not get
10126 anything in this case. */
10127
10128 if (forever) /* Watchdog went off? Kill the target. */
10129 {
10130 remote_unpush_target (this);
10131 throw_error (TARGET_CLOSE_ERROR,
10132 _("Watchdog timeout has expired. "
10133 "Target detached."));
10134 }
10135
10136 remote_debug_printf ("Timed out.");
10137 }
10138 else
10139 {
10140 /* We've found the start of a packet or notification.
10141 Now collect the data. */
10142 val = read_frame (buf);
10143 if (val >= 0)
10144 break;
10145 }
10146
10147 remote_serial_write ("-", 1);
10148 }
10149
10150 if (tries > MAX_TRIES)
10151 {
10152 /* We have tried hard enough, and just can't receive the
10153 packet/notification. Give up. */
10154 gdb_printf (_("Ignoring packet error, continuing...\n"));
10155
10156 /* Skip the ack char if we're in no-ack mode. */
10157 if (!rs->noack_mode)
10158 remote_serial_write ("+", 1);
10159 return -1;
10160 }
10161
10162 /* If we got an ordinary packet, return that to our caller. */
10163 if (c == '$')
10164 {
10165 if (remote_debug)
10166 {
10167 int max_chars;
10168
10169 if (remote_packet_max_chars < 0)
10170 max_chars = val;
10171 else
10172 max_chars = remote_packet_max_chars;
10173
10174 std::string str
10175 = escape_buffer (buf->data (),
10176 std::min (val, max_chars));
10177
10178 if (val > max_chars)
10179 remote_debug_printf_nofunc
10180 ("Packet received: %s [%d bytes omitted]", str.c_str (),
10181 val - max_chars);
10182 else
10183 remote_debug_printf_nofunc ("Packet received: %s",
10184 str.c_str ());
10185 }
10186
10187 /* Skip the ack char if we're in no-ack mode. */
10188 if (!rs->noack_mode)
10189 remote_serial_write ("+", 1);
10190 if (is_notif != NULL)
10191 *is_notif = 0;
10192 return val;
10193 }
10194
10195 /* If we got a notification, handle it, and go back to looking
10196 for a packet. */
10197 else
10198 {
10199 gdb_assert (c == '%');
10200
10201 remote_debug_printf_nofunc
10202 (" Notification received: %s",
10203 escape_buffer (buf->data (), val).c_str ());
10204
10205 if (is_notif != NULL)
10206 *is_notif = 1;
10207
10208 handle_notification (rs->notif_state, buf->data ());
10209
10210 /* Notifications require no acknowledgement. */
10211
10212 if (expecting_notif)
10213 return val;
10214 }
10215 }
10216 }
10217
10218 int
10219 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
10220 {
10221 return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
10222 }
10223
10224 int
10225 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
10226 int *is_notif)
10227 {
10228 return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
10229 }
10230
10231 /* Kill any new fork children of inferior INF that haven't been
10232 processed by follow_fork. */
10233
10234 void
10235 remote_target::kill_new_fork_children (inferior *inf)
10236 {
10237 remote_state *rs = get_remote_state ();
10238 const notif_client *notif = &notif_client_stop;
10239
10240 /* Kill the fork child threads of any threads in inferior INF that are stopped
10241 at a fork event. */
10242 for (thread_info *thread : inf->non_exited_threads ())
10243 {
10244 const target_waitstatus *ws = thread_pending_fork_status (thread);
10245
10246 if (ws == nullptr)
10247 continue;
10248
10249 int child_pid = ws->child_ptid ().pid ();
10250 int res = remote_vkill (child_pid);
10251
10252 if (res != 0)
10253 error (_("Can't kill fork child process %d"), child_pid);
10254 }
10255
10256 /* Check for any pending fork events (not reported or processed yet)
10257 in inferior INF and kill those fork child threads as well. */
10258 remote_notif_get_pending_events (notif);
10259 for (auto &event : rs->stop_reply_queue)
10260 {
10261 if (event->ptid.pid () != inf->pid)
10262 continue;
10263
10264 if (!is_fork_status (event->ws.kind ()))
10265 continue;
10266
10267 int child_pid = event->ws.child_ptid ().pid ();
10268 int res = remote_vkill (child_pid);
10269
10270 if (res != 0)
10271 error (_("Can't kill fork child process %d"), child_pid);
10272 }
10273 }
10274
10275 \f
10276 /* Target hook to kill the current inferior. */
10277
10278 void
10279 remote_target::kill ()
10280 {
10281 int res = -1;
10282 inferior *inf = find_inferior_pid (this, inferior_ptid.pid ());
10283
10284 gdb_assert (inf != nullptr);
10285
10286 if (m_features.packet_support (PACKET_vKill) != PACKET_DISABLE)
10287 {
10288 /* If we're stopped while forking and we haven't followed yet,
10289 kill the child task. We need to do this before killing the
10290 parent task because if this is a vfork then the parent will
10291 be sleeping. */
10292 kill_new_fork_children (inf);
10293
10294 res = remote_vkill (inf->pid);
10295 if (res == 0)
10296 {
10297 target_mourn_inferior (inferior_ptid);
10298 return;
10299 }
10300 }
10301
10302 /* If we are in 'target remote' mode and we are killing the only
10303 inferior, then we will tell gdbserver to exit and unpush the
10304 target. */
10305 if (res == -1 && !m_features.remote_multi_process_p ()
10306 && number_of_live_inferiors (this) == 1)
10307 {
10308 remote_kill_k ();
10309
10310 /* We've killed the remote end, we get to mourn it. If we are
10311 not in extended mode, mourning the inferior also unpushes
10312 remote_ops from the target stack, which closes the remote
10313 connection. */
10314 target_mourn_inferior (inferior_ptid);
10315
10316 return;
10317 }
10318
10319 error (_("Can't kill process"));
10320 }
10321
10322 /* Send a kill request to the target using the 'vKill' packet. */
10323
10324 int
10325 remote_target::remote_vkill (int pid)
10326 {
10327 if (m_features.packet_support (PACKET_vKill) == PACKET_DISABLE)
10328 return -1;
10329
10330 remote_state *rs = get_remote_state ();
10331
10332 /* Tell the remote target to detach. */
10333 xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
10334 putpkt (rs->buf);
10335 getpkt (&rs->buf, 0);
10336
10337 switch (m_features.packet_ok (rs->buf, PACKET_vKill))
10338 {
10339 case PACKET_OK:
10340 return 0;
10341 case PACKET_ERROR:
10342 return 1;
10343 case PACKET_UNKNOWN:
10344 return -1;
10345 default:
10346 internal_error (_("Bad result from packet_ok"));
10347 }
10348 }
10349
10350 /* Send a kill request to the target using the 'k' packet. */
10351
10352 void
10353 remote_target::remote_kill_k ()
10354 {
10355 /* Catch errors so the user can quit from gdb even when we
10356 aren't on speaking terms with the remote system. */
10357 try
10358 {
10359 putpkt ("k");
10360 }
10361 catch (const gdb_exception_error &ex)
10362 {
10363 if (ex.error == TARGET_CLOSE_ERROR)
10364 {
10365 /* If we got an (EOF) error that caused the target
10366 to go away, then we're done, that's what we wanted.
10367 "k" is susceptible to cause a premature EOF, given
10368 that the remote server isn't actually required to
10369 reply to "k", and it can happen that it doesn't
10370 even get to reply ACK to the "k". */
10371 return;
10372 }
10373
10374 /* Otherwise, something went wrong. We didn't actually kill
10375 the target. Just propagate the exception, and let the
10376 user or higher layers decide what to do. */
10377 throw;
10378 }
10379 }
10380
10381 void
10382 remote_target::mourn_inferior ()
10383 {
10384 struct remote_state *rs = get_remote_state ();
10385
10386 /* We're no longer interested in notification events of an inferior
10387 that exited or was killed/detached. */
10388 discard_pending_stop_replies (current_inferior ());
10389
10390 /* In 'target remote' mode with one inferior, we close the connection. */
10391 if (!rs->extended && number_of_live_inferiors (this) <= 1)
10392 {
10393 remote_unpush_target (this);
10394 return;
10395 }
10396
10397 /* In case we got here due to an error, but we're going to stay
10398 connected. */
10399 rs->waiting_for_stop_reply = 0;
10400
10401 /* If the current general thread belonged to the process we just
10402 detached from or has exited, the remote side current general
10403 thread becomes undefined. Considering a case like this:
10404
10405 - We just got here due to a detach.
10406 - The process that we're detaching from happens to immediately
10407 report a global breakpoint being hit in non-stop mode, in the
10408 same thread we had selected before.
10409 - GDB attaches to this process again.
10410 - This event happens to be the next event we handle.
10411
10412 GDB would consider that the current general thread didn't need to
10413 be set on the stub side (with Hg), since for all it knew,
10414 GENERAL_THREAD hadn't changed.
10415
10416 Notice that although in all-stop mode, the remote server always
10417 sets the current thread to the thread reporting the stop event,
10418 that doesn't happen in non-stop mode; in non-stop, the stub *must
10419 not* change the current thread when reporting a breakpoint hit,
10420 due to the decoupling of event reporting and event handling.
10421
10422 To keep things simple, we always invalidate our notion of the
10423 current thread. */
10424 record_currthread (rs, minus_one_ptid);
10425
10426 /* Call common code to mark the inferior as not running. */
10427 generic_mourn_inferior ();
10428 }
10429
10430 bool
10431 extended_remote_target::supports_disable_randomization ()
10432 {
10433 return (m_features.packet_support (PACKET_QDisableRandomization)
10434 == PACKET_ENABLE);
10435 }
10436
10437 void
10438 remote_target::extended_remote_disable_randomization (int val)
10439 {
10440 struct remote_state *rs = get_remote_state ();
10441 char *reply;
10442
10443 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10444 "QDisableRandomization:%x", val);
10445 putpkt (rs->buf);
10446 reply = remote_get_noisy_reply ();
10447 if (*reply == '\0')
10448 error (_("Target does not support QDisableRandomization."));
10449 if (strcmp (reply, "OK") != 0)
10450 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10451 }
10452
10453 int
10454 remote_target::extended_remote_run (const std::string &args)
10455 {
10456 struct remote_state *rs = get_remote_state ();
10457 int len;
10458 const char *remote_exec_file = get_remote_exec_file ();
10459
10460 /* If the user has disabled vRun support, or we have detected that
10461 support is not available, do not try it. */
10462 if (m_features.packet_support (PACKET_vRun) == PACKET_DISABLE)
10463 return -1;
10464
10465 strcpy (rs->buf.data (), "vRun;");
10466 len = strlen (rs->buf.data ());
10467
10468 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10469 error (_("Remote file name too long for run packet"));
10470 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
10471 strlen (remote_exec_file));
10472
10473 if (!args.empty ())
10474 {
10475 int i;
10476
10477 gdb_argv argv (args.c_str ());
10478 for (i = 0; argv[i] != NULL; i++)
10479 {
10480 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10481 error (_("Argument list too long for run packet"));
10482 rs->buf[len++] = ';';
10483 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
10484 strlen (argv[i]));
10485 }
10486 }
10487
10488 rs->buf[len++] = '\0';
10489
10490 putpkt (rs->buf);
10491 getpkt (&rs->buf, 0);
10492
10493 switch (m_features.packet_ok (rs->buf, PACKET_vRun))
10494 {
10495 case PACKET_OK:
10496 /* We have a wait response. All is well. */
10497 return 0;
10498 case PACKET_UNKNOWN:
10499 return -1;
10500 case PACKET_ERROR:
10501 if (remote_exec_file[0] == '\0')
10502 error (_("Running the default executable on the remote target failed; "
10503 "try \"set remote exec-file\"?"));
10504 else
10505 error (_("Running \"%s\" on the remote target failed"),
10506 remote_exec_file);
10507 default:
10508 gdb_assert_not_reached ("bad switch");
10509 }
10510 }
10511
10512 /* Helper function to send set/unset environment packets. ACTION is
10513 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
10514 or "QEnvironmentUnsetVariable". VALUE is the variable to be
10515 sent. */
10516
10517 void
10518 remote_target::send_environment_packet (const char *action,
10519 const char *packet,
10520 const char *value)
10521 {
10522 remote_state *rs = get_remote_state ();
10523
10524 /* Convert the environment variable to an hex string, which
10525 is the best format to be transmitted over the wire. */
10526 std::string encoded_value = bin2hex ((const gdb_byte *) value,
10527 strlen (value));
10528
10529 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10530 "%s:%s", packet, encoded_value.c_str ());
10531
10532 putpkt (rs->buf);
10533 getpkt (&rs->buf, 0);
10534 if (strcmp (rs->buf.data (), "OK") != 0)
10535 warning (_("Unable to %s environment variable '%s' on remote."),
10536 action, value);
10537 }
10538
10539 /* Helper function to handle the QEnvironment* packets. */
10540
10541 void
10542 remote_target::extended_remote_environment_support ()
10543 {
10544 remote_state *rs = get_remote_state ();
10545
10546 if (m_features.packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10547 {
10548 putpkt ("QEnvironmentReset");
10549 getpkt (&rs->buf, 0);
10550 if (strcmp (rs->buf.data (), "OK") != 0)
10551 warning (_("Unable to reset environment on remote."));
10552 }
10553
10554 gdb_environ *e = &current_inferior ()->environment;
10555
10556 if (m_features.packet_support (PACKET_QEnvironmentHexEncoded)
10557 != PACKET_DISABLE)
10558 {
10559 for (const std::string &el : e->user_set_env ())
10560 send_environment_packet ("set", "QEnvironmentHexEncoded",
10561 el.c_str ());
10562 }
10563
10564
10565 if (m_features.packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10566 for (const std::string &el : e->user_unset_env ())
10567 send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10568 }
10569
10570 /* Helper function to set the current working directory for the
10571 inferior in the remote target. */
10572
10573 void
10574 remote_target::extended_remote_set_inferior_cwd ()
10575 {
10576 if (m_features.packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10577 {
10578 const std::string &inferior_cwd = current_inferior ()->cwd ();
10579 remote_state *rs = get_remote_state ();
10580
10581 if (!inferior_cwd.empty ())
10582 {
10583 std::string hexpath
10584 = bin2hex ((const gdb_byte *) inferior_cwd.data (),
10585 inferior_cwd.size ());
10586
10587 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10588 "QSetWorkingDir:%s", hexpath.c_str ());
10589 }
10590 else
10591 {
10592 /* An empty inferior_cwd means that the user wants us to
10593 reset the remote server's inferior's cwd. */
10594 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10595 "QSetWorkingDir:");
10596 }
10597
10598 putpkt (rs->buf);
10599 getpkt (&rs->buf, 0);
10600 if (m_features.packet_ok (rs->buf, PACKET_QSetWorkingDir) != PACKET_OK)
10601 error (_("\
10602 Remote replied unexpectedly while setting the inferior's working\n\
10603 directory: %s"),
10604 rs->buf.data ());
10605
10606 }
10607 }
10608
10609 /* In the extended protocol we want to be able to do things like
10610 "run" and have them basically work as expected. So we need
10611 a special create_inferior function. We support changing the
10612 executable file and the command line arguments, but not the
10613 environment. */
10614
10615 void
10616 extended_remote_target::create_inferior (const char *exec_file,
10617 const std::string &args,
10618 char **env, int from_tty)
10619 {
10620 int run_worked;
10621 char *stop_reply;
10622 struct remote_state *rs = get_remote_state ();
10623 const char *remote_exec_file = get_remote_exec_file ();
10624
10625 /* If running asynchronously, register the target file descriptor
10626 with the event loop. */
10627 if (target_can_async_p ())
10628 target_async (true);
10629
10630 /* Disable address space randomization if requested (and supported). */
10631 if (supports_disable_randomization ())
10632 extended_remote_disable_randomization (disable_randomization);
10633
10634 /* If startup-with-shell is on, we inform gdbserver to start the
10635 remote inferior using a shell. */
10636 if (m_features.packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10637 {
10638 xsnprintf (rs->buf.data (), get_remote_packet_size (),
10639 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10640 putpkt (rs->buf);
10641 getpkt (&rs->buf, 0);
10642 if (strcmp (rs->buf.data (), "OK") != 0)
10643 error (_("\
10644 Remote replied unexpectedly while setting startup-with-shell: %s"),
10645 rs->buf.data ());
10646 }
10647
10648 extended_remote_environment_support ();
10649
10650 extended_remote_set_inferior_cwd ();
10651
10652 /* Now restart the remote server. */
10653 run_worked = extended_remote_run (args) != -1;
10654 if (!run_worked)
10655 {
10656 /* vRun was not supported. Fail if we need it to do what the
10657 user requested. */
10658 if (remote_exec_file[0])
10659 error (_("Remote target does not support \"set remote exec-file\""));
10660 if (!args.empty ())
10661 error (_("Remote target does not support \"set args\" or run ARGS"));
10662
10663 /* Fall back to "R". */
10664 extended_remote_restart ();
10665 }
10666
10667 /* vRun's success return is a stop reply. */
10668 stop_reply = run_worked ? rs->buf.data () : NULL;
10669 add_current_inferior_and_thread (stop_reply);
10670
10671 /* Get updated offsets, if the stub uses qOffsets. */
10672 get_offsets ();
10673 }
10674 \f
10675
10676 /* Given a location's target info BP_TGT and the packet buffer BUF, output
10677 the list of conditions (in agent expression bytecode format), if any, the
10678 target needs to evaluate. The output is placed into the packet buffer
10679 started from BUF and ended at BUF_END. */
10680
10681 static int
10682 remote_add_target_side_condition (struct gdbarch *gdbarch,
10683 struct bp_target_info *bp_tgt, char *buf,
10684 char *buf_end)
10685 {
10686 if (bp_tgt->conditions.empty ())
10687 return 0;
10688
10689 buf += strlen (buf);
10690 xsnprintf (buf, buf_end - buf, "%s", ";");
10691 buf++;
10692
10693 /* Send conditions to the target. */
10694 for (agent_expr *aexpr : bp_tgt->conditions)
10695 {
10696 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10697 buf += strlen (buf);
10698 for (int i = 0; i < aexpr->len; ++i)
10699 buf = pack_hex_byte (buf, aexpr->buf[i]);
10700 *buf = '\0';
10701 }
10702 return 0;
10703 }
10704
10705 static void
10706 remote_add_target_side_commands (struct gdbarch *gdbarch,
10707 struct bp_target_info *bp_tgt, char *buf)
10708 {
10709 if (bp_tgt->tcommands.empty ())
10710 return;
10711
10712 buf += strlen (buf);
10713
10714 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10715 buf += strlen (buf);
10716
10717 /* Concatenate all the agent expressions that are commands into the
10718 cmds parameter. */
10719 for (agent_expr *aexpr : bp_tgt->tcommands)
10720 {
10721 sprintf (buf, "X%x,", aexpr->len);
10722 buf += strlen (buf);
10723 for (int i = 0; i < aexpr->len; ++i)
10724 buf = pack_hex_byte (buf, aexpr->buf[i]);
10725 *buf = '\0';
10726 }
10727 }
10728
10729 /* Insert a breakpoint. On targets that have software breakpoint
10730 support, we ask the remote target to do the work; on targets
10731 which don't, we insert a traditional memory breakpoint. */
10732
10733 int
10734 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10735 struct bp_target_info *bp_tgt)
10736 {
10737 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10738 If it succeeds, then set the support to PACKET_ENABLE. If it
10739 fails, and the user has explicitly requested the Z support then
10740 report an error, otherwise, mark it disabled and go on. */
10741
10742 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10743 {
10744 CORE_ADDR addr = bp_tgt->reqstd_address;
10745 struct remote_state *rs;
10746 char *p, *endbuf;
10747
10748 /* Make sure the remote is pointing at the right process, if
10749 necessary. */
10750 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10751 set_general_process ();
10752
10753 rs = get_remote_state ();
10754 p = rs->buf.data ();
10755 endbuf = p + get_remote_packet_size ();
10756
10757 *(p++) = 'Z';
10758 *(p++) = '0';
10759 *(p++) = ',';
10760 addr = (ULONGEST) remote_address_masked (addr);
10761 p += hexnumstr (p, addr);
10762 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10763
10764 if (supports_evaluation_of_breakpoint_conditions ())
10765 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10766
10767 if (can_run_breakpoint_commands ())
10768 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10769
10770 putpkt (rs->buf);
10771 getpkt (&rs->buf, 0);
10772
10773 switch (m_features.packet_ok (rs->buf, PACKET_Z0))
10774 {
10775 case PACKET_ERROR:
10776 return -1;
10777 case PACKET_OK:
10778 return 0;
10779 case PACKET_UNKNOWN:
10780 break;
10781 }
10782 }
10783
10784 /* If this breakpoint has target-side commands but this stub doesn't
10785 support Z0 packets, throw error. */
10786 if (!bp_tgt->tcommands.empty ())
10787 throw_error (NOT_SUPPORTED_ERROR, _("\
10788 Target doesn't support breakpoints that have target side commands."));
10789
10790 return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10791 }
10792
10793 int
10794 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10795 struct bp_target_info *bp_tgt,
10796 enum remove_bp_reason reason)
10797 {
10798 CORE_ADDR addr = bp_tgt->placed_address;
10799 struct remote_state *rs = get_remote_state ();
10800
10801 if (m_features.packet_support (PACKET_Z0) != PACKET_DISABLE)
10802 {
10803 char *p = rs->buf.data ();
10804 char *endbuf = p + get_remote_packet_size ();
10805
10806 /* Make sure the remote is pointing at the right process, if
10807 necessary. */
10808 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10809 set_general_process ();
10810
10811 *(p++) = 'z';
10812 *(p++) = '0';
10813 *(p++) = ',';
10814
10815 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10816 p += hexnumstr (p, addr);
10817 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10818
10819 putpkt (rs->buf);
10820 getpkt (&rs->buf, 0);
10821
10822 return (rs->buf[0] == 'E');
10823 }
10824
10825 return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10826 }
10827
10828 static enum Z_packet_type
10829 watchpoint_to_Z_packet (int type)
10830 {
10831 switch (type)
10832 {
10833 case hw_write:
10834 return Z_PACKET_WRITE_WP;
10835 break;
10836 case hw_read:
10837 return Z_PACKET_READ_WP;
10838 break;
10839 case hw_access:
10840 return Z_PACKET_ACCESS_WP;
10841 break;
10842 default:
10843 internal_error (_("hw_bp_to_z: bad watchpoint type %d"), type);
10844 }
10845 }
10846
10847 int
10848 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10849 enum target_hw_bp_type type, struct expression *cond)
10850 {
10851 struct remote_state *rs = get_remote_state ();
10852 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10853 char *p;
10854 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10855
10856 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10857 return 1;
10858
10859 /* Make sure the remote is pointing at the right process, if
10860 necessary. */
10861 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10862 set_general_process ();
10863
10864 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10865 p = strchr (rs->buf.data (), '\0');
10866 addr = remote_address_masked (addr);
10867 p += hexnumstr (p, (ULONGEST) addr);
10868 xsnprintf (p, endbuf - p, ",%x", len);
10869
10870 putpkt (rs->buf);
10871 getpkt (&rs->buf, 0);
10872
10873 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
10874 {
10875 case PACKET_ERROR:
10876 return -1;
10877 case PACKET_UNKNOWN:
10878 return 1;
10879 case PACKET_OK:
10880 return 0;
10881 }
10882 internal_error (_("remote_insert_watchpoint: reached end of function"));
10883 }
10884
10885 bool
10886 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10887 CORE_ADDR start, int length)
10888 {
10889 CORE_ADDR diff = remote_address_masked (addr - start);
10890
10891 return diff < length;
10892 }
10893
10894
10895 int
10896 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10897 enum target_hw_bp_type type, struct expression *cond)
10898 {
10899 struct remote_state *rs = get_remote_state ();
10900 char *endbuf = rs->buf.data () + get_remote_packet_size ();
10901 char *p;
10902 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10903
10904 if (m_features.packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10905 return -1;
10906
10907 /* Make sure the remote is pointing at the right process, if
10908 necessary. */
10909 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10910 set_general_process ();
10911
10912 xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10913 p = strchr (rs->buf.data (), '\0');
10914 addr = remote_address_masked (addr);
10915 p += hexnumstr (p, (ULONGEST) addr);
10916 xsnprintf (p, endbuf - p, ",%x", len);
10917 putpkt (rs->buf);
10918 getpkt (&rs->buf, 0);
10919
10920 switch (m_features.packet_ok (rs->buf, PACKET_Z0 + packet))
10921 {
10922 case PACKET_ERROR:
10923 case PACKET_UNKNOWN:
10924 return -1;
10925 case PACKET_OK:
10926 return 0;
10927 }
10928 internal_error (_("remote_remove_watchpoint: reached end of function"));
10929 }
10930
10931
10932 static int remote_hw_watchpoint_limit = -1;
10933 static int remote_hw_watchpoint_length_limit = -1;
10934 static int remote_hw_breakpoint_limit = -1;
10935
10936 int
10937 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10938 {
10939 if (remote_hw_watchpoint_length_limit == 0)
10940 return 0;
10941 else if (remote_hw_watchpoint_length_limit < 0)
10942 return 1;
10943 else if (len <= remote_hw_watchpoint_length_limit)
10944 return 1;
10945 else
10946 return 0;
10947 }
10948
10949 int
10950 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10951 {
10952 if (type == bp_hardware_breakpoint)
10953 {
10954 if (remote_hw_breakpoint_limit == 0)
10955 return 0;
10956 else if (remote_hw_breakpoint_limit < 0)
10957 return 1;
10958 else if (cnt <= remote_hw_breakpoint_limit)
10959 return 1;
10960 }
10961 else
10962 {
10963 if (remote_hw_watchpoint_limit == 0)
10964 return 0;
10965 else if (remote_hw_watchpoint_limit < 0)
10966 return 1;
10967 else if (ot)
10968 return -1;
10969 else if (cnt <= remote_hw_watchpoint_limit)
10970 return 1;
10971 }
10972 return -1;
10973 }
10974
10975 /* The to_stopped_by_sw_breakpoint method of target remote. */
10976
10977 bool
10978 remote_target::stopped_by_sw_breakpoint ()
10979 {
10980 struct thread_info *thread = inferior_thread ();
10981
10982 return (thread->priv != NULL
10983 && (get_remote_thread_info (thread)->stop_reason
10984 == TARGET_STOPPED_BY_SW_BREAKPOINT));
10985 }
10986
10987 /* The to_supports_stopped_by_sw_breakpoint method of target
10988 remote. */
10989
10990 bool
10991 remote_target::supports_stopped_by_sw_breakpoint ()
10992 {
10993 return (m_features.packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10994 }
10995
10996 /* The to_stopped_by_hw_breakpoint method of target remote. */
10997
10998 bool
10999 remote_target::stopped_by_hw_breakpoint ()
11000 {
11001 struct thread_info *thread = inferior_thread ();
11002
11003 return (thread->priv != NULL
11004 && (get_remote_thread_info (thread)->stop_reason
11005 == TARGET_STOPPED_BY_HW_BREAKPOINT));
11006 }
11007
11008 /* The to_supports_stopped_by_hw_breakpoint method of target
11009 remote. */
11010
11011 bool
11012 remote_target::supports_stopped_by_hw_breakpoint ()
11013 {
11014 return (m_features.packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
11015 }
11016
11017 bool
11018 remote_target::stopped_by_watchpoint ()
11019 {
11020 struct thread_info *thread = inferior_thread ();
11021
11022 return (thread->priv != NULL
11023 && (get_remote_thread_info (thread)->stop_reason
11024 == TARGET_STOPPED_BY_WATCHPOINT));
11025 }
11026
11027 bool
11028 remote_target::stopped_data_address (CORE_ADDR *addr_p)
11029 {
11030 struct thread_info *thread = inferior_thread ();
11031
11032 if (thread->priv != NULL
11033 && (get_remote_thread_info (thread)->stop_reason
11034 == TARGET_STOPPED_BY_WATCHPOINT))
11035 {
11036 *addr_p = get_remote_thread_info (thread)->watch_data_address;
11037 return true;
11038 }
11039
11040 return false;
11041 }
11042
11043
11044 int
11045 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
11046 struct bp_target_info *bp_tgt)
11047 {
11048 CORE_ADDR addr = bp_tgt->reqstd_address;
11049 struct remote_state *rs;
11050 char *p, *endbuf;
11051 char *message;
11052
11053 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11054 return -1;
11055
11056 /* Make sure the remote is pointing at the right process, if
11057 necessary. */
11058 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11059 set_general_process ();
11060
11061 rs = get_remote_state ();
11062 p = rs->buf.data ();
11063 endbuf = p + get_remote_packet_size ();
11064
11065 *(p++) = 'Z';
11066 *(p++) = '1';
11067 *(p++) = ',';
11068
11069 addr = remote_address_masked (addr);
11070 p += hexnumstr (p, (ULONGEST) addr);
11071 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11072
11073 if (supports_evaluation_of_breakpoint_conditions ())
11074 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
11075
11076 if (can_run_breakpoint_commands ())
11077 remote_add_target_side_commands (gdbarch, bp_tgt, p);
11078
11079 putpkt (rs->buf);
11080 getpkt (&rs->buf, 0);
11081
11082 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11083 {
11084 case PACKET_ERROR:
11085 if (rs->buf[1] == '.')
11086 {
11087 message = strchr (&rs->buf[2], '.');
11088 if (message)
11089 error (_("Remote failure reply: %s"), message + 1);
11090 }
11091 return -1;
11092 case PACKET_UNKNOWN:
11093 return -1;
11094 case PACKET_OK:
11095 return 0;
11096 }
11097 internal_error (_("remote_insert_hw_breakpoint: reached end of function"));
11098 }
11099
11100
11101 int
11102 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
11103 struct bp_target_info *bp_tgt)
11104 {
11105 CORE_ADDR addr;
11106 struct remote_state *rs = get_remote_state ();
11107 char *p = rs->buf.data ();
11108 char *endbuf = p + get_remote_packet_size ();
11109
11110 if (m_features.packet_support (PACKET_Z1) == PACKET_DISABLE)
11111 return -1;
11112
11113 /* Make sure the remote is pointing at the right process, if
11114 necessary. */
11115 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
11116 set_general_process ();
11117
11118 *(p++) = 'z';
11119 *(p++) = '1';
11120 *(p++) = ',';
11121
11122 addr = remote_address_masked (bp_tgt->placed_address);
11123 p += hexnumstr (p, (ULONGEST) addr);
11124 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
11125
11126 putpkt (rs->buf);
11127 getpkt (&rs->buf, 0);
11128
11129 switch (m_features.packet_ok (rs->buf, PACKET_Z1))
11130 {
11131 case PACKET_ERROR:
11132 case PACKET_UNKNOWN:
11133 return -1;
11134 case PACKET_OK:
11135 return 0;
11136 }
11137 internal_error (_("remote_remove_hw_breakpoint: reached end of function"));
11138 }
11139
11140 /* Verify memory using the "qCRC:" request. */
11141
11142 int
11143 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
11144 {
11145 struct remote_state *rs = get_remote_state ();
11146 unsigned long host_crc, target_crc;
11147 char *tmp;
11148
11149 /* It doesn't make sense to use qCRC if the remote target is
11150 connected but not running. */
11151 if (target_has_execution ()
11152 && m_features.packet_support (PACKET_qCRC) != PACKET_DISABLE)
11153 {
11154 enum packet_result result;
11155
11156 /* Make sure the remote is pointing at the right process. */
11157 set_general_process ();
11158
11159 /* FIXME: assumes lma can fit into long. */
11160 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
11161 (long) lma, (long) size);
11162 putpkt (rs->buf);
11163
11164 /* Be clever; compute the host_crc before waiting for target
11165 reply. */
11166 host_crc = xcrc32 (data, size, 0xffffffff);
11167
11168 getpkt (&rs->buf, 0);
11169
11170 result = m_features.packet_ok (rs->buf, PACKET_qCRC);
11171 if (result == PACKET_ERROR)
11172 return -1;
11173 else if (result == PACKET_OK)
11174 {
11175 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
11176 target_crc = target_crc * 16 + fromhex (*tmp);
11177
11178 return (host_crc == target_crc);
11179 }
11180 }
11181
11182 return simple_verify_memory (this, data, lma, size);
11183 }
11184
11185 /* compare-sections command
11186
11187 With no arguments, compares each loadable section in the exec bfd
11188 with the same memory range on the target, and reports mismatches.
11189 Useful for verifying the image on the target against the exec file. */
11190
11191 static void
11192 compare_sections_command (const char *args, int from_tty)
11193 {
11194 asection *s;
11195 const char *sectname;
11196 bfd_size_type size;
11197 bfd_vma lma;
11198 int matched = 0;
11199 int mismatched = 0;
11200 int res;
11201 int read_only = 0;
11202
11203 if (!current_program_space->exec_bfd ())
11204 error (_("command cannot be used without an exec file"));
11205
11206 if (args != NULL && strcmp (args, "-r") == 0)
11207 {
11208 read_only = 1;
11209 args = NULL;
11210 }
11211
11212 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
11213 {
11214 if (!(s->flags & SEC_LOAD))
11215 continue; /* Skip non-loadable section. */
11216
11217 if (read_only && (s->flags & SEC_READONLY) == 0)
11218 continue; /* Skip writeable sections */
11219
11220 size = bfd_section_size (s);
11221 if (size == 0)
11222 continue; /* Skip zero-length section. */
11223
11224 sectname = bfd_section_name (s);
11225 if (args && strcmp (args, sectname) != 0)
11226 continue; /* Not the section selected by user. */
11227
11228 matched = 1; /* Do this section. */
11229 lma = s->lma;
11230
11231 gdb::byte_vector sectdata (size);
11232 bfd_get_section_contents (current_program_space->exec_bfd (), s,
11233 sectdata.data (), 0, size);
11234
11235 res = target_verify_memory (sectdata.data (), lma, size);
11236
11237 if (res == -1)
11238 error (_("target memory fault, section %s, range %s -- %s"), sectname,
11239 paddress (target_gdbarch (), lma),
11240 paddress (target_gdbarch (), lma + size));
11241
11242 gdb_printf ("Section %s, range %s -- %s: ", sectname,
11243 paddress (target_gdbarch (), lma),
11244 paddress (target_gdbarch (), lma + size));
11245 if (res)
11246 gdb_printf ("matched.\n");
11247 else
11248 {
11249 gdb_printf ("MIS-MATCHED!\n");
11250 mismatched++;
11251 }
11252 }
11253 if (mismatched > 0)
11254 warning (_("One or more sections of the target image does "
11255 "not match the loaded file"));
11256 if (args && !matched)
11257 gdb_printf (_("No loaded section named '%s'.\n"), args);
11258 }
11259
11260 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
11261 into remote target. The number of bytes written to the remote
11262 target is returned, or -1 for error. */
11263
11264 target_xfer_status
11265 remote_target::remote_write_qxfer (const char *object_name,
11266 const char *annex, const gdb_byte *writebuf,
11267 ULONGEST offset, LONGEST len,
11268 ULONGEST *xfered_len,
11269 const unsigned int which_packet)
11270 {
11271 int i, buf_len;
11272 ULONGEST n;
11273 struct remote_state *rs = get_remote_state ();
11274 int max_size = get_memory_write_packet_size ();
11275
11276 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11277 return TARGET_XFER_E_IO;
11278
11279 /* Insert header. */
11280 i = snprintf (rs->buf.data (), max_size,
11281 "qXfer:%s:write:%s:%s:",
11282 object_name, annex ? annex : "",
11283 phex_nz (offset, sizeof offset));
11284 max_size -= (i + 1);
11285
11286 /* Escape as much data as fits into rs->buf. */
11287 buf_len = remote_escape_output
11288 (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
11289
11290 if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
11291 || getpkt_sane (&rs->buf, 0) < 0
11292 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11293 return TARGET_XFER_E_IO;
11294
11295 unpack_varlen_hex (rs->buf.data (), &n);
11296
11297 *xfered_len = n;
11298 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11299 }
11300
11301 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
11302 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
11303 number of bytes read is returned, or 0 for EOF, or -1 for error.
11304 The number of bytes read may be less than LEN without indicating an
11305 EOF. PACKET is checked and updated to indicate whether the remote
11306 target supports this object. */
11307
11308 target_xfer_status
11309 remote_target::remote_read_qxfer (const char *object_name,
11310 const char *annex,
11311 gdb_byte *readbuf, ULONGEST offset,
11312 LONGEST len,
11313 ULONGEST *xfered_len,
11314 const unsigned int which_packet)
11315 {
11316 struct remote_state *rs = get_remote_state ();
11317 LONGEST i, n, packet_len;
11318
11319 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
11320 return TARGET_XFER_E_IO;
11321
11322 /* Check whether we've cached an end-of-object packet that matches
11323 this request. */
11324 if (rs->finished_object)
11325 {
11326 if (strcmp (object_name, rs->finished_object) == 0
11327 && strcmp (annex ? annex : "", rs->finished_annex) == 0
11328 && offset == rs->finished_offset)
11329 return TARGET_XFER_EOF;
11330
11331
11332 /* Otherwise, we're now reading something different. Discard
11333 the cache. */
11334 xfree (rs->finished_object);
11335 xfree (rs->finished_annex);
11336 rs->finished_object = NULL;
11337 rs->finished_annex = NULL;
11338 }
11339
11340 /* Request only enough to fit in a single packet. The actual data
11341 may not, since we don't know how much of it will need to be escaped;
11342 the target is free to respond with slightly less data. We subtract
11343 five to account for the response type and the protocol frame. */
11344 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
11345 snprintf (rs->buf.data (), get_remote_packet_size () - 4,
11346 "qXfer:%s:read:%s:%s,%s",
11347 object_name, annex ? annex : "",
11348 phex_nz (offset, sizeof offset),
11349 phex_nz (n, sizeof n));
11350 i = putpkt (rs->buf);
11351 if (i < 0)
11352 return TARGET_XFER_E_IO;
11353
11354 rs->buf[0] = '\0';
11355 packet_len = getpkt_sane (&rs->buf, 0);
11356 if (packet_len < 0
11357 || m_features.packet_ok (rs->buf, which_packet) != PACKET_OK)
11358 return TARGET_XFER_E_IO;
11359
11360 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
11361 error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
11362
11363 /* 'm' means there is (or at least might be) more data after this
11364 batch. That does not make sense unless there's at least one byte
11365 of data in this reply. */
11366 if (rs->buf[0] == 'm' && packet_len == 1)
11367 error (_("Remote qXfer reply contained no data."));
11368
11369 /* Got some data. */
11370 i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
11371 packet_len - 1, readbuf, n);
11372
11373 /* 'l' is an EOF marker, possibly including a final block of data,
11374 or possibly empty. If we have the final block of a non-empty
11375 object, record this fact to bypass a subsequent partial read. */
11376 if (rs->buf[0] == 'l' && offset + i > 0)
11377 {
11378 rs->finished_object = xstrdup (object_name);
11379 rs->finished_annex = xstrdup (annex ? annex : "");
11380 rs->finished_offset = offset + i;
11381 }
11382
11383 if (i == 0)
11384 return TARGET_XFER_EOF;
11385 else
11386 {
11387 *xfered_len = i;
11388 return TARGET_XFER_OK;
11389 }
11390 }
11391
11392 enum target_xfer_status
11393 remote_target::xfer_partial (enum target_object object,
11394 const char *annex, gdb_byte *readbuf,
11395 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11396 ULONGEST *xfered_len)
11397 {
11398 struct remote_state *rs;
11399 int i;
11400 char *p2;
11401 char query_type;
11402 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11403
11404 set_remote_traceframe ();
11405 set_general_thread (inferior_ptid);
11406
11407 rs = get_remote_state ();
11408
11409 /* Handle memory using the standard memory routines. */
11410 if (object == TARGET_OBJECT_MEMORY)
11411 {
11412 /* If the remote target is connected but not running, we should
11413 pass this request down to a lower stratum (e.g. the executable
11414 file). */
11415 if (!target_has_execution ())
11416 return TARGET_XFER_EOF;
11417
11418 if (writebuf != NULL)
11419 return remote_write_bytes (offset, writebuf, len, unit_size,
11420 xfered_len);
11421 else
11422 return remote_read_bytes (offset, readbuf, len, unit_size,
11423 xfered_len);
11424 }
11425
11426 /* Handle extra signal info using qxfer packets. */
11427 if (object == TARGET_OBJECT_SIGNAL_INFO)
11428 {
11429 if (readbuf)
11430 return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11431 xfered_len, PACKET_qXfer_siginfo_read);
11432 else
11433 return remote_write_qxfer ("siginfo", annex, writebuf, offset, len,
11434 xfered_len, PACKET_qXfer_siginfo_write);
11435 }
11436
11437 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11438 {
11439 if (readbuf)
11440 return remote_read_qxfer ("statictrace", annex,
11441 readbuf, offset, len, xfered_len,
11442 PACKET_qXfer_statictrace_read);
11443 else
11444 return TARGET_XFER_E_IO;
11445 }
11446
11447 /* Only handle flash writes. */
11448 if (writebuf != NULL)
11449 {
11450 switch (object)
11451 {
11452 case TARGET_OBJECT_FLASH:
11453 return remote_flash_write (offset, len, xfered_len,
11454 writebuf);
11455
11456 default:
11457 return TARGET_XFER_E_IO;
11458 }
11459 }
11460
11461 /* Map pre-existing objects onto letters. DO NOT do this for new
11462 objects!!! Instead specify new query packets. */
11463 switch (object)
11464 {
11465 case TARGET_OBJECT_AVR:
11466 query_type = 'R';
11467 break;
11468
11469 case TARGET_OBJECT_AUXV:
11470 gdb_assert (annex == NULL);
11471 return remote_read_qxfer
11472 ("auxv", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_auxv);
11473
11474 case TARGET_OBJECT_AVAILABLE_FEATURES:
11475 return remote_read_qxfer
11476 ("features", annex, readbuf, offset, len, xfered_len,
11477 PACKET_qXfer_features);
11478
11479 case TARGET_OBJECT_LIBRARIES:
11480 return remote_read_qxfer
11481 ("libraries", annex, readbuf, offset, len, xfered_len,
11482 PACKET_qXfer_libraries);
11483
11484 case TARGET_OBJECT_LIBRARIES_SVR4:
11485 return remote_read_qxfer
11486 ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11487 PACKET_qXfer_libraries_svr4);
11488
11489 case TARGET_OBJECT_MEMORY_MAP:
11490 gdb_assert (annex == NULL);
11491 return remote_read_qxfer
11492 ("memory-map", annex, readbuf, offset, len, xfered_len,
11493 PACKET_qXfer_memory_map);
11494
11495 case TARGET_OBJECT_OSDATA:
11496 /* Should only get here if we're connected. */
11497 gdb_assert (rs->remote_desc);
11498 return remote_read_qxfer
11499 ("osdata", annex, readbuf, offset, len, xfered_len,
11500 PACKET_qXfer_osdata);
11501
11502 case TARGET_OBJECT_THREADS:
11503 gdb_assert (annex == NULL);
11504 return remote_read_qxfer
11505 ("threads", annex, readbuf, offset, len, xfered_len,
11506 PACKET_qXfer_threads);
11507
11508 case TARGET_OBJECT_TRACEFRAME_INFO:
11509 gdb_assert (annex == NULL);
11510 return remote_read_qxfer
11511 ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11512 PACKET_qXfer_traceframe_info);
11513
11514 case TARGET_OBJECT_FDPIC:
11515 return remote_read_qxfer
11516 ("fdpic", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_fdpic);
11517
11518 case TARGET_OBJECT_OPENVMS_UIB:
11519 return remote_read_qxfer
11520 ("uib", annex, readbuf, offset, len, xfered_len, PACKET_qXfer_uib);
11521
11522 case TARGET_OBJECT_BTRACE:
11523 return remote_read_qxfer
11524 ("btrace", annex, readbuf, offset, len, xfered_len,
11525 PACKET_qXfer_btrace);
11526
11527 case TARGET_OBJECT_BTRACE_CONF:
11528 return remote_read_qxfer
11529 ("btrace-conf", annex, readbuf, offset, len, xfered_len,
11530 PACKET_qXfer_btrace_conf);
11531
11532 case TARGET_OBJECT_EXEC_FILE:
11533 return remote_read_qxfer
11534 ("exec-file", annex, readbuf, offset, len, xfered_len,
11535 PACKET_qXfer_exec_file);
11536
11537 default:
11538 return TARGET_XFER_E_IO;
11539 }
11540
11541 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
11542 large enough let the caller deal with it. */
11543 if (len < get_remote_packet_size ())
11544 return TARGET_XFER_E_IO;
11545 len = get_remote_packet_size ();
11546
11547 /* Except for querying the minimum buffer size, target must be open. */
11548 if (!rs->remote_desc)
11549 error (_("remote query is only available after target open"));
11550
11551 gdb_assert (annex != NULL);
11552 gdb_assert (readbuf != NULL);
11553
11554 p2 = rs->buf.data ();
11555 *p2++ = 'q';
11556 *p2++ = query_type;
11557
11558 /* We used one buffer char for the remote protocol q command and
11559 another for the query type. As the remote protocol encapsulation
11560 uses 4 chars plus one extra in case we are debugging
11561 (remote_debug), we have PBUFZIZ - 7 left to pack the query
11562 string. */
11563 i = 0;
11564 while (annex[i] && (i < (get_remote_packet_size () - 8)))
11565 {
11566 /* Bad caller may have sent forbidden characters. */
11567 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11568 *p2++ = annex[i];
11569 i++;
11570 }
11571 *p2 = '\0';
11572 gdb_assert (annex[i] == '\0');
11573
11574 i = putpkt (rs->buf);
11575 if (i < 0)
11576 return TARGET_XFER_E_IO;
11577
11578 getpkt (&rs->buf, 0);
11579 strcpy ((char *) readbuf, rs->buf.data ());
11580
11581 *xfered_len = strlen ((char *) readbuf);
11582 return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11583 }
11584
11585 /* Implementation of to_get_memory_xfer_limit. */
11586
11587 ULONGEST
11588 remote_target::get_memory_xfer_limit ()
11589 {
11590 return get_memory_write_packet_size ();
11591 }
11592
11593 int
11594 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11595 const gdb_byte *pattern, ULONGEST pattern_len,
11596 CORE_ADDR *found_addrp)
11597 {
11598 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11599 struct remote_state *rs = get_remote_state ();
11600 int max_size = get_memory_write_packet_size ();
11601
11602 /* Number of packet bytes used to encode the pattern;
11603 this could be more than PATTERN_LEN due to escape characters. */
11604 int escaped_pattern_len;
11605 /* Amount of pattern that was encodable in the packet. */
11606 int used_pattern_len;
11607 int i;
11608 int found;
11609 ULONGEST found_addr;
11610
11611 auto read_memory = [=] (CORE_ADDR addr, gdb_byte *result, size_t len)
11612 {
11613 return (target_read (this, TARGET_OBJECT_MEMORY, NULL, result, addr, len)
11614 == len);
11615 };
11616
11617 /* Don't go to the target if we don't have to. This is done before
11618 checking packet_support to avoid the possibility that a success for this
11619 edge case means the facility works in general. */
11620 if (pattern_len > search_space_len)
11621 return 0;
11622 if (pattern_len == 0)
11623 {
11624 *found_addrp = start_addr;
11625 return 1;
11626 }
11627
11628 /* If we already know the packet isn't supported, fall back to the simple
11629 way of searching memory. */
11630
11631 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11632 {
11633 /* Target doesn't provided special support, fall back and use the
11634 standard support (copy memory and do the search here). */
11635 return simple_search_memory (read_memory, start_addr, search_space_len,
11636 pattern, pattern_len, found_addrp);
11637 }
11638
11639 /* Make sure the remote is pointing at the right process. */
11640 set_general_process ();
11641
11642 /* Insert header. */
11643 i = snprintf (rs->buf.data (), max_size,
11644 "qSearch:memory:%s;%s;",
11645 phex_nz (start_addr, addr_size),
11646 phex_nz (search_space_len, sizeof (search_space_len)));
11647 max_size -= (i + 1);
11648
11649 /* Escape as much data as fits into rs->buf. */
11650 escaped_pattern_len =
11651 remote_escape_output (pattern, pattern_len, 1,
11652 (gdb_byte *) rs->buf.data () + i,
11653 &used_pattern_len, max_size);
11654
11655 /* Bail if the pattern is too large. */
11656 if (used_pattern_len != pattern_len)
11657 error (_("Pattern is too large to transmit to remote target."));
11658
11659 if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11660 || getpkt_sane (&rs->buf, 0) < 0
11661 || m_features.packet_ok (rs->buf, PACKET_qSearch_memory) != PACKET_OK)
11662 {
11663 /* The request may not have worked because the command is not
11664 supported. If so, fall back to the simple way. */
11665 if (m_features.packet_support (PACKET_qSearch_memory) == PACKET_DISABLE)
11666 {
11667 return simple_search_memory (read_memory, start_addr, search_space_len,
11668 pattern, pattern_len, found_addrp);
11669 }
11670 return -1;
11671 }
11672
11673 if (rs->buf[0] == '0')
11674 found = 0;
11675 else if (rs->buf[0] == '1')
11676 {
11677 found = 1;
11678 if (rs->buf[1] != ',')
11679 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11680 unpack_varlen_hex (&rs->buf[2], &found_addr);
11681 *found_addrp = found_addr;
11682 }
11683 else
11684 error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11685
11686 return found;
11687 }
11688
11689 void
11690 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11691 {
11692 struct remote_state *rs = get_remote_state ();
11693 char *p = rs->buf.data ();
11694
11695 if (!rs->remote_desc)
11696 error (_("remote rcmd is only available after target open"));
11697
11698 /* Send a NULL command across as an empty command. */
11699 if (command == NULL)
11700 command = "";
11701
11702 /* The query prefix. */
11703 strcpy (rs->buf.data (), "qRcmd,");
11704 p = strchr (rs->buf.data (), '\0');
11705
11706 if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11707 > get_remote_packet_size ())
11708 error (_("\"monitor\" command ``%s'' is too long."), command);
11709
11710 /* Encode the actual command. */
11711 bin2hex ((const gdb_byte *) command, p, strlen (command));
11712
11713 if (putpkt (rs->buf) < 0)
11714 error (_("Communication problem with target."));
11715
11716 /* get/display the response */
11717 while (1)
11718 {
11719 char *buf;
11720
11721 /* XXX - see also remote_get_noisy_reply(). */
11722 QUIT; /* Allow user to bail out with ^C. */
11723 rs->buf[0] = '\0';
11724 if (getpkt_sane (&rs->buf, 0) == -1)
11725 {
11726 /* Timeout. Continue to (try to) read responses.
11727 This is better than stopping with an error, assuming the stub
11728 is still executing the (long) monitor command.
11729 If needed, the user can interrupt gdb using C-c, obtaining
11730 an effect similar to stop on timeout. */
11731 continue;
11732 }
11733 buf = rs->buf.data ();
11734 if (buf[0] == '\0')
11735 error (_("Target does not support this command."));
11736 if (buf[0] == 'O' && buf[1] != 'K')
11737 {
11738 remote_console_output (buf + 1); /* 'O' message from stub. */
11739 continue;
11740 }
11741 if (strcmp (buf, "OK") == 0)
11742 break;
11743 if (strlen (buf) == 3 && buf[0] == 'E'
11744 && isxdigit (buf[1]) && isxdigit (buf[2]))
11745 {
11746 error (_("Protocol error with Rcmd"));
11747 }
11748 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11749 {
11750 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11751
11752 gdb_putc (c, outbuf);
11753 }
11754 break;
11755 }
11756 }
11757
11758 std::vector<mem_region>
11759 remote_target::memory_map ()
11760 {
11761 std::vector<mem_region> result;
11762 gdb::optional<gdb::char_vector> text
11763 = target_read_stralloc (current_inferior ()->top_target (),
11764 TARGET_OBJECT_MEMORY_MAP, NULL);
11765
11766 if (text)
11767 result = parse_memory_map (text->data ());
11768
11769 return result;
11770 }
11771
11772 /* Set of callbacks used to implement the 'maint packet' command. */
11773
11774 struct cli_packet_command_callbacks : public send_remote_packet_callbacks
11775 {
11776 /* Called before the packet is sent. BUF is the packet content before
11777 the protocol specific prefix, suffix, and escaping is added. */
11778
11779 void sending (gdb::array_view<const char> &buf) override
11780 {
11781 gdb_puts ("sending: ");
11782 print_packet (buf);
11783 gdb_puts ("\n");
11784 }
11785
11786 /* Called with BUF, the reply from the remote target. */
11787
11788 void received (gdb::array_view<const char> &buf) override
11789 {
11790 gdb_puts ("received: \"");
11791 print_packet (buf);
11792 gdb_puts ("\"\n");
11793 }
11794
11795 private:
11796
11797 /* Print BUF o gdb_stdout. Any non-printable bytes in BUF are printed as
11798 '\x??' with '??' replaced by the hexadecimal value of the byte. */
11799
11800 static void
11801 print_packet (gdb::array_view<const char> &buf)
11802 {
11803 string_file stb;
11804
11805 for (int i = 0; i < buf.size (); ++i)
11806 {
11807 gdb_byte c = buf[i];
11808 if (isprint (c))
11809 gdb_putc (c, &stb);
11810 else
11811 gdb_printf (&stb, "\\x%02x", (unsigned char) c);
11812 }
11813
11814 gdb_puts (stb.string ().c_str ());
11815 }
11816 };
11817
11818 /* See remote.h. */
11819
11820 void
11821 send_remote_packet (gdb::array_view<const char> &buf,
11822 send_remote_packet_callbacks *callbacks)
11823 {
11824 if (buf.size () == 0 || buf.data ()[0] == '\0')
11825 error (_("a remote packet must not be empty"));
11826
11827 remote_target *remote = get_current_remote_target ();
11828 if (remote == nullptr)
11829 error (_("packets can only be sent to a remote target"));
11830
11831 callbacks->sending (buf);
11832
11833 remote->putpkt_binary (buf.data (), buf.size ());
11834 remote_state *rs = remote->get_remote_state ();
11835 int bytes = remote->getpkt_sane (&rs->buf, 0);
11836
11837 if (bytes < 0)
11838 error (_("error while fetching packet from remote target"));
11839
11840 gdb::array_view<const char> view (&rs->buf[0], bytes);
11841 callbacks->received (view);
11842 }
11843
11844 /* Entry point for the 'maint packet' command. */
11845
11846 static void
11847 cli_packet_command (const char *args, int from_tty)
11848 {
11849 cli_packet_command_callbacks cb;
11850 gdb::array_view<const char> view
11851 = gdb::make_array_view (args, args == nullptr ? 0 : strlen (args));
11852 send_remote_packet (view, &cb);
11853 }
11854
11855 #if 0
11856 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11857
11858 static void display_thread_info (struct gdb_ext_thread_info *info);
11859
11860 static void threadset_test_cmd (char *cmd, int tty);
11861
11862 static void threadalive_test (char *cmd, int tty);
11863
11864 static void threadlist_test_cmd (char *cmd, int tty);
11865
11866 int get_and_display_threadinfo (threadref *ref);
11867
11868 static void threadinfo_test_cmd (char *cmd, int tty);
11869
11870 static int thread_display_step (threadref *ref, void *context);
11871
11872 static void threadlist_update_test_cmd (char *cmd, int tty);
11873
11874 static void init_remote_threadtests (void);
11875
11876 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
11877
11878 static void
11879 threadset_test_cmd (const char *cmd, int tty)
11880 {
11881 int sample_thread = SAMPLE_THREAD;
11882
11883 gdb_printf (_("Remote threadset test\n"));
11884 set_general_thread (sample_thread);
11885 }
11886
11887
11888 static void
11889 threadalive_test (const char *cmd, int tty)
11890 {
11891 int sample_thread = SAMPLE_THREAD;
11892 int pid = inferior_ptid.pid ();
11893 ptid_t ptid = ptid_t (pid, sample_thread, 0);
11894
11895 if (remote_thread_alive (ptid))
11896 gdb_printf ("PASS: Thread alive test\n");
11897 else
11898 gdb_printf ("FAIL: Thread alive test\n");
11899 }
11900
11901 void output_threadid (char *title, threadref *ref);
11902
11903 void
11904 output_threadid (char *title, threadref *ref)
11905 {
11906 char hexid[20];
11907
11908 pack_threadid (&hexid[0], ref); /* Convert thread id into hex. */
11909 hexid[16] = 0;
11910 gdb_printf ("%s %s\n", title, (&hexid[0]));
11911 }
11912
11913 static void
11914 threadlist_test_cmd (const char *cmd, int tty)
11915 {
11916 int startflag = 1;
11917 threadref nextthread;
11918 int done, result_count;
11919 threadref threadlist[3];
11920
11921 gdb_printf ("Remote Threadlist test\n");
11922 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11923 &result_count, &threadlist[0]))
11924 gdb_printf ("FAIL: threadlist test\n");
11925 else
11926 {
11927 threadref *scan = threadlist;
11928 threadref *limit = scan + result_count;
11929
11930 while (scan < limit)
11931 output_threadid (" thread ", scan++);
11932 }
11933 }
11934
11935 void
11936 display_thread_info (struct gdb_ext_thread_info *info)
11937 {
11938 output_threadid ("Threadid: ", &info->threadid);
11939 gdb_printf ("Name: %s\n ", info->shortname);
11940 gdb_printf ("State: %s\n", info->display);
11941 gdb_printf ("other: %s\n\n", info->more_display);
11942 }
11943
11944 int
11945 get_and_display_threadinfo (threadref *ref)
11946 {
11947 int result;
11948 int set;
11949 struct gdb_ext_thread_info threadinfo;
11950
11951 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11952 | TAG_MOREDISPLAY | TAG_DISPLAY;
11953 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11954 display_thread_info (&threadinfo);
11955 return result;
11956 }
11957
11958 static void
11959 threadinfo_test_cmd (const char *cmd, int tty)
11960 {
11961 int athread = SAMPLE_THREAD;
11962 threadref thread;
11963 int set;
11964
11965 int_to_threadref (&thread, athread);
11966 gdb_printf ("Remote Threadinfo test\n");
11967 if (!get_and_display_threadinfo (&thread))
11968 gdb_printf ("FAIL cannot get thread info\n");
11969 }
11970
11971 static int
11972 thread_display_step (threadref *ref, void *context)
11973 {
11974 /* output_threadid(" threadstep ",ref); *//* simple test */
11975 return get_and_display_threadinfo (ref);
11976 }
11977
11978 static void
11979 threadlist_update_test_cmd (const char *cmd, int tty)
11980 {
11981 gdb_printf ("Remote Threadlist update test\n");
11982 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11983 }
11984
11985 static void
11986 init_remote_threadtests (void)
11987 {
11988 add_com ("tlist", class_obscure, threadlist_test_cmd,
11989 _("Fetch and print the remote list of "
11990 "thread identifiers, one pkt only."));
11991 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11992 _("Fetch and display info about one thread."));
11993 add_com ("tset", class_obscure, threadset_test_cmd,
11994 _("Test setting to a different thread."));
11995 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11996 _("Iterate through updating all remote thread info."));
11997 add_com ("talive", class_obscure, threadalive_test,
11998 _("Remote thread alive test."));
11999 }
12000
12001 #endif /* 0 */
12002
12003 /* Convert a thread ID to a string. */
12004
12005 std::string
12006 remote_target::pid_to_str (ptid_t ptid)
12007 {
12008 if (ptid == null_ptid)
12009 return normal_pid_to_str (ptid);
12010 else if (ptid.is_pid ())
12011 {
12012 /* Printing an inferior target id. */
12013
12014 /* When multi-process extensions are off, there's no way in the
12015 remote protocol to know the remote process id, if there's any
12016 at all. There's one exception --- when we're connected with
12017 target extended-remote, and we manually attached to a process
12018 with "attach PID". We don't record anywhere a flag that
12019 allows us to distinguish that case from the case of
12020 connecting with extended-remote and the stub already being
12021 attached to a process, and reporting yes to qAttached, hence
12022 no smart special casing here. */
12023 if (!m_features.remote_multi_process_p ())
12024 return "Remote target";
12025
12026 return normal_pid_to_str (ptid);
12027 }
12028 else
12029 {
12030 if (magic_null_ptid == ptid)
12031 return "Thread <main>";
12032 else if (m_features.remote_multi_process_p ())
12033 if (ptid.lwp () == 0)
12034 return normal_pid_to_str (ptid);
12035 else
12036 return string_printf ("Thread %d.%ld",
12037 ptid.pid (), ptid.lwp ());
12038 else
12039 return string_printf ("Thread %ld", ptid.lwp ());
12040 }
12041 }
12042
12043 /* Get the address of the thread local variable in OBJFILE which is
12044 stored at OFFSET within the thread local storage for thread PTID. */
12045
12046 CORE_ADDR
12047 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
12048 CORE_ADDR offset)
12049 {
12050 if (m_features.packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
12051 {
12052 struct remote_state *rs = get_remote_state ();
12053 char *p = rs->buf.data ();
12054 char *endp = p + get_remote_packet_size ();
12055 enum packet_result result;
12056
12057 strcpy (p, "qGetTLSAddr:");
12058 p += strlen (p);
12059 p = write_ptid (p, endp, ptid);
12060 *p++ = ',';
12061 p += hexnumstr (p, offset);
12062 *p++ = ',';
12063 p += hexnumstr (p, lm);
12064 *p++ = '\0';
12065
12066 putpkt (rs->buf);
12067 getpkt (&rs->buf, 0);
12068 result = m_features.packet_ok (rs->buf, PACKET_qGetTLSAddr);
12069 if (result == PACKET_OK)
12070 {
12071 ULONGEST addr;
12072
12073 unpack_varlen_hex (rs->buf.data (), &addr);
12074 return addr;
12075 }
12076 else if (result == PACKET_UNKNOWN)
12077 throw_error (TLS_GENERIC_ERROR,
12078 _("Remote target doesn't support qGetTLSAddr packet"));
12079 else
12080 throw_error (TLS_GENERIC_ERROR,
12081 _("Remote target failed to process qGetTLSAddr request"));
12082 }
12083 else
12084 throw_error (TLS_GENERIC_ERROR,
12085 _("TLS not supported or disabled on this target"));
12086 /* Not reached. */
12087 return 0;
12088 }
12089
12090 /* Provide thread local base, i.e. Thread Information Block address.
12091 Returns 1 if ptid is found and thread_local_base is non zero. */
12092
12093 bool
12094 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
12095 {
12096 if (m_features.packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
12097 {
12098 struct remote_state *rs = get_remote_state ();
12099 char *p = rs->buf.data ();
12100 char *endp = p + get_remote_packet_size ();
12101 enum packet_result result;
12102
12103 strcpy (p, "qGetTIBAddr:");
12104 p += strlen (p);
12105 p = write_ptid (p, endp, ptid);
12106 *p++ = '\0';
12107
12108 putpkt (rs->buf);
12109 getpkt (&rs->buf, 0);
12110 result = m_features.packet_ok (rs->buf, PACKET_qGetTIBAddr);
12111 if (result == PACKET_OK)
12112 {
12113 ULONGEST val;
12114 unpack_varlen_hex (rs->buf.data (), &val);
12115 if (addr)
12116 *addr = (CORE_ADDR) val;
12117 return true;
12118 }
12119 else if (result == PACKET_UNKNOWN)
12120 error (_("Remote target doesn't support qGetTIBAddr packet"));
12121 else
12122 error (_("Remote target failed to process qGetTIBAddr request"));
12123 }
12124 else
12125 error (_("qGetTIBAddr not supported or disabled on this target"));
12126 /* Not reached. */
12127 return false;
12128 }
12129
12130 /* Support for inferring a target description based on the current
12131 architecture and the size of a 'g' packet. While the 'g' packet
12132 can have any size (since optional registers can be left off the
12133 end), some sizes are easily recognizable given knowledge of the
12134 approximate architecture. */
12135
12136 struct remote_g_packet_guess
12137 {
12138 remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
12139 : bytes (bytes_),
12140 tdesc (tdesc_)
12141 {
12142 }
12143
12144 int bytes;
12145 const struct target_desc *tdesc;
12146 };
12147
12148 struct remote_g_packet_data
12149 {
12150 std::vector<remote_g_packet_guess> guesses;
12151 };
12152
12153 static const registry<gdbarch>::key<struct remote_g_packet_data>
12154 remote_g_packet_data_handle;
12155
12156 static struct remote_g_packet_data *
12157 get_g_packet_data (struct gdbarch *gdbarch)
12158 {
12159 struct remote_g_packet_data *data
12160 = remote_g_packet_data_handle.get (gdbarch);
12161 if (data == nullptr)
12162 data = remote_g_packet_data_handle.emplace (gdbarch);
12163 return data;
12164 }
12165
12166 void
12167 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
12168 const struct target_desc *tdesc)
12169 {
12170 struct remote_g_packet_data *data = get_g_packet_data (gdbarch);
12171
12172 gdb_assert (tdesc != NULL);
12173
12174 for (const remote_g_packet_guess &guess : data->guesses)
12175 if (guess.bytes == bytes)
12176 internal_error (_("Duplicate g packet description added for size %d"),
12177 bytes);
12178
12179 data->guesses.emplace_back (bytes, tdesc);
12180 }
12181
12182 /* Return true if remote_read_description would do anything on this target
12183 and architecture, false otherwise. */
12184
12185 static bool
12186 remote_read_description_p (struct target_ops *target)
12187 {
12188 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12189
12190 return !data->guesses.empty ();
12191 }
12192
12193 const struct target_desc *
12194 remote_target::read_description ()
12195 {
12196 struct remote_g_packet_data *data = get_g_packet_data (target_gdbarch ());
12197
12198 /* Do not try this during initial connection, when we do not know
12199 whether there is a running but stopped thread. */
12200 if (!target_has_execution () || inferior_ptid == null_ptid)
12201 return beneath ()->read_description ();
12202
12203 if (!data->guesses.empty ())
12204 {
12205 int bytes = send_g_packet ();
12206
12207 for (const remote_g_packet_guess &guess : data->guesses)
12208 if (guess.bytes == bytes)
12209 return guess.tdesc;
12210
12211 /* We discard the g packet. A minor optimization would be to
12212 hold on to it, and fill the register cache once we have selected
12213 an architecture, but it's too tricky to do safely. */
12214 }
12215
12216 return beneath ()->read_description ();
12217 }
12218
12219 /* Remote file transfer support. This is host-initiated I/O, not
12220 target-initiated; for target-initiated, see remote-fileio.c. */
12221
12222 /* If *LEFT is at least the length of STRING, copy STRING to
12223 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12224 decrease *LEFT. Otherwise raise an error. */
12225
12226 static void
12227 remote_buffer_add_string (char **buffer, int *left, const char *string)
12228 {
12229 int len = strlen (string);
12230
12231 if (len > *left)
12232 error (_("Packet too long for target."));
12233
12234 memcpy (*buffer, string, len);
12235 *buffer += len;
12236 *left -= len;
12237
12238 /* NUL-terminate the buffer as a convenience, if there is
12239 room. */
12240 if (*left)
12241 **buffer = '\0';
12242 }
12243
12244 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
12245 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12246 decrease *LEFT. Otherwise raise an error. */
12247
12248 static void
12249 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
12250 int len)
12251 {
12252 if (2 * len > *left)
12253 error (_("Packet too long for target."));
12254
12255 bin2hex (bytes, *buffer, len);
12256 *buffer += 2 * len;
12257 *left -= 2 * len;
12258
12259 /* NUL-terminate the buffer as a convenience, if there is
12260 room. */
12261 if (*left)
12262 **buffer = '\0';
12263 }
12264
12265 /* If *LEFT is large enough, convert VALUE to hex and add it to
12266 *BUFFER, update *BUFFER to point to the new end of the buffer, and
12267 decrease *LEFT. Otherwise raise an error. */
12268
12269 static void
12270 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
12271 {
12272 int len = hexnumlen (value);
12273
12274 if (len > *left)
12275 error (_("Packet too long for target."));
12276
12277 hexnumstr (*buffer, value);
12278 *buffer += len;
12279 *left -= len;
12280
12281 /* NUL-terminate the buffer as a convenience, if there is
12282 room. */
12283 if (*left)
12284 **buffer = '\0';
12285 }
12286
12287 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
12288 value, *REMOTE_ERRNO to the remote error number or FILEIO_SUCCESS if none
12289 was included, and *ATTACHMENT to point to the start of the annex
12290 if any. The length of the packet isn't needed here; there may
12291 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
12292
12293 Return 0 if the packet could be parsed, -1 if it could not. If
12294 -1 is returned, the other variables may not be initialized. */
12295
12296 static int
12297 remote_hostio_parse_result (const char *buffer, int *retcode,
12298 fileio_error *remote_errno, const char **attachment)
12299 {
12300 char *p, *p2;
12301
12302 *remote_errno = FILEIO_SUCCESS;
12303 *attachment = NULL;
12304
12305 if (buffer[0] != 'F')
12306 return -1;
12307
12308 errno = 0;
12309 *retcode = strtol (&buffer[1], &p, 16);
12310 if (errno != 0 || p == &buffer[1])
12311 return -1;
12312
12313 /* Check for ",errno". */
12314 if (*p == ',')
12315 {
12316 errno = 0;
12317 *remote_errno = (fileio_error) strtol (p + 1, &p2, 16);
12318 if (errno != 0 || p + 1 == p2)
12319 return -1;
12320 p = p2;
12321 }
12322
12323 /* Check for ";attachment". If there is no attachment, the
12324 packet should end here. */
12325 if (*p == ';')
12326 {
12327 *attachment = p + 1;
12328 return 0;
12329 }
12330 else if (*p == '\0')
12331 return 0;
12332 else
12333 return -1;
12334 }
12335
12336 /* Send a prepared I/O packet to the target and read its response.
12337 The prepared packet is in the global RS->BUF before this function
12338 is called, and the answer is there when we return.
12339
12340 COMMAND_BYTES is the length of the request to send, which may include
12341 binary data. WHICH_PACKET is the packet configuration to check
12342 before attempting a packet. If an error occurs, *REMOTE_ERRNO
12343 is set to the error number and -1 is returned. Otherwise the value
12344 returned by the function is returned.
12345
12346 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
12347 attachment is expected; an error will be reported if there's a
12348 mismatch. If one is found, *ATTACHMENT will be set to point into
12349 the packet buffer and *ATTACHMENT_LEN will be set to the
12350 attachment's length. */
12351
12352 int
12353 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
12354 fileio_error *remote_errno, const char **attachment,
12355 int *attachment_len)
12356 {
12357 struct remote_state *rs = get_remote_state ();
12358 int ret, bytes_read;
12359 const char *attachment_tmp;
12360
12361 if (m_features.packet_support (which_packet) == PACKET_DISABLE)
12362 {
12363 *remote_errno = FILEIO_ENOSYS;
12364 return -1;
12365 }
12366
12367 putpkt_binary (rs->buf.data (), command_bytes);
12368 bytes_read = getpkt_sane (&rs->buf, 0);
12369
12370 /* If it timed out, something is wrong. Don't try to parse the
12371 buffer. */
12372 if (bytes_read < 0)
12373 {
12374 *remote_errno = FILEIO_EINVAL;
12375 return -1;
12376 }
12377
12378 switch (m_features.packet_ok (rs->buf, which_packet))
12379 {
12380 case PACKET_ERROR:
12381 *remote_errno = FILEIO_EINVAL;
12382 return -1;
12383 case PACKET_UNKNOWN:
12384 *remote_errno = FILEIO_ENOSYS;
12385 return -1;
12386 case PACKET_OK:
12387 break;
12388 }
12389
12390 if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
12391 &attachment_tmp))
12392 {
12393 *remote_errno = FILEIO_EINVAL;
12394 return -1;
12395 }
12396
12397 /* Make sure we saw an attachment if and only if we expected one. */
12398 if ((attachment_tmp == NULL && attachment != NULL)
12399 || (attachment_tmp != NULL && attachment == NULL))
12400 {
12401 *remote_errno = FILEIO_EINVAL;
12402 return -1;
12403 }
12404
12405 /* If an attachment was found, it must point into the packet buffer;
12406 work out how many bytes there were. */
12407 if (attachment_tmp != NULL)
12408 {
12409 *attachment = attachment_tmp;
12410 *attachment_len = bytes_read - (*attachment - rs->buf.data ());
12411 }
12412
12413 return ret;
12414 }
12415
12416 /* See declaration.h. */
12417
12418 void
12419 readahead_cache::invalidate ()
12420 {
12421 this->fd = -1;
12422 }
12423
12424 /* See declaration.h. */
12425
12426 void
12427 readahead_cache::invalidate_fd (int fd)
12428 {
12429 if (this->fd == fd)
12430 this->fd = -1;
12431 }
12432
12433 /* Set the filesystem remote_hostio functions that take FILENAME
12434 arguments will use. Return 0 on success, or -1 if an error
12435 occurs (and set *REMOTE_ERRNO). */
12436
12437 int
12438 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12439 fileio_error *remote_errno)
12440 {
12441 struct remote_state *rs = get_remote_state ();
12442 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12443 char *p = rs->buf.data ();
12444 int left = get_remote_packet_size () - 1;
12445 char arg[9];
12446 int ret;
12447
12448 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12449 return 0;
12450
12451 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12452 return 0;
12453
12454 remote_buffer_add_string (&p, &left, "vFile:setfs:");
12455
12456 xsnprintf (arg, sizeof (arg), "%x", required_pid);
12457 remote_buffer_add_string (&p, &left, arg);
12458
12459 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
12460 remote_errno, NULL, NULL);
12461
12462 if (m_features.packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12463 return 0;
12464
12465 if (ret == 0)
12466 rs->fs_pid = required_pid;
12467
12468 return ret;
12469 }
12470
12471 /* Implementation of to_fileio_open. */
12472
12473 int
12474 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12475 int flags, int mode, int warn_if_slow,
12476 fileio_error *remote_errno)
12477 {
12478 struct remote_state *rs = get_remote_state ();
12479 char *p = rs->buf.data ();
12480 int left = get_remote_packet_size () - 1;
12481
12482 if (warn_if_slow)
12483 {
12484 static int warning_issued = 0;
12485
12486 gdb_printf (_("Reading %s from remote target...\n"),
12487 filename);
12488
12489 if (!warning_issued)
12490 {
12491 warning (_("File transfers from remote targets can be slow."
12492 " Use \"set sysroot\" to access files locally"
12493 " instead."));
12494 warning_issued = 1;
12495 }
12496 }
12497
12498 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12499 return -1;
12500
12501 remote_buffer_add_string (&p, &left, "vFile:open:");
12502
12503 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12504 strlen (filename));
12505 remote_buffer_add_string (&p, &left, ",");
12506
12507 remote_buffer_add_int (&p, &left, flags);
12508 remote_buffer_add_string (&p, &left, ",");
12509
12510 remote_buffer_add_int (&p, &left, mode);
12511
12512 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
12513 remote_errno, NULL, NULL);
12514 }
12515
12516 int
12517 remote_target::fileio_open (struct inferior *inf, const char *filename,
12518 int flags, int mode, int warn_if_slow,
12519 fileio_error *remote_errno)
12520 {
12521 return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12522 remote_errno);
12523 }
12524
12525 /* Implementation of to_fileio_pwrite. */
12526
12527 int
12528 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12529 ULONGEST offset, fileio_error *remote_errno)
12530 {
12531 struct remote_state *rs = get_remote_state ();
12532 char *p = rs->buf.data ();
12533 int left = get_remote_packet_size ();
12534 int out_len;
12535
12536 rs->readahead_cache.invalidate_fd (fd);
12537
12538 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12539
12540 remote_buffer_add_int (&p, &left, fd);
12541 remote_buffer_add_string (&p, &left, ",");
12542
12543 remote_buffer_add_int (&p, &left, offset);
12544 remote_buffer_add_string (&p, &left, ",");
12545
12546 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12547 (get_remote_packet_size ()
12548 - (p - rs->buf.data ())));
12549
12550 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
12551 remote_errno, NULL, NULL);
12552 }
12553
12554 int
12555 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12556 ULONGEST offset, fileio_error *remote_errno)
12557 {
12558 return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12559 }
12560
12561 /* Helper for the implementation of to_fileio_pread. Read the file
12562 from the remote side with vFile:pread. */
12563
12564 int
12565 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12566 ULONGEST offset, fileio_error *remote_errno)
12567 {
12568 struct remote_state *rs = get_remote_state ();
12569 char *p = rs->buf.data ();
12570 const char *attachment;
12571 int left = get_remote_packet_size ();
12572 int ret, attachment_len;
12573 int read_len;
12574
12575 remote_buffer_add_string (&p, &left, "vFile:pread:");
12576
12577 remote_buffer_add_int (&p, &left, fd);
12578 remote_buffer_add_string (&p, &left, ",");
12579
12580 remote_buffer_add_int (&p, &left, len);
12581 remote_buffer_add_string (&p, &left, ",");
12582
12583 remote_buffer_add_int (&p, &left, offset);
12584
12585 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12586 remote_errno, &attachment,
12587 &attachment_len);
12588
12589 if (ret < 0)
12590 return ret;
12591
12592 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12593 read_buf, len);
12594 if (read_len != ret)
12595 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12596
12597 return ret;
12598 }
12599
12600 /* See declaration.h. */
12601
12602 int
12603 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12604 ULONGEST offset)
12605 {
12606 if (this->fd == fd
12607 && this->offset <= offset
12608 && offset < this->offset + this->bufsize)
12609 {
12610 ULONGEST max = this->offset + this->bufsize;
12611
12612 if (offset + len > max)
12613 len = max - offset;
12614
12615 memcpy (read_buf, this->buf + offset - this->offset, len);
12616 return len;
12617 }
12618
12619 return 0;
12620 }
12621
12622 /* Implementation of to_fileio_pread. */
12623
12624 int
12625 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12626 ULONGEST offset, fileio_error *remote_errno)
12627 {
12628 int ret;
12629 struct remote_state *rs = get_remote_state ();
12630 readahead_cache *cache = &rs->readahead_cache;
12631
12632 ret = cache->pread (fd, read_buf, len, offset);
12633 if (ret > 0)
12634 {
12635 cache->hit_count++;
12636
12637 remote_debug_printf ("readahead cache hit %s",
12638 pulongest (cache->hit_count));
12639 return ret;
12640 }
12641
12642 cache->miss_count++;
12643
12644 remote_debug_printf ("readahead cache miss %s",
12645 pulongest (cache->miss_count));
12646
12647 cache->fd = fd;
12648 cache->offset = offset;
12649 cache->bufsize = get_remote_packet_size ();
12650 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12651
12652 ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12653 cache->offset, remote_errno);
12654 if (ret <= 0)
12655 {
12656 cache->invalidate_fd (fd);
12657 return ret;
12658 }
12659
12660 cache->bufsize = ret;
12661 return cache->pread (fd, read_buf, len, offset);
12662 }
12663
12664 int
12665 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12666 ULONGEST offset, fileio_error *remote_errno)
12667 {
12668 return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12669 }
12670
12671 /* Implementation of to_fileio_close. */
12672
12673 int
12674 remote_target::remote_hostio_close (int fd, fileio_error *remote_errno)
12675 {
12676 struct remote_state *rs = get_remote_state ();
12677 char *p = rs->buf.data ();
12678 int left = get_remote_packet_size () - 1;
12679
12680 rs->readahead_cache.invalidate_fd (fd);
12681
12682 remote_buffer_add_string (&p, &left, "vFile:close:");
12683
12684 remote_buffer_add_int (&p, &left, fd);
12685
12686 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12687 remote_errno, NULL, NULL);
12688 }
12689
12690 int
12691 remote_target::fileio_close (int fd, fileio_error *remote_errno)
12692 {
12693 return remote_hostio_close (fd, remote_errno);
12694 }
12695
12696 /* Implementation of to_fileio_unlink. */
12697
12698 int
12699 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12700 fileio_error *remote_errno)
12701 {
12702 struct remote_state *rs = get_remote_state ();
12703 char *p = rs->buf.data ();
12704 int left = get_remote_packet_size () - 1;
12705
12706 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12707 return -1;
12708
12709 remote_buffer_add_string (&p, &left, "vFile:unlink:");
12710
12711 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12712 strlen (filename));
12713
12714 return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12715 remote_errno, NULL, NULL);
12716 }
12717
12718 int
12719 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12720 fileio_error *remote_errno)
12721 {
12722 return remote_hostio_unlink (inf, filename, remote_errno);
12723 }
12724
12725 /* Implementation of to_fileio_readlink. */
12726
12727 gdb::optional<std::string>
12728 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12729 fileio_error *remote_errno)
12730 {
12731 struct remote_state *rs = get_remote_state ();
12732 char *p = rs->buf.data ();
12733 const char *attachment;
12734 int left = get_remote_packet_size ();
12735 int len, attachment_len;
12736 int read_len;
12737
12738 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12739 return {};
12740
12741 remote_buffer_add_string (&p, &left, "vFile:readlink:");
12742
12743 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12744 strlen (filename));
12745
12746 len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12747 remote_errno, &attachment,
12748 &attachment_len);
12749
12750 if (len < 0)
12751 return {};
12752
12753 std::string ret (len, '\0');
12754
12755 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12756 (gdb_byte *) &ret[0], len);
12757 if (read_len != len)
12758 error (_("Readlink returned %d, but %d bytes."), len, read_len);
12759
12760 return ret;
12761 }
12762
12763 /* Implementation of to_fileio_fstat. */
12764
12765 int
12766 remote_target::fileio_fstat (int fd, struct stat *st, fileio_error *remote_errno)
12767 {
12768 struct remote_state *rs = get_remote_state ();
12769 char *p = rs->buf.data ();
12770 int left = get_remote_packet_size ();
12771 int attachment_len, ret;
12772 const char *attachment;
12773 struct fio_stat fst;
12774 int read_len;
12775
12776 remote_buffer_add_string (&p, &left, "vFile:fstat:");
12777
12778 remote_buffer_add_int (&p, &left, fd);
12779
12780 ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12781 remote_errno, &attachment,
12782 &attachment_len);
12783 if (ret < 0)
12784 {
12785 if (*remote_errno != FILEIO_ENOSYS)
12786 return ret;
12787
12788 /* Strictly we should return -1, ENOSYS here, but when
12789 "set sysroot remote:" was implemented in August 2008
12790 BFD's need for a stat function was sidestepped with
12791 this hack. This was not remedied until March 2015
12792 so we retain the previous behavior to avoid breaking
12793 compatibility.
12794
12795 Note that the memset is a March 2015 addition; older
12796 GDBs set st_size *and nothing else* so the structure
12797 would have garbage in all other fields. This might
12798 break something but retaining the previous behavior
12799 here would be just too wrong. */
12800
12801 memset (st, 0, sizeof (struct stat));
12802 st->st_size = INT_MAX;
12803 return 0;
12804 }
12805
12806 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12807 (gdb_byte *) &fst, sizeof (fst));
12808
12809 if (read_len != ret)
12810 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12811
12812 if (read_len != sizeof (fst))
12813 error (_("vFile:fstat returned %d bytes, but expecting %d."),
12814 read_len, (int) sizeof (fst));
12815
12816 remote_fileio_to_host_stat (&fst, st);
12817
12818 return 0;
12819 }
12820
12821 /* Implementation of to_filesystem_is_local. */
12822
12823 bool
12824 remote_target::filesystem_is_local ()
12825 {
12826 /* Valgrind GDB presents itself as a remote target but works
12827 on the local filesystem: it does not implement remote get
12828 and users are not expected to set a sysroot. To handle
12829 this case we treat the remote filesystem as local if the
12830 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12831 does not support vFile:open. */
12832 if (gdb_sysroot == TARGET_SYSROOT_PREFIX)
12833 {
12834 packet_support ps = m_features.packet_support (PACKET_vFile_open);
12835
12836 if (ps == PACKET_SUPPORT_UNKNOWN)
12837 {
12838 int fd;
12839 fileio_error remote_errno;
12840
12841 /* Try opening a file to probe support. The supplied
12842 filename is irrelevant, we only care about whether
12843 the stub recognizes the packet or not. */
12844 fd = remote_hostio_open (NULL, "just probing",
12845 FILEIO_O_RDONLY, 0700, 0,
12846 &remote_errno);
12847
12848 if (fd >= 0)
12849 remote_hostio_close (fd, &remote_errno);
12850
12851 ps = m_features.packet_support (PACKET_vFile_open);
12852 }
12853
12854 if (ps == PACKET_DISABLE)
12855 {
12856 static int warning_issued = 0;
12857
12858 if (!warning_issued)
12859 {
12860 warning (_("remote target does not support file"
12861 " transfer, attempting to access files"
12862 " from local filesystem."));
12863 warning_issued = 1;
12864 }
12865
12866 return true;
12867 }
12868 }
12869
12870 return false;
12871 }
12872
12873 static char *
12874 remote_hostio_error (fileio_error errnum)
12875 {
12876 int host_error = fileio_error_to_host (errnum);
12877
12878 if (host_error == -1)
12879 error (_("Unknown remote I/O error %d"), errnum);
12880 else
12881 error (_("Remote I/O error: %s"), safe_strerror (host_error));
12882 }
12883
12884 /* A RAII wrapper around a remote file descriptor. */
12885
12886 class scoped_remote_fd
12887 {
12888 public:
12889 scoped_remote_fd (remote_target *remote, int fd)
12890 : m_remote (remote), m_fd (fd)
12891 {
12892 }
12893
12894 ~scoped_remote_fd ()
12895 {
12896 if (m_fd != -1)
12897 {
12898 try
12899 {
12900 fileio_error remote_errno;
12901 m_remote->remote_hostio_close (m_fd, &remote_errno);
12902 }
12903 catch (...)
12904 {
12905 /* Swallow exception before it escapes the dtor. If
12906 something goes wrong, likely the connection is gone,
12907 and there's nothing else that can be done. */
12908 }
12909 }
12910 }
12911
12912 DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12913
12914 /* Release ownership of the file descriptor, and return it. */
12915 ATTRIBUTE_UNUSED_RESULT int release () noexcept
12916 {
12917 int fd = m_fd;
12918 m_fd = -1;
12919 return fd;
12920 }
12921
12922 /* Return the owned file descriptor. */
12923 int get () const noexcept
12924 {
12925 return m_fd;
12926 }
12927
12928 private:
12929 /* The remote target. */
12930 remote_target *m_remote;
12931
12932 /* The owned remote I/O file descriptor. */
12933 int m_fd;
12934 };
12935
12936 void
12937 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12938 {
12939 remote_target *remote = get_current_remote_target ();
12940
12941 if (remote == nullptr)
12942 error (_("command can only be used with remote target"));
12943
12944 remote->remote_file_put (local_file, remote_file, from_tty);
12945 }
12946
12947 void
12948 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12949 int from_tty)
12950 {
12951 int retcode, bytes, io_size;
12952 fileio_error remote_errno;
12953 int bytes_in_buffer;
12954 int saw_eof;
12955 ULONGEST offset;
12956
12957 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12958 if (file == NULL)
12959 perror_with_name (local_file);
12960
12961 scoped_remote_fd fd
12962 (this, remote_hostio_open (NULL,
12963 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12964 | FILEIO_O_TRUNC),
12965 0700, 0, &remote_errno));
12966 if (fd.get () == -1)
12967 remote_hostio_error (remote_errno);
12968
12969 /* Send up to this many bytes at once. They won't all fit in the
12970 remote packet limit, so we'll transfer slightly fewer. */
12971 io_size = get_remote_packet_size ();
12972 gdb::byte_vector buffer (io_size);
12973
12974 bytes_in_buffer = 0;
12975 saw_eof = 0;
12976 offset = 0;
12977 while (bytes_in_buffer || !saw_eof)
12978 {
12979 if (!saw_eof)
12980 {
12981 bytes = fread (buffer.data () + bytes_in_buffer, 1,
12982 io_size - bytes_in_buffer,
12983 file.get ());
12984 if (bytes == 0)
12985 {
12986 if (ferror (file.get ()))
12987 error (_("Error reading %s."), local_file);
12988 else
12989 {
12990 /* EOF. Unless there is something still in the
12991 buffer from the last iteration, we are done. */
12992 saw_eof = 1;
12993 if (bytes_in_buffer == 0)
12994 break;
12995 }
12996 }
12997 }
12998 else
12999 bytes = 0;
13000
13001 bytes += bytes_in_buffer;
13002 bytes_in_buffer = 0;
13003
13004 retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
13005 offset, &remote_errno);
13006
13007 if (retcode < 0)
13008 remote_hostio_error (remote_errno);
13009 else if (retcode == 0)
13010 error (_("Remote write of %d bytes returned 0!"), bytes);
13011 else if (retcode < bytes)
13012 {
13013 /* Short write. Save the rest of the read data for the next
13014 write. */
13015 bytes_in_buffer = bytes - retcode;
13016 memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
13017 }
13018
13019 offset += retcode;
13020 }
13021
13022 if (remote_hostio_close (fd.release (), &remote_errno))
13023 remote_hostio_error (remote_errno);
13024
13025 if (from_tty)
13026 gdb_printf (_("Successfully sent file \"%s\".\n"), local_file);
13027 }
13028
13029 void
13030 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
13031 {
13032 remote_target *remote = get_current_remote_target ();
13033
13034 if (remote == nullptr)
13035 error (_("command can only be used with remote target"));
13036
13037 remote->remote_file_get (remote_file, local_file, from_tty);
13038 }
13039
13040 void
13041 remote_target::remote_file_get (const char *remote_file, const char *local_file,
13042 int from_tty)
13043 {
13044 fileio_error remote_errno;
13045 int bytes, io_size;
13046 ULONGEST offset;
13047
13048 scoped_remote_fd fd
13049 (this, remote_hostio_open (NULL,
13050 remote_file, FILEIO_O_RDONLY, 0, 0,
13051 &remote_errno));
13052 if (fd.get () == -1)
13053 remote_hostio_error (remote_errno);
13054
13055 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
13056 if (file == NULL)
13057 perror_with_name (local_file);
13058
13059 /* Send up to this many bytes at once. They won't all fit in the
13060 remote packet limit, so we'll transfer slightly fewer. */
13061 io_size = get_remote_packet_size ();
13062 gdb::byte_vector buffer (io_size);
13063
13064 offset = 0;
13065 while (1)
13066 {
13067 bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
13068 &remote_errno);
13069 if (bytes == 0)
13070 /* Success, but no bytes, means end-of-file. */
13071 break;
13072 if (bytes == -1)
13073 remote_hostio_error (remote_errno);
13074
13075 offset += bytes;
13076
13077 bytes = fwrite (buffer.data (), 1, bytes, file.get ());
13078 if (bytes == 0)
13079 perror_with_name (local_file);
13080 }
13081
13082 if (remote_hostio_close (fd.release (), &remote_errno))
13083 remote_hostio_error (remote_errno);
13084
13085 if (from_tty)
13086 gdb_printf (_("Successfully fetched file \"%s\".\n"), remote_file);
13087 }
13088
13089 void
13090 remote_file_delete (const char *remote_file, int from_tty)
13091 {
13092 remote_target *remote = get_current_remote_target ();
13093
13094 if (remote == nullptr)
13095 error (_("command can only be used with remote target"));
13096
13097 remote->remote_file_delete (remote_file, from_tty);
13098 }
13099
13100 void
13101 remote_target::remote_file_delete (const char *remote_file, int from_tty)
13102 {
13103 int retcode;
13104 fileio_error remote_errno;
13105
13106 retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
13107 if (retcode == -1)
13108 remote_hostio_error (remote_errno);
13109
13110 if (from_tty)
13111 gdb_printf (_("Successfully deleted file \"%s\".\n"), remote_file);
13112 }
13113
13114 static void
13115 remote_put_command (const char *args, int from_tty)
13116 {
13117 if (args == NULL)
13118 error_no_arg (_("file to put"));
13119
13120 gdb_argv argv (args);
13121 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13122 error (_("Invalid parameters to remote put"));
13123
13124 remote_file_put (argv[0], argv[1], from_tty);
13125 }
13126
13127 static void
13128 remote_get_command (const char *args, int from_tty)
13129 {
13130 if (args == NULL)
13131 error_no_arg (_("file to get"));
13132
13133 gdb_argv argv (args);
13134 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
13135 error (_("Invalid parameters to remote get"));
13136
13137 remote_file_get (argv[0], argv[1], from_tty);
13138 }
13139
13140 static void
13141 remote_delete_command (const char *args, int from_tty)
13142 {
13143 if (args == NULL)
13144 error_no_arg (_("file to delete"));
13145
13146 gdb_argv argv (args);
13147 if (argv[0] == NULL || argv[1] != NULL)
13148 error (_("Invalid parameters to remote delete"));
13149
13150 remote_file_delete (argv[0], from_tty);
13151 }
13152
13153 bool
13154 remote_target::can_execute_reverse ()
13155 {
13156 if (m_features.packet_support (PACKET_bs) == PACKET_ENABLE
13157 || m_features.packet_support (PACKET_bc) == PACKET_ENABLE)
13158 return true;
13159 else
13160 return false;
13161 }
13162
13163 bool
13164 remote_target::supports_non_stop ()
13165 {
13166 return true;
13167 }
13168
13169 bool
13170 remote_target::supports_disable_randomization ()
13171 {
13172 /* Only supported in extended mode. */
13173 return false;
13174 }
13175
13176 bool
13177 remote_target::supports_multi_process ()
13178 {
13179 return m_features.remote_multi_process_p ();
13180 }
13181
13182 int
13183 remote_target::remote_supports_cond_tracepoints ()
13184 {
13185 return (m_features.packet_support (PACKET_ConditionalTracepoints)
13186 == PACKET_ENABLE);
13187 }
13188
13189 bool
13190 remote_target::supports_evaluation_of_breakpoint_conditions ()
13191 {
13192 return (m_features.packet_support (PACKET_ConditionalBreakpoints)
13193 == PACKET_ENABLE);
13194 }
13195
13196 int
13197 remote_target::remote_supports_fast_tracepoints ()
13198 {
13199 return m_features.packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
13200 }
13201
13202 int
13203 remote_target::remote_supports_static_tracepoints ()
13204 {
13205 return m_features.packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
13206 }
13207
13208 int
13209 remote_target::remote_supports_install_in_trace ()
13210 {
13211 return m_features.packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
13212 }
13213
13214 bool
13215 remote_target::supports_enable_disable_tracepoint ()
13216 {
13217 return (m_features.packet_support (PACKET_EnableDisableTracepoints_feature)
13218 == PACKET_ENABLE);
13219 }
13220
13221 bool
13222 remote_target::supports_string_tracing ()
13223 {
13224 return m_features.packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
13225 }
13226
13227 bool
13228 remote_target::can_run_breakpoint_commands ()
13229 {
13230 return m_features.packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
13231 }
13232
13233 void
13234 remote_target::trace_init ()
13235 {
13236 struct remote_state *rs = get_remote_state ();
13237
13238 putpkt ("QTinit");
13239 remote_get_noisy_reply ();
13240 if (strcmp (rs->buf.data (), "OK") != 0)
13241 error (_("Target does not support this command."));
13242 }
13243
13244 /* Recursive routine to walk through command list including loops, and
13245 download packets for each command. */
13246
13247 void
13248 remote_target::remote_download_command_source (int num, ULONGEST addr,
13249 struct command_line *cmds)
13250 {
13251 struct remote_state *rs = get_remote_state ();
13252 struct command_line *cmd;
13253
13254 for (cmd = cmds; cmd; cmd = cmd->next)
13255 {
13256 QUIT; /* Allow user to bail out with ^C. */
13257 strcpy (rs->buf.data (), "QTDPsrc:");
13258 encode_source_string (num, addr, "cmd", cmd->line,
13259 rs->buf.data () + strlen (rs->buf.data ()),
13260 rs->buf.size () - strlen (rs->buf.data ()));
13261 putpkt (rs->buf);
13262 remote_get_noisy_reply ();
13263 if (strcmp (rs->buf.data (), "OK"))
13264 warning (_("Target does not support source download."));
13265
13266 if (cmd->control_type == while_control
13267 || cmd->control_type == while_stepping_control)
13268 {
13269 remote_download_command_source (num, addr, cmd->body_list_0.get ());
13270
13271 QUIT; /* Allow user to bail out with ^C. */
13272 strcpy (rs->buf.data (), "QTDPsrc:");
13273 encode_source_string (num, addr, "cmd", "end",
13274 rs->buf.data () + strlen (rs->buf.data ()),
13275 rs->buf.size () - strlen (rs->buf.data ()));
13276 putpkt (rs->buf);
13277 remote_get_noisy_reply ();
13278 if (strcmp (rs->buf.data (), "OK"))
13279 warning (_("Target does not support source download."));
13280 }
13281 }
13282 }
13283
13284 void
13285 remote_target::download_tracepoint (struct bp_location *loc)
13286 {
13287 CORE_ADDR tpaddr;
13288 char addrbuf[40];
13289 std::vector<std::string> tdp_actions;
13290 std::vector<std::string> stepping_actions;
13291 char *pkt;
13292 struct breakpoint *b = loc->owner;
13293 struct tracepoint *t = (struct tracepoint *) b;
13294 struct remote_state *rs = get_remote_state ();
13295 int ret;
13296 const char *err_msg = _("Tracepoint packet too large for target.");
13297 size_t size_left;
13298
13299 /* We use a buffer other than rs->buf because we'll build strings
13300 across multiple statements, and other statements in between could
13301 modify rs->buf. */
13302 gdb::char_vector buf (get_remote_packet_size ());
13303
13304 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
13305
13306 tpaddr = loc->address;
13307 strcpy (addrbuf, phex (tpaddr, sizeof (CORE_ADDR)));
13308 ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
13309 b->number, addrbuf, /* address */
13310 (b->enable_state == bp_enabled ? 'E' : 'D'),
13311 t->step_count, t->pass_count);
13312
13313 if (ret < 0 || ret >= buf.size ())
13314 error ("%s", err_msg);
13315
13316 /* Fast tracepoints are mostly handled by the target, but we can
13317 tell the target how big of an instruction block should be moved
13318 around. */
13319 if (b->type == bp_fast_tracepoint)
13320 {
13321 /* Only test for support at download time; we may not know
13322 target capabilities at definition time. */
13323 if (remote_supports_fast_tracepoints ())
13324 {
13325 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
13326 NULL))
13327 {
13328 size_left = buf.size () - strlen (buf.data ());
13329 ret = snprintf (buf.data () + strlen (buf.data ()),
13330 size_left, ":F%x",
13331 gdb_insn_length (loc->gdbarch, tpaddr));
13332
13333 if (ret < 0 || ret >= size_left)
13334 error ("%s", err_msg);
13335 }
13336 else
13337 /* If it passed validation at definition but fails now,
13338 something is very wrong. */
13339 internal_error (_("Fast tracepoint not valid during download"));
13340 }
13341 else
13342 /* Fast tracepoints are functionally identical to regular
13343 tracepoints, so don't take lack of support as a reason to
13344 give up on the trace run. */
13345 warning (_("Target does not support fast tracepoints, "
13346 "downloading %d as regular tracepoint"), b->number);
13347 }
13348 else if (b->type == bp_static_tracepoint
13349 || b->type == bp_static_marker_tracepoint)
13350 {
13351 /* Only test for support at download time; we may not know
13352 target capabilities at definition time. */
13353 if (remote_supports_static_tracepoints ())
13354 {
13355 struct static_tracepoint_marker marker;
13356
13357 if (target_static_tracepoint_marker_at (tpaddr, &marker))
13358 {
13359 size_left = buf.size () - strlen (buf.data ());
13360 ret = snprintf (buf.data () + strlen (buf.data ()),
13361 size_left, ":S");
13362
13363 if (ret < 0 || ret >= size_left)
13364 error ("%s", err_msg);
13365 }
13366 else
13367 error (_("Static tracepoint not valid during download"));
13368 }
13369 else
13370 /* Fast tracepoints are functionally identical to regular
13371 tracepoints, so don't take lack of support as a reason
13372 to give up on the trace run. */
13373 error (_("Target does not support static tracepoints"));
13374 }
13375 /* If the tracepoint has a conditional, make it into an agent
13376 expression and append to the definition. */
13377 if (loc->cond)
13378 {
13379 /* Only test support at download time, we may not know target
13380 capabilities at definition time. */
13381 if (remote_supports_cond_tracepoints ())
13382 {
13383 agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
13384 loc->cond.get ());
13385
13386 size_left = buf.size () - strlen (buf.data ());
13387
13388 ret = snprintf (buf.data () + strlen (buf.data ()),
13389 size_left, ":X%x,", aexpr->len);
13390
13391 if (ret < 0 || ret >= size_left)
13392 error ("%s", err_msg);
13393
13394 size_left = buf.size () - strlen (buf.data ());
13395
13396 /* Two bytes to encode each aexpr byte, plus the terminating
13397 null byte. */
13398 if (aexpr->len * 2 + 1 > size_left)
13399 error ("%s", err_msg);
13400
13401 pkt = buf.data () + strlen (buf.data ());
13402
13403 for (int ndx = 0; ndx < aexpr->len; ++ndx)
13404 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13405 *pkt = '\0';
13406 }
13407 else
13408 warning (_("Target does not support conditional tracepoints, "
13409 "ignoring tp %d cond"), b->number);
13410 }
13411
13412 if (b->commands || !default_collect.empty ())
13413 {
13414 size_left = buf.size () - strlen (buf.data ());
13415
13416 ret = snprintf (buf.data () + strlen (buf.data ()),
13417 size_left, "-");
13418
13419 if (ret < 0 || ret >= size_left)
13420 error ("%s", err_msg);
13421 }
13422
13423 putpkt (buf.data ());
13424 remote_get_noisy_reply ();
13425 if (strcmp (rs->buf.data (), "OK"))
13426 error (_("Target does not support tracepoints."));
13427
13428 /* do_single_steps (t); */
13429 for (auto action_it = tdp_actions.begin ();
13430 action_it != tdp_actions.end (); action_it++)
13431 {
13432 QUIT; /* Allow user to bail out with ^C. */
13433
13434 bool has_more = ((action_it + 1) != tdp_actions.end ()
13435 || !stepping_actions.empty ());
13436
13437 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
13438 b->number, addrbuf, /* address */
13439 action_it->c_str (),
13440 has_more ? '-' : 0);
13441
13442 if (ret < 0 || ret >= buf.size ())
13443 error ("%s", err_msg);
13444
13445 putpkt (buf.data ());
13446 remote_get_noisy_reply ();
13447 if (strcmp (rs->buf.data (), "OK"))
13448 error (_("Error on target while setting tracepoints."));
13449 }
13450
13451 for (auto action_it = stepping_actions.begin ();
13452 action_it != stepping_actions.end (); action_it++)
13453 {
13454 QUIT; /* Allow user to bail out with ^C. */
13455
13456 bool is_first = action_it == stepping_actions.begin ();
13457 bool has_more = (action_it + 1) != stepping_actions.end ();
13458
13459 ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13460 b->number, addrbuf, /* address */
13461 is_first ? "S" : "",
13462 action_it->c_str (),
13463 has_more ? "-" : "");
13464
13465 if (ret < 0 || ret >= buf.size ())
13466 error ("%s", err_msg);
13467
13468 putpkt (buf.data ());
13469 remote_get_noisy_reply ();
13470 if (strcmp (rs->buf.data (), "OK"))
13471 error (_("Error on target while setting tracepoints."));
13472 }
13473
13474 if (m_features.packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13475 {
13476 if (b->locspec != nullptr)
13477 {
13478 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13479
13480 if (ret < 0 || ret >= buf.size ())
13481 error ("%s", err_msg);
13482
13483 const char *str = b->locspec->to_string ();
13484 encode_source_string (b->number, loc->address, "at", str,
13485 buf.data () + strlen (buf.data ()),
13486 buf.size () - strlen (buf.data ()));
13487 putpkt (buf.data ());
13488 remote_get_noisy_reply ();
13489 if (strcmp (rs->buf.data (), "OK"))
13490 warning (_("Target does not support source download."));
13491 }
13492 if (b->cond_string)
13493 {
13494 ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13495
13496 if (ret < 0 || ret >= buf.size ())
13497 error ("%s", err_msg);
13498
13499 encode_source_string (b->number, loc->address,
13500 "cond", b->cond_string.get (),
13501 buf.data () + strlen (buf.data ()),
13502 buf.size () - strlen (buf.data ()));
13503 putpkt (buf.data ());
13504 remote_get_noisy_reply ();
13505 if (strcmp (rs->buf.data (), "OK"))
13506 warning (_("Target does not support source download."));
13507 }
13508 remote_download_command_source (b->number, loc->address,
13509 breakpoint_commands (b));
13510 }
13511 }
13512
13513 bool
13514 remote_target::can_download_tracepoint ()
13515 {
13516 struct remote_state *rs = get_remote_state ();
13517 struct trace_status *ts;
13518 int status;
13519
13520 /* Don't try to install tracepoints until we've relocated our
13521 symbols, and fetched and merged the target's tracepoint list with
13522 ours. */
13523 if (rs->starting_up)
13524 return false;
13525
13526 ts = current_trace_status ();
13527 status = get_trace_status (ts);
13528
13529 if (status == -1 || !ts->running_known || !ts->running)
13530 return false;
13531
13532 /* If we are in a tracing experiment, but remote stub doesn't support
13533 installing tracepoint in trace, we have to return. */
13534 if (!remote_supports_install_in_trace ())
13535 return false;
13536
13537 return true;
13538 }
13539
13540
13541 void
13542 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13543 {
13544 struct remote_state *rs = get_remote_state ();
13545 char *p;
13546
13547 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13548 tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13549 tsv.builtin);
13550 p = rs->buf.data () + strlen (rs->buf.data ());
13551 if ((p - rs->buf.data ()) + tsv.name.length () * 2
13552 >= get_remote_packet_size ())
13553 error (_("Trace state variable name too long for tsv definition packet"));
13554 p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13555 *p++ = '\0';
13556 putpkt (rs->buf);
13557 remote_get_noisy_reply ();
13558 if (rs->buf[0] == '\0')
13559 error (_("Target does not support this command."));
13560 if (strcmp (rs->buf.data (), "OK") != 0)
13561 error (_("Error on target while downloading trace state variable."));
13562 }
13563
13564 void
13565 remote_target::enable_tracepoint (struct bp_location *location)
13566 {
13567 struct remote_state *rs = get_remote_state ();
13568
13569 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13570 location->owner->number,
13571 phex (location->address, sizeof (CORE_ADDR)));
13572 putpkt (rs->buf);
13573 remote_get_noisy_reply ();
13574 if (rs->buf[0] == '\0')
13575 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13576 if (strcmp (rs->buf.data (), "OK") != 0)
13577 error (_("Error on target while enabling tracepoint."));
13578 }
13579
13580 void
13581 remote_target::disable_tracepoint (struct bp_location *location)
13582 {
13583 struct remote_state *rs = get_remote_state ();
13584
13585 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13586 location->owner->number,
13587 phex (location->address, sizeof (CORE_ADDR)));
13588 putpkt (rs->buf);
13589 remote_get_noisy_reply ();
13590 if (rs->buf[0] == '\0')
13591 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13592 if (strcmp (rs->buf.data (), "OK") != 0)
13593 error (_("Error on target while disabling tracepoint."));
13594 }
13595
13596 void
13597 remote_target::trace_set_readonly_regions ()
13598 {
13599 asection *s;
13600 bfd_size_type size;
13601 bfd_vma vma;
13602 int anysecs = 0;
13603 int offset = 0;
13604 bfd *abfd = current_program_space->exec_bfd ();
13605
13606 if (!abfd)
13607 return; /* No information to give. */
13608
13609 struct remote_state *rs = get_remote_state ();
13610
13611 strcpy (rs->buf.data (), "QTro");
13612 offset = strlen (rs->buf.data ());
13613 for (s = abfd->sections; s; s = s->next)
13614 {
13615 char tmp1[40], tmp2[40];
13616 int sec_length;
13617
13618 if ((s->flags & SEC_LOAD) == 0
13619 /* || (s->flags & SEC_CODE) == 0 */
13620 || (s->flags & SEC_READONLY) == 0)
13621 continue;
13622
13623 anysecs = 1;
13624 vma = bfd_section_vma (s);
13625 size = bfd_section_size (s);
13626 bfd_sprintf_vma (abfd, tmp1, vma);
13627 bfd_sprintf_vma (abfd, tmp2, vma + size);
13628 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13629 if (offset + sec_length + 1 > rs->buf.size ())
13630 {
13631 if (m_features.packet_support (PACKET_qXfer_traceframe_info)
13632 != PACKET_ENABLE)
13633 warning (_("\
13634 Too many sections for read-only sections definition packet."));
13635 break;
13636 }
13637 xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13638 tmp1, tmp2);
13639 offset += sec_length;
13640 }
13641 if (anysecs)
13642 {
13643 putpkt (rs->buf);
13644 getpkt (&rs->buf, 0);
13645 }
13646 }
13647
13648 void
13649 remote_target::trace_start ()
13650 {
13651 struct remote_state *rs = get_remote_state ();
13652
13653 putpkt ("QTStart");
13654 remote_get_noisy_reply ();
13655 if (rs->buf[0] == '\0')
13656 error (_("Target does not support this command."));
13657 if (strcmp (rs->buf.data (), "OK") != 0)
13658 error (_("Bogus reply from target: %s"), rs->buf.data ());
13659 }
13660
13661 int
13662 remote_target::get_trace_status (struct trace_status *ts)
13663 {
13664 /* Initialize it just to avoid a GCC false warning. */
13665 char *p = NULL;
13666 enum packet_result result;
13667 struct remote_state *rs = get_remote_state ();
13668
13669 if (m_features.packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13670 return -1;
13671
13672 /* FIXME we need to get register block size some other way. */
13673 trace_regblock_size
13674 = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13675
13676 putpkt ("qTStatus");
13677
13678 try
13679 {
13680 p = remote_get_noisy_reply ();
13681 }
13682 catch (const gdb_exception_error &ex)
13683 {
13684 if (ex.error != TARGET_CLOSE_ERROR)
13685 {
13686 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13687 return -1;
13688 }
13689 throw;
13690 }
13691
13692 result = m_features.packet_ok (p, PACKET_qTStatus);
13693
13694 /* If the remote target doesn't do tracing, flag it. */
13695 if (result == PACKET_UNKNOWN)
13696 return -1;
13697
13698 /* We're working with a live target. */
13699 ts->filename = NULL;
13700
13701 if (*p++ != 'T')
13702 error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13703
13704 /* Function 'parse_trace_status' sets default value of each field of
13705 'ts' at first, so we don't have to do it here. */
13706 parse_trace_status (p, ts);
13707
13708 return ts->running;
13709 }
13710
13711 void
13712 remote_target::get_tracepoint_status (struct breakpoint *bp,
13713 struct uploaded_tp *utp)
13714 {
13715 struct remote_state *rs = get_remote_state ();
13716 char *reply;
13717 struct tracepoint *tp = (struct tracepoint *) bp;
13718 size_t size = get_remote_packet_size ();
13719
13720 if (tp)
13721 {
13722 tp->hit_count = 0;
13723 tp->traceframe_usage = 0;
13724 for (bp_location &loc : tp->locations ())
13725 {
13726 /* If the tracepoint was never downloaded, don't go asking for
13727 any status. */
13728 if (tp->number_on_target == 0)
13729 continue;
13730 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13731 phex_nz (loc.address, 0));
13732 putpkt (rs->buf);
13733 reply = remote_get_noisy_reply ();
13734 if (reply && *reply)
13735 {
13736 if (*reply == 'V')
13737 parse_tracepoint_status (reply + 1, bp, utp);
13738 }
13739 }
13740 }
13741 else if (utp)
13742 {
13743 utp->hit_count = 0;
13744 utp->traceframe_usage = 0;
13745 xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13746 phex_nz (utp->addr, 0));
13747 putpkt (rs->buf);
13748 reply = remote_get_noisy_reply ();
13749 if (reply && *reply)
13750 {
13751 if (*reply == 'V')
13752 parse_tracepoint_status (reply + 1, bp, utp);
13753 }
13754 }
13755 }
13756
13757 void
13758 remote_target::trace_stop ()
13759 {
13760 struct remote_state *rs = get_remote_state ();
13761
13762 putpkt ("QTStop");
13763 remote_get_noisy_reply ();
13764 if (rs->buf[0] == '\0')
13765 error (_("Target does not support this command."));
13766 if (strcmp (rs->buf.data (), "OK") != 0)
13767 error (_("Bogus reply from target: %s"), rs->buf.data ());
13768 }
13769
13770 int
13771 remote_target::trace_find (enum trace_find_type type, int num,
13772 CORE_ADDR addr1, CORE_ADDR addr2,
13773 int *tpp)
13774 {
13775 struct remote_state *rs = get_remote_state ();
13776 char *endbuf = rs->buf.data () + get_remote_packet_size ();
13777 char *p, *reply;
13778 int target_frameno = -1, target_tracept = -1;
13779
13780 /* Lookups other than by absolute frame number depend on the current
13781 trace selected, so make sure it is correct on the remote end
13782 first. */
13783 if (type != tfind_number)
13784 set_remote_traceframe ();
13785
13786 p = rs->buf.data ();
13787 strcpy (p, "QTFrame:");
13788 p = strchr (p, '\0');
13789 switch (type)
13790 {
13791 case tfind_number:
13792 xsnprintf (p, endbuf - p, "%x", num);
13793 break;
13794 case tfind_pc:
13795 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13796 break;
13797 case tfind_tp:
13798 xsnprintf (p, endbuf - p, "tdp:%x", num);
13799 break;
13800 case tfind_range:
13801 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13802 phex_nz (addr2, 0));
13803 break;
13804 case tfind_outside:
13805 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13806 phex_nz (addr2, 0));
13807 break;
13808 default:
13809 error (_("Unknown trace find type %d"), type);
13810 }
13811
13812 putpkt (rs->buf);
13813 reply = remote_get_noisy_reply ();
13814 if (*reply == '\0')
13815 error (_("Target does not support this command."));
13816
13817 while (reply && *reply)
13818 switch (*reply)
13819 {
13820 case 'F':
13821 p = ++reply;
13822 target_frameno = (int) strtol (p, &reply, 16);
13823 if (reply == p)
13824 error (_("Unable to parse trace frame number"));
13825 /* Don't update our remote traceframe number cache on failure
13826 to select a remote traceframe. */
13827 if (target_frameno == -1)
13828 return -1;
13829 break;
13830 case 'T':
13831 p = ++reply;
13832 target_tracept = (int) strtol (p, &reply, 16);
13833 if (reply == p)
13834 error (_("Unable to parse tracepoint number"));
13835 break;
13836 case 'O': /* "OK"? */
13837 if (reply[1] == 'K' && reply[2] == '\0')
13838 reply += 2;
13839 else
13840 error (_("Bogus reply from target: %s"), reply);
13841 break;
13842 default:
13843 error (_("Bogus reply from target: %s"), reply);
13844 }
13845 if (tpp)
13846 *tpp = target_tracept;
13847
13848 rs->remote_traceframe_number = target_frameno;
13849 return target_frameno;
13850 }
13851
13852 bool
13853 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13854 {
13855 struct remote_state *rs = get_remote_state ();
13856 char *reply;
13857 ULONGEST uval;
13858
13859 set_remote_traceframe ();
13860
13861 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13862 putpkt (rs->buf);
13863 reply = remote_get_noisy_reply ();
13864 if (reply && *reply)
13865 {
13866 if (*reply == 'V')
13867 {
13868 unpack_varlen_hex (reply + 1, &uval);
13869 *val = (LONGEST) uval;
13870 return true;
13871 }
13872 }
13873 return false;
13874 }
13875
13876 int
13877 remote_target::save_trace_data (const char *filename)
13878 {
13879 struct remote_state *rs = get_remote_state ();
13880 char *p, *reply;
13881
13882 p = rs->buf.data ();
13883 strcpy (p, "QTSave:");
13884 p += strlen (p);
13885 if ((p - rs->buf.data ()) + strlen (filename) * 2
13886 >= get_remote_packet_size ())
13887 error (_("Remote file name too long for trace save packet"));
13888 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13889 *p++ = '\0';
13890 putpkt (rs->buf);
13891 reply = remote_get_noisy_reply ();
13892 if (*reply == '\0')
13893 error (_("Target does not support this command."));
13894 if (strcmp (reply, "OK") != 0)
13895 error (_("Bogus reply from target: %s"), reply);
13896 return 0;
13897 }
13898
13899 /* This is basically a memory transfer, but needs to be its own packet
13900 because we don't know how the target actually organizes its trace
13901 memory, plus we want to be able to ask for as much as possible, but
13902 not be unhappy if we don't get as much as we ask for. */
13903
13904 LONGEST
13905 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13906 {
13907 struct remote_state *rs = get_remote_state ();
13908 char *reply;
13909 char *p;
13910 int rslt;
13911
13912 p = rs->buf.data ();
13913 strcpy (p, "qTBuffer:");
13914 p += strlen (p);
13915 p += hexnumstr (p, offset);
13916 *p++ = ',';
13917 p += hexnumstr (p, len);
13918 *p++ = '\0';
13919
13920 putpkt (rs->buf);
13921 reply = remote_get_noisy_reply ();
13922 if (reply && *reply)
13923 {
13924 /* 'l' by itself means we're at the end of the buffer and
13925 there is nothing more to get. */
13926 if (*reply == 'l')
13927 return 0;
13928
13929 /* Convert the reply into binary. Limit the number of bytes to
13930 convert according to our passed-in buffer size, rather than
13931 what was returned in the packet; if the target is
13932 unexpectedly generous and gives us a bigger reply than we
13933 asked for, we don't want to crash. */
13934 rslt = hex2bin (reply, buf, len);
13935 return rslt;
13936 }
13937
13938 /* Something went wrong, flag as an error. */
13939 return -1;
13940 }
13941
13942 void
13943 remote_target::set_disconnected_tracing (int val)
13944 {
13945 struct remote_state *rs = get_remote_state ();
13946
13947 if (m_features.packet_support (PACKET_DisconnectedTracing_feature)
13948 == PACKET_ENABLE)
13949 {
13950 char *reply;
13951
13952 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13953 "QTDisconnected:%x", val);
13954 putpkt (rs->buf);
13955 reply = remote_get_noisy_reply ();
13956 if (*reply == '\0')
13957 error (_("Target does not support this command."));
13958 if (strcmp (reply, "OK") != 0)
13959 error (_("Bogus reply from target: %s"), reply);
13960 }
13961 else if (val)
13962 warning (_("Target does not support disconnected tracing."));
13963 }
13964
13965 int
13966 remote_target::core_of_thread (ptid_t ptid)
13967 {
13968 thread_info *info = this->find_thread (ptid);
13969
13970 if (info != NULL && info->priv != NULL)
13971 return get_remote_thread_info (info)->core;
13972
13973 return -1;
13974 }
13975
13976 void
13977 remote_target::set_circular_trace_buffer (int val)
13978 {
13979 struct remote_state *rs = get_remote_state ();
13980 char *reply;
13981
13982 xsnprintf (rs->buf.data (), get_remote_packet_size (),
13983 "QTBuffer:circular:%x", val);
13984 putpkt (rs->buf);
13985 reply = remote_get_noisy_reply ();
13986 if (*reply == '\0')
13987 error (_("Target does not support this command."));
13988 if (strcmp (reply, "OK") != 0)
13989 error (_("Bogus reply from target: %s"), reply);
13990 }
13991
13992 traceframe_info_up
13993 remote_target::traceframe_info ()
13994 {
13995 gdb::optional<gdb::char_vector> text
13996 = target_read_stralloc (current_inferior ()->top_target (),
13997 TARGET_OBJECT_TRACEFRAME_INFO,
13998 NULL);
13999 if (text)
14000 return parse_traceframe_info (text->data ());
14001
14002 return NULL;
14003 }
14004
14005 /* Handle the qTMinFTPILen packet. Returns the minimum length of
14006 instruction on which a fast tracepoint may be placed. Returns -1
14007 if the packet is not supported, and 0 if the minimum instruction
14008 length is unknown. */
14009
14010 int
14011 remote_target::get_min_fast_tracepoint_insn_len ()
14012 {
14013 struct remote_state *rs = get_remote_state ();
14014 char *reply;
14015
14016 /* If we're not debugging a process yet, the IPA can't be
14017 loaded. */
14018 if (!target_has_execution ())
14019 return 0;
14020
14021 /* Make sure the remote is pointing at the right process. */
14022 set_general_process ();
14023
14024 xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
14025 putpkt (rs->buf);
14026 reply = remote_get_noisy_reply ();
14027 if (*reply == '\0')
14028 return -1;
14029 else
14030 {
14031 ULONGEST min_insn_len;
14032
14033 unpack_varlen_hex (reply, &min_insn_len);
14034
14035 return (int) min_insn_len;
14036 }
14037 }
14038
14039 void
14040 remote_target::set_trace_buffer_size (LONGEST val)
14041 {
14042 if (m_features.packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
14043 {
14044 struct remote_state *rs = get_remote_state ();
14045 char *buf = rs->buf.data ();
14046 char *endbuf = buf + get_remote_packet_size ();
14047 enum packet_result result;
14048
14049 gdb_assert (val >= 0 || val == -1);
14050 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
14051 /* Send -1 as literal "-1" to avoid host size dependency. */
14052 if (val < 0)
14053 {
14054 *buf++ = '-';
14055 buf += hexnumstr (buf, (ULONGEST) -val);
14056 }
14057 else
14058 buf += hexnumstr (buf, (ULONGEST) val);
14059
14060 putpkt (rs->buf);
14061 remote_get_noisy_reply ();
14062 result = m_features.packet_ok (rs->buf, PACKET_QTBuffer_size);
14063
14064 if (result != PACKET_OK)
14065 warning (_("Bogus reply from target: %s"), rs->buf.data ());
14066 }
14067 }
14068
14069 bool
14070 remote_target::set_trace_notes (const char *user, const char *notes,
14071 const char *stop_notes)
14072 {
14073 struct remote_state *rs = get_remote_state ();
14074 char *reply;
14075 char *buf = rs->buf.data ();
14076 char *endbuf = buf + get_remote_packet_size ();
14077 int nbytes;
14078
14079 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
14080 if (user)
14081 {
14082 buf += xsnprintf (buf, endbuf - buf, "user:");
14083 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
14084 buf += 2 * nbytes;
14085 *buf++ = ';';
14086 }
14087 if (notes)
14088 {
14089 buf += xsnprintf (buf, endbuf - buf, "notes:");
14090 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
14091 buf += 2 * nbytes;
14092 *buf++ = ';';
14093 }
14094 if (stop_notes)
14095 {
14096 buf += xsnprintf (buf, endbuf - buf, "tstop:");
14097 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
14098 buf += 2 * nbytes;
14099 *buf++ = ';';
14100 }
14101 /* Ensure the buffer is terminated. */
14102 *buf = '\0';
14103
14104 putpkt (rs->buf);
14105 reply = remote_get_noisy_reply ();
14106 if (*reply == '\0')
14107 return false;
14108
14109 if (strcmp (reply, "OK") != 0)
14110 error (_("Bogus reply from target: %s"), reply);
14111
14112 return true;
14113 }
14114
14115 bool
14116 remote_target::use_agent (bool use)
14117 {
14118 if (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE)
14119 {
14120 struct remote_state *rs = get_remote_state ();
14121
14122 /* If the stub supports QAgent. */
14123 xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
14124 putpkt (rs->buf);
14125 getpkt (&rs->buf, 0);
14126
14127 if (strcmp (rs->buf.data (), "OK") == 0)
14128 {
14129 ::use_agent = use;
14130 return true;
14131 }
14132 }
14133
14134 return false;
14135 }
14136
14137 bool
14138 remote_target::can_use_agent ()
14139 {
14140 return (m_features.packet_support (PACKET_QAgent) != PACKET_DISABLE);
14141 }
14142
14143 struct btrace_target_info
14144 {
14145 /* The ptid of the traced thread. */
14146 ptid_t ptid;
14147
14148 /* The obtained branch trace configuration. */
14149 struct btrace_config conf;
14150 };
14151
14152 /* Reset our idea of our target's btrace configuration. */
14153
14154 static void
14155 remote_btrace_reset (remote_state *rs)
14156 {
14157 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
14158 }
14159
14160 /* Synchronize the configuration with the target. */
14161
14162 void
14163 remote_target::btrace_sync_conf (const btrace_config *conf)
14164 {
14165 struct remote_state *rs;
14166 char *buf, *pos, *endbuf;
14167
14168 rs = get_remote_state ();
14169 buf = rs->buf.data ();
14170 endbuf = buf + get_remote_packet_size ();
14171
14172 if (m_features.packet_support (PACKET_Qbtrace_conf_bts_size) == PACKET_ENABLE
14173 && conf->bts.size != rs->btrace_config.bts.size)
14174 {
14175 pos = buf;
14176 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14177 packets_descriptions[PACKET_Qbtrace_conf_bts_size].name,
14178 conf->bts.size);
14179
14180 putpkt (buf);
14181 getpkt (&rs->buf, 0);
14182
14183 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_bts_size)
14184 == PACKET_ERROR)
14185 {
14186 if (buf[0] == 'E' && buf[1] == '.')
14187 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
14188 else
14189 error (_("Failed to configure the BTS buffer size."));
14190 }
14191
14192 rs->btrace_config.bts.size = conf->bts.size;
14193 }
14194
14195 if (m_features.packet_support (PACKET_Qbtrace_conf_pt_size) == PACKET_ENABLE
14196 && conf->pt.size != rs->btrace_config.pt.size)
14197 {
14198 pos = buf;
14199 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x",
14200 packets_descriptions[PACKET_Qbtrace_conf_pt_size].name,
14201 conf->pt.size);
14202
14203 putpkt (buf);
14204 getpkt (&rs->buf, 0);
14205
14206 if (m_features.packet_ok (buf, PACKET_Qbtrace_conf_pt_size)
14207 == PACKET_ERROR)
14208 {
14209 if (buf[0] == 'E' && buf[1] == '.')
14210 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
14211 else
14212 error (_("Failed to configure the trace buffer size."));
14213 }
14214
14215 rs->btrace_config.pt.size = conf->pt.size;
14216 }
14217 }
14218
14219 /* Read TP's btrace configuration from the target and store it into CONF. */
14220
14221 static void
14222 btrace_read_config (thread_info *tp, struct btrace_config *conf)
14223 {
14224 /* target_read_stralloc relies on INFERIOR_PTID. */
14225 scoped_restore_current_thread restore_thread;
14226 switch_to_thread (tp);
14227
14228 gdb::optional<gdb::char_vector> xml
14229 = target_read_stralloc (current_inferior ()->top_target (),
14230 TARGET_OBJECT_BTRACE_CONF, "");
14231 if (xml)
14232 parse_xml_btrace_conf (conf, xml->data ());
14233 }
14234
14235 /* Maybe reopen target btrace. */
14236
14237 void
14238 remote_target::remote_btrace_maybe_reopen ()
14239 {
14240 struct remote_state *rs = get_remote_state ();
14241 int btrace_target_pushed = 0;
14242 #if !defined (HAVE_LIBIPT)
14243 int warned = 0;
14244 #endif
14245
14246 /* Don't bother walking the entirety of the remote thread list when
14247 we know the feature isn't supported by the remote. */
14248 if (m_features.packet_support (PACKET_qXfer_btrace_conf) != PACKET_ENABLE)
14249 return;
14250
14251 for (thread_info *tp : all_non_exited_threads (this))
14252 {
14253 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
14254 btrace_read_config (tp, &rs->btrace_config);
14255
14256 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
14257 continue;
14258
14259 #if !defined (HAVE_LIBIPT)
14260 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
14261 {
14262 if (!warned)
14263 {
14264 warned = 1;
14265 warning (_("Target is recording using Intel Processor Trace "
14266 "but support was disabled at compile time."));
14267 }
14268
14269 continue;
14270 }
14271 #endif /* !defined (HAVE_LIBIPT) */
14272
14273 /* Push target, once, but before anything else happens. This way our
14274 changes to the threads will be cleaned up by unpushing the target
14275 in case btrace_read_config () throws. */
14276 if (!btrace_target_pushed)
14277 {
14278 btrace_target_pushed = 1;
14279 record_btrace_push_target ();
14280 gdb_printf (_("Target is recording using %s.\n"),
14281 btrace_format_string (rs->btrace_config.format));
14282 }
14283
14284 tp->btrace.target = XCNEW (struct btrace_target_info);
14285 tp->btrace.target->ptid = tp->ptid;
14286 tp->btrace.target->conf = rs->btrace_config;
14287 }
14288 }
14289
14290 /* Enable branch tracing. */
14291
14292 struct btrace_target_info *
14293 remote_target::enable_btrace (thread_info *tp,
14294 const struct btrace_config *conf)
14295 {
14296 struct btrace_target_info *tinfo = NULL;
14297 struct packet_config *packet = NULL;
14298 struct remote_state *rs = get_remote_state ();
14299 char *buf = rs->buf.data ();
14300 char *endbuf = buf + get_remote_packet_size ();
14301
14302 unsigned int which_packet;
14303 switch (conf->format)
14304 {
14305 case BTRACE_FORMAT_BTS:
14306 which_packet = PACKET_Qbtrace_bts;
14307 break;
14308 case BTRACE_FORMAT_PT:
14309 which_packet = PACKET_Qbtrace_pt;
14310 break;
14311 default:
14312 internal_error (_("Bad branch btrace format: %u."),
14313 (unsigned int) conf->format);
14314 }
14315
14316 packet = &m_features.m_protocol_packets[which_packet];
14317 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
14318 error (_("Target does not support branch tracing."));
14319
14320 btrace_sync_conf (conf);
14321
14322 ptid_t ptid = tp->ptid;
14323 set_general_thread (ptid);
14324
14325 buf += xsnprintf (buf, endbuf - buf, "%s",
14326 packets_descriptions[which_packet].name);
14327 putpkt (rs->buf);
14328 getpkt (&rs->buf, 0);
14329
14330 if (m_features.packet_ok (rs->buf, which_packet) == PACKET_ERROR)
14331 {
14332 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14333 error (_("Could not enable branch tracing for %s: %s"),
14334 target_pid_to_str (ptid).c_str (), &rs->buf[2]);
14335 else
14336 error (_("Could not enable branch tracing for %s."),
14337 target_pid_to_str (ptid).c_str ());
14338 }
14339
14340 tinfo = XCNEW (struct btrace_target_info);
14341 tinfo->ptid = ptid;
14342
14343 /* If we fail to read the configuration, we lose some information, but the
14344 tracing itself is not impacted. */
14345 try
14346 {
14347 btrace_read_config (tp, &tinfo->conf);
14348 }
14349 catch (const gdb_exception_error &err)
14350 {
14351 if (err.message != NULL)
14352 warning ("%s", err.what ());
14353 }
14354
14355 return tinfo;
14356 }
14357
14358 /* Disable branch tracing. */
14359
14360 void
14361 remote_target::disable_btrace (struct btrace_target_info *tinfo)
14362 {
14363 struct remote_state *rs = get_remote_state ();
14364 char *buf = rs->buf.data ();
14365 char *endbuf = buf + get_remote_packet_size ();
14366
14367 if (m_features.packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
14368 error (_("Target does not support branch tracing."));
14369
14370 set_general_thread (tinfo->ptid);
14371
14372 buf += xsnprintf (buf, endbuf - buf, "%s",
14373 packets_descriptions[PACKET_Qbtrace_off].name);
14374 putpkt (rs->buf);
14375 getpkt (&rs->buf, 0);
14376
14377 if (m_features.packet_ok (rs->buf, PACKET_Qbtrace_off) == PACKET_ERROR)
14378 {
14379 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
14380 error (_("Could not disable branch tracing for %s: %s"),
14381 target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
14382 else
14383 error (_("Could not disable branch tracing for %s."),
14384 target_pid_to_str (tinfo->ptid).c_str ());
14385 }
14386
14387 xfree (tinfo);
14388 }
14389
14390 /* Teardown branch tracing. */
14391
14392 void
14393 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
14394 {
14395 /* We must not talk to the target during teardown. */
14396 xfree (tinfo);
14397 }
14398
14399 /* Read the branch trace. */
14400
14401 enum btrace_error
14402 remote_target::read_btrace (struct btrace_data *btrace,
14403 struct btrace_target_info *tinfo,
14404 enum btrace_read_type type)
14405 {
14406 const char *annex;
14407
14408 if (m_features.packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
14409 error (_("Target does not support branch tracing."));
14410
14411 #if !defined(HAVE_LIBEXPAT)
14412 error (_("Cannot process branch tracing result. XML parsing not supported."));
14413 #endif
14414
14415 switch (type)
14416 {
14417 case BTRACE_READ_ALL:
14418 annex = "all";
14419 break;
14420 case BTRACE_READ_NEW:
14421 annex = "new";
14422 break;
14423 case BTRACE_READ_DELTA:
14424 annex = "delta";
14425 break;
14426 default:
14427 internal_error (_("Bad branch tracing read type: %u."),
14428 (unsigned int) type);
14429 }
14430
14431 gdb::optional<gdb::char_vector> xml
14432 = target_read_stralloc (current_inferior ()->top_target (),
14433 TARGET_OBJECT_BTRACE, annex);
14434 if (!xml)
14435 return BTRACE_ERR_UNKNOWN;
14436
14437 parse_xml_btrace (btrace, xml->data ());
14438
14439 return BTRACE_ERR_NONE;
14440 }
14441
14442 const struct btrace_config *
14443 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14444 {
14445 return &tinfo->conf;
14446 }
14447
14448 bool
14449 remote_target::augmented_libraries_svr4_read ()
14450 {
14451 return
14452 (m_features.packet_support (PACKET_augmented_libraries_svr4_read_feature)
14453 == PACKET_ENABLE);
14454 }
14455
14456 /* Implementation of to_load. */
14457
14458 void
14459 remote_target::load (const char *name, int from_tty)
14460 {
14461 generic_load (name, from_tty);
14462 }
14463
14464 /* Accepts an integer PID; returns a string representing a file that
14465 can be opened on the remote side to get the symbols for the child
14466 process. Returns NULL if the operation is not supported. */
14467
14468 const char *
14469 remote_target::pid_to_exec_file (int pid)
14470 {
14471 static gdb::optional<gdb::char_vector> filename;
14472 char *annex = NULL;
14473
14474 if (m_features.packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14475 return NULL;
14476
14477 inferior *inf = find_inferior_pid (this, pid);
14478 if (inf == NULL)
14479 internal_error (_("not currently attached to process %d"), pid);
14480
14481 if (!inf->fake_pid_p)
14482 {
14483 const int annex_size = 9;
14484
14485 annex = (char *) alloca (annex_size);
14486 xsnprintf (annex, annex_size, "%x", pid);
14487 }
14488
14489 filename = target_read_stralloc (current_inferior ()->top_target (),
14490 TARGET_OBJECT_EXEC_FILE, annex);
14491
14492 return filename ? filename->data () : nullptr;
14493 }
14494
14495 /* Implement the to_can_do_single_step target_ops method. */
14496
14497 int
14498 remote_target::can_do_single_step ()
14499 {
14500 /* We can only tell whether target supports single step or not by
14501 supported s and S vCont actions if the stub supports vContSupported
14502 feature. If the stub doesn't support vContSupported feature,
14503 we have conservatively to think target doesn't supports single
14504 step. */
14505 if (m_features.packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14506 {
14507 struct remote_state *rs = get_remote_state ();
14508
14509 return rs->supports_vCont.s && rs->supports_vCont.S;
14510 }
14511 else
14512 return 0;
14513 }
14514
14515 /* Implementation of the to_execution_direction method for the remote
14516 target. */
14517
14518 enum exec_direction_kind
14519 remote_target::execution_direction ()
14520 {
14521 struct remote_state *rs = get_remote_state ();
14522
14523 return rs->last_resume_exec_dir;
14524 }
14525
14526 /* Return pointer to the thread_info struct which corresponds to
14527 THREAD_HANDLE (having length HANDLE_LEN). */
14528
14529 thread_info *
14530 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14531 int handle_len,
14532 inferior *inf)
14533 {
14534 for (thread_info *tp : all_non_exited_threads (this))
14535 {
14536 remote_thread_info *priv = get_remote_thread_info (tp);
14537
14538 if (tp->inf == inf && priv != NULL)
14539 {
14540 if (handle_len != priv->thread_handle.size ())
14541 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14542 handle_len, priv->thread_handle.size ());
14543 if (memcmp (thread_handle, priv->thread_handle.data (),
14544 handle_len) == 0)
14545 return tp;
14546 }
14547 }
14548
14549 return NULL;
14550 }
14551
14552 gdb::byte_vector
14553 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14554 {
14555 remote_thread_info *priv = get_remote_thread_info (tp);
14556 return priv->thread_handle;
14557 }
14558
14559 bool
14560 remote_target::can_async_p ()
14561 {
14562 /* This flag should be checked in the common target.c code. */
14563 gdb_assert (target_async_permitted);
14564
14565 /* We're async whenever the serial device can. */
14566 struct remote_state *rs = get_remote_state ();
14567 return serial_can_async_p (rs->remote_desc);
14568 }
14569
14570 bool
14571 remote_target::is_async_p ()
14572 {
14573 /* We're async whenever the serial device is. */
14574 struct remote_state *rs = get_remote_state ();
14575 return serial_is_async_p (rs->remote_desc);
14576 }
14577
14578 /* Pass the SERIAL event on and up to the client. One day this code
14579 will be able to delay notifying the client of an event until the
14580 point where an entire packet has been received. */
14581
14582 static serial_event_ftype remote_async_serial_handler;
14583
14584 static void
14585 remote_async_serial_handler (struct serial *scb, void *context)
14586 {
14587 /* Don't propogate error information up to the client. Instead let
14588 the client find out about the error by querying the target. */
14589 inferior_event_handler (INF_REG_EVENT);
14590 }
14591
14592 static void
14593 remote_async_inferior_event_handler (gdb_client_data data)
14594 {
14595 inferior_event_handler (INF_REG_EVENT);
14596 }
14597
14598 int
14599 remote_target::async_wait_fd ()
14600 {
14601 struct remote_state *rs = get_remote_state ();
14602 return rs->remote_desc->fd;
14603 }
14604
14605 void
14606 remote_target::async (bool enable)
14607 {
14608 struct remote_state *rs = get_remote_state ();
14609
14610 if (enable)
14611 {
14612 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14613
14614 /* If there are pending events in the stop reply queue tell the
14615 event loop to process them. */
14616 if (!rs->stop_reply_queue.empty ())
14617 mark_async_event_handler (rs->remote_async_inferior_event_token);
14618 /* For simplicity, below we clear the pending events token
14619 without remembering whether it is marked, so here we always
14620 mark it. If there's actually no pending notification to
14621 process, this ends up being a no-op (other than a spurious
14622 event-loop wakeup). */
14623 if (target_is_non_stop_p ())
14624 mark_async_event_handler (rs->notif_state->get_pending_events_token);
14625 }
14626 else
14627 {
14628 serial_async (rs->remote_desc, NULL, NULL);
14629 /* If the core is disabling async, it doesn't want to be
14630 disturbed with target events. Clear all async event sources
14631 too. */
14632 clear_async_event_handler (rs->remote_async_inferior_event_token);
14633 if (target_is_non_stop_p ())
14634 clear_async_event_handler (rs->notif_state->get_pending_events_token);
14635 }
14636 }
14637
14638 /* Implementation of the to_thread_events method. */
14639
14640 void
14641 remote_target::thread_events (int enable)
14642 {
14643 struct remote_state *rs = get_remote_state ();
14644 size_t size = get_remote_packet_size ();
14645
14646 if (m_features.packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14647 return;
14648
14649 xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14650 putpkt (rs->buf);
14651 getpkt (&rs->buf, 0);
14652
14653 switch (m_features.packet_ok (rs->buf, PACKET_QThreadEvents))
14654 {
14655 case PACKET_OK:
14656 if (strcmp (rs->buf.data (), "OK") != 0)
14657 error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14658 break;
14659 case PACKET_ERROR:
14660 warning (_("Remote failure reply: %s"), rs->buf.data ());
14661 break;
14662 case PACKET_UNKNOWN:
14663 break;
14664 }
14665 }
14666
14667 static void
14668 show_remote_cmd (const char *args, int from_tty)
14669 {
14670 /* We can't just use cmd_show_list here, because we want to skip
14671 the redundant "show remote Z-packet" and the legacy aliases. */
14672 struct cmd_list_element *list = remote_show_cmdlist;
14673 struct ui_out *uiout = current_uiout;
14674
14675 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14676 for (; list != NULL; list = list->next)
14677 if (strcmp (list->name, "Z-packet") == 0)
14678 continue;
14679 else if (list->type == not_set_cmd)
14680 /* Alias commands are exactly like the original, except they
14681 don't have the normal type. */
14682 continue;
14683 else
14684 {
14685 ui_out_emit_tuple option_emitter (uiout, "option");
14686
14687 uiout->field_string ("name", list->name);
14688 uiout->text (": ");
14689 if (list->type == show_cmd)
14690 do_show_command (NULL, from_tty, list);
14691 else
14692 cmd_func (list, NULL, from_tty);
14693 }
14694 }
14695
14696
14697 /* Function to be called whenever a new objfile (shlib) is detected. */
14698 static void
14699 remote_new_objfile (struct objfile *objfile)
14700 {
14701 /* The objfile change happened in that program space. */
14702 program_space *pspace = current_program_space;
14703
14704 /* The affected program space is possibly shared by multiple inferiors.
14705 Consider sending a qSymbol packet for each of the inferiors using that
14706 program space. */
14707 for (inferior *inf : all_inferiors ())
14708 {
14709 if (inf->pspace != pspace)
14710 continue;
14711
14712 /* Check whether the inferior's process target is a remote target. */
14713 remote_target *remote = as_remote_target (inf->process_target ());
14714 if (remote == nullptr)
14715 continue;
14716
14717 /* When we are attaching or handling a fork child and the shared library
14718 subsystem reads the list of loaded libraries, we receive new objfile
14719 events in between each found library. The libraries are read in an
14720 undefined order, so if we gave the remote side a chance to look up
14721 symbols between each objfile, we might give it an inconsistent picture
14722 of the inferior. It could appear that a library A appears loaded but
14723 a library B does not, even though library A requires library B. That
14724 would present a state that couldn't normally exist in the inferior.
14725
14726 So, skip these events, we'll give the remote a chance to look up
14727 symbols once all the loaded libraries and their symbols are known to
14728 GDB. */
14729 if (inf->in_initial_library_scan)
14730 continue;
14731
14732 if (!remote->has_execution (inf))
14733 continue;
14734
14735 /* Need to switch to a specific thread, because remote_check_symbols will
14736 set the general thread using INFERIOR_PTID.
14737
14738 It's possible to have inferiors with no thread here, because we are
14739 called very early in the connection process, while the inferior is
14740 being set up, before threads are added. Just skip it, start_remote_1
14741 also calls remote_check_symbols when it's done setting things up. */
14742 thread_info *thread = any_thread_of_inferior (inf);
14743 if (thread != nullptr)
14744 {
14745 scoped_restore_current_thread restore_thread;
14746 switch_to_thread (thread);
14747 remote->remote_check_symbols ();
14748 }
14749 }
14750 }
14751
14752 /* Pull all the tracepoints defined on the target and create local
14753 data structures representing them. We don't want to create real
14754 tracepoints yet, we don't want to mess up the user's existing
14755 collection. */
14756
14757 int
14758 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14759 {
14760 struct remote_state *rs = get_remote_state ();
14761 char *p;
14762
14763 /* Ask for a first packet of tracepoint definition. */
14764 putpkt ("qTfP");
14765 getpkt (&rs->buf, 0);
14766 p = rs->buf.data ();
14767 while (*p && *p != 'l')
14768 {
14769 parse_tracepoint_definition (p, utpp);
14770 /* Ask for another packet of tracepoint definition. */
14771 putpkt ("qTsP");
14772 getpkt (&rs->buf, 0);
14773 p = rs->buf.data ();
14774 }
14775 return 0;
14776 }
14777
14778 int
14779 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14780 {
14781 struct remote_state *rs = get_remote_state ();
14782 char *p;
14783
14784 /* Ask for a first packet of variable definition. */
14785 putpkt ("qTfV");
14786 getpkt (&rs->buf, 0);
14787 p = rs->buf.data ();
14788 while (*p && *p != 'l')
14789 {
14790 parse_tsv_definition (p, utsvp);
14791 /* Ask for another packet of variable definition. */
14792 putpkt ("qTsV");
14793 getpkt (&rs->buf, 0);
14794 p = rs->buf.data ();
14795 }
14796 return 0;
14797 }
14798
14799 /* The "set/show range-stepping" show hook. */
14800
14801 static void
14802 show_range_stepping (struct ui_file *file, int from_tty,
14803 struct cmd_list_element *c,
14804 const char *value)
14805 {
14806 gdb_printf (file,
14807 _("Debugger's willingness to use range stepping "
14808 "is %s.\n"), value);
14809 }
14810
14811 /* Return true if the vCont;r action is supported by the remote
14812 stub. */
14813
14814 bool
14815 remote_target::vcont_r_supported ()
14816 {
14817 return (m_features.packet_support (PACKET_vCont) == PACKET_ENABLE
14818 && get_remote_state ()->supports_vCont.r);
14819 }
14820
14821 /* The "set/show range-stepping" set hook. */
14822
14823 static void
14824 set_range_stepping (const char *ignore_args, int from_tty,
14825 struct cmd_list_element *c)
14826 {
14827 /* When enabling, check whether range stepping is actually supported
14828 by the target, and warn if not. */
14829 if (use_range_stepping)
14830 {
14831 remote_target *remote = get_current_remote_target ();
14832 if (remote == NULL
14833 || !remote->vcont_r_supported ())
14834 warning (_("Range stepping is not supported by the current target"));
14835 }
14836 }
14837
14838 static void
14839 show_remote_debug (struct ui_file *file, int from_tty,
14840 struct cmd_list_element *c, const char *value)
14841 {
14842 gdb_printf (file, _("Debugging of remote protocol is %s.\n"),
14843 value);
14844 }
14845
14846 static void
14847 show_remote_timeout (struct ui_file *file, int from_tty,
14848 struct cmd_list_element *c, const char *value)
14849 {
14850 gdb_printf (file,
14851 _("Timeout limit to wait for target to respond is %s.\n"),
14852 value);
14853 }
14854
14855 /* Implement the "supports_memory_tagging" target_ops method. */
14856
14857 bool
14858 remote_target::supports_memory_tagging ()
14859 {
14860 return m_features.remote_memory_tagging_p ();
14861 }
14862
14863 /* Create the qMemTags packet given ADDRESS, LEN and TYPE. */
14864
14865 static void
14866 create_fetch_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14867 size_t len, int type)
14868 {
14869 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14870
14871 std::string request = string_printf ("qMemTags:%s,%s:%s",
14872 phex_nz (address, addr_size),
14873 phex_nz (len, sizeof (len)),
14874 phex_nz (type, sizeof (type)));
14875
14876 strcpy (packet.data (), request.c_str ());
14877 }
14878
14879 /* Parse the qMemTags packet reply into TAGS.
14880
14881 Return true if successful, false otherwise. */
14882
14883 static bool
14884 parse_fetch_memtags_reply (const gdb::char_vector &reply,
14885 gdb::byte_vector &tags)
14886 {
14887 if (reply.empty () || reply[0] == 'E' || reply[0] != 'm')
14888 return false;
14889
14890 /* Copy the tag data. */
14891 tags = hex2bin (reply.data () + 1);
14892
14893 return true;
14894 }
14895
14896 /* Create the QMemTags packet given ADDRESS, LEN, TYPE and TAGS. */
14897
14898 static void
14899 create_store_memtags_request (gdb::char_vector &packet, CORE_ADDR address,
14900 size_t len, int type,
14901 const gdb::byte_vector &tags)
14902 {
14903 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
14904
14905 /* Put together the main packet, address and length. */
14906 std::string request = string_printf ("QMemTags:%s,%s:%s:",
14907 phex_nz (address, addr_size),
14908 phex_nz (len, sizeof (len)),
14909 phex_nz (type, sizeof (type)));
14910 request += bin2hex (tags.data (), tags.size ());
14911
14912 /* Check if we have exceeded the maximum packet size. */
14913 if (packet.size () < request.length ())
14914 error (_("Contents too big for packet QMemTags."));
14915
14916 strcpy (packet.data (), request.c_str ());
14917 }
14918
14919 /* Implement the "fetch_memtags" target_ops method. */
14920
14921 bool
14922 remote_target::fetch_memtags (CORE_ADDR address, size_t len,
14923 gdb::byte_vector &tags, int type)
14924 {
14925 /* Make sure the qMemTags packet is supported. */
14926 if (!m_features.remote_memory_tagging_p ())
14927 gdb_assert_not_reached ("remote fetch_memtags called with packet disabled");
14928
14929 struct remote_state *rs = get_remote_state ();
14930
14931 create_fetch_memtags_request (rs->buf, address, len, type);
14932
14933 putpkt (rs->buf);
14934 getpkt (&rs->buf, 0);
14935
14936 return parse_fetch_memtags_reply (rs->buf, tags);
14937 }
14938
14939 /* Implement the "store_memtags" target_ops method. */
14940
14941 bool
14942 remote_target::store_memtags (CORE_ADDR address, size_t len,
14943 const gdb::byte_vector &tags, int type)
14944 {
14945 /* Make sure the QMemTags packet is supported. */
14946 if (!m_features.remote_memory_tagging_p ())
14947 gdb_assert_not_reached ("remote store_memtags called with packet disabled");
14948
14949 struct remote_state *rs = get_remote_state ();
14950
14951 create_store_memtags_request (rs->buf, address, len, type, tags);
14952
14953 putpkt (rs->buf);
14954 getpkt (&rs->buf, 0);
14955
14956 /* Verify if the request was successful. */
14957 return packet_check_result (rs->buf.data ()) == PACKET_OK;
14958 }
14959
14960 /* Return true if remote target T is non-stop. */
14961
14962 bool
14963 remote_target_is_non_stop_p (remote_target *t)
14964 {
14965 scoped_restore_current_thread restore_thread;
14966 switch_to_target_no_thread (t);
14967
14968 return target_is_non_stop_p ();
14969 }
14970
14971 #if GDB_SELF_TEST
14972
14973 namespace selftests {
14974
14975 static void
14976 test_memory_tagging_functions ()
14977 {
14978 remote_target remote;
14979
14980 struct packet_config *config
14981 = &remote.m_features.m_protocol_packets[PACKET_memory_tagging_feature];
14982
14983 scoped_restore restore_memtag_support_
14984 = make_scoped_restore (&config->support);
14985
14986 /* Test memory tagging packet support. */
14987 config->support = PACKET_SUPPORT_UNKNOWN;
14988 SELF_CHECK (remote.supports_memory_tagging () == false);
14989 config->support = PACKET_DISABLE;
14990 SELF_CHECK (remote.supports_memory_tagging () == false);
14991 config->support = PACKET_ENABLE;
14992 SELF_CHECK (remote.supports_memory_tagging () == true);
14993
14994 /* Setup testing. */
14995 gdb::char_vector packet;
14996 gdb::byte_vector tags, bv;
14997 std::string expected, reply;
14998 packet.resize (32000);
14999
15000 /* Test creating a qMemTags request. */
15001
15002 expected = "qMemTags:0,0:0";
15003 create_fetch_memtags_request (packet, 0x0, 0x0, 0);
15004 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15005
15006 expected = "qMemTags:deadbeef,10:1";
15007 create_fetch_memtags_request (packet, 0xdeadbeef, 16, 1);
15008 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
15009
15010 /* Test parsing a qMemTags reply. */
15011
15012 /* Error reply, tags vector unmodified. */
15013 reply = "E00";
15014 strcpy (packet.data (), reply.c_str ());
15015 tags.resize (0);
15016 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == false);
15017 SELF_CHECK (tags.size () == 0);
15018
15019 /* Valid reply, tags vector updated. */
15020 tags.resize (0);
15021 bv.resize (0);
15022
15023 for (int i = 0; i < 5; i++)
15024 bv.push_back (i);
15025
15026 reply = "m" + bin2hex (bv.data (), bv.size ());
15027 strcpy (packet.data (), reply.c_str ());
15028
15029 SELF_CHECK (parse_fetch_memtags_reply (packet, tags) == true);
15030 SELF_CHECK (tags.size () == 5);
15031
15032 for (int i = 0; i < 5; i++)
15033 SELF_CHECK (tags[i] == i);
15034
15035 /* Test creating a QMemTags request. */
15036
15037 /* Empty tag data. */
15038 tags.resize (0);
15039 expected = "QMemTags:0,0:0:";
15040 create_store_memtags_request (packet, 0x0, 0x0, 0, tags);
15041 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15042 expected.length ()) == 0);
15043
15044 /* Non-empty tag data. */
15045 tags.resize (0);
15046 for (int i = 0; i < 5; i++)
15047 tags.push_back (i);
15048 expected = "QMemTags:deadbeef,ff:1:0001020304";
15049 create_store_memtags_request (packet, 0xdeadbeef, 255, 1, tags);
15050 SELF_CHECK (memcmp (packet.data (), expected.c_str (),
15051 expected.length ()) == 0);
15052 }
15053
15054 } // namespace selftests
15055 #endif /* GDB_SELF_TEST */
15056
15057 void _initialize_remote ();
15058 void
15059 _initialize_remote ()
15060 {
15061 add_target (remote_target_info, remote_target::open);
15062 add_target (extended_remote_target_info, extended_remote_target::open);
15063
15064 /* Hook into new objfile notification. */
15065 gdb::observers::new_objfile.attach (remote_new_objfile, "remote");
15066
15067 #if 0
15068 init_remote_threadtests ();
15069 #endif
15070
15071 /* set/show remote ... */
15072
15073 add_basic_prefix_cmd ("remote", class_maintenance, _("\
15074 Remote protocol specific variables.\n\
15075 Configure various remote-protocol specific variables such as\n\
15076 the packets being used."),
15077 &remote_set_cmdlist,
15078 0 /* allow-unknown */, &setlist);
15079 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
15080 Remote protocol specific variables.\n\
15081 Configure various remote-protocol specific variables such as\n\
15082 the packets being used."),
15083 &remote_show_cmdlist,
15084 0 /* allow-unknown */, &showlist);
15085
15086 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
15087 Compare section data on target to the exec file.\n\
15088 Argument is a single section name (default: all loaded sections).\n\
15089 To compare only read-only loaded sections, specify the -r option."),
15090 &cmdlist);
15091
15092 add_cmd ("packet", class_maintenance, cli_packet_command, _("\
15093 Send an arbitrary packet to a remote target.\n\
15094 maintenance packet TEXT\n\
15095 If GDB is talking to an inferior via the GDB serial protocol, then\n\
15096 this command sends the string TEXT to the inferior, and displays the\n\
15097 response packet. GDB supplies the initial `$' character, and the\n\
15098 terminating `#' character and checksum."),
15099 &maintenancelist);
15100
15101 set_show_commands remotebreak_cmds
15102 = add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
15103 Set whether to send break if interrupted."), _("\
15104 Show whether to send break if interrupted."), _("\
15105 If set, a break, instead of a cntrl-c, is sent to the remote target."),
15106 set_remotebreak, show_remotebreak,
15107 &setlist, &showlist);
15108 deprecate_cmd (remotebreak_cmds.set, "set remote interrupt-sequence");
15109 deprecate_cmd (remotebreak_cmds.show, "show remote interrupt-sequence");
15110
15111 add_setshow_enum_cmd ("interrupt-sequence", class_support,
15112 interrupt_sequence_modes, &interrupt_sequence_mode,
15113 _("\
15114 Set interrupt sequence to remote target."), _("\
15115 Show interrupt sequence to remote target."), _("\
15116 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
15117 NULL, show_interrupt_sequence,
15118 &remote_set_cmdlist,
15119 &remote_show_cmdlist);
15120
15121 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
15122 &interrupt_on_connect, _("\
15123 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15124 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("\
15125 If set, interrupt sequence is sent to remote target."),
15126 NULL, NULL,
15127 &remote_set_cmdlist, &remote_show_cmdlist);
15128
15129 /* Install commands for configuring memory read/write packets. */
15130
15131 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
15132 Set the maximum number of bytes per memory write packet (deprecated)."),
15133 &setlist);
15134 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
15135 Show the maximum number of bytes per memory write packet (deprecated)."),
15136 &showlist);
15137 add_cmd ("memory-write-packet-size", no_class,
15138 set_memory_write_packet_size, _("\
15139 Set the maximum number of bytes per memory-write packet.\n\
15140 Specify the number of bytes in a packet or 0 (zero) for the\n\
15141 default packet size. The actual limit is further reduced\n\
15142 dependent on the target. Specify \"fixed\" to disable the\n\
15143 further restriction and \"limit\" to enable that restriction."),
15144 &remote_set_cmdlist);
15145 add_cmd ("memory-read-packet-size", no_class,
15146 set_memory_read_packet_size, _("\
15147 Set the maximum number of bytes per memory-read packet.\n\
15148 Specify the number of bytes in a packet or 0 (zero) for the\n\
15149 default packet size. The actual limit is further reduced\n\
15150 dependent on the target. Specify \"fixed\" to disable the\n\
15151 further restriction and \"limit\" to enable that restriction."),
15152 &remote_set_cmdlist);
15153 add_cmd ("memory-write-packet-size", no_class,
15154 show_memory_write_packet_size,
15155 _("Show the maximum number of bytes per memory-write packet."),
15156 &remote_show_cmdlist);
15157 add_cmd ("memory-read-packet-size", no_class,
15158 show_memory_read_packet_size,
15159 _("Show the maximum number of bytes per memory-read packet."),
15160 &remote_show_cmdlist);
15161
15162 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
15163 &remote_hw_watchpoint_limit, _("\
15164 Set the maximum number of target hardware watchpoints."), _("\
15165 Show the maximum number of target hardware watchpoints."), _("\
15166 Specify \"unlimited\" for unlimited hardware watchpoints."),
15167 NULL, show_hardware_watchpoint_limit,
15168 &remote_set_cmdlist,
15169 &remote_show_cmdlist);
15170 add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
15171 no_class,
15172 &remote_hw_watchpoint_length_limit, _("\
15173 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
15174 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
15175 Specify \"unlimited\" to allow watchpoints of unlimited size."),
15176 NULL, show_hardware_watchpoint_length_limit,
15177 &remote_set_cmdlist, &remote_show_cmdlist);
15178 add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
15179 &remote_hw_breakpoint_limit, _("\
15180 Set the maximum number of target hardware breakpoints."), _("\
15181 Show the maximum number of target hardware breakpoints."), _("\
15182 Specify \"unlimited\" for unlimited hardware breakpoints."),
15183 NULL, show_hardware_breakpoint_limit,
15184 &remote_set_cmdlist, &remote_show_cmdlist);
15185
15186 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
15187 &remote_address_size, _("\
15188 Set the maximum size of the address (in bits) in a memory packet."), _("\
15189 Show the maximum size of the address (in bits) in a memory packet."), NULL,
15190 NULL,
15191 NULL, /* FIXME: i18n: */
15192 &setlist, &showlist);
15193
15194 init_all_packet_configs ();
15195
15196 add_packet_config_cmd (PACKET_X, "X", "binary-download", 1);
15197
15198 add_packet_config_cmd (PACKET_vCont, "vCont", "verbose-resume", 0);
15199
15200 add_packet_config_cmd (PACKET_QPassSignals, "QPassSignals", "pass-signals",
15201 0);
15202
15203 add_packet_config_cmd (PACKET_QCatchSyscalls, "QCatchSyscalls",
15204 "catch-syscalls", 0);
15205
15206 add_packet_config_cmd (PACKET_QProgramSignals, "QProgramSignals",
15207 "program-signals", 0);
15208
15209 add_packet_config_cmd (PACKET_QSetWorkingDir, "QSetWorkingDir",
15210 "set-working-dir", 0);
15211
15212 add_packet_config_cmd (PACKET_QStartupWithShell, "QStartupWithShell",
15213 "startup-with-shell", 0);
15214
15215 add_packet_config_cmd (PACKET_QEnvironmentHexEncoded,"QEnvironmentHexEncoded",
15216 "environment-hex-encoded", 0);
15217
15218 add_packet_config_cmd (PACKET_QEnvironmentReset, "QEnvironmentReset",
15219 "environment-reset", 0);
15220
15221 add_packet_config_cmd (PACKET_QEnvironmentUnset, "QEnvironmentUnset",
15222 "environment-unset", 0);
15223
15224 add_packet_config_cmd (PACKET_qSymbol, "qSymbol", "symbol-lookup", 0);
15225
15226 add_packet_config_cmd (PACKET_P, "P", "set-register", 1);
15227
15228 add_packet_config_cmd (PACKET_p, "p", "fetch-register", 1);
15229
15230 add_packet_config_cmd (PACKET_Z0, "Z0", "software-breakpoint", 0);
15231
15232 add_packet_config_cmd (PACKET_Z1, "Z1", "hardware-breakpoint", 0);
15233
15234 add_packet_config_cmd (PACKET_Z2, "Z2", "write-watchpoint", 0);
15235
15236 add_packet_config_cmd (PACKET_Z3, "Z3", "read-watchpoint", 0);
15237
15238 add_packet_config_cmd (PACKET_Z4, "Z4", "access-watchpoint", 0);
15239
15240 add_packet_config_cmd (PACKET_qXfer_auxv, "qXfer:auxv:read",
15241 "read-aux-vector", 0);
15242
15243 add_packet_config_cmd (PACKET_qXfer_exec_file, "qXfer:exec-file:read",
15244 "pid-to-exec-file", 0);
15245
15246 add_packet_config_cmd (PACKET_qXfer_features,
15247 "qXfer:features:read", "target-features", 0);
15248
15249 add_packet_config_cmd (PACKET_qXfer_libraries, "qXfer:libraries:read",
15250 "library-info", 0);
15251
15252 add_packet_config_cmd (PACKET_qXfer_libraries_svr4,
15253 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
15254
15255 add_packet_config_cmd (PACKET_qXfer_memory_map, "qXfer:memory-map:read",
15256 "memory-map", 0);
15257
15258 add_packet_config_cmd (PACKET_qXfer_osdata, "qXfer:osdata:read", "osdata", 0);
15259
15260 add_packet_config_cmd (PACKET_qXfer_threads, "qXfer:threads:read", "threads",
15261 0);
15262
15263 add_packet_config_cmd (PACKET_qXfer_siginfo_read, "qXfer:siginfo:read",
15264 "read-siginfo-object", 0);
15265
15266 add_packet_config_cmd (PACKET_qXfer_siginfo_write, "qXfer:siginfo:write",
15267 "write-siginfo-object", 0);
15268
15269 add_packet_config_cmd (PACKET_qXfer_traceframe_info,
15270 "qXfer:traceframe-info:read", "traceframe-info", 0);
15271
15272 add_packet_config_cmd (PACKET_qXfer_uib, "qXfer:uib:read",
15273 "unwind-info-block", 0);
15274
15275 add_packet_config_cmd (PACKET_qGetTLSAddr, "qGetTLSAddr",
15276 "get-thread-local-storage-address", 0);
15277
15278 add_packet_config_cmd (PACKET_qGetTIBAddr, "qGetTIBAddr",
15279 "get-thread-information-block-address", 0);
15280
15281 add_packet_config_cmd (PACKET_bc, "bc", "reverse-continue", 0);
15282
15283 add_packet_config_cmd (PACKET_bs, "bs", "reverse-step", 0);
15284
15285 add_packet_config_cmd (PACKET_qSupported, "qSupported", "supported-packets",
15286 0);
15287
15288 add_packet_config_cmd (PACKET_qSearch_memory, "qSearch:memory",
15289 "search-memory", 0);
15290
15291 add_packet_config_cmd (PACKET_qTStatus, "qTStatus", "trace-status", 0);
15292
15293 add_packet_config_cmd (PACKET_vFile_setfs, "vFile:setfs", "hostio-setfs", 0);
15294
15295 add_packet_config_cmd (PACKET_vFile_open, "vFile:open", "hostio-open", 0);
15296
15297 add_packet_config_cmd (PACKET_vFile_pread, "vFile:pread", "hostio-pread", 0);
15298
15299 add_packet_config_cmd (PACKET_vFile_pwrite, "vFile:pwrite", "hostio-pwrite",
15300 0);
15301
15302 add_packet_config_cmd (PACKET_vFile_close, "vFile:close", "hostio-close", 0);
15303
15304 add_packet_config_cmd (PACKET_vFile_unlink, "vFile:unlink", "hostio-unlink",
15305 0);
15306
15307 add_packet_config_cmd (PACKET_vFile_readlink, "vFile:readlink",
15308 "hostio-readlink", 0);
15309
15310 add_packet_config_cmd (PACKET_vFile_fstat, "vFile:fstat", "hostio-fstat", 0);
15311
15312 add_packet_config_cmd (PACKET_vAttach, "vAttach", "attach", 0);
15313
15314 add_packet_config_cmd (PACKET_vRun, "vRun", "run", 0);
15315
15316 add_packet_config_cmd (PACKET_QStartNoAckMode, "QStartNoAckMode", "noack", 0);
15317
15318 add_packet_config_cmd (PACKET_vKill, "vKill", "kill", 0);
15319
15320 add_packet_config_cmd (PACKET_qAttached, "qAttached", "query-attached", 0);
15321
15322 add_packet_config_cmd (PACKET_ConditionalTracepoints,
15323 "ConditionalTracepoints", "conditional-tracepoints",
15324 0);
15325
15326 add_packet_config_cmd (PACKET_ConditionalBreakpoints,
15327 "ConditionalBreakpoints", "conditional-breakpoints",
15328 0);
15329
15330 add_packet_config_cmd (PACKET_BreakpointCommands, "BreakpointCommands",
15331 "breakpoint-commands", 0);
15332
15333 add_packet_config_cmd (PACKET_FastTracepoints, "FastTracepoints",
15334 "fast-tracepoints", 0);
15335
15336 add_packet_config_cmd (PACKET_TracepointSource, "TracepointSource",
15337 "TracepointSource", 0);
15338
15339 add_packet_config_cmd (PACKET_QAllow, "QAllow", "allow", 0);
15340
15341 add_packet_config_cmd (PACKET_StaticTracepoints, "StaticTracepoints",
15342 "static-tracepoints", 0);
15343
15344 add_packet_config_cmd (PACKET_InstallInTrace, "InstallInTrace",
15345 "install-in-trace", 0);
15346
15347 add_packet_config_cmd (PACKET_qXfer_statictrace_read,
15348 "qXfer:statictrace:read", "read-sdata-object", 0);
15349
15350 add_packet_config_cmd (PACKET_qXfer_fdpic, "qXfer:fdpic:read",
15351 "read-fdpic-loadmap", 0);
15352
15353 add_packet_config_cmd (PACKET_QDisableRandomization, "QDisableRandomization",
15354 "disable-randomization", 0);
15355
15356 add_packet_config_cmd (PACKET_QAgent, "QAgent", "agent", 0);
15357
15358 add_packet_config_cmd (PACKET_QTBuffer_size, "QTBuffer:size",
15359 "trace-buffer-size", 0);
15360
15361 add_packet_config_cmd (PACKET_Qbtrace_off, "Qbtrace:off", "disable-btrace",
15362 0);
15363
15364 add_packet_config_cmd (PACKET_Qbtrace_bts, "Qbtrace:bts", "enable-btrace-bts",
15365 0);
15366
15367 add_packet_config_cmd (PACKET_Qbtrace_pt, "Qbtrace:pt", "enable-btrace-pt",
15368 0);
15369
15370 add_packet_config_cmd (PACKET_qXfer_btrace, "qXfer:btrace", "read-btrace", 0);
15371
15372 add_packet_config_cmd (PACKET_qXfer_btrace_conf, "qXfer:btrace-conf",
15373 "read-btrace-conf", 0);
15374
15375 add_packet_config_cmd (PACKET_Qbtrace_conf_bts_size, "Qbtrace-conf:bts:size",
15376 "btrace-conf-bts-size", 0);
15377
15378 add_packet_config_cmd (PACKET_multiprocess_feature, "multiprocess-feature",
15379 "multiprocess-feature", 0);
15380
15381 add_packet_config_cmd (PACKET_swbreak_feature, "swbreak-feature",
15382 "swbreak-feature", 0);
15383
15384 add_packet_config_cmd (PACKET_hwbreak_feature, "hwbreak-feature",
15385 "hwbreak-feature", 0);
15386
15387 add_packet_config_cmd (PACKET_fork_event_feature, "fork-event-feature",
15388 "fork-event-feature", 0);
15389
15390 add_packet_config_cmd (PACKET_vfork_event_feature, "vfork-event-feature",
15391 "vfork-event-feature", 0);
15392
15393 add_packet_config_cmd (PACKET_Qbtrace_conf_pt_size, "Qbtrace-conf:pt:size",
15394 "btrace-conf-pt-size", 0);
15395
15396 add_packet_config_cmd (PACKET_vContSupported, "vContSupported",
15397 "verbose-resume-supported", 0);
15398
15399 add_packet_config_cmd (PACKET_exec_event_feature, "exec-event-feature",
15400 "exec-event-feature", 0);
15401
15402 add_packet_config_cmd (PACKET_vCtrlC, "vCtrlC", "ctrl-c", 0);
15403
15404 add_packet_config_cmd (PACKET_QThreadEvents, "QThreadEvents", "thread-events",
15405 0);
15406
15407 add_packet_config_cmd (PACKET_no_resumed, "N stop reply",
15408 "no-resumed-stop-reply", 0);
15409
15410 add_packet_config_cmd (PACKET_memory_tagging_feature,
15411 "memory-tagging-feature", "memory-tagging-feature", 0);
15412
15413 /* Assert that we've registered "set remote foo-packet" commands
15414 for all packet configs. */
15415 {
15416 int i;
15417
15418 for (i = 0; i < PACKET_MAX; i++)
15419 {
15420 /* Ideally all configs would have a command associated. Some
15421 still don't though. */
15422 int excepted;
15423
15424 switch (i)
15425 {
15426 case PACKET_QNonStop:
15427 case PACKET_EnableDisableTracepoints_feature:
15428 case PACKET_tracenz_feature:
15429 case PACKET_DisconnectedTracing_feature:
15430 case PACKET_augmented_libraries_svr4_read_feature:
15431 case PACKET_qCRC:
15432 /* Additions to this list need to be well justified:
15433 pre-existing packets are OK; new packets are not. */
15434 excepted = 1;
15435 break;
15436 default:
15437 excepted = 0;
15438 break;
15439 }
15440
15441 /* This catches both forgetting to add a config command, and
15442 forgetting to remove a packet from the exception list. */
15443 gdb_assert (excepted == (packets_descriptions[i].name == NULL));
15444 }
15445 }
15446
15447 /* Keep the old ``set remote Z-packet ...'' working. Each individual
15448 Z sub-packet has its own set and show commands, but users may
15449 have sets to this variable in their .gdbinit files (or in their
15450 documentation). */
15451 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
15452 &remote_Z_packet_detect, _("\
15453 Set use of remote protocol `Z' packets."), _("\
15454 Show use of remote protocol `Z' packets."), _("\
15455 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
15456 packets."),
15457 set_remote_protocol_Z_packet_cmd,
15458 show_remote_protocol_Z_packet_cmd,
15459 /* FIXME: i18n: Use of remote protocol
15460 `Z' packets is %s. */
15461 &remote_set_cmdlist, &remote_show_cmdlist);
15462
15463 add_basic_prefix_cmd ("remote", class_files, _("\
15464 Manipulate files on the remote system.\n\
15465 Transfer files to and from the remote target system."),
15466 &remote_cmdlist,
15467 0 /* allow-unknown */, &cmdlist);
15468
15469 add_cmd ("put", class_files, remote_put_command,
15470 _("Copy a local file to the remote system."),
15471 &remote_cmdlist);
15472
15473 add_cmd ("get", class_files, remote_get_command,
15474 _("Copy a remote file to the local system."),
15475 &remote_cmdlist);
15476
15477 add_cmd ("delete", class_files, remote_delete_command,
15478 _("Delete a remote file."),
15479 &remote_cmdlist);
15480
15481 add_setshow_string_noescape_cmd ("exec-file", class_files,
15482 &remote_exec_file_var, _("\
15483 Set the remote pathname for \"run\"."), _("\
15484 Show the remote pathname for \"run\"."), NULL,
15485 set_remote_exec_file,
15486 show_remote_exec_file,
15487 &remote_set_cmdlist,
15488 &remote_show_cmdlist);
15489
15490 add_setshow_boolean_cmd ("range-stepping", class_run,
15491 &use_range_stepping, _("\
15492 Enable or disable range stepping."), _("\
15493 Show whether target-assisted range stepping is enabled."), _("\
15494 If on, and the target supports it, when stepping a source line, GDB\n\
15495 tells the target to step the corresponding range of addresses itself instead\n\
15496 of issuing multiple single-steps. This speeds up source level\n\
15497 stepping. If off, GDB always issues single-steps, even if range\n\
15498 stepping is supported by the target. The default is on."),
15499 set_range_stepping,
15500 show_range_stepping,
15501 &setlist,
15502 &showlist);
15503
15504 add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
15505 Set watchdog timer."), _("\
15506 Show watchdog timer."), _("\
15507 When non-zero, this timeout is used instead of waiting forever for a target\n\
15508 to finish a low-level step or continue operation. If the specified amount\n\
15509 of time passes without a response from the target, an error occurs."),
15510 NULL,
15511 show_watchdog,
15512 &setlist, &showlist);
15513
15514 add_setshow_zuinteger_unlimited_cmd ("remote-packet-max-chars", no_class,
15515 &remote_packet_max_chars, _("\
15516 Set the maximum number of characters to display for each remote packet."), _("\
15517 Show the maximum number of characters to display for each remote packet."), _("\
15518 Specify \"unlimited\" to display all the characters."),
15519 NULL, show_remote_packet_max_chars,
15520 &setdebuglist, &showdebuglist);
15521
15522 add_setshow_boolean_cmd ("remote", no_class, &remote_debug,
15523 _("Set debugging of remote protocol."),
15524 _("Show debugging of remote protocol."),
15525 _("\
15526 When enabled, each packet sent or received with the remote target\n\
15527 is displayed."),
15528 NULL,
15529 show_remote_debug,
15530 &setdebuglist, &showdebuglist);
15531
15532 add_setshow_zuinteger_unlimited_cmd ("remotetimeout", no_class,
15533 &remote_timeout, _("\
15534 Set timeout limit to wait for target to respond."), _("\
15535 Show timeout limit to wait for target to respond."), _("\
15536 This value is used to set the time limit for gdb to wait for a response\n\
15537 from the target."),
15538 NULL,
15539 show_remote_timeout,
15540 &setlist, &showlist);
15541
15542 /* Eventually initialize fileio. See fileio.c */
15543 initialize_remote_fileio (&remote_set_cmdlist, &remote_show_cmdlist);
15544
15545 #if GDB_SELF_TEST
15546 selftests::register_test ("remote_memory_tagging",
15547 selftests::test_memory_tagging_functions);
15548 #endif
15549 }